Cleaning error before return Invalid_argument. (#19660)
[mono-project.git] / mono / mini / debugger-agent.c
blob018f73356f7e05557ca302588f7439e6c4fed7eb
1 /**
2 * \file
3 * Soft Debugger back-end module
5 * Author:
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright 2011 Xamarin Inc.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 #include <config.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #ifdef HAVE_SYS_TYPES_H
18 #include <sys/types.h>
19 #endif
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.h>
22 #endif
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
25 #endif
26 #ifdef HAVE_NETINET_TCP_H
27 #include <netinet/tcp.h>
28 #endif
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #include <errno.h>
36 #include <glib.h>
38 #ifdef HAVE_PTHREAD_H
39 #include <pthread.h>
40 #endif
42 #ifdef HOST_WIN32
43 #ifdef _MSC_VER
44 #include <winsock2.h>
45 #include <process.h>
46 #endif
47 #include <ws2tcpip.h>
48 #include <windows.h>
49 #endif
51 #ifdef HOST_ANDROID
52 #include <linux/in.h>
53 #include <linux/tcp.h>
54 #include <sys/endian.h>
55 #endif
57 #include <mono/metadata/mono-debug.h>
58 #include <mono/metadata/debug-internals.h>
59 #include <mono/metadata/domain-internals.h>
60 #include <mono/metadata/gc-internals.h>
61 #include <mono/metadata/environment.h>
62 #include <mono/metadata/mono-hash-internals.h>
63 #include <mono/metadata/threads-types.h>
64 #include <mono/metadata/threadpool.h>
65 #include <mono/metadata/assembly.h>
66 #include <mono/metadata/assembly-internals.h>
67 #include <mono/metadata/runtime.h>
68 #include <mono/metadata/verify-internals.h>
69 #include <mono/metadata/reflection-internals.h>
70 #include <mono/metadata/w32socket.h>
71 #include <mono/utils/mono-coop-mutex.h>
72 #include <mono/utils/mono-coop-semaphore.h>
73 #include <mono/utils/mono-error-internals.h>
74 #include <mono/utils/mono-stack-unwinding.h>
75 #include <mono/utils/mono-time.h>
76 #include <mono/utils/mono-threads.h>
77 #include <mono/utils/networking.h>
78 #include <mono/utils/mono-proclib.h>
79 #include <mono/utils/w32api.h>
80 #include <mono/utils/mono-logger-internals.h>
81 #include "debugger-state-machine.h"
82 #include "debugger-agent.h"
83 #include "mini.h"
84 #include "seq-points.h"
85 #include "aot-runtime.h"
86 #include "mini-runtime.h"
87 #include "interp/interp.h"
88 #include "debugger-engine.h"
89 #include "mono/metadata/debug-mono-ppdb.h"
90 #include "mono/metadata/custom-attrs-internals.h"
93 * On iOS we can't use System.Environment.Exit () as it will do the wrong
94 * shutdown sequence.
96 #if !defined (TARGET_IOS)
97 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
98 #endif
100 #if DISABLE_SOCKETS
101 #define DISABLE_SOCKET_TRANSPORT
102 #endif
104 #ifndef DISABLE_SDB
106 #include <mono/utils/mono-os-mutex.h>
108 #include <fcntl.h>
109 #include <sys/stat.h>
111 #ifndef S_IWUSR
112 #define S_IWUSR S_IWRITE
113 #endif
115 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
117 #if _MSC_VER
118 #pragma warning(disable:4312) // FIXME pointer cast to different size
119 #endif
121 typedef struct {
122 gboolean enabled;
123 char *transport;
124 char *address;
125 int log_level;
126 char *log_file;
127 gboolean suspend;
128 gboolean server;
129 gboolean onuncaught;
130 GSList *onthrow;
131 int timeout;
132 char *launch;
133 gboolean embedding;
134 gboolean defer;
135 int keepalive;
136 gboolean setpgid;
137 } AgentConfig;
139 typedef struct
141 //Must be the first field to ensure pointer equivalence
142 DbgEngineStackFrame de;
143 int id;
144 guint32 il_offset;
146 * If method is gshared, this is the actual instance, otherwise this is equal to
147 * method.
149 MonoMethod *actual_method;
151 * This is the method which is visible to debugger clients. Same as method,
152 * except for native-to-managed wrappers.
154 MonoMethod *api_method;
155 MonoContext ctx;
156 MonoDebugMethodJitInfo *jit;
157 MonoInterpFrameHandle interp_frame;
158 gpointer frame_addr;
159 int flags;
160 host_mgreg_t *reg_locations [MONO_MAX_IREGS];
162 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
163 * the frame can become invalid.
165 gboolean has_ctx;
166 } StackFrame;
168 typedef struct _InvokeData InvokeData;
170 struct _InvokeData
172 int id;
173 int flags;
174 guint8 *p;
175 guint8 *endp;
176 /* This is the context which needs to be restored after the invoke */
177 MonoContext ctx;
178 gboolean has_ctx;
180 * If this is set, invoke this method with the arguments given by ARGS.
182 MonoMethod *method;
183 gpointer *args;
184 guint32 suspend_count;
185 int nmethods;
187 InvokeData *last_invoke;
190 struct _DebuggerTlsData {
191 MonoThreadUnwindState context;
193 /* This is computed on demand when it is requested using the wire protocol */
194 /* It is freed up when the thread is resumed */
195 int frame_count;
196 StackFrame **frames;
198 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
199 * re-compute it.
201 gboolean frames_up_to_date;
203 * Points to data about a pending invoke which needs to be executed after the thread
204 * resumes.
206 InvokeData *pending_invoke;
208 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
209 * native code.
211 gboolean suspended;
213 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
214 * within a finite amount of time.
216 gboolean suspending;
218 * Set to TRUE if this thread is suspended in suspend_current ().
220 gboolean really_suspended;
221 /* Used to pass the context to the breakpoint/single step handler */
222 MonoContext handler_ctx;
223 /* Whenever thread_stop () was called for this thread */
224 gboolean terminated;
226 /* Whenever to disable breakpoints (used during invokes) */
227 gboolean disable_breakpoints;
230 * Number of times this thread has been resumed using resume_thread ().
232 guint32 resume_count;
233 guint32 resume_count_internal;
234 guint32 suspend_count;
236 MonoInternalThread *thread;
237 intptr_t thread_id;
240 * Information about the frame which transitioned to native code for running
241 * threads.
243 StackFrameInfo async_last_frame;
246 * The context where the stack walk can be started for running threads.
248 MonoThreadUnwindState async_state;
251 * The context used for filter clauses
253 MonoThreadUnwindState filter_state;
255 gboolean abort_requested;
258 * The current mono_runtime_invoke_checked invocation.
260 InvokeData *invoke;
262 StackFrameInfo catch_frame;
263 gboolean has_catch_frame;
266 * The context which needs to be restored after handling a single step/breakpoint
267 * event. This is the same as the ctx at step/breakpoint site, but includes changes
268 * to caller saved registers done by set_var ().
270 MonoThreadUnwindState restore_state;
271 /* Frames computed from restore_state */
272 int restore_frame_count;
273 StackFrame **restore_frames;
275 /* The currently unloading appdomain */
276 MonoDomain *domain_unloading;
278 // The state that the debugger expects the thread to be in
279 MonoDebuggerThreadState thread_state;
280 MonoStopwatch step_time;
282 gboolean gc_finalizing;
285 typedef struct {
286 const char *name;
287 void (*connect) (const char *address);
288 void (*close1) (void);
289 void (*close2) (void);
290 gboolean (*send) (void *buf, int len);
291 int (*recv) (void *buf, int len);
292 } DebuggerTransport;
295 * Wire Protocol definitions
298 #define HEADER_LENGTH 11
300 #define MAJOR_VERSION 2
301 #define MINOR_VERSION 57
303 typedef enum {
304 CMD_SET_VM = 1,
305 CMD_SET_OBJECT_REF = 9,
306 CMD_SET_STRING_REF = 10,
307 CMD_SET_THREAD = 11,
308 CMD_SET_ARRAY_REF = 13,
309 CMD_SET_EVENT_REQUEST = 15,
310 CMD_SET_STACK_FRAME = 16,
311 CMD_SET_APPDOMAIN = 20,
312 CMD_SET_ASSEMBLY = 21,
313 CMD_SET_METHOD = 22,
314 CMD_SET_TYPE = 23,
315 CMD_SET_MODULE = 24,
316 CMD_SET_FIELD = 25,
317 CMD_SET_EVENT = 64,
318 CMD_SET_POINTER = 65
319 } CommandSet;
321 typedef enum {
322 SUSPEND_POLICY_NONE = 0,
323 SUSPEND_POLICY_EVENT_THREAD = 1,
324 SUSPEND_POLICY_ALL = 2
325 } SuspendPolicy;
327 typedef enum {
328 ERR_NONE = 0,
329 ERR_INVALID_OBJECT = 20,
330 ERR_INVALID_FIELDID = 25,
331 ERR_INVALID_FRAMEID = 30,
332 ERR_NOT_IMPLEMENTED = 100,
333 ERR_NOT_SUSPENDED = 101,
334 ERR_INVALID_ARGUMENT = 102,
335 ERR_UNLOADED = 103,
336 ERR_NO_INVOCATION = 104,
337 ERR_ABSENT_INFORMATION = 105,
338 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
339 ERR_INVOKE_ABORTED = 107,
340 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
341 } ErrorCode;
343 typedef enum {
344 TOKEN_TYPE_STRING = 0,
345 TOKEN_TYPE_TYPE = 1,
346 TOKEN_TYPE_FIELD = 2,
347 TOKEN_TYPE_METHOD = 3,
348 TOKEN_TYPE_UNKNOWN = 4
349 } DebuggerTokenType;
351 typedef enum {
352 VALUE_TYPE_ID_NULL = 0xf0,
353 VALUE_TYPE_ID_TYPE = 0xf1,
354 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2,
355 VALUE_TYPE_ID_FIXED_ARRAY = 0xf3
356 } ValueTypeId;
358 typedef enum {
359 FRAME_FLAG_DEBUGGER_INVOKE = 1,
360 FRAME_FLAG_NATIVE_TRANSITION = 2
361 } StackFrameFlags;
363 typedef enum {
364 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
365 INVOKE_FLAG_SINGLE_THREADED = 2,
366 INVOKE_FLAG_RETURN_OUT_THIS = 4,
367 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
368 INVOKE_FLAG_VIRTUAL = 16
369 } InvokeFlags;
371 typedef enum {
372 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
373 } BindingFlagsExtensions;
375 typedef enum {
376 CMD_VM_VERSION = 1,
377 CMD_VM_ALL_THREADS = 2,
378 CMD_VM_SUSPEND = 3,
379 CMD_VM_RESUME = 4,
380 CMD_VM_EXIT = 5,
381 CMD_VM_DISPOSE = 6,
382 CMD_VM_INVOKE_METHOD = 7,
383 CMD_VM_SET_PROTOCOL_VERSION = 8,
384 CMD_VM_ABORT_INVOKE = 9,
385 CMD_VM_SET_KEEPALIVE = 10,
386 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
387 CMD_VM_GET_TYPES = 12,
388 CMD_VM_INVOKE_METHODS = 13,
389 CMD_VM_START_BUFFERING = 14,
390 CMD_VM_STOP_BUFFERING = 15
391 } CmdVM;
393 typedef enum {
394 CMD_THREAD_GET_FRAME_INFO = 1,
395 CMD_THREAD_GET_NAME = 2,
396 CMD_THREAD_GET_STATE = 3,
397 CMD_THREAD_GET_INFO = 4,
398 CMD_THREAD_GET_ID = 5,
399 CMD_THREAD_GET_TID = 6,
400 CMD_THREAD_SET_IP = 7,
401 CMD_THREAD_ELAPSED_TIME = 8
402 } CmdThread;
404 typedef enum {
405 CMD_EVENT_REQUEST_SET = 1,
406 CMD_EVENT_REQUEST_CLEAR = 2,
407 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
408 } CmdEvent;
410 typedef enum {
411 CMD_COMPOSITE = 100
412 } CmdComposite;
414 typedef enum {
415 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
416 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
417 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
418 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
419 CMD_APPDOMAIN_CREATE_STRING = 5,
420 CMD_APPDOMAIN_GET_CORLIB = 6,
421 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
422 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
423 } CmdAppDomain;
425 typedef enum {
426 CMD_ASSEMBLY_GET_LOCATION = 1,
427 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
428 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
429 CMD_ASSEMBLY_GET_OBJECT = 4,
430 CMD_ASSEMBLY_GET_TYPE = 5,
431 CMD_ASSEMBLY_GET_NAME = 6,
432 CMD_ASSEMBLY_GET_DOMAIN = 7,
433 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
434 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
435 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
436 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
437 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
438 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13
439 } CmdAssembly;
441 typedef enum {
442 CMD_MODULE_GET_INFO = 1,
443 } CmdModule;
445 typedef enum {
446 CMD_FIELD_GET_INFO = 1,
447 } CmdField;
449 typedef enum {
450 CMD_METHOD_GET_NAME = 1,
451 CMD_METHOD_GET_DECLARING_TYPE = 2,
452 CMD_METHOD_GET_DEBUG_INFO = 3,
453 CMD_METHOD_GET_PARAM_INFO = 4,
454 CMD_METHOD_GET_LOCALS_INFO = 5,
455 CMD_METHOD_GET_INFO = 6,
456 CMD_METHOD_GET_BODY = 7,
457 CMD_METHOD_RESOLVE_TOKEN = 8,
458 CMD_METHOD_GET_CATTRS = 9,
459 CMD_METHOD_MAKE_GENERIC_METHOD = 10
460 } CmdMethod;
462 typedef enum {
463 CMD_TYPE_GET_INFO = 1,
464 CMD_TYPE_GET_METHODS = 2,
465 CMD_TYPE_GET_FIELDS = 3,
466 CMD_TYPE_GET_VALUES = 4,
467 CMD_TYPE_GET_OBJECT = 5,
468 CMD_TYPE_GET_SOURCE_FILES = 6,
469 CMD_TYPE_SET_VALUES = 7,
470 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
471 CMD_TYPE_GET_PROPERTIES = 9,
472 CMD_TYPE_GET_CATTRS = 10,
473 CMD_TYPE_GET_FIELD_CATTRS = 11,
474 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
475 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
476 CMD_TYPE_GET_VALUES_2 = 14,
477 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
478 CMD_TYPE_GET_INTERFACES = 16,
479 CMD_TYPE_GET_INTERFACE_MAP = 17,
480 CMD_TYPE_IS_INITIALIZED = 18,
481 CMD_TYPE_CREATE_INSTANCE = 19,
482 CMD_TYPE_GET_VALUE_SIZE = 20
483 } CmdType;
485 typedef enum {
486 CMD_STACK_FRAME_GET_VALUES = 1,
487 CMD_STACK_FRAME_GET_THIS = 2,
488 CMD_STACK_FRAME_SET_VALUES = 3,
489 CMD_STACK_FRAME_GET_DOMAIN = 4,
490 CMD_STACK_FRAME_SET_THIS = 5,
491 } CmdStackFrame;
493 typedef enum {
494 CMD_ARRAY_REF_GET_LENGTH = 1,
495 CMD_ARRAY_REF_GET_VALUES = 2,
496 CMD_ARRAY_REF_SET_VALUES = 3,
497 } CmdArray;
499 typedef enum {
500 CMD_STRING_REF_GET_VALUE = 1,
501 CMD_STRING_REF_GET_LENGTH = 2,
502 CMD_STRING_REF_GET_CHARS = 3
503 } CmdString;
505 typedef enum {
506 CMD_POINTER_GET_VALUE = 1
507 } CmdPointer;
509 typedef enum {
510 CMD_OBJECT_REF_GET_TYPE = 1,
511 CMD_OBJECT_REF_GET_VALUES = 2,
512 CMD_OBJECT_REF_IS_COLLECTED = 3,
513 CMD_OBJECT_REF_GET_ADDRESS = 4,
514 CMD_OBJECT_REF_GET_DOMAIN = 5,
515 CMD_OBJECT_REF_SET_VALUES = 6,
516 CMD_OBJECT_REF_GET_INFO = 7,
517 } CmdObject;
520 * Contains additional information for an event
522 typedef struct {
523 /* For EVENT_KIND_EXCEPTION */
524 MonoObject *exc;
525 MonoContext catch_ctx;
526 gboolean caught;
527 /* For EVENT_KIND_USER_LOG */
528 int level;
529 char *category, *message;
530 /* For EVENT_KIND_TYPE_LOAD */
531 MonoClass *klass;
532 /* For EVENT_KIND_CRASH */
533 char *dump;
534 MonoStackHash *hashes;
535 } EventInfo;
537 typedef struct {
538 guint8 *buf, *p, *end;
539 } Buffer;
541 typedef struct ReplyPacket {
542 int id;
543 int error;
544 Buffer *data;
545 } ReplyPacket;
547 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
549 #ifdef HOST_ANDROID
550 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
551 #else
552 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
553 #endif
555 #ifdef HOST_WIN32
556 #define get_last_sock_error() WSAGetLastError()
557 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
558 #define MONO_EINTR WSAEINTR
559 #else
560 #define get_last_sock_error() errno
561 #define MONO_EWOULDBLOCK EWOULDBLOCK
562 #define MONO_EINTR EINTR
563 #endif
565 #define CHECK_PROTOCOL_VERSION(major,minor) \
566 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
569 * Globals
572 static AgentConfig agent_config;
575 * Whenever the agent is fully initialized.
576 * When using the onuncaught or onthrow options, only some parts of the agent are
577 * initialized on startup, and the full initialization which includes connection
578 * establishment and the startup of the agent thread is only done in response to
579 * an event.
581 static gint32 inited;
583 #ifndef DISABLE_SOCKET_TRANSPORT
584 static int conn_fd;
585 static int listen_fd;
586 #endif
588 static int packet_id = 0;
590 static int objref_id = 0;
592 static int event_request_id = 0;
594 static int frame_id = 0;
596 static GPtrArray *event_requests;
598 static MonoNativeTlsKey debugger_tls_id;
600 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
602 /* Maps MonoInternalThread -> DebuggerTlsData */
603 /* Protected by the loader lock */
604 static MonoGHashTable *thread_to_tls;
606 /* Maps tid -> MonoInternalThread */
607 /* Protected by the loader lock */
608 static MonoGHashTable *tid_to_thread;
610 /* Maps tid -> MonoThread (not MonoInternalThread) */
611 /* Protected by the loader lock */
612 static MonoGHashTable *tid_to_thread_obj;
614 static MonoNativeThreadId debugger_thread_id;
616 static MonoThreadHandle *debugger_thread_handle;
618 static int log_level;
620 static int file_check_valid_memory = -1;
622 static char* filename_check_valid_memory;
624 static gboolean embedding;
626 static FILE *log_file;
628 /* Assemblies whose assembly load event has no been sent yet */
629 /* Protected by the dbg lock */
630 static GPtrArray *pending_assembly_loads;
632 /* Whenever the debugger thread has exited */
633 static gboolean debugger_thread_exited;
635 /* Cond variable used to wait for debugger_thread_exited becoming true */
636 static MonoCoopCond debugger_thread_exited_cond;
638 /* Mutex for the cond var above */
639 static MonoCoopMutex debugger_thread_exited_mutex;
641 /* The protocol version of the client */
642 static int major_version, minor_version;
644 /* Whenever the variables above are set by the client */
645 static gboolean protocol_version_set;
647 /* The number of times the runtime is suspended */
648 static gint32 suspend_count;
650 /* Whenever to buffer reply messages and send them together */
651 static gboolean buffer_replies;
653 /* Buffered reply packets */
654 static ReplyPacket reply_packets [128];
655 static int nreply_packets;
657 #define dbg_lock mono_de_lock
658 #define dbg_unlock mono_de_unlock
660 static void transport_init (void);
661 static void transport_connect (const char *address);
662 static gboolean transport_handshake (void);
663 static void register_transport (DebuggerTransport *trans);
665 static gsize WINAPI debugger_thread (void *arg);
667 static void runtime_initialized (MonoProfiler *prof);
669 static void runtime_shutdown (MonoProfiler *prof);
671 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
673 static void thread_end (MonoProfiler *prof, uintptr_t tid);
675 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
677 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
679 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
681 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
683 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
685 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
687 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
689 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
691 static void gc_finalizing (MonoProfiler *prof);
693 static void gc_finalized (MonoProfiler *prof);
695 static void emit_assembly_load (gpointer assembly, gpointer user_data);
697 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
699 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
701 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
703 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
705 static void suspend_current (void);
707 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
709 static void clear_types_for_assembly (MonoAssembly *assembly);
711 static void process_profiler_event (EventKind event, gpointer arg);
713 /* Submodule init/cleanup */
714 static void event_requests_cleanup (void);
716 static void objrefs_init (void);
717 static void objrefs_cleanup (void);
719 static void ids_init (void);
720 static void ids_cleanup (void);
722 static void suspend_init (void);
724 static void start_debugger_thread (MonoError *error);
725 static void stop_debugger_thread (void);
727 static void finish_agent_init (gboolean on_startup);
729 static void process_profiler_event (EventKind event, gpointer arg);
731 static void invalidate_frames (DebuggerTlsData *tls);
733 /* Callbacks used by debugger-engine */
734 static MonoContext* tls_get_restore_state (void *the_tls);
735 static gboolean try_process_suspend (void *tls, MonoContext *ctx, gboolean from_breakpoint);
736 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
737 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
738 static void ss_discard_frame_context (void *the_tls);
739 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
740 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
741 static int ensure_runtime_is_suspended (void);
742 static int get_this_async_id (DbgEngineStackFrame *frame);
743 static gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame);
744 static MonoMethod* get_notify_debugger_of_wait_completion_method (void);
745 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
746 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
747 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
748 static void ss_args_destroy (SingleStepArgs *ss_args);
749 static int handle_multiple_ss_requests (void);
751 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
753 #ifndef DISABLE_SOCKET_TRANSPORT
754 static void
755 register_socket_transport (void);
756 #endif
758 static gboolean
759 is_debugger_thread (void)
761 MonoInternalThread *internal;
763 internal = mono_thread_internal_current ();
764 if (!internal)
765 return FALSE;
767 return internal->debugger_thread;
770 static int
771 parse_address (char *address, char **host, int *port)
773 char *pos = strchr (address, ':');
775 if (pos == NULL || pos == address)
776 return 1;
778 size_t len = pos - address;
779 *host = (char *)g_malloc (len + 1);
780 memcpy (*host, address, len);
781 (*host) [len] = '\0';
783 *port = atoi (pos + 1);
785 return 0;
788 static void
789 print_usage (void)
791 g_printerr ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
792 g_printerr ("Available options:\n");
793 g_printerr (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
794 g_printerr (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
795 g_printerr (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
796 g_printerr (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
797 g_printerr (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
798 g_printerr (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
799 g_printerr (" server=y/n\t\t\tWhether to listen for a client connection.\n");
800 g_printerr (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
801 g_printerr (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
802 g_printerr (" help\t\t\t\tPrint this help.\n");
805 static gboolean
806 parse_flag (const char *option, char *flag)
808 if (!strcmp (flag, "y"))
809 return TRUE;
810 else if (!strcmp (flag, "n"))
811 return FALSE;
812 else {
813 g_printerr ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
814 exit (1);
815 return FALSE;
819 static void
820 debugger_agent_parse_options (char *options)
822 char **args, **ptr;
823 char *host;
824 int port;
825 char *extra;
827 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
828 g_printerr ("--debugger-agent is not supported on this platform.\n");
829 exit (1);
830 #endif
832 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
833 if (extra) {
834 options = g_strdup_printf ("%s,%s", options, extra);
835 g_free (extra);
838 agent_config.enabled = TRUE;
839 agent_config.suspend = TRUE;
840 agent_config.server = FALSE;
841 agent_config.defer = FALSE;
842 agent_config.address = NULL;
844 //agent_config.log_level = 10;
846 args = g_strsplit (options, ",", -1);
847 for (ptr = args; ptr && *ptr; ptr ++) {
848 char *arg = *ptr;
850 if (strncmp (arg, "transport=", 10) == 0) {
851 agent_config.transport = g_strdup (arg + 10);
852 } else if (strncmp (arg, "address=", 8) == 0) {
853 agent_config.address = g_strdup (arg + 8);
854 } else if (strncmp (arg, "loglevel=", 9) == 0) {
855 agent_config.log_level = atoi (arg + 9);
856 } else if (strncmp (arg, "logfile=", 8) == 0) {
857 agent_config.log_file = g_strdup (arg + 8);
858 } else if (strncmp (arg, "suspend=", 8) == 0) {
859 agent_config.suspend = parse_flag ("suspend", arg + 8);
860 } else if (strncmp (arg, "server=", 7) == 0) {
861 agent_config.server = parse_flag ("server", arg + 7);
862 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
863 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
864 } else if (strncmp (arg, "onthrow=", 8) == 0) {
865 /* We support multiple onthrow= options */
866 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
867 } else if (strncmp (arg, "onthrow", 7) == 0) {
868 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
869 } else if (strncmp (arg, "help", 4) == 0) {
870 print_usage ();
871 exit (0);
872 } else if (strncmp (arg, "timeout=", 8) == 0) {
873 agent_config.timeout = atoi (arg + 8);
874 } else if (strncmp (arg, "launch=", 7) == 0) {
875 agent_config.launch = g_strdup (arg + 7);
876 } else if (strncmp (arg, "embedding=", 10) == 0) {
877 agent_config.embedding = atoi (arg + 10) == 1;
878 } else if (strncmp (arg, "keepalive=", 10) == 0) {
879 agent_config.keepalive = atoi (arg + 10);
880 } else if (strncmp (arg, "setpgid=", 8) == 0) {
881 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
882 } else {
883 print_usage ();
884 exit (1);
888 if (agent_config.server && !agent_config.suspend) {
889 /* Waiting for deferred attachment */
890 agent_config.defer = TRUE;
891 if (agent_config.address == NULL) {
892 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
896 //agent_config.log_level = 0;
898 if (agent_config.transport == NULL) {
899 g_printerr ("debugger-agent: The 'transport' option is mandatory.\n");
900 exit (1);
903 if (agent_config.address == NULL && !agent_config.server) {
904 g_printerr ("debugger-agent: The 'address' option is mandatory.\n");
905 exit (1);
908 // FIXME:
909 if (!strcmp (agent_config.transport, "dt_socket")) {
910 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
911 g_printerr ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
912 exit (1);
917 void
918 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
920 g_assertf (tls, "Cannot get state of null thread", NULL);
922 g_assert (tls->thread_state == expected);
924 tls->thread_state = set;
927 MonoDebuggerThreadState
928 mono_debugger_get_thread_state (DebuggerTlsData *tls)
930 g_assertf (tls, "Cannot get state of null thread", NULL);
932 return tls->thread_state;
935 gsize
936 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
938 if (!tls)
939 return 0;
941 return tls->thread_id;
944 // Only call this function with the loader lock held
945 MonoGHashTable *
946 mono_debugger_get_thread_states (void)
948 return thread_to_tls;
951 gboolean
952 mono_debugger_is_disconnected (void)
954 return disconnected;
957 static void
958 debugger_agent_init (void)
960 if (!agent_config.enabled)
961 return;
963 DebuggerEngineCallbacks cbs;
964 memset (&cbs, 0, sizeof (cbs));
965 cbs.tls_get_restore_state = tls_get_restore_state;
966 cbs.try_process_suspend = try_process_suspend;
967 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
968 cbs.begin_single_step_processing = begin_single_step_processing;
969 cbs.ss_discard_frame_context = ss_discard_frame_context;
970 cbs.ss_calculate_framecount = ss_calculate_framecount;
971 cbs.ensure_jit = ensure_jit;
972 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
973 cbs.get_this_async_id = get_this_async_id;
974 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
975 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
976 cbs.create_breakpoint_events = create_breakpoint_events;
977 cbs.process_breakpoint_events = process_breakpoint_events;
978 cbs.ss_create_init_args = ss_create_init_args;
979 cbs.ss_args_destroy = ss_args_destroy;
980 cbs.handle_multiple_ss_requests = handle_multiple_ss_requests;
982 mono_de_init (&cbs);
984 transport_init ();
986 /* Need to know whenever a thread has acquired the loader mutex */
987 mono_loader_lock_track_ownership (TRUE);
989 event_requests = g_ptr_array_new ();
991 mono_coop_mutex_init (&debugger_thread_exited_mutex);
992 mono_coop_cond_init (&debugger_thread_exited_cond);
994 MonoProfilerHandle prof = mono_profiler_create (NULL);
995 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
996 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
997 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
998 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
999 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
1000 mono_profiler_set_thread_started_callback (prof, thread_startup);
1001 mono_profiler_set_thread_stopped_callback (prof, thread_end);
1002 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
1003 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
1004 mono_profiler_set_jit_done_callback (prof, jit_done);
1005 mono_profiler_set_jit_failed_callback (prof, jit_failed);
1006 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
1007 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
1009 mono_native_tls_alloc (&debugger_tls_id, NULL);
1011 /* Needed by the hash_table_new_type () call below */
1012 mono_gc_base_init ();
1014 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");
1016 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
1018 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");
1020 pending_assembly_loads = g_ptr_array_new ();
1022 log_level = agent_config.log_level;
1024 embedding = agent_config.embedding;
1025 disconnected = TRUE;
1027 if (agent_config.log_file) {
1028 log_file = fopen (agent_config.log_file, "w+");
1029 if (!log_file) {
1030 g_printerr ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1031 exit (1);
1033 } else {
1034 log_file = stdout;
1036 mono_de_set_log_level (log_level, log_file);
1038 ids_init ();
1039 objrefs_init ();
1040 suspend_init ();
1042 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1044 * This is needed because currently we don't handle liveness info.
1046 mini_get_debug_options ()->mdb_optimizations = TRUE;
1048 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1049 /* This is needed because we can't set local variables in registers yet */
1050 mono_disable_optimizations (MONO_OPT_LINEARS);
1051 #endif
1054 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1055 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1056 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1057 * workaround.
1059 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1061 #ifdef HAVE_SETPGID
1062 if (agent_config.setpgid)
1063 setpgid (0, 0);
1064 #endif
1066 if (!agent_config.onuncaught && !agent_config.onthrow)
1067 finish_agent_init (TRUE);
1071 * finish_agent_init:
1073 * Finish the initialization of the agent. This involves connecting the transport
1074 * and starting the agent thread. This is either done at startup, or
1075 * in response to some event like an unhandled exception.
1077 static void
1078 finish_agent_init (gboolean on_startup)
1080 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1081 return;
1083 if (agent_config.launch) {
1085 // FIXME: Generated address
1086 // FIXME: Races with transport_connect ()
1088 char *argv [ ] = {
1089 agent_config.launch,
1090 agent_config.transport,
1091 agent_config.address,
1092 NULL
1094 #ifdef G_OS_WIN32
1095 // Nothing. FIXME? g_spawn_async_with_pipes is easy enough to provide for Windows if needed.
1096 #elif !HAVE_G_SPAWN
1097 g_printerr ("g_spawn_async_with_pipes not supported on this platform\n");
1098 exit (1);
1099 #else
1100 int res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1101 if (!res) {
1102 g_printerr ("Failed to execute '%s'.\n", agent_config.launch);
1103 exit (1);
1105 #endif
1108 transport_connect (agent_config.address);
1110 if (!on_startup) {
1111 /* Do some which is usually done after sending the VMStart () event */
1112 vm_start_event_sent = TRUE;
1113 ERROR_DECL (error);
1114 start_debugger_thread (error);
1115 mono_error_assert_ok (error);
1119 static void
1120 mono_debugger_agent_cleanup (void)
1122 if (!inited)
1123 return;
1125 stop_debugger_thread ();
1127 event_requests_cleanup ();
1128 objrefs_cleanup ();
1129 ids_cleanup ();
1131 mono_de_cleanup ();
1133 if (file_check_valid_memory != -1) {
1134 remove (filename_check_valid_memory);
1135 g_free (filename_check_valid_memory);
1136 close (file_check_valid_memory);
1141 * SOCKET TRANSPORT
1144 #ifndef DISABLE_SOCKET_TRANSPORT
1147 * recv_length:
1149 * recv() + handle incomplete reads and EINTR
1151 static int
1152 socket_transport_recv (void *buf, int len)
1154 int res;
1155 int total = 0;
1156 int fd = conn_fd;
1157 int flags = 0;
1158 static gint64 last_keepalive;
1159 gint64 msecs;
1161 MONO_ENTER_GC_SAFE;
1163 do {
1164 again:
1165 res = recv (fd, (char *) buf + total, len - total, flags);
1166 if (res > 0)
1167 total += res;
1168 if (agent_config.keepalive) {
1169 gboolean need_keepalive = FALSE;
1170 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1171 need_keepalive = TRUE;
1172 } else if (res == -1) {
1173 /* This could happen if recv () is interrupted repeatedly */
1174 msecs = mono_msec_ticks ();
1175 if (msecs - last_keepalive >= agent_config.keepalive) {
1176 need_keepalive = TRUE;
1177 last_keepalive = msecs;
1180 if (need_keepalive) {
1181 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1182 goto again;
1185 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1187 MONO_EXIT_GC_SAFE;
1189 return total;
1192 static void
1193 set_keepalive (void)
1195 struct timeval tv;
1196 int result;
1198 if (!agent_config.keepalive || !conn_fd)
1199 return;
1201 tv.tv_sec = agent_config.keepalive / 1000;
1202 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1204 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1205 g_assert (result >= 0);
1208 static int
1209 socket_transport_accept (int socket_fd)
1211 MONO_ENTER_GC_SAFE;
1212 conn_fd = accept (socket_fd, NULL, NULL);
1213 MONO_EXIT_GC_SAFE;
1215 if (conn_fd == -1) {
1216 g_printerr ("debugger-agent: Unable to listen on %d\n", socket_fd);
1217 } else {
1218 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1221 return conn_fd;
1224 static gboolean
1225 socket_transport_send (void *data, int len)
1227 int res;
1229 MONO_ENTER_GC_SAFE;
1231 do {
1232 res = send (conn_fd, (const char*)data, len, 0);
1233 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1235 MONO_EXIT_GC_SAFE;
1237 if (res != len)
1238 return FALSE;
1239 else
1240 return TRUE;
1244 * socket_transport_connect:
1246 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1248 static void
1249 socket_transport_connect (const char *address)
1251 MonoAddressInfo *result;
1252 MonoAddressEntry *rp;
1253 int sfd = -1, s, res;
1254 char *host;
1255 int port;
1257 if (agent_config.address) {
1258 res = parse_address (agent_config.address, &host, &port);
1259 g_assert (res == 0);
1260 } else {
1261 host = NULL;
1262 port = 0;
1265 conn_fd = -1;
1266 listen_fd = -1;
1268 if (host) {
1269 int hints[] = {
1270 MONO_HINT_IPV4 | MONO_HINT_NUMERIC_HOST,
1271 MONO_HINT_IPV6 | MONO_HINT_NUMERIC_HOST,
1272 MONO_HINT_UNSPECIFIED
1275 mono_network_init ();
1277 for (int i = 0; i < sizeof(hints) / sizeof(int); i++) {
1278 /* Obtain address(es) matching host/port */
1279 s = mono_get_address_info (host, port, hints[i], &result);
1280 if (s == 0)
1281 break;
1283 if (s != 0) {
1284 g_printerr ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1285 exit (1);
1289 if (agent_config.server) {
1290 /* Wait for a connection */
1291 if (!host) {
1292 struct sockaddr_in addr;
1293 socklen_t addrlen;
1295 /* No address, generate one */
1296 sfd = socket (AF_INET, SOCK_STREAM, 0);
1297 if (sfd == -1) {
1298 g_printerr ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1299 exit (1);
1302 /* This will bind the socket to a random port */
1303 res = listen (sfd, 16);
1304 if (res == -1) {
1305 g_printerr ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1306 exit (1);
1308 listen_fd = sfd;
1310 addrlen = sizeof (addr);
1311 memset (&addr, 0, sizeof (addr));
1312 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1313 g_assert (res == 0);
1315 host = (char*)"127.0.0.1";
1316 port = ntohs (addr.sin_port);
1318 /* Emit the address to stdout */
1319 /* FIXME: Should print another interface, not localhost */
1320 printf ("%s:%d\n", host, port);
1321 } else {
1322 /* Listen on the provided address */
1323 for (rp = result->entries; rp != NULL; rp = rp->next) {
1324 MonoSocketAddress sockaddr;
1325 socklen_t sock_len;
1326 int n = 1;
1328 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1330 sfd = socket (rp->family, rp->socktype,
1331 rp->protocol);
1332 if (sfd == -1)
1333 continue;
1335 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1336 continue;
1338 res = bind (sfd, &sockaddr.addr, sock_len);
1339 if (res == -1)
1340 continue;
1342 res = listen (sfd, 16);
1343 if (res == -1)
1344 continue;
1345 listen_fd = sfd;
1346 break;
1349 mono_free_address_info (result);
1352 if (agent_config.defer)
1353 return;
1355 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1357 if (agent_config.timeout) {
1358 fd_set readfds;
1359 struct timeval tv;
1361 tv.tv_sec = 0;
1362 tv.tv_usec = agent_config.timeout * 1000;
1363 FD_ZERO (&readfds);
1364 FD_SET (sfd, &readfds);
1366 MONO_ENTER_GC_SAFE;
1367 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1368 MONO_EXIT_GC_SAFE;
1370 if (res == 0) {
1371 g_printerr ("debugger-agent: Timed out waiting to connect.\n");
1372 exit (1);
1376 conn_fd = socket_transport_accept (sfd);
1377 if (conn_fd == -1)
1378 exit (1);
1380 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1381 } else {
1382 /* Connect to the specified address */
1383 /* FIXME: Respect the timeout */
1384 for (rp = result->entries; rp != NULL; rp = rp->next) {
1385 MonoSocketAddress sockaddr;
1386 socklen_t sock_len;
1388 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1390 sfd = socket (rp->family, rp->socktype,
1391 rp->protocol);
1392 if (sfd == -1)
1393 continue;
1395 MONO_ENTER_GC_SAFE;
1396 res = connect (sfd, &sockaddr.addr, sock_len);
1397 MONO_EXIT_GC_SAFE;
1399 if (res != -1)
1400 break; /* Success */
1402 MONO_ENTER_GC_SAFE;
1403 #ifdef HOST_WIN32
1404 closesocket (sfd);
1405 #else
1406 close (sfd);
1407 #endif
1408 MONO_EXIT_GC_SAFE;
1411 if (rp == 0) {
1412 g_printerr ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1413 exit (1);
1416 conn_fd = sfd;
1418 mono_free_address_info (result);
1421 if (!transport_handshake ())
1422 exit (1);
1425 static void
1426 socket_transport_close1 (void)
1428 /* This will interrupt the agent thread */
1429 /* Close the read part only so it can still send back replies */
1430 /* Also shut down the connection listener so that we can exit normally */
1431 #ifdef HOST_WIN32
1432 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1433 shutdown (conn_fd, SD_BOTH);
1434 shutdown (listen_fd, SD_BOTH);
1435 closesocket (listen_fd);
1436 #else
1437 shutdown (conn_fd, SHUT_RD);
1438 shutdown (listen_fd, SHUT_RDWR);
1439 MONO_ENTER_GC_SAFE;
1440 close (listen_fd);
1441 MONO_EXIT_GC_SAFE;
1442 #endif
1445 static void
1446 socket_transport_close2 (void)
1448 #ifdef HOST_WIN32
1449 shutdown (conn_fd, SD_BOTH);
1450 #else
1451 shutdown (conn_fd, SHUT_RDWR);
1452 #endif
1455 static void
1456 register_socket_transport (void)
1458 DebuggerTransport trans;
1460 trans.name = "dt_socket";
1461 trans.connect = socket_transport_connect;
1462 trans.close1 = socket_transport_close1;
1463 trans.close2 = socket_transport_close2;
1464 trans.send = socket_transport_send;
1465 trans.recv = socket_transport_recv;
1467 register_transport (&trans);
1471 * socket_fd_transport_connect:
1474 static void
1475 socket_fd_transport_connect (const char *address)
1477 int res;
1479 res = sscanf (address, "%d", &conn_fd);
1480 if (res != 1) {
1481 g_printerr ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1482 exit (1);
1485 if (!transport_handshake ())
1486 exit (1);
1489 static void
1490 register_socket_fd_transport (void)
1492 DebuggerTransport trans;
1494 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1495 trans.name = "socket-fd";
1496 trans.connect = socket_fd_transport_connect;
1497 trans.close1 = socket_transport_close1;
1498 trans.close2 = socket_transport_close2;
1499 trans.send = socket_transport_send;
1500 trans.recv = socket_transport_recv;
1502 register_transport (&trans);
1505 #endif /* DISABLE_SOCKET_TRANSPORT */
1508 * TRANSPORT CODE
1511 #define MAX_TRANSPORTS 16
1513 static DebuggerTransport *transport;
1515 static DebuggerTransport transports [MAX_TRANSPORTS];
1516 static int ntransports;
1518 MONO_API void
1519 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1521 void
1522 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1524 register_transport (trans);
1527 static void
1528 register_transport (DebuggerTransport *trans)
1530 g_assert (ntransports < MAX_TRANSPORTS);
1532 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1533 ntransports ++;
1536 static void
1537 transport_init (void)
1539 int i;
1541 #ifndef DISABLE_SOCKET_TRANSPORT
1542 register_socket_transport ();
1543 register_socket_fd_transport ();
1544 #endif
1546 for (i = 0; i < ntransports; ++i) {
1547 if (!strcmp (agent_config.transport, transports [i].name))
1548 break;
1550 if (i == ntransports) {
1551 g_printerr ("debugger-agent: The supported values for the 'transport' option are: ");
1552 for (i = 0; i < ntransports; ++i)
1553 g_printerr ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1554 g_printerr ("\n");
1555 exit (1);
1557 transport = &transports [i];
1560 void
1561 transport_connect (const char *address)
1563 transport->connect (address);
1566 static void
1567 transport_close1 (void)
1569 transport->close1 ();
1572 static void
1573 transport_close2 (void)
1575 transport->close2 ();
1578 static int
1579 transport_send (void *buf, int len)
1581 return transport->send (buf, len);
1584 static int
1585 transport_recv (void *buf, int len)
1587 return transport->recv (buf, len);
1590 gboolean
1591 mono_debugger_agent_transport_handshake (void)
1593 return transport_handshake ();
1596 static gboolean
1597 transport_handshake (void)
1599 char handshake_msg [128];
1600 guint8 buf [128];
1601 int res;
1603 disconnected = TRUE;
1605 /* Write handshake message */
1606 sprintf (handshake_msg, "DWP-Handshake");
1608 do {
1609 res = transport_send (handshake_msg, strlen (handshake_msg));
1610 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1612 g_assert (res != -1);
1614 /* Read answer */
1615 res = transport_recv (buf, strlen (handshake_msg));
1616 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1617 g_printerr ("debugger-agent: DWP handshake failed.\n");
1618 return FALSE;
1622 * To support older clients, the client sends its protocol version after connecting
1623 * using a command. Until that is received, default to our protocol version.
1625 major_version = MAJOR_VERSION;
1626 minor_version = MINOR_VERSION;
1627 protocol_version_set = FALSE;
1629 #ifndef DISABLE_SOCKET_TRANSPORT
1630 // FIXME: Move this somewhere else
1632 * Set TCP_NODELAY on the socket so the client receives events/command
1633 * results immediately.
1635 if (conn_fd) {
1636 int flag = 1;
1637 int result = setsockopt (conn_fd,
1638 IPPROTO_TCP,
1639 TCP_NODELAY,
1640 (char *) &flag,
1641 sizeof(int));
1642 g_assert (result >= 0);
1645 set_keepalive ();
1646 #endif
1648 disconnected = FALSE;
1649 return TRUE;
1652 static void
1653 stop_debugger_thread (void)
1655 if (!inited)
1656 return;
1658 transport_close1 ();
1661 * Wait for the thread to exit.
1663 * If we continue with the shutdown without waiting for it, then the client might
1664 * not receive an answer to its last command like a resume.
1666 if (!is_debugger_thread ()) {
1667 do {
1668 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1669 if (!debugger_thread_exited)
1670 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1671 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1672 } while (!debugger_thread_exited);
1674 if (debugger_thread_handle)
1675 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1678 transport_close2 ();
1681 static void
1682 start_debugger_thread (MonoError *error)
1684 MonoInternalThread *thread;
1686 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1687 return_if_nok (error);
1689 /* Is it possible for the thread to be dead alreay ? */
1690 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1691 g_assert (debugger_thread_handle);
1696 * Functions to decode protocol data
1699 static int
1700 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1702 *endbuf = buf + 1;
1703 g_assert (*endbuf <= limit);
1704 return buf [0];
1707 static int
1708 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1710 *endbuf = buf + 4;
1711 g_assert (*endbuf <= limit);
1713 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1716 static gint64
1717 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1719 guint32 high = decode_int (buf, &buf, limit);
1720 guint32 low = decode_int (buf, &buf, limit);
1722 *endbuf = buf;
1724 return ((((guint64)high) << 32) | ((guint64)low));
1727 static int
1728 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1730 return decode_int (buf, endbuf, limit);
1733 static char*
1734 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1736 int len = decode_int (buf, &buf, limit);
1737 char *s;
1739 if (len < 0) {
1740 *endbuf = buf;
1741 return NULL;
1744 s = (char *)g_malloc (len + 1);
1745 g_assert (s);
1747 memcpy (s, buf, len);
1748 s [len] = '\0';
1749 buf += len;
1750 *endbuf = buf;
1752 return s;
1756 * Functions to encode protocol data
1759 static void
1760 buffer_init (Buffer *buf, int size)
1762 buf->buf = (guint8 *)g_malloc (size);
1763 buf->p = buf->buf;
1764 buf->end = buf->buf + size;
1767 static int
1768 buffer_len (Buffer *buf)
1770 return buf->p - buf->buf;
1773 static void
1774 buffer_make_room (Buffer *buf, int size)
1776 if (buf->end - buf->p < size) {
1777 int new_size = buf->end - buf->buf + size + 32;
1778 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1779 size = buf->p - buf->buf;
1780 buf->buf = p;
1781 buf->p = p + size;
1782 buf->end = buf->buf + new_size;
1786 static void
1787 buffer_add_byte (Buffer *buf, guint8 val)
1789 buffer_make_room (buf, 1);
1790 buf->p [0] = val;
1791 buf->p++;
1794 static void
1795 buffer_add_short (Buffer *buf, guint32 val)
1797 buffer_make_room (buf, 2);
1798 buf->p [0] = (val >> 8) & 0xff;
1799 buf->p [1] = (val >> 0) & 0xff;
1800 buf->p += 2;
1803 static void
1804 buffer_add_int (Buffer *buf, guint32 val)
1806 buffer_make_room (buf, 4);
1807 buf->p [0] = (val >> 24) & 0xff;
1808 buf->p [1] = (val >> 16) & 0xff;
1809 buf->p [2] = (val >> 8) & 0xff;
1810 buf->p [3] = (val >> 0) & 0xff;
1811 buf->p += 4;
1814 static void
1815 buffer_add_long (Buffer *buf, guint64 l)
1817 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1818 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1821 static void
1822 buffer_add_id (Buffer *buf, int id)
1824 buffer_add_int (buf, (guint64)id);
1827 static void
1828 buffer_add_data (Buffer *buf, guint8 *data, int len)
1830 buffer_make_room (buf, len);
1831 memcpy (buf->p, data, len);
1832 buf->p += len;
1835 static void
1836 buffer_add_string (Buffer *buf, const char *str)
1838 int len;
1840 if (str == NULL) {
1841 buffer_add_int (buf, 0);
1842 } else {
1843 len = strlen (str);
1844 buffer_add_int (buf, len);
1845 buffer_add_data (buf, (guint8*)str, len);
1849 static void
1850 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1852 buffer_add_int (buf, arr_len);
1853 buffer_add_data (buf, bytes, arr_len);
1856 static void
1857 buffer_add_buffer (Buffer *buf, Buffer *data)
1859 buffer_add_data (buf, data->buf, buffer_len (data));
1862 static void
1863 buffer_free (Buffer *buf)
1865 g_free (buf->buf);
1868 static gboolean
1869 send_packet (int command_set, int command, Buffer *data)
1871 Buffer buf;
1872 int len, id;
1873 gboolean res;
1875 id = mono_atomic_inc_i32 (&packet_id);
1877 len = data->p - data->buf + 11;
1878 buffer_init (&buf, len);
1879 buffer_add_int (&buf, len);
1880 buffer_add_int (&buf, id);
1881 buffer_add_byte (&buf, 0); /* flags */
1882 buffer_add_byte (&buf, command_set);
1883 buffer_add_byte (&buf, command);
1884 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1886 res = transport_send (buf.buf, len);
1888 buffer_free (&buf);
1890 return res;
1893 static gboolean
1894 send_reply_packets (int npackets, ReplyPacket *packets)
1896 Buffer buf;
1897 int i, len;
1898 gboolean res;
1900 len = 0;
1901 for (i = 0; i < npackets; ++i)
1902 len += buffer_len (packets [i].data) + 11;
1903 buffer_init (&buf, len);
1904 for (i = 0; i < npackets; ++i) {
1905 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1906 buffer_add_int (&buf, packets [i].id);
1907 buffer_add_byte (&buf, 0x80); /* flags */
1908 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1909 buffer_add_byte (&buf, packets [i].error);
1910 buffer_add_buffer (&buf, packets [i].data);
1913 res = transport_send (buf.buf, len);
1915 buffer_free (&buf);
1917 return res;
1920 static gboolean
1921 send_reply_packet (int id, int error, Buffer *data)
1923 ReplyPacket packet;
1925 memset (&packet, 0, sizeof (packet));
1926 packet.id = id;
1927 packet.error = error;
1928 packet.data = data;
1930 return send_reply_packets (1, &packet);
1933 static void
1934 send_buffered_reply_packets (void)
1936 int i;
1938 send_reply_packets (nreply_packets, reply_packets);
1939 for (i = 0; i < nreply_packets; ++i)
1940 buffer_free (reply_packets [i].data);
1941 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1942 nreply_packets = 0;
1945 static void
1946 buffer_reply_packet (int id, int error, Buffer *data)
1948 ReplyPacket *p;
1950 if (nreply_packets == 128)
1951 send_buffered_reply_packets ();
1953 p = &reply_packets [nreply_packets];
1954 p->id = id;
1955 p->error = error;
1956 p->data = g_new0 (Buffer, 1);
1957 buffer_init (p->data, buffer_len (data));
1958 buffer_add_buffer (p->data, data);
1959 nreply_packets ++;
1963 /* Maps objid -> ObjRef */
1964 /* Protected by the loader lock */
1965 static GHashTable *objrefs;
1966 /* Protected by the loader lock */
1967 static GHashTable *obj_to_objref;
1968 /* Protected by the dbg lock */
1969 static MonoGHashTable *suspended_objs;
1973 static void
1974 objrefs_init (void)
1976 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1977 obj_to_objref = g_hash_table_new (NULL, NULL);
1978 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");
1981 static void
1982 objrefs_cleanup (void)
1984 g_hash_table_destroy (objrefs);
1985 objrefs = NULL;
1989 * Return an ObjRef for OBJ.
1991 static ObjRef*
1992 get_objref (MonoObject *obj)
1994 ObjRef *ref;
1995 GSList *reflist = NULL, *l;
1996 int hash = 0;
1998 if (obj == NULL)
1999 return NULL;
2001 if (suspend_count) {
2003 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
2005 dbg_lock ();
2006 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
2007 dbg_unlock ();
2010 mono_loader_lock ();
2012 /* FIXME: The tables can grow indefinitely */
2014 if (mono_gc_is_moving ()) {
2016 * Objects can move, so use a hash table mapping hash codes to lists of
2017 * ObjRef structures.
2019 hash = mono_object_hash_internal (obj);
2021 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2022 for (l = reflist; l; l = l->next) {
2023 ref = (ObjRef *)l->data;
2024 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2025 mono_loader_unlock ();
2026 return ref;
2029 } else {
2030 /* Use a hash table with masked pointers to internalize object references */
2031 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2032 /* ref might refer to a different object with the same addr which was GCd */
2033 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2034 mono_loader_unlock ();
2035 return ref;
2039 ref = g_new0 (ObjRef, 1);
2040 ref->id = mono_atomic_inc_i32 (&objref_id);
2041 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2043 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2045 if (mono_gc_is_moving ()) {
2046 reflist = g_slist_append (reflist, ref);
2047 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2048 } else {
2049 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2052 mono_loader_unlock ();
2054 return ref;
2057 static gboolean
2058 true_pred (gpointer key, gpointer value, gpointer user_data)
2060 return TRUE;
2063 static void
2064 clear_suspended_objs (void)
2066 dbg_lock ();
2067 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2068 dbg_unlock ();
2071 static int
2072 get_objid (MonoObject *obj)
2074 if (!obj)
2075 return 0;
2076 else
2077 return get_objref (obj)->id;
2081 * Set OBJ to the object identified by OBJID.
2082 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2083 * collected.
2085 static ErrorCode
2086 get_object_allow_null (int objid, MonoObject **obj)
2088 ObjRef *ref;
2090 if (objid == 0) {
2091 *obj = NULL;
2092 return ERR_NONE;
2095 if (!objrefs)
2096 return ERR_INVALID_OBJECT;
2098 mono_loader_lock ();
2100 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2102 if (ref) {
2103 *obj = mono_gchandle_get_target_internal (ref->handle);
2104 mono_loader_unlock ();
2105 if (!(*obj))
2106 return ERR_INVALID_OBJECT;
2107 return ERR_NONE;
2108 } else {
2109 mono_loader_unlock ();
2110 return ERR_INVALID_OBJECT;
2114 static ErrorCode
2115 get_object (int objid, MonoObject **obj)
2117 ErrorCode err = get_object_allow_null (objid, obj);
2119 if (err != ERR_NONE)
2120 return err;
2121 if (!(*obj))
2122 return ERR_INVALID_OBJECT;
2123 return ERR_NONE;
2126 static int
2127 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2129 return decode_id (buf, endbuf, limit);
2132 static void
2133 buffer_add_objid (Buffer *buf, MonoObject *o)
2135 buffer_add_id (buf, get_objid (o));
2139 * IDS
2142 typedef enum {
2143 ID_ASSEMBLY = 0,
2144 ID_MODULE = 1,
2145 ID_TYPE = 2,
2146 ID_METHOD = 3,
2147 ID_FIELD = 4,
2148 ID_DOMAIN = 5,
2149 ID_PROPERTY = 6,
2150 ID_NUM
2151 } IdType;
2154 * Represents a runtime structure accessible to the debugger client
2156 typedef struct {
2157 /* Unique id used in the wire protocol */
2158 int id;
2159 /* Domain of the runtime structure, NULL if the domain was unloaded */
2160 MonoDomain *domain;
2161 union {
2162 gpointer val;
2163 MonoClass *klass;
2164 MonoMethod *method;
2165 MonoImage *image;
2166 MonoAssembly *assembly;
2167 MonoClassField *field;
2168 MonoDomain *domain;
2169 MonoProperty *property;
2170 } data;
2171 } Id;
2173 typedef struct {
2174 /* Maps runtime structure -> Id */
2175 /* Protected by the dbg lock */
2176 GHashTable *val_to_id [ID_NUM];
2177 /* Classes whose class load event has been sent */
2178 /* Protected by the loader lock */
2179 GHashTable *loaded_classes;
2180 /* Maps MonoClass->GPtrArray of file names */
2181 GHashTable *source_files;
2182 /* Maps source file basename -> GSList of classes */
2183 GHashTable *source_file_to_class;
2184 /* Same with ignore-case */
2185 GHashTable *source_file_to_class_ignorecase;
2186 } AgentDomainInfo;
2188 /* Maps id -> Id */
2189 /* Protected by the dbg lock */
2190 static GPtrArray *ids [ID_NUM];
2192 static void
2193 ids_init (void)
2195 int i;
2197 for (i = 0; i < ID_NUM; ++i)
2198 ids [i] = g_ptr_array_new ();
2201 static void
2202 ids_cleanup (void)
2204 int i, j;
2206 for (i = 0; i < ID_NUM; ++i) {
2207 if (ids [i]) {
2208 for (j = 0; j < ids [i]->len; ++j)
2209 g_free (g_ptr_array_index (ids [i], j));
2210 g_ptr_array_free (ids [i], TRUE);
2212 ids [i] = NULL;
2216 static void
2217 debugger_agent_free_domain_info (MonoDomain *domain)
2219 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2220 int i, j;
2221 GHashTableIter iter;
2222 GPtrArray *file_names;
2223 char *basename;
2224 GSList *l;
2226 if (info) {
2227 for (i = 0; i < ID_NUM; ++i)
2228 g_hash_table_destroy (info->val_to_id [i]);
2229 g_hash_table_destroy (info->loaded_classes);
2231 g_hash_table_iter_init (&iter, info->source_files);
2232 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2233 for (i = 0; i < file_names->len; ++i)
2234 g_free (g_ptr_array_index (file_names, i));
2235 g_ptr_array_free (file_names, TRUE);
2238 g_hash_table_iter_init (&iter, info->source_file_to_class);
2239 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2240 g_free (basename);
2241 g_slist_free (l);
2244 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2245 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2246 g_free (basename);
2247 g_slist_free (l);
2250 g_free (info);
2253 domain_jit_info (domain)->agent_info = NULL;
2255 /* Clear ids referencing structures in the domain */
2256 dbg_lock ();
2257 for (i = 0; i < ID_NUM; ++i) {
2258 if (ids [i]) {
2259 for (j = 0; j < ids [i]->len; ++j) {
2260 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2261 if (id->domain == domain)
2262 id->domain = NULL;
2266 dbg_unlock ();
2268 mono_de_domain_remove (domain);
2271 static AgentDomainInfo*
2272 get_agent_domain_info (MonoDomain *domain)
2274 AgentDomainInfo *info = NULL;
2275 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2277 info = (AgentDomainInfo *)jit_info->agent_info;
2279 if (info) {
2280 mono_memory_read_barrier ();
2281 return info;
2284 info = g_new0 (AgentDomainInfo, 1);
2285 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2286 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2287 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2288 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2290 mono_memory_write_barrier ();
2292 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2294 if (other_info != NULL) {
2295 g_hash_table_destroy (info->loaded_classes);
2296 g_hash_table_destroy (info->source_files);
2297 g_hash_table_destroy (info->source_file_to_class);
2298 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2299 g_free (info);
2302 return (AgentDomainInfo *)jit_info->agent_info;
2305 static int
2306 get_id (MonoDomain *domain, IdType type, gpointer val)
2308 Id *id;
2309 AgentDomainInfo *info;
2311 if (val == NULL)
2312 return 0;
2314 info = get_agent_domain_info (domain);
2316 dbg_lock ();
2318 if (info->val_to_id [type] == NULL)
2319 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2321 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2322 if (id) {
2323 dbg_unlock ();
2324 return id->id;
2327 id = g_new0 (Id, 1);
2328 /* Reserve id 0 */
2329 id->id = ids [type]->len + 1;
2330 id->domain = domain;
2331 id->data.val = val;
2333 g_hash_table_insert (info->val_to_id [type], val, id);
2334 g_ptr_array_add (ids [type], id);
2336 dbg_unlock ();
2338 return id->id;
2341 static gpointer
2342 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2344 Id *res;
2346 int id = decode_id (buf, endbuf, limit);
2348 *err = ERR_NONE;
2349 if (domain)
2350 *domain = NULL;
2352 if (id == 0)
2353 return NULL;
2355 // FIXME: error handling
2356 dbg_lock ();
2357 g_assert (id > 0 && id <= ids [type]->len);
2359 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2360 dbg_unlock ();
2362 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2363 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2364 *err = ERR_UNLOADED;
2365 return NULL;
2368 if (domain)
2369 *domain = res->domain;
2371 return res->data.val;
2374 static int
2375 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2377 int id = get_id (domain, type, val);
2379 buffer_add_id (buf, id);
2380 return id;
2383 static MonoClass*
2384 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2386 MonoClass *klass;
2388 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2389 if (G_UNLIKELY (log_level >= 2) && klass) {
2390 char *s;
2392 s = mono_type_full_name (m_class_get_byval_arg (klass));
2393 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2394 g_free (s);
2396 return klass;
2399 static MonoAssembly*
2400 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2402 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2405 static MonoImage*
2406 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2408 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2411 static MonoMethod*
2412 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2414 MonoMethod *m;
2416 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2417 if (G_UNLIKELY (log_level >= 2) && m) {
2418 char *s;
2420 s = mono_method_full_name (m, TRUE);
2421 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2422 g_free (s);
2424 return m;
2427 static MonoClassField*
2428 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2430 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2433 static MonoDomain*
2434 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2436 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2439 static MonoProperty*
2440 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2442 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2445 static void
2446 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2448 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2449 if (G_UNLIKELY (log_level >= 2) && klass) {
2450 char *s;
2452 s = mono_type_full_name (m_class_get_byval_arg (klass));
2453 if (is_debugger_thread ())
2454 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2455 else
2456 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2457 g_free (s);
2461 static void
2462 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2464 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2465 if (G_UNLIKELY (log_level >= 2) && method) {
2466 char *s;
2468 s = mono_method_full_name (method, 1);
2469 if (is_debugger_thread ())
2470 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2471 else
2472 DEBUG_PRINTF (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2473 g_free (s);
2477 static void
2478 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2480 int id;
2482 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2483 if (G_UNLIKELY (log_level >= 2) && assembly)
2484 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2487 static void
2488 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2490 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2493 static void
2494 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2496 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2499 static void
2500 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2502 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2505 static void
2506 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2508 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2511 static void invoke_method (void);
2514 * SUSPEND/RESUME
2517 static MonoJitInfo*
2518 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2520 MonoJitInfo *ji;
2522 if (out_ip)
2523 *out_ip = ip;
2525 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2526 if (!ji) {
2527 /* Could be an interpreter method */
2529 MonoLMF *lmf = mono_get_lmf ();
2530 MonoInterpFrameHandle *frame;
2532 g_assert (((gsize)lmf->previous_lmf) & 2);
2533 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2535 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2536 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2537 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2538 if (domain)
2539 *domain = mono_domain_get ();
2540 if (out_ip)
2541 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2543 return ji;
2547 * save_thread_context:
2549 * Set CTX as the current threads context which is used for computing stack traces.
2550 * This function is signal-safe.
2552 static void
2553 save_thread_context (MonoContext *ctx)
2555 DebuggerTlsData *tls;
2557 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2558 g_assert (tls);
2560 if (ctx)
2561 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2562 else
2563 mono_thread_state_init_from_current (&tls->context);
2566 static MonoCoopMutex suspend_mutex;
2568 /* Cond variable used to wait for suspend_count becoming 0 */
2569 static MonoCoopCond suspend_cond;
2571 /* Semaphore used to wait for a thread becoming suspended */
2572 static MonoCoopSem suspend_sem;
2574 static void
2575 suspend_init (void)
2577 mono_coop_mutex_init (&suspend_mutex);
2578 mono_coop_cond_init (&suspend_cond);
2579 mono_coop_sem_init (&suspend_sem, 0);
2582 typedef struct
2584 StackFrameInfo last_frame;
2585 gboolean last_frame_set;
2586 MonoContext ctx;
2587 gpointer lmf;
2588 MonoDomain *domain;
2589 } GetLastFrameUserData;
2591 static gboolean
2592 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2594 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2596 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2597 return FALSE;
2599 if (!data->last_frame_set) {
2600 /* Store the last frame */
2601 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2602 data->last_frame_set = TRUE;
2603 return FALSE;
2604 } else {
2605 /* Store the context/lmf for the frame above the last frame */
2606 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2607 data->lmf = info->lmf;
2608 data->domain = info->domain;
2609 return TRUE;
2613 static void
2614 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2616 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2618 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2619 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2620 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2621 to->valid = TRUE;
2625 * thread_interrupt:
2627 * Process interruption of a thread. This should be signal safe.
2629 * This always runs in the debugger thread.
2631 static void
2632 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2634 gpointer ip;
2635 MonoNativeThreadId tid;
2637 g_assert (info);
2639 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2640 tid = mono_thread_info_get_tid (info);
2642 // FIXME: Races when the thread leaves managed code before hitting a single step
2643 // event.
2645 if (ji && !ji->is_trampoline) {
2646 /* Running managed code, will be suspended by the single step code */
2647 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2648 } else {
2650 * Running native code, will be suspended when it returns to/enters
2651 * managed code. Treat it as already suspended.
2652 * This might interrupt the code in mono_de_process_single_step (), we use the
2653 * tls->suspending flag to avoid races when that happens.
2655 if (!tls->suspended && !tls->suspending) {
2656 GetLastFrameUserData data;
2658 // FIXME: printf is not signal safe, but this is only used during
2659 // debugger debugging
2660 if (ip)
2661 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2662 //save_thread_context (&ctx);
2664 if (!tls->thread)
2665 /* Already terminated */
2666 return;
2669 * We are in a difficult position: we want to be able to provide stack
2670 * traces for this thread, but we can't use the current ctx+lmf, since
2671 * the thread is still running, so it might return to managed code,
2672 * making these invalid.
2673 * So we start a stack walk and save the first frame, along with the
2674 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2675 * suspended when it returns to managed code, so the parent's ctx should
2676 * remain valid.
2678 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2680 data.last_frame_set = FALSE;
2681 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2682 if (data.last_frame_set) {
2683 gpointer jit_tls = tls->thread->thread_info->jit_data;
2685 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2687 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2689 * Store the current lmf instead of the parent one, since that
2690 * contains the interp exit data.
2692 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2695 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2696 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2697 } else {
2698 tls->async_state.valid = FALSE;
2701 mono_memory_barrier ();
2703 tls->suspended = TRUE;
2704 mono_coop_sem_post (&suspend_sem);
2710 * reset_native_thread_suspend_state:
2712 * Reset the suspended flag and state on native threads
2714 static void
2715 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2717 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2719 if (!tls->really_suspended && tls->suspended) {
2720 tls->suspended = FALSE;
2722 * The thread might still be running if it was executing native code, so the state won't be invalided by
2723 * suspend_current ().
2725 tls->context.valid = FALSE;
2726 tls->async_state.valid = FALSE;
2727 invalidate_frames (tls);
2729 tls->resume_count_internal++;
2733 typedef struct {
2734 DebuggerTlsData *tls;
2735 gboolean valid_info;
2736 } InterruptData;
2738 static SuspendThreadResult
2739 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2741 InterruptData *data = (InterruptData *)user_data;
2742 MonoJitInfo *ji;
2744 data->valid_info = TRUE;
2745 MonoDomain *domain = (MonoDomain *) mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN];
2746 if (!domain) {
2747 /* not attached */
2748 ji = NULL;
2749 } else {
2750 ji = mono_jit_info_table_find_internal ( domain, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx), TRUE, TRUE);
2753 /* This is signal safe */
2754 thread_interrupt (data->tls, info, ji);
2755 return MonoResumeThread;
2759 * notify_thread:
2761 * Notify a thread that it needs to suspend.
2763 static void
2764 notify_thread (gpointer key, gpointer value, gpointer user_data)
2766 MonoInternalThread *thread = (MonoInternalThread *)key;
2767 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2768 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2770 if (mono_thread_internal_is_current (thread) || tls->terminated)
2771 return;
2773 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)(gsize)tid);
2775 /* This is _not_ equivalent to mono_thread_internal_abort () */
2776 InterruptData interrupt_data = { 0 };
2777 interrupt_data.tls = tls;
2779 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2780 if (!interrupt_data.valid_info) {
2781 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2783 * Attached thread which died without detaching.
2785 tls->terminated = TRUE;
2789 static void
2790 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2792 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2793 MonoJitInfo *ji;
2794 MonoMethod *method;
2796 if (mono_loader_lock_is_owned_by_self ()) {
2798 * Shortcut for the check in suspend_current (). This speeds up processing
2799 * when executing long running code inside the loader lock, i.e. assembly load
2800 * hooks.
2802 return;
2805 if (is_debugger_thread ())
2806 return;
2808 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2809 if (suspend_count - tls->resume_count > 0)
2810 tls->suspending = TRUE;
2812 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2814 if (suspend_count - tls->resume_count == 0) {
2816 * We are executing a single threaded invoke but the single step for
2817 * suspending is still active.
2818 * FIXME: This slows down single threaded invokes.
2820 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2821 return;
2824 ji = get_top_method_ji (ip, NULL, NULL);
2825 g_assert (ji);
2826 /* Can't suspend in these methods */
2827 method = jinfo_get_method (ji);
2828 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2829 return;
2831 save_thread_context (ctx);
2833 suspend_current ();
2837 /* Conditionally call process_suspend depending oh the current state */
2838 static gboolean
2839 try_process_suspend (void *the_tls, MonoContext *ctx, gboolean from_breakpoint)
2841 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2842 /* if there is a suspend pending that is not executed yes */
2843 if (suspend_count > 0) {
2844 /* Fastpath during invokes, see in process_suspend () */
2845 /* if there is a suspend pending but this thread is already resumed, we shouldn't suspend it again and the breakpoint/ss can run */
2846 if (suspend_count - tls->resume_count == 0)
2847 return FALSE;
2848 /* if there is in a invoke the breakpoint/step should be executed even with the suspend pending */
2849 if (tls->invoke)
2850 return FALSE;
2851 /* with the multithreaded single step check if there is a suspend_count pending in the current thread and not in the vm */
2852 if (from_breakpoint && tls->suspend_count <= tls->resume_count_internal)
2853 return FALSE;
2854 process_suspend (tls, ctx);
2855 return TRUE;
2856 } /* if there isn't any suspend pending, the breakpoint/ss will be executed and will suspend then vm when the event is sent */
2857 return FALSE;
2861 * suspend_vm:
2863 * Increase the suspend count of the VM. While the suspend count is greater
2864 * than 0, runtime threads are suspended at certain points during execution.
2866 static void
2867 suspend_vm (void)
2869 gboolean tp_suspend = FALSE;
2870 mono_loader_lock ();
2872 mono_coop_mutex_lock (&suspend_mutex);
2874 suspend_count ++;
2876 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2878 if (suspend_count == 1) {
2879 // FIXME: Is it safe to call this inside the lock ?
2880 mono_de_start_single_stepping ();
2881 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2884 mono_coop_mutex_unlock (&suspend_mutex);
2886 if (suspend_count == 1)
2888 * Suspend creation of new threadpool threads, since they cannot run
2890 tp_suspend = TRUE;
2891 mono_loader_unlock ();
2893 #ifndef ENABLE_NETCORE
2894 if (tp_suspend)
2895 mono_threadpool_suspend ();
2896 #endif
2900 * resume_vm:
2902 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2903 * are resumed.
2905 static void
2906 resume_vm (void)
2908 g_assert (is_debugger_thread ());
2909 gboolean tp_resume = FALSE;
2911 mono_loader_lock ();
2913 mono_coop_mutex_lock (&suspend_mutex);
2915 g_assert (suspend_count > 0);
2916 suspend_count --;
2918 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2920 if (suspend_count == 0) {
2921 // FIXME: Is it safe to call this inside the lock ?
2922 mono_de_stop_single_stepping ();
2923 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2926 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2927 mono_coop_cond_broadcast (&suspend_cond);
2929 mono_coop_mutex_unlock (&suspend_mutex);
2930 //g_assert (err == 0);
2932 if (suspend_count == 0)
2933 tp_resume = TRUE;
2934 mono_loader_unlock ();
2936 #ifndef ENABLE_NETCORE
2937 if (tp_resume)
2938 mono_threadpool_resume ();
2939 #endif
2943 * resume_thread:
2945 * Resume just one thread.
2947 static void
2948 resume_thread (MonoInternalThread *thread)
2950 DebuggerTlsData *tls;
2952 g_assert (is_debugger_thread ());
2954 mono_loader_lock ();
2956 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2957 g_assert (tls);
2959 mono_coop_mutex_lock (&suspend_mutex);
2961 g_assert (suspend_count > 0);
2963 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2965 tls->resume_count += suspend_count;
2966 tls->resume_count_internal += tls->suspend_count;
2967 tls->suspend_count = 0;
2970 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2971 * but only the one whose resume_count field is > 0 will be resumed.
2973 mono_coop_cond_broadcast (&suspend_cond);
2975 mono_coop_mutex_unlock (&suspend_mutex);
2976 //g_assert (err == 0);
2978 mono_loader_unlock ();
2981 static void
2982 free_frames (StackFrame **frames, int nframes)
2984 int i;
2986 for (i = 0; i < nframes; ++i) {
2987 if (frames [i]->jit)
2988 mono_debug_free_method_jit_info (frames [i]->jit);
2989 g_free (frames [i]);
2991 g_free (frames);
2994 static void
2995 invalidate_frames (DebuggerTlsData *tls)
2997 mono_loader_lock ();
2999 if (!tls)
3000 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3001 g_assert (tls);
3003 free_frames (tls->frames, tls->frame_count);
3004 tls->frame_count = 0;
3005 tls->frames = NULL;
3007 free_frames (tls->restore_frames, tls->restore_frame_count);
3008 tls->restore_frame_count = 0;
3009 tls->restore_frames = NULL;
3011 mono_loader_unlock ();
3015 * suspend_current:
3017 * Suspend the current thread until the runtime is resumed. If the thread has a
3018 * pending invoke, then the invoke is executed before this function returns.
3020 static void
3021 suspend_current (void)
3023 DebuggerTlsData *tls;
3025 g_assert (!is_debugger_thread ());
3027 if (mono_loader_lock_is_owned_by_self ()) {
3029 * If we own the loader mutex, can't suspend until we release it, since the
3030 * whole runtime can deadlock otherwise.
3032 return;
3035 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3036 g_assert (tls);
3038 gboolean do_resume = FALSE;
3039 while (!do_resume) {
3040 mono_coop_mutex_lock (&suspend_mutex);
3042 tls->suspending = FALSE;
3043 tls->really_suspended = TRUE;
3045 if (!tls->suspended) {
3046 tls->suspended = TRUE;
3047 mono_coop_sem_post (&suspend_sem);
3050 mono_debugger_log_suspend (tls);
3051 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3053 while (suspend_count - tls->resume_count > 0) {
3054 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
3057 tls->suspended = FALSE;
3058 tls->really_suspended = FALSE;
3060 mono_coop_mutex_unlock (&suspend_mutex);
3062 mono_debugger_log_resume (tls);
3063 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3065 if (tls->pending_invoke) {
3066 /* Save the original context */
3067 tls->pending_invoke->has_ctx = TRUE;
3068 tls->pending_invoke->ctx = tls->context.ctx;
3070 invoke_method ();
3072 /* Have to suspend again */
3073 } else {
3074 do_resume = TRUE;
3078 /* The frame info becomes invalid after a resume */
3079 tls->context.valid = FALSE;
3080 tls->async_state.valid = FALSE;
3081 invalidate_frames (tls);
3082 mono_stopwatch_start (&tls->step_time);
3085 static void
3086 count_thread (gpointer key, gpointer value, gpointer user_data)
3088 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3090 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3091 *(int*)user_data = *(int*)user_data + 1;
3094 static int
3095 count_threads_to_wait_for (void)
3097 int count = 0;
3099 mono_loader_lock ();
3100 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3101 mono_loader_unlock ();
3103 return count;
3107 * wait_for_suspend:
3109 * Wait until the runtime is completely suspended.
3111 static void
3112 wait_for_suspend (void)
3114 int nthreads, nwait, err;
3115 gboolean waited = FALSE;
3117 // FIXME: Threads starting/stopping ?
3118 mono_loader_lock ();
3119 nthreads = mono_g_hash_table_size (thread_to_tls);
3120 mono_loader_unlock ();
3122 while (TRUE) {
3123 nwait = count_threads_to_wait_for ();
3124 if (nwait) {
3125 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3126 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3127 g_assert (err == 0);
3128 waited = TRUE;
3129 } else {
3130 break;
3134 if (waited)
3135 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3139 * is_suspended:
3141 * Return whenever the runtime is suspended.
3143 static gboolean
3144 is_suspended (void)
3146 return count_threads_to_wait_for () == 0;
3149 static void
3150 no_seq_points_found (MonoMethod *method, int offset)
3153 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3155 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3158 static int
3159 calc_il_offset (MonoDomain *domain, MonoMethod *method, int native_offset, gboolean is_top_frame)
3161 int ret = -1;
3162 if (is_top_frame) {
3163 SeqPoint sp;
3164 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3165 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
3166 ret = sp.il_offset;
3168 if (ret == -1)
3169 ret = mono_debug_il_offset_from_address (method, domain, native_offset);
3170 return ret;
3173 typedef struct {
3174 DebuggerTlsData *tls;
3175 GSList *frames;
3176 gboolean set_debugger_flag;
3177 } ComputeFramesUserData;
3179 static gboolean
3180 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3182 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3183 StackFrame *frame;
3184 MonoMethod *method, *actual_method, *api_method;
3185 int flags = 0;
3187 mono_loader_lock ();
3188 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3189 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3190 /* Mark the last frame as an invoke frame */
3191 if (ud->frames)
3192 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3193 else
3194 ud->set_debugger_flag = TRUE;
3196 mono_loader_unlock ();
3197 return FALSE;
3200 if (info->ji)
3201 method = jinfo_get_method (info->ji);
3202 else
3203 method = info->method;
3204 actual_method = info->actual_method;
3205 api_method = method;
3207 if (!method) {
3208 mono_loader_unlock ();
3209 return FALSE;
3212 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3213 mono_loader_unlock ();
3214 return FALSE;
3217 if (info->il_offset == -1) {
3218 info->il_offset = calc_il_offset (info->domain, method, info->native_offset, ud->frames == NULL);
3221 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);
3223 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3224 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3225 /* Older clients can't handle this flag */
3226 mono_loader_unlock ();
3227 return FALSE;
3229 api_method = mono_marshal_method_from_wrapper (method);
3230 if (!api_method) {
3231 mono_loader_unlock ();
3232 return FALSE;
3234 actual_method = api_method;
3235 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3238 if (ud->set_debugger_flag) {
3239 g_assert (g_slist_length (ud->frames) == 0);
3240 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3241 ud->set_debugger_flag = FALSE;
3244 frame = g_new0 (StackFrame, 1);
3245 frame->de.ji = info->ji;
3246 frame->de.domain = info->domain;
3247 frame->de.method = method;
3248 frame->de.native_offset = info->native_offset;
3250 frame->actual_method = actual_method;
3251 frame->api_method = api_method;
3252 frame->il_offset = info->il_offset;
3253 frame->flags = flags;
3254 frame->interp_frame = info->interp_frame;
3255 frame->frame_addr = info->frame_addr;
3256 if (info->reg_locations)
3257 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3258 if (ctx) {
3259 frame->ctx = *ctx;
3260 frame->has_ctx = TRUE;
3263 ud->frames = g_slist_append (ud->frames, frame);
3265 mono_loader_unlock ();
3266 return FALSE;
3269 static gint32 isFixedSizeArray (MonoClassField *f)
3271 ERROR_DECL (error);
3272 if (!CHECK_PROTOCOL_VERSION (2, 53) || f->type->type != MONO_TYPE_VALUETYPE) {
3273 return 1;
3275 MonoCustomAttrInfo *cinfo;
3276 MonoCustomAttrEntry *attr;
3277 int aindex;
3278 gint32 ret = 1;
3279 cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error);
3280 goto_if_nok (error, leave);
3281 attr = NULL;
3282 if (cinfo) {
3283 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
3284 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
3285 MonoClass *fixed_size_class = mono_class_try_get_fixed_buffer_class ();
3286 if (fixed_size_class != NULL && mono_class_has_parent (ctor_class, fixed_size_class)) {
3287 attr = &cinfo->attrs [aindex];
3288 gpointer *typed_args, *named_args;
3289 CattrNamedArg *arginfo;
3290 int num_named_args;
3292 mono_reflection_create_custom_attr_data_args_noalloc (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size,
3293 &typed_args, &named_args, &num_named_args, &arginfo, error);
3294 if (!is_ok (error)) {
3295 ret = 0;
3296 goto leave;
3298 ret = *(gint32*)typed_args [1];
3299 g_free (typed_args [1]);
3300 g_free (typed_args);
3301 g_free (named_args);
3302 g_free (arginfo);
3303 return ret;
3307 leave:
3308 mono_error_cleanup (error);
3309 return ret;
3312 static gboolean
3313 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3315 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3318 * 'tls->filter_ctx' is the location of the throw site.
3320 * mono_walk_stack() will never actually hit the throw site, but unwind
3321 * directly from the filter to the call site; we abort stack unwinding here
3322 * once this happens and resume from the throw site.
3324 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3325 return TRUE;
3327 return process_frame (info, ctx, user_data);
3331 * Return a malloc-ed list of StackFrame structures.
3333 static StackFrame**
3334 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3336 ComputeFramesUserData user_data;
3337 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3338 StackFrame **res;
3339 int i, nframes;
3340 GSList *l;
3342 user_data.tls = tls;
3343 user_data.frames = NULL;
3345 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3347 nframes = g_slist_length (user_data.frames);
3348 res = g_new0 (StackFrame*, nframes);
3349 l = user_data.frames;
3350 for (i = 0; i < nframes; ++i) {
3351 res [i] = (StackFrame *)l->data;
3352 l = l->next;
3354 *out_nframes = nframes;
3356 return res;
3359 static void
3360 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3362 ComputeFramesUserData user_data;
3363 GSList *tmp;
3364 int i, findex, new_frame_count;
3365 StackFrame **new_frames, *f;
3366 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3368 // FIXME: Locking on tls
3369 if (tls->frames && tls->frames_up_to_date && !force_update)
3370 return;
3372 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3374 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3375 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
3376 new_frames = compute_frame_info_from (thread, tls, &tls->restore_state, &new_frame_count);
3377 invalidate_frames (tls);
3379 tls->frames = new_frames;
3380 tls->frame_count = new_frame_count;
3381 tls->frames_up_to_date = TRUE;
3382 return;
3386 user_data.tls = tls;
3387 user_data.frames = NULL;
3388 if (tls->terminated) {
3389 tls->frame_count = 0;
3390 return;
3391 } if (!tls->really_suspended && tls->async_state.valid) {
3392 /* Have to use the state saved by the signal handler */
3393 process_frame (&tls->async_last_frame, NULL, &user_data);
3394 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3395 } else if (tls->filter_state.valid) {
3397 * We are inside an exception filter.
3399 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3401 if (tls->context.valid) {
3402 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3403 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3406 * After that, we resume unwinding from the location where the exception has been thrown.
3408 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3409 } else if (tls->context.valid) {
3410 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3411 } else {
3412 // FIXME:
3413 tls->frame_count = 0;
3414 return;
3417 new_frame_count = g_slist_length (user_data.frames);
3418 new_frames = g_new0 (StackFrame*, new_frame_count);
3419 findex = 0;
3420 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3421 f = (StackFrame *)tmp->data;
3424 * Reuse the id for already existing stack frames, so invokes don't invalidate
3425 * the still valid stack frames.
3427 for (i = 0; i < tls->frame_count; ++i) {
3428 if (tls->frames [i]->frame_addr == f->frame_addr) {
3429 f->id = tls->frames [i]->id;
3430 break;
3434 if (i >= tls->frame_count)
3435 f->id = mono_atomic_inc_i32 (&frame_id);
3437 new_frames [findex ++] = f;
3440 g_slist_free (user_data.frames);
3442 invalidate_frames (tls);
3444 tls->frames = new_frames;
3445 tls->frame_count = new_frame_count;
3446 tls->frames_up_to_date = TRUE;
3448 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3449 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
3450 gboolean has_interp_resume_state = FALSE;
3451 MonoInterpFrameHandle interp_resume_frame = NULL;
3452 gpointer interp_resume_ip = 0;
3453 mini_get_interp_callbacks ()->get_resume_state (jit_data, &has_interp_resume_state, &interp_resume_frame, &interp_resume_ip);
3454 if (has_interp_resume_state && tls->frame_count > 0) {
3455 StackFrame *top_frame = tls->frames [0];
3456 if (interp_resume_frame == top_frame->interp_frame) {
3457 int native_offset = (int) ((uintptr_t) interp_resume_ip - (uintptr_t) top_frame->de.ji->code_start);
3458 top_frame->il_offset = calc_il_offset (top_frame->de.domain, top_frame->de.method, native_offset, TRUE);
3465 * GHFunc to emit an appdomain creation event
3466 * @param key Don't care
3467 * @param value A loaded appdomain
3468 * @param user_data Don't care
3470 static void
3471 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3473 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3474 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3478 * GHFunc to emit a thread start event
3479 * @param key A thread id
3480 * @param value A thread object
3481 * @param user_data Don't care
3483 static void
3484 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3486 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3487 process_profiler_event (EVENT_KIND_THREAD_START, value);
3491 * GFunc to emit an assembly load event
3492 * @param value A loaded assembly
3493 * @param user_data Don't care
3495 static void
3496 emit_assembly_load (gpointer value, gpointer user_data)
3498 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3502 * GFunc to emit a type load event
3503 * @param value A loaded type
3504 * @param user_data Don't care
3506 static void
3507 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3509 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3513 static void gc_finalizing (MonoProfiler *prof)
3515 DebuggerTlsData *tls;
3517 if (is_debugger_thread ())
3518 return;
3520 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3521 g_assert (tls);
3522 tls->gc_finalizing = TRUE;
3525 static void gc_finalized (MonoProfiler *prof)
3527 DebuggerTlsData *tls;
3529 if (is_debugger_thread ())
3530 return;
3532 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3533 g_assert (tls);
3534 tls->gc_finalizing = FALSE;
3538 static char*
3539 strdup_tolower (char *s)
3541 char *s2, *p;
3543 s2 = g_strdup (s);
3544 for (p = s2; *p; ++p)
3545 *p = tolower (*p);
3546 return s2;
3550 * Same as g_path_get_basename () but handles windows paths as well,
3551 * which can occur in .mdb files created by pdb2mdb.
3553 static char*
3554 dbg_path_get_basename (const char *filename)
3556 char *r;
3558 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3559 return g_path_get_basename (filename);
3561 /* From gpath.c */
3563 /* No separator -> filename */
3564 r = (char*)strrchr (filename, '\\');
3565 if (r == NULL)
3566 return g_strdup (filename);
3568 /* Trailing slash, remove component */
3569 if (r [1] == 0){
3570 char *copy = g_strdup (filename);
3571 copy [r-filename] = 0;
3572 r = strrchr (copy, '\\');
3574 if (r == NULL){
3575 g_free (copy);
3576 return g_strdup ("/");
3578 r = g_strdup (&r[1]);
3579 g_free (copy);
3580 return r;
3583 return g_strdup (&r[1]);
3586 static void
3587 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3589 ERROR_DECL (error);
3590 MonoCustomAttrInfo *ainfo;
3592 if (ji->dbg_attrs_inited)
3593 return;
3595 MONO_STATIC_POINTER_INIT (MonoClass, hidden_klass)
3596 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3597 MONO_STATIC_POINTER_INIT_END (MonoClass, hidden_klass)
3600 MONO_STATIC_POINTER_INIT (MonoClass, step_through_klass)
3601 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3602 MONO_STATIC_POINTER_INIT_END (MonoClass, step_through_klass)
3604 MONO_STATIC_POINTER_INIT (MonoClass, non_user_klass)
3605 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3606 MONO_STATIC_POINTER_INIT_END (MonoClass, non_user_klass)
3608 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3609 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3610 if (ainfo) {
3611 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3612 ji->dbg_hidden = TRUE;
3613 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3614 ji->dbg_step_through = TRUE;
3615 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3616 ji->dbg_non_user_code = TRUE;
3617 mono_custom_attrs_free (ainfo);
3620 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3621 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3622 if (ainfo) {
3623 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3624 ji->dbg_step_through = TRUE;
3625 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3626 ji->dbg_non_user_code = TRUE;
3627 mono_custom_attrs_free (ainfo);
3630 mono_memory_barrier ();
3631 ji->dbg_attrs_inited = TRUE;
3635 * EVENT HANDLING
3639 * create_event_list:
3641 * Return a list of event request ids matching EVENT, starting from REQS, which
3642 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3643 * policy.
3644 * We return request ids, instead of requests, to simplify threading, since
3645 * requests could be deleted anytime when the loader lock is not held.
3646 * LOCKING: Assumes the loader lock is held.
3648 static GSList*
3649 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3651 int i, j;
3652 GSList *events = NULL;
3654 *suspend_policy = SUSPEND_POLICY_NONE;
3656 if (!reqs)
3657 reqs = event_requests;
3659 if (!reqs)
3660 return NULL;
3661 gboolean has_everything_else = FALSE;
3662 gboolean is_new_filtered_exception = FALSE;
3663 gboolean filteredException = TRUE;
3664 gint filtered_suspend_policy = 0;
3665 gint filtered_req_id = 0;
3666 gint everything_else_suspend_policy = 0;
3667 gint everything_else_req_id = 0;
3668 gboolean is_already_filtered = FALSE;
3669 for (i = 0; i < reqs->len; ++i) {
3670 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3671 if (req->event_kind == event) {
3672 gboolean filtered = FALSE;
3674 /* Apply filters */
3675 for (j = 0; j < req->nmodifiers; ++j) {
3676 Modifier *mod = &req->modifiers [j];
3678 if (mod->kind == MOD_KIND_COUNT) {
3679 filtered = TRUE;
3680 if (mod->data.count > 0) {
3681 if (mod->data.count > 0) {
3682 mod->data.count --;
3683 if (mod->data.count == 0)
3684 filtered = FALSE;
3687 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3688 if (mod->data.thread != mono_thread_internal_current ())
3689 filtered = TRUE;
3690 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && !mod->not_filtered_feature && ei) {
3691 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3692 filtered = TRUE;
3693 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3694 filtered = TRUE;
3695 if (ei->caught && !mod->caught)
3696 filtered = TRUE;
3697 if (!ei->caught && !mod->uncaught)
3698 filtered = TRUE;
3699 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && mod->not_filtered_feature && ei) {
3700 is_new_filtered_exception = TRUE;
3701 if ((mod->data.exc_class && mod->subclasses && mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass)) ||
3702 (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)) {
3703 is_already_filtered = TRUE;
3704 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3705 filteredException = FALSE;
3706 filtered_suspend_policy = req->suspend_policy;
3707 filtered_req_id = req->id;
3710 if (!mod->data.exc_class && mod->everything_else) {
3711 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3712 has_everything_else = TRUE;
3713 everything_else_req_id = req->id;
3714 everything_else_suspend_policy = req->suspend_policy;
3717 if (!mod->data.exc_class && !mod->everything_else) {
3718 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3719 filteredException = FALSE;
3720 filtered_suspend_policy = req->suspend_policy;
3721 filtered_req_id = req->id;
3724 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3725 int k;
3726 gboolean found = FALSE;
3727 MonoAssembly **assemblies = mod->data.assemblies;
3729 if (assemblies) {
3730 for (k = 0; assemblies [k]; ++k)
3731 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3732 found = TRUE;
3734 if (!found)
3735 filtered = TRUE;
3736 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3737 gpointer iter = NULL;
3738 MonoMethod *method;
3739 MonoDebugSourceInfo *sinfo;
3740 char *s;
3741 gboolean found = FALSE;
3742 int i;
3743 GPtrArray *source_file_list;
3745 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3746 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3748 if (minfo) {
3749 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
3750 for (i = 0; i < source_file_list->len; ++i) {
3751 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3753 * Do a case-insesitive match by converting the file name to
3754 * lowercase.
3756 s = strdup_tolower (sinfo->source_file);
3757 if (g_hash_table_lookup (mod->data.source_files, s))
3758 found = TRUE;
3759 else {
3760 char *s2 = dbg_path_get_basename (sinfo->source_file);
3761 char *s3 = strdup_tolower (s2);
3763 if (g_hash_table_lookup (mod->data.source_files, s3))
3764 found = TRUE;
3765 g_free (s2);
3766 g_free (s3);
3768 g_free (s);
3770 g_ptr_array_free (source_file_list, TRUE);
3773 if (!found)
3774 filtered = TRUE;
3775 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3776 char *s;
3778 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3779 if (!g_hash_table_lookup (mod->data.type_names, s))
3780 filtered = TRUE;
3781 g_free (s);
3782 } else if (mod->kind == MOD_KIND_STEP) {
3783 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3784 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3785 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3786 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3787 filtered = TRUE;
3788 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3789 init_jit_info_dbg_attrs (ji);
3790 if (ji->dbg_hidden)
3791 filtered = TRUE;
3793 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3794 init_jit_info_dbg_attrs (ji);
3795 if (ji->dbg_step_through)
3796 filtered = TRUE;
3798 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3799 init_jit_info_dbg_attrs (ji);
3800 if (ji->dbg_non_user_code)
3801 filtered = TRUE;
3806 if (!filtered && !is_new_filtered_exception) {
3807 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3808 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3813 if (has_everything_else && !is_already_filtered) {
3814 filteredException = FALSE;
3815 filtered_suspend_policy = everything_else_suspend_policy;
3816 filtered_req_id = everything_else_req_id;
3819 if (!filteredException) {
3820 *suspend_policy = MAX (*suspend_policy, filtered_suspend_policy);
3821 events = g_slist_append (events, GINT_TO_POINTER (filtered_req_id));
3824 /* Send a VM START/DEATH event by default */
3825 if (event == EVENT_KIND_VM_START)
3826 events = g_slist_append (events, GINT_TO_POINTER (0));
3827 if (event == EVENT_KIND_VM_DEATH)
3828 events = g_slist_append (events, GINT_TO_POINTER (0));
3830 return events;
3833 static G_GNUC_UNUSED const char*
3834 event_to_string (EventKind event)
3836 switch (event) {
3837 case EVENT_KIND_VM_START: return "VM_START";
3838 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3839 case EVENT_KIND_THREAD_START: return "THREAD_START";
3840 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3841 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3842 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3843 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3844 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3845 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3846 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3847 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3848 case EVENT_KIND_STEP: return "STEP";
3849 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3850 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3851 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3852 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3853 case EVENT_KIND_USER_LOG: return "USER_LOG";
3854 case EVENT_KIND_CRASH: return "CRASH";
3855 default:
3856 g_assert_not_reached ();
3857 return "";
3862 * process_event:
3864 * Send an event to the client, suspending the vm if needed.
3865 * LOCKING: Since this can suspend the calling thread, no locks should be held
3866 * by the caller.
3867 * The EVENTS list is freed by this function.
3869 static void
3870 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3872 Buffer buf;
3873 GSList *l;
3874 MonoDomain *domain = mono_domain_get ();
3875 MonoThread *thread = NULL;
3876 MonoObject *keepalive_obj = NULL;
3877 gboolean send_success = FALSE;
3878 static int ecount;
3879 int nevents;
3881 if (!inited) {
3882 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3883 return;
3886 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3887 // FIXME: We miss those events
3888 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3889 return;
3892 if (vm_death_event_sent) {
3893 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3894 return;
3897 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3898 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3899 return;
3902 if (disconnected) {
3903 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3904 return;
3907 if (event == EVENT_KIND_KEEPALIVE)
3908 suspend_policy = SUSPEND_POLICY_NONE;
3909 else {
3910 if (events == NULL)
3911 return;
3913 if (agent_config.defer) {
3914 if (is_debugger_thread ()) {
3915 /* Don't suspend on events from the debugger thread */
3916 suspend_policy = SUSPEND_POLICY_NONE;
3918 } else {
3919 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3920 // FIXME: Send these with a NULL thread, don't suspend the current thread
3921 return;
3925 if (event == EVENT_KIND_VM_START)
3926 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3928 nevents = g_slist_length (events);
3929 buffer_init (&buf, 128);
3930 buffer_add_byte (&buf, suspend_policy);
3931 buffer_add_int (&buf, nevents);
3933 for (l = events; l; l = l->next) {
3934 buffer_add_byte (&buf, event); // event kind
3935 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3937 ecount ++;
3939 if (event == EVENT_KIND_VM_DEATH) {
3940 thread = NULL;
3941 } else {
3942 if (!thread)
3943 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3945 if (event == EVENT_KIND_VM_START && arg != NULL)
3946 thread = (MonoThread *)arg;
3949 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3951 switch (event) {
3952 case EVENT_KIND_THREAD_START:
3953 case EVENT_KIND_THREAD_DEATH:
3954 break;
3955 case EVENT_KIND_APPDOMAIN_CREATE:
3956 case EVENT_KIND_APPDOMAIN_UNLOAD:
3957 buffer_add_domainid (&buf, (MonoDomain *)arg);
3958 break;
3959 case EVENT_KIND_METHOD_ENTRY:
3960 case EVENT_KIND_METHOD_EXIT:
3961 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3962 break;
3963 case EVENT_KIND_ASSEMBLY_LOAD:
3964 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3965 break;
3966 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3967 DebuggerTlsData *tls;
3969 /* The domain the assembly belonged to is not equal to the current domain */
3970 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3971 g_assert (tls);
3972 g_assert (tls->domain_unloading);
3974 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3975 break;
3977 case EVENT_KIND_TYPE_LOAD:
3978 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3979 break;
3980 case EVENT_KIND_BREAKPOINT:
3981 case EVENT_KIND_STEP: {
3982 DebuggerTlsData *tls;
3983 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3984 g_assert (tls);
3985 mono_stopwatch_stop (&tls->step_time);
3986 MonoMethod *method = (MonoMethod *)arg;
3988 buffer_add_methodid (&buf, domain, method);
3989 buffer_add_long (&buf, il_offset);
3990 break;
3992 case EVENT_KIND_VM_START:
3993 buffer_add_domainid (&buf, mono_get_root_domain ());
3994 break;
3995 case EVENT_KIND_VM_DEATH:
3996 if (CHECK_PROTOCOL_VERSION (2, 27))
3997 buffer_add_int (&buf, mono_environment_exitcode_get ());
3998 break;
3999 case EVENT_KIND_CRASH: {
4000 EventInfo *ei = (EventInfo *)arg;
4001 buffer_add_long (&buf, ei->hashes->offset_free_hash);
4002 buffer_add_string (&buf, ei->dump);
4003 break;
4005 case EVENT_KIND_EXCEPTION: {
4006 EventInfo *ei = (EventInfo *)arg;
4007 buffer_add_objid (&buf, ei->exc);
4009 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
4010 * later after the suspension. (#12494).
4012 keepalive_obj = ei->exc;
4013 break;
4015 case EVENT_KIND_USER_BREAK: {
4016 DebuggerTlsData *tls;
4017 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4018 g_assert (tls);
4019 mono_stopwatch_stop (&tls->step_time);
4020 break;
4022 case EVENT_KIND_USER_LOG: {
4023 EventInfo *ei = (EventInfo *)arg;
4024 buffer_add_int (&buf, ei->level);
4025 buffer_add_string (&buf, ei->category ? ei->category : "");
4026 buffer_add_string (&buf, ei->message ? ei->message : "");
4027 break;
4029 case EVENT_KIND_KEEPALIVE:
4030 suspend_policy = SUSPEND_POLICY_NONE;
4031 break;
4032 default:
4033 g_assert_not_reached ();
4037 if (event == EVENT_KIND_VM_START) {
4038 if (!agent_config.defer) {
4039 ERROR_DECL (error);
4040 start_debugger_thread (error);
4041 mono_error_assert_ok (error);
4045 if (event == EVENT_KIND_VM_DEATH) {
4046 vm_death_event_sent = TRUE;
4047 suspend_policy = SUSPEND_POLICY_NONE;
4050 if (mono_runtime_is_shutting_down ())
4051 suspend_policy = SUSPEND_POLICY_NONE;
4053 if (suspend_policy != SUSPEND_POLICY_NONE) {
4055 * Save the thread context and start suspending before sending the packet,
4056 * since we could be receiving the resume request before send_packet ()
4057 * returns.
4059 save_thread_context (ctx);
4060 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, mono_thread_internal_current ());
4061 tls->suspend_count++;
4062 suspend_vm ();
4064 if (keepalive_obj)
4065 /* This will keep this object alive */
4066 get_objref (keepalive_obj);
4069 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
4071 if (send_success) {
4072 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4073 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
4076 buffer_free (&buf);
4078 g_slist_free (events);
4079 events = NULL;
4081 if (!send_success) {
4082 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
4083 return;
4086 if (event == EVENT_KIND_VM_START) {
4087 vm_start_event_sent = TRUE;
4090 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);
4092 switch (suspend_policy) {
4093 case SUSPEND_POLICY_NONE:
4094 break;
4095 case SUSPEND_POLICY_ALL:
4096 suspend_current ();
4097 break;
4098 case SUSPEND_POLICY_EVENT_THREAD:
4099 NOT_IMPLEMENTED;
4100 break;
4101 default:
4102 g_assert_not_reached ();
4106 static void
4107 process_profiler_event (EventKind event, gpointer arg)
4109 int suspend_policy;
4110 GSList *events;
4111 EventInfo ei, *ei_arg = NULL;
4113 if (event == EVENT_KIND_TYPE_LOAD) {
4114 ei.klass = (MonoClass *)arg;
4115 ei_arg = &ei;
4118 mono_loader_lock ();
4119 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
4120 mono_loader_unlock ();
4122 process_event (event, arg, 0, NULL, events, suspend_policy);
4125 static void
4126 runtime_initialized (MonoProfiler *prof)
4128 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
4129 if (agent_config.defer) {
4130 ERROR_DECL (error);
4131 start_debugger_thread (error);
4132 mono_error_assert_ok (error);
4136 static void
4137 runtime_shutdown (MonoProfiler *prof)
4139 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
4141 mono_debugger_agent_cleanup ();
4144 static void
4145 thread_startup (MonoProfiler *prof, uintptr_t tid)
4147 MonoInternalThread *thread = mono_thread_internal_current ();
4148 MonoInternalThread *old_thread;
4149 DebuggerTlsData *tls;
4151 if (is_debugger_thread ())
4152 return;
4154 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
4156 mono_loader_lock ();
4157 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4158 mono_loader_unlock ();
4159 if (old_thread) {
4160 if (thread == old_thread) {
4162 * For some reason, thread_startup () might be called for the same thread
4163 * multiple times (attach ?).
4165 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4166 return;
4167 } else {
4169 * thread_end () might not be called for some threads, and the tid could
4170 * get reused.
4172 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4173 mono_loader_lock ();
4174 mono_g_hash_table_remove (thread_to_tls, old_thread);
4175 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
4176 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4177 mono_loader_unlock ();
4181 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4182 g_assert (!tls);
4183 // FIXME: Free this somewhere
4184 tls = g_new0 (DebuggerTlsData, 1);
4185 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
4186 tls->thread = thread;
4187 // Do so we have thread id even after termination
4188 tls->thread_id = (intptr_t) thread->tid;
4189 mono_native_tls_set_value (debugger_tls_id, tls);
4191 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4193 mono_loader_lock ();
4194 mono_g_hash_table_insert_internal (thread_to_tls, thread, tls);
4195 mono_g_hash_table_insert_internal (tid_to_thread, (gpointer)tid, thread);
4196 mono_g_hash_table_insert_internal (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
4197 mono_loader_unlock ();
4199 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4202 * suspend_vm () could have missed this thread, so wait for a resume.
4205 suspend_current ();
4208 static void
4209 thread_end (MonoProfiler *prof, uintptr_t tid)
4211 MonoInternalThread *thread;
4212 DebuggerTlsData *tls = NULL;
4214 mono_loader_lock ();
4215 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4216 if (thread) {
4217 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4218 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4219 if (tls) {
4220 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4221 tls->terminated = TRUE;
4222 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4223 MONO_GC_UNREGISTER_ROOT (tls->thread);
4224 tls->thread = NULL;
4227 mono_loader_unlock ();
4229 /* We might be called for threads started before we registered the start callback */
4230 if (thread) {
4231 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p (domain=%p).\n", (gpointer)tid, thread, tls, (gpointer)mono_domain_get ());
4233 if (mono_thread_internal_is_current (thread) &&
4234 (!mono_native_tls_get_value (debugger_tls_id) ||
4235 !mono_domain_get ())
4238 * This can happen on darwin and android since we
4239 * deregister threads using pthread dtors.
4240 * process_profiler_event () and the code it calls
4241 * cannot handle a null TLS value.
4243 return;
4246 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4250 static void
4251 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4253 mono_de_domain_add (domain);
4255 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4258 static void
4259 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4261 DebuggerTlsData *tls;
4263 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4264 if (is_debugger_thread ())
4265 return;
4268 * Remember the currently unloading appdomain as it is needed to generate
4269 * proper ids for unloading assemblies.
4271 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4272 g_assert (tls);
4273 tls->domain_unloading = domain;
4276 static void
4277 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4279 DebuggerTlsData *tls;
4281 if (is_debugger_thread ())
4282 return;
4284 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4285 g_assert (tls);
4286 tls->domain_unloading = NULL;
4288 mono_de_clear_breakpoints_for_domain (domain);
4290 mono_loader_lock ();
4291 /* Invalidate each thread's frame stack */
4292 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4293 mono_loader_unlock ();
4295 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4299 * invalidate_each_thread:
4301 * A GHFunc to invalidate frames.
4302 * value must be a DebuggerTlsData*
4304 static void
4305 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4307 invalidate_frames ((DebuggerTlsData *)value);
4310 static void
4311 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4313 /* Sent later in jit_end () */
4314 dbg_lock ();
4315 g_ptr_array_add (pending_assembly_loads, assembly);
4316 dbg_unlock ();
4319 static void
4320 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4322 if (is_debugger_thread ())
4323 return;
4325 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4327 clear_event_requests_for_assembly (assembly);
4328 clear_types_for_assembly (assembly);
4331 static void
4332 send_type_load (MonoClass *klass)
4334 gboolean type_load = FALSE;
4335 MonoDomain *domain = mono_domain_get ();
4336 AgentDomainInfo *info = NULL;
4338 info = get_agent_domain_info (domain);
4340 mono_loader_lock ();
4342 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4343 type_load = TRUE;
4344 g_hash_table_insert (info->loaded_classes, klass, klass);
4347 mono_loader_unlock ();
4349 if (type_load)
4350 emit_type_load (klass, klass, NULL);
4354 * Emit load events for all types currently loaded in the domain.
4355 * Takes the loader and domain locks.
4356 * user_data is unused.
4358 static void
4359 send_types_for_domain (MonoDomain *domain, void *user_data)
4361 MonoDomain* old_domain;
4362 AgentDomainInfo *info = NULL;
4364 if (mono_domain_is_unloading (domain))
4365 return;
4367 info = get_agent_domain_info (domain);
4368 g_assert (info);
4370 old_domain = mono_domain_get ();
4372 mono_domain_set_fast (domain, TRUE);
4374 mono_loader_lock ();
4375 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4376 mono_loader_unlock ();
4378 mono_domain_set_fast (old_domain, TRUE);
4381 static void
4382 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4384 GSList *tmp;
4385 MonoDomain* old_domain;
4387 if (mono_domain_is_unloading (domain))
4388 return;
4390 old_domain = mono_domain_get ();
4392 mono_domain_set_fast (domain, TRUE);
4394 mono_domain_assemblies_lock (domain);
4395 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4396 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4397 emit_assembly_load (ass, NULL);
4399 mono_domain_assemblies_unlock (domain);
4401 mono_domain_set_fast (old_domain, TRUE);
4404 static void
4405 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4407 jit_end (prof, method, jinfo);
4410 static void
4411 jit_failed (MonoProfiler *prof, MonoMethod *method)
4413 jit_end (prof, method, NULL);
4416 static void
4417 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4420 * We emit type load events when the first method of the type is JITted,
4421 * since the class load profiler callbacks might be called with the
4422 * loader lock held. They could also occur in the debugger thread.
4423 * Same for assembly load events.
4425 while (TRUE) {
4426 MonoAssembly *assembly = NULL;
4428 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4429 dbg_lock ();
4430 if (pending_assembly_loads->len > 0) {
4431 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4432 g_ptr_array_remove_index (pending_assembly_loads, 0);
4434 dbg_unlock ();
4436 if (assembly) {
4437 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4438 } else {
4439 break;
4443 send_type_load (method->klass);
4445 if (jinfo)
4446 mono_de_add_pending_breakpoints (method, jinfo);
4450 * SINGLE STEPPING
4453 static void
4454 event_requests_cleanup (void)
4456 mono_loader_lock ();
4457 int i = 0;
4458 while (i < event_requests->len) {
4459 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4461 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4462 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4463 g_ptr_array_remove_index_fast (event_requests, i);
4464 g_free (req);
4465 } else {
4466 i ++;
4469 mono_loader_unlock ();
4473 * ss_calculate_framecount:
4475 * Ensure DebuggerTlsData fields are filled out.
4477 static void
4478 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4480 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4482 if (force_use_ctx || !tls->context.valid)
4483 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4484 compute_frame_info (tls->thread, tls, FALSE);
4485 if (frames)
4486 *frames = (DbgEngineStackFrame**)tls->frames;
4487 if (nframes)
4488 *nframes = tls->frame_count;
4492 * ss_discard_frame_data:
4494 * Discard frame data and invalidate any context
4496 static void
4497 ss_discard_frame_context (void *the_tls)
4499 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4500 tls->context.valid = FALSE;
4501 tls->async_state.valid = FALSE;
4502 invalidate_frames (tls);
4505 static MonoContext*
4506 tls_get_restore_state (void *the_tls)
4508 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4510 return &tls->restore_state.ctx;
4513 static gboolean
4514 ensure_jit (DbgEngineStackFrame* the_frame)
4516 StackFrame *frame = (StackFrame*)the_frame;
4517 if (!frame->jit) {
4518 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4519 if (!frame->jit && frame->api_method->is_inflated)
4520 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4521 if (!frame->jit) {
4522 char *s;
4524 /* This could happen for aot images with no jit debug info */
4525 s = mono_method_full_name (frame->api_method, TRUE);
4526 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4527 g_free (s);
4528 return FALSE;
4531 return TRUE;
4534 static gboolean
4535 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4537 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4540 static gpointer
4541 get_this_addr (DbgEngineStackFrame *the_frame)
4543 StackFrame *frame = (StackFrame *)the_frame;
4544 if (frame->de.ji->is_interp)
4545 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4547 MonoDebugVarInfo *var = frame->jit->this_var;
4548 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4549 return NULL;
4551 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4552 addr += (gint32)var->offset;
4553 return addr;
4556 static MonoMethod*
4557 get_set_notification_method (MonoClass* async_builder_class)
4559 ERROR_DECL (error);
4560 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, 1, FALSE, error);
4561 mono_error_assert_ok (error);
4562 if (array->len == 0) {
4563 g_ptr_array_free (array, TRUE);
4564 return NULL;
4566 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4567 g_ptr_array_free (array, TRUE);
4568 return set_notification_method;
4571 static MonoMethod*
4572 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4574 ERROR_DECL (error);
4575 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, 1, FALSE, error);
4576 mono_error_assert_ok (error);
4577 g_assert (array->len == 1);
4578 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4579 g_ptr_array_free (array, TRUE);
4580 return method;
4583 static MonoClass *
4584 get_class_to_get_builder_field(DbgEngineStackFrame *frame)
4586 ERROR_DECL (error);
4587 gpointer this_addr = get_this_addr (frame);
4588 MonoClass *original_class = frame->method->klass;
4589 MonoClass *ret;
4590 if (!m_class_is_valuetype (original_class) && mono_class_is_open_constructed_type (m_class_get_byval_arg (original_class))) {
4591 MonoObject *this_obj = *(MonoObject**)this_addr;
4592 MonoGenericContext context;
4593 MonoType *inflated_type;
4595 g_assert (this_obj);
4596 context = mono_get_generic_context_from_stack_frame (frame->ji, this_obj->vtable);
4597 inflated_type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (original_class), &context, error);
4598 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4600 ret = mono_class_from_mono_type_internal (inflated_type);
4601 mono_metadata_free_type (inflated_type);
4602 return ret;
4604 return original_class;
4608 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4609 static gpointer
4610 get_async_method_builder (DbgEngineStackFrame *frame)
4612 MonoObject *this_obj;
4613 MonoClassField *builder_field;
4614 gpointer builder;
4615 gpointer this_addr;
4616 MonoClass* klass = frame->method->klass;
4618 klass = get_class_to_get_builder_field(frame);
4619 builder_field = mono_class_get_field_from_name_full (klass, "<>t__builder", NULL);
4620 g_assert (builder_field);
4622 this_addr = get_this_addr (frame);
4623 if (!this_addr)
4624 return NULL;
4626 if (m_class_is_valuetype (klass)) {
4627 builder = mono_vtype_get_field_addr (*(guint8**)this_addr, builder_field);
4628 } else {
4629 this_obj = *(MonoObject**)this_addr;
4630 builder = (char*)this_obj + builder_field->offset;
4633 return builder;
4636 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4637 //since thread probably changed...
4638 static int
4639 get_this_async_id (DbgEngineStackFrame *frame)
4641 MonoClassField *builder_field;
4642 gpointer builder;
4643 MonoMethod *method;
4644 MonoObject *ex;
4645 ERROR_DECL (error);
4646 MonoObject *obj;
4647 gboolean old_disable_breakpoints = FALSE;
4648 DebuggerTlsData *tls;
4651 * FRAME points to a method in a state machine class/struct.
4652 * Call the ObjectIdForDebugger method of the associated method builder type.
4654 builder = get_async_method_builder (frame);
4655 if (!builder)
4656 return 0;
4658 builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4659 g_assert (builder_field);
4661 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4662 if (tls) {
4663 old_disable_breakpoints = tls->disable_breakpoints;
4664 tls->disable_breakpoints = TRUE;
4667 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4668 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4669 mono_error_assert_ok (error);
4671 if (tls)
4672 tls->disable_breakpoints = old_disable_breakpoints;
4674 return get_objid (obj);
4677 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4678 // false if not(AsyncVoidBuilder)
4679 static gboolean
4680 set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame)
4682 MonoClassField *builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4683 g_assert (builder_field);
4684 gpointer builder = get_async_method_builder (frame);
4685 g_assert (builder);
4687 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type_internal (builder_field->type));
4688 if (method == NULL)
4689 return FALSE;
4690 gboolean arg = TRUE;
4691 ERROR_DECL (error);
4692 void *args [ ] = { &arg };
4693 mono_runtime_invoke_checked (method, builder, args, error);
4694 mono_error_assert_ok (error);
4695 return TRUE;
4698 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4700 static MonoMethod*
4701 get_notify_debugger_of_wait_completion_method (void)
4703 if (notify_debugger_of_wait_completion_method_cache != NULL)
4704 return notify_debugger_of_wait_completion_method_cache;
4705 ERROR_DECL (error);
4706 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4707 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error);
4708 mono_error_assert_ok (error);
4709 g_assert (array->len == 1);
4710 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4711 g_ptr_array_free (array, TRUE);
4712 return notify_debugger_of_wait_completion_method_cache;
4715 static gboolean
4716 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4718 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4721 * Skip the instruction causing the breakpoint signal.
4723 if (from_signal)
4724 mono_arch_skip_breakpoint (ctx, ji);
4726 if (tls->disable_breakpoints)
4727 return FALSE;
4728 return TRUE;
4731 typedef struct {
4732 GSList *bp_events, *ss_events, *enter_leave_events;
4733 EventKind kind;
4734 int suspend_policy;
4735 } BreakPointEvents;
4737 static void*
4738 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4740 int suspend_policy = 0;
4741 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4742 if (ss_reqs && ss_reqs->len > 0)
4743 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4744 else if (bp_reqs && bp_reqs->len > 0)
4745 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4746 else if (kind != EVENT_KIND_BREAKPOINT)
4747 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4749 evts->kind = kind;
4750 evts->suspend_policy = suspend_policy;
4751 return evts;
4754 static void
4755 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4757 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4759 * FIXME: The first event will suspend, so the second will only be sent after the
4760 * resume.
4762 if (evts->ss_events)
4763 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4764 if (evts->bp_events)
4765 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4766 if (evts->enter_leave_events)
4767 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4769 g_free (evts);
4772 /* Process a breakpoint/single step event after resuming from a signal handler */
4773 static void
4774 process_signal_event (void (*func) (void*, gboolean))
4776 DebuggerTlsData *tls;
4777 MonoThreadUnwindState orig_restore_state;
4778 MonoContext ctx;
4780 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4781 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4782 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4783 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4785 func (tls, TRUE);
4787 /* This is called when resuming from a signal handler, so it shouldn't return */
4788 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4789 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4790 mono_restore_context (&ctx);
4791 g_assert_not_reached ();
4794 static void
4795 process_breakpoint_from_signal (void)
4797 process_signal_event (mono_de_process_breakpoint);
4800 static void
4801 resume_from_signal_handler (void *sigctx, void *func)
4803 DebuggerTlsData *tls;
4804 MonoContext ctx;
4806 /* Save the original context in TLS */
4807 // FIXME: This might not work on an altstack ?
4808 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4809 if (!tls)
4810 g_printerr ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4811 g_assert (tls);
4813 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4814 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4815 // clob:c could be added to op_seq_point.
4817 mono_sigctx_to_monoctx (sigctx, &ctx);
4818 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4819 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4820 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4821 #else
4822 MONO_CONTEXT_SET_IP (&ctx, func);
4823 #endif
4824 mono_monoctx_to_sigctx (&ctx, sigctx);
4827 static void
4828 debugger_agent_breakpoint_hit (void *sigctx)
4831 * We are called from a signal handler, and running code there causes all kinds of
4832 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4833 * So set up the signal context to return to the real breakpoint handler function.
4835 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4838 typedef struct {
4839 gboolean found;
4840 MonoContext *ctx;
4841 } UserBreakCbData;
4843 static gboolean
4844 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4846 UserBreakCbData *data = (UserBreakCbData*)user_data;
4848 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4849 data->found = TRUE;
4850 return TRUE;
4852 if (frame->managed) {
4853 data->found = TRUE;
4854 *data->ctx = *ctx;
4856 return TRUE;
4858 return FALSE;
4862 * Called by System.Diagnostics.Debugger:Break ().
4864 static void
4865 debugger_agent_user_break (void)
4867 if (agent_config.enabled) {
4868 MonoContext ctx;
4869 int suspend_policy;
4870 GSList *events;
4871 UserBreakCbData data;
4873 memset (&data, 0, sizeof (data));
4874 data.ctx = &ctx;
4876 /* Obtain a context */
4877 MONO_CONTEXT_SET_IP (&ctx, NULL);
4878 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4879 g_assert (data.found);
4881 mono_loader_lock ();
4882 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4883 mono_loader_unlock ();
4885 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4886 } else if (mini_debug_options.native_debugger_break) {
4887 G_BREAKPOINT ();
4891 static void
4892 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4894 if (from_signal)
4895 mono_arch_skip_single_step (ctx);
4898 static void
4899 process_single_step (void)
4901 process_signal_event (mono_de_process_single_step);
4905 * debugger_agent_single_step_event:
4907 * Called from a signal handler to handle a single step event.
4909 static void
4910 debugger_agent_single_step_event (void *sigctx)
4912 /* Resume to process_single_step through the signal context */
4914 // FIXME: Since step out/over is implemented using step in, the step in case should
4915 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4916 // here
4918 if (is_debugger_thread ()) {
4920 * This could happen despite our best effors when the runtime calls
4921 * assembly/type resolve hooks.
4922 * FIXME: Breakpoints too.
4924 MonoContext ctx;
4926 mono_sigctx_to_monoctx (sigctx, &ctx);
4927 mono_arch_skip_single_step (&ctx);
4928 mono_monoctx_to_sigctx (&ctx, sigctx);
4929 return;
4932 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4935 static void
4936 debugger_agent_single_step_from_context (MonoContext *ctx)
4938 DebuggerTlsData *tls;
4939 MonoThreadUnwindState orig_restore_state;
4941 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4942 /* Fastpath during invokes, see in process_suspend () */
4943 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4944 return;
4946 if (is_debugger_thread ())
4947 return;
4949 g_assert (tls);
4951 tls->terminated = FALSE;
4953 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4954 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4955 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4956 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4958 mono_de_process_single_step (tls, FALSE);
4960 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4961 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4964 static void
4965 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4967 DebuggerTlsData *tls;
4968 MonoThreadUnwindState orig_restore_state;
4969 guint8 *orig_ip;
4971 if (is_debugger_thread ())
4972 return;
4974 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4975 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4977 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4978 g_assert (tls);
4980 //if a thread was suspended and doesn't have any managed stack, it was considered as terminated,
4981 //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
4982 tls->terminated = FALSE;
4984 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4985 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4986 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4988 mono_de_process_breakpoint (tls, FALSE);
4990 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4991 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4992 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4993 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4995 static void
4996 ss_args_destroy (SingleStepArgs *ss_args)
4998 if (ss_args->frames)
4999 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
5002 static int
5003 handle_multiple_ss_requests (void)
5005 if (!CHECK_PROTOCOL_VERSION (2, 57))
5006 return DE_ERR_NOT_IMPLEMENTED;
5007 return 1;
5010 static int
5011 ensure_runtime_is_suspended (void)
5013 if (suspend_count == 0)
5014 return ERR_NOT_SUSPENDED;
5016 wait_for_suspend ();
5018 return ERR_NONE;
5021 static int
5022 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
5024 MonoSeqPointInfo *info = NULL;
5025 gboolean found_sp;
5026 MonoMethod *method = NULL;
5027 MonoDebugMethodInfo *minfo;
5028 gboolean step_to_catch = FALSE;
5029 gboolean set_ip = FALSE;
5030 StackFrame **frames = NULL;
5031 int nframes = 0;
5033 mono_loader_lock ();
5034 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5035 mono_loader_unlock ();
5036 g_assert (tls);
5037 if (!tls->context.valid) {
5038 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5039 return ERR_INVALID_ARGUMENT;
5042 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5044 * Need to start single stepping from restore_state and not from the current state
5046 set_ip = TRUE;
5047 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
5050 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5052 if (tls->has_catch_frame) {
5053 StackFrameInfo frame;
5056 * We are stopped at a throw site. Stepping should go to the catch site.
5058 frame = tls->catch_frame;
5059 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
5062 * Find the seq point corresponding to the landing site ip, which is the first seq
5063 * point after ip.
5065 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
5066 if (!found_sp)
5067 no_seq_points_found (frame.method, frame.native_offset);
5068 g_assert (found_sp);
5070 method = frame.method;
5072 step_to_catch = TRUE;
5073 /* This make sure the seq point is not skipped by process_single_step () */
5074 ss_req->last_sp = NULL;
5077 if (!step_to_catch) {
5078 StackFrame *frame = NULL;
5080 if (set_ip) {
5081 if (frames && nframes)
5082 frame = frames [0];
5083 } else {
5084 compute_frame_info (ss_req->thread, tls, FALSE);
5086 if (tls->frame_count)
5087 frame = tls->frames [0];
5090 if (ss_req->size == STEP_SIZE_LINE) {
5091 if (frame) {
5092 ss_req->last_method = frame->de.method;
5093 ss_req->last_line = -1;
5095 minfo = mono_debug_lookup_method (frame->de.method);
5096 if (minfo && frame->il_offset != -1) {
5097 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5099 if (loc) {
5100 ss_req->last_line = loc->row;
5101 g_free (loc);
5107 if (frame) {
5108 if (!method && frame->il_offset != -1) {
5109 /* FIXME: Sort the table and use a binary search */
5110 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
5111 if (!found_sp)
5112 no_seq_points_found (frame->de.method, frame->de.native_offset);
5113 g_assert (found_sp);
5114 method = frame->de.method;
5119 ss_req->start_method = method;
5121 args->method = method;
5122 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
5123 args->tls = tls;
5124 args->step_to_catch = step_to_catch;
5125 args->info = info;
5126 args->frames = (DbgEngineStackFrame**)frames;
5127 args->nframes = nframes;
5129 return ERR_NONE;
5132 static void
5133 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5135 GSList *l;
5136 gboolean found = TRUE;
5138 while (found) {
5139 found = FALSE;
5140 for (l = req->bps; l; l = l->next) {
5141 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5142 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
5143 req->bps = g_slist_delete_link (req->bps, l);
5144 found = TRUE;
5145 break;
5152 * This takes a lot of locks and stuff. Do this at the end, after
5153 * other things have dumped us, so that getting stuck here won't
5154 * prevent seeing other crash information
5156 static void
5157 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
5159 MONO_ENTER_GC_UNSAFE;
5160 #ifndef DISABLE_CRASH_REPORTING
5161 int suspend_policy;
5162 GSList *events;
5163 EventInfo ei;
5165 if (!agent_config.enabled)
5166 return;
5168 // Don't send the event if the client doesn't expect it
5169 if (!CHECK_PROTOCOL_VERSION (2, 49))
5170 return;
5172 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5173 // actually enabled. Therefore we do the wait here.
5174 sleep (pause);
5176 // Don't heap allocate when we can avoid it
5177 EventRequest request;
5178 memset (&request, 0, sizeof (request));
5179 request.event_kind = EVENT_KIND_CRASH;
5181 gpointer pdata [1];
5182 pdata [0] = &request;
5183 GPtrArray array;
5184 memset (&array, 0, sizeof (array));
5185 array.pdata = pdata;
5186 array.len = 1;
5188 mono_loader_lock ();
5189 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5190 mono_loader_unlock ();
5192 ei.dump = json_dump;
5193 ei.hashes = hashes;
5195 g_assert (events != NULL);
5197 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5199 // Don't die before it is sent.
5200 sleep (4);
5201 #endif
5202 MONO_EXIT_GC_UNSAFE;
5206 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5208 static void
5209 debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5211 ERROR_DECL (error);
5212 int suspend_policy;
5213 GSList *events;
5214 EventInfo ei;
5216 if (!agent_config.enabled)
5217 return;
5219 memset (&ei, 0, sizeof (ei));
5221 mono_loader_lock ();
5222 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5223 mono_loader_unlock ();
5225 ei.level = level;
5226 if (category) {
5227 ei.category = mono_string_to_utf8_checked_internal (category, error);
5228 mono_error_cleanup (error);
5229 error_init (error);
5231 if (message) {
5232 ei.message = mono_string_to_utf8_checked_internal (message, error);
5233 mono_error_cleanup (error);
5236 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5238 g_free (ei.category);
5239 g_free (ei.message);
5242 static gboolean
5243 debugger_agent_debug_log_is_enabled (void)
5245 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5246 return agent_config.enabled;
5249 static void
5250 debugger_agent_unhandled_exception (MonoException *exc)
5252 int suspend_policy;
5253 GSList *events;
5254 EventInfo ei;
5256 if (!inited)
5257 return;
5259 memset (&ei, 0, sizeof (ei));
5260 ei.exc = (MonoObject*)exc;
5262 mono_loader_lock ();
5263 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5264 mono_loader_unlock ();
5266 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5269 static void
5270 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5271 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5273 if (catch_ctx == NULL && catch_frame == NULL && mini_debug_options.suspend_on_unhandled && mono_object_class (exc) != mono_defaults.threadabortexception_class) {
5274 mono_runtime_printf_err ("Unhandled exception, suspending...");
5275 while (1)
5279 int i, j, suspend_policy;
5280 GSList *events;
5281 MonoJitInfo *ji, *catch_ji;
5282 EventInfo ei;
5283 DebuggerTlsData *tls = NULL;
5285 if (thread_to_tls != NULL) {
5286 MonoInternalThread *thread = mono_thread_internal_current ();
5288 mono_loader_lock ();
5289 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5290 mono_loader_unlock ();
5292 if (tls && tls->abort_requested)
5293 return;
5294 if (tls && tls->disable_breakpoints)
5295 return;
5298 memset (&ei, 0, sizeof (ei));
5300 /* Just-In-Time debugging */
5301 if (!catch_ctx) {
5302 if (agent_config.onuncaught && !inited) {
5303 finish_agent_init (FALSE);
5306 * Send an unsolicited EXCEPTION event with a dummy request id.
5308 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5309 ei.exc = (MonoObject*)exc;
5310 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5311 return;
5313 } else if (agent_config.onthrow && !inited) {
5314 GSList *l;
5315 gboolean found = FALSE;
5317 for (l = agent_config.onthrow; l; l = l->next) {
5318 char *ex_type = (char *)l->data;
5319 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5321 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5322 found = TRUE;
5324 g_free (f);
5327 if (found) {
5328 finish_agent_init (FALSE);
5331 * Send an unsolicited EXCEPTION event with a dummy request id.
5333 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5334 ei.exc = (MonoObject*)exc;
5335 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5336 return;
5340 if (!inited)
5341 return;
5343 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5344 if (catch_frame)
5345 catch_ji = catch_frame->ji;
5346 else
5347 catch_ji = NULL;
5349 ei.exc = (MonoObject*)exc;
5350 ei.caught = catch_ctx != NULL;
5352 mono_loader_lock ();
5354 /* Treat exceptions which are caught in non-user code as unhandled */
5355 for (i = 0; i < event_requests->len; ++i) {
5356 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5357 if (req->event_kind != EVENT_KIND_EXCEPTION)
5358 continue;
5360 for (j = 0; j < req->nmodifiers; ++j) {
5361 Modifier *mod = &req->modifiers [j];
5363 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5364 int k;
5365 gboolean found = FALSE;
5366 MonoAssembly **assemblies = mod->data.assemblies;
5368 if (assemblies) {
5369 for (k = 0; assemblies [k]; ++k)
5370 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5371 found = TRUE;
5373 if (!found)
5374 ei.caught = FALSE;
5379 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5380 mono_loader_unlock ();
5382 if (tls && ei.caught && catch_ctx) {
5383 if (catch_frame) {
5384 tls->has_catch_frame = TRUE;
5385 tls->catch_frame = *catch_frame;
5386 } else {
5387 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5391 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5393 if (tls)
5394 tls->has_catch_frame = FALSE;
5397 static void
5398 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5400 DebuggerTlsData *tls;
5402 if (!inited)
5403 return;
5405 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5406 if (!tls)
5407 return;
5410 * We're about to invoke an exception filter during the first pass of exception handling.
5412 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5413 * 'orig_ctx' is the context where the exception has been thrown.
5416 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5418 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5419 * the call site (line 37) and then continue to Main(), but it would never
5420 * include the throw site (line 32).
5422 * Since exception filters are invoked during the first pass of exception handling,
5423 * the stack frames of the throw site are still intact, so we should include them
5424 * in a stack trace.
5426 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5428 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5429 * but report the location of the 'throw' to the user.
5433 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5436 static void
5437 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5439 DebuggerTlsData *tls;
5441 if (!inited)
5442 return;
5444 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5445 if (!tls)
5446 return;
5448 tls->filter_state.valid = FALSE;
5451 static void
5452 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5453 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5455 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5456 buffer_add_byte (buf, t->type);
5457 buffer_add_int (buf, len_fixed_array );
5458 for (int i = 0; i < len_fixed_array; i++) {
5459 switch (t->type) {
5460 case MONO_TYPE_BOOLEAN:
5461 case MONO_TYPE_I1:
5462 case MONO_TYPE_U1:
5463 buffer_add_int (buf, ((gint8*)addr)[i]);
5464 break;
5465 case MONO_TYPE_CHAR:
5466 case MONO_TYPE_I2:
5467 case MONO_TYPE_U2:
5468 buffer_add_int (buf, ((gint16*)addr)[i]);
5469 break;
5470 case MONO_TYPE_I4:
5471 case MONO_TYPE_U4:
5472 case MONO_TYPE_R4:
5473 buffer_add_int (buf, ((gint32*)addr)[i]);
5474 break;
5475 case MONO_TYPE_I8:
5476 case MONO_TYPE_U8:
5477 case MONO_TYPE_R8:
5478 buffer_add_long (buf, ((gint64*)addr)[i]);
5479 break;
5480 case MONO_TYPE_PTR: {
5481 gssize val = *(gssize*)addr;
5483 buffer_add_byte (buf, t->type);
5484 buffer_add_long (buf, val);
5485 if (CHECK_PROTOCOL_VERSION(2, 46))
5486 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5487 break;
5493 * buffer_add_value_full:
5495 * Add the encoding of the value at ADDR described by T to the buffer.
5496 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5497 * vtypes.
5499 static void
5500 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5501 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5503 MonoObject *obj;
5504 gboolean boxed_vtype = FALSE;
5506 if (t->byref) {
5507 if (!(*(void**)addr)) {
5508 /* This can happen with compiler generated locals */
5509 //printf ("%s\n", mono_type_full_name (t));
5510 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5511 return;
5513 g_assert (*(void**)addr);
5514 addr = *(void**)addr;
5517 if (as_vtype) {
5518 switch (t->type) {
5519 case MONO_TYPE_BOOLEAN:
5520 case MONO_TYPE_I1:
5521 case MONO_TYPE_U1:
5522 case MONO_TYPE_CHAR:
5523 case MONO_TYPE_I2:
5524 case MONO_TYPE_U2:
5525 case MONO_TYPE_I4:
5526 case MONO_TYPE_U4:
5527 case MONO_TYPE_R4:
5528 case MONO_TYPE_I8:
5529 case MONO_TYPE_U8:
5530 case MONO_TYPE_R8:
5531 case MONO_TYPE_I:
5532 case MONO_TYPE_U:
5533 case MONO_TYPE_PTR:
5534 goto handle_vtype;
5535 break;
5536 default:
5537 break;
5541 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5543 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5544 return;
5546 switch (t->type) {
5547 case MONO_TYPE_VOID:
5548 buffer_add_byte (buf, t->type);
5549 break;
5550 case MONO_TYPE_BOOLEAN:
5551 case MONO_TYPE_I1:
5552 case MONO_TYPE_U1:
5553 buffer_add_byte (buf, t->type);
5554 buffer_add_int (buf, *(gint8*)addr);
5555 break;
5556 case MONO_TYPE_CHAR:
5557 case MONO_TYPE_I2:
5558 case MONO_TYPE_U2:
5559 buffer_add_byte (buf, t->type);
5560 buffer_add_int (buf, *(gint16*)addr);
5561 break;
5562 case MONO_TYPE_I4:
5563 case MONO_TYPE_U4:
5564 case MONO_TYPE_R4:
5565 buffer_add_byte (buf, t->type);
5566 buffer_add_int (buf, *(gint32*)addr);
5567 break;
5568 case MONO_TYPE_I8:
5569 case MONO_TYPE_U8:
5570 case MONO_TYPE_R8:
5571 buffer_add_byte (buf, t->type);
5572 buffer_add_long (buf, *(gint64*)addr);
5573 break;
5574 case MONO_TYPE_I:
5575 case MONO_TYPE_U:
5576 /* Treat it as a vtype */
5577 goto handle_vtype;
5578 case MONO_TYPE_PTR: {
5579 gssize val = *(gssize*)addr;
5581 buffer_add_byte (buf, t->type);
5582 buffer_add_long (buf, val);
5583 if (CHECK_PROTOCOL_VERSION(2, 46))
5584 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5585 break;
5587 handle_ref:
5588 case MONO_TYPE_STRING:
5589 case MONO_TYPE_SZARRAY:
5590 case MONO_TYPE_OBJECT:
5591 case MONO_TYPE_CLASS:
5592 case MONO_TYPE_ARRAY:
5593 obj = *(MonoObject**)addr;
5595 if (!obj) {
5596 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5597 } else {
5598 if (m_class_is_valuetype (obj->vtable->klass)) {
5599 t = m_class_get_byval_arg (obj->vtable->klass);
5600 addr = mono_object_unbox_internal (obj);
5601 boxed_vtype = TRUE;
5602 goto handle_vtype;
5603 } else if (m_class_get_rank (obj->vtable->klass)) {
5604 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5605 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5606 buffer_add_byte (buf, MONO_TYPE_CLASS);
5607 } else {
5608 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5610 buffer_add_objid (buf, obj);
5612 break;
5613 handle_vtype:
5614 case MONO_TYPE_VALUETYPE:
5615 case MONO_TYPE_TYPEDBYREF: {
5616 int nfields;
5617 gpointer iter;
5618 MonoClassField *f;
5619 MonoClass *klass = mono_class_from_mono_type_internal (t);
5620 int vtype_index;
5622 if (boxed_vtype) {
5624 * Handle boxed vtypes recursively referencing themselves using fields.
5626 if (!parent_vtypes)
5627 parent_vtypes = g_hash_table_new (NULL, NULL);
5628 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5629 if (vtype_index) {
5630 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5631 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5632 buffer_add_int (buf, vtype_index - 1);
5633 } else {
5634 /* The client can't handle PARENT_VTYPE */
5635 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5637 break;
5638 } else {
5639 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5643 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5644 buffer_add_byte (buf, m_class_is_enumtype (klass));
5645 buffer_add_typeid (buf, domain, klass);
5647 nfields = 0;
5648 iter = NULL;
5649 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5650 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5651 continue;
5652 if (mono_field_is_deleted (f))
5653 continue;
5654 nfields ++;
5656 buffer_add_int (buf, nfields);
5658 iter = NULL;
5659 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5660 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5661 continue;
5662 if (mono_field_is_deleted (f))
5663 continue;
5664 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));
5667 if (boxed_vtype) {
5668 g_hash_table_remove (parent_vtypes, addr);
5669 if (g_hash_table_size (parent_vtypes) == 0) {
5670 g_hash_table_destroy (parent_vtypes);
5671 parent_vtypes = NULL;
5674 break;
5676 case MONO_TYPE_GENERICINST:
5677 if (mono_type_generic_inst_is_valuetype (t)) {
5678 goto handle_vtype;
5679 } else {
5680 goto handle_ref;
5682 break;
5683 default:
5684 NOT_IMPLEMENTED;
5688 static void
5689 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5691 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5694 static gboolean
5695 obj_is_of_type (MonoObject *obj, MonoType *t)
5697 MonoClass *klass = obj->vtable->klass;
5698 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5699 if (mono_class_is_transparent_proxy (klass)) {
5700 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5701 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5702 return TRUE;
5705 return FALSE;
5707 return TRUE;
5710 static ErrorCode
5711 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5713 static ErrorCode
5714 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5716 guint8 *addr = (guint8*)void_addr;
5717 guint8 *buf = (guint8*)void_buf;
5718 gboolean is_enum;
5719 MonoClass *klass;
5720 MonoClassField *f;
5721 int nfields;
5722 gpointer iter = NULL;
5723 MonoDomain *d;
5724 ErrorCode err;
5726 is_enum = decode_byte (buf, &buf, limit);
5727 /* Enums are sent as a normal vtype */
5728 if (is_enum)
5729 return ERR_NOT_IMPLEMENTED;
5730 klass = decode_typeid (buf, &buf, limit, &d, &err);
5731 if (err != ERR_NONE)
5732 return err;
5734 if (t && klass != mono_class_from_mono_type_internal (t)) {
5735 char *name = mono_type_full_name (t);
5736 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5737 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5738 g_free (name);
5739 g_free (name2);
5740 return ERR_INVALID_ARGUMENT;
5743 nfields = decode_int (buf, &buf, limit);
5744 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5745 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5746 continue;
5747 if (mono_field_is_deleted (f))
5748 continue;
5749 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5750 if (err != ERR_NONE)
5751 return err;
5752 nfields --;
5754 g_assert (nfields == 0);
5756 *endbuf = buf;
5758 return ERR_NONE;
5760 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)
5762 ErrorCode err = ERR_NONE;
5763 int fixedSizeLen = 1;
5764 int newType = MONO_TYPE_END;
5765 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5766 newType = decode_byte (buf, &buf, limit);
5767 fixedSizeLen = decode_int (buf, &buf, limit);
5768 //t->type = newType;
5770 for (int i = 0 ; i < fixedSizeLen; i++) {
5771 switch (newType) {
5772 case MONO_TYPE_BOOLEAN:
5773 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5774 break;
5775 case MONO_TYPE_CHAR:
5776 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5777 break;
5778 case MONO_TYPE_I1:
5779 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5780 break;
5781 case MONO_TYPE_U1:
5782 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5783 break;
5784 case MONO_TYPE_I2:
5785 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5786 break;
5787 case MONO_TYPE_U2:
5788 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5789 break;
5790 case MONO_TYPE_I4:
5791 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5792 break;
5793 case MONO_TYPE_U4:
5794 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5795 break;
5796 case MONO_TYPE_I8:
5797 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5798 break;
5799 case MONO_TYPE_U8:
5800 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5801 break;
5802 case MONO_TYPE_R4:
5803 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5804 break;
5805 case MONO_TYPE_R8:
5806 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5807 break;
5810 *endbuf = buf;
5811 return err;
5813 static ErrorCode
5814 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5816 ErrorCode err;
5817 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5818 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5819 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5820 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5821 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5822 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5823 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5824 char *name = mono_type_full_name (t);
5825 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5826 g_free (name);
5827 return ERR_INVALID_ARGUMENT;
5829 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5830 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5831 return ERR_NONE;
5834 switch (t->type) {
5835 case MONO_TYPE_BOOLEAN:
5836 *(guint8*)addr = decode_int (buf, &buf, limit);
5837 break;
5838 case MONO_TYPE_CHAR:
5839 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5840 break;
5841 case MONO_TYPE_I1:
5842 *(gint8*)addr = decode_int (buf, &buf, limit);
5843 break;
5844 case MONO_TYPE_U1:
5845 *(guint8*)addr = decode_int (buf, &buf, limit);
5846 break;
5847 case MONO_TYPE_I2:
5848 *(gint16*)addr = decode_int (buf, &buf, limit);
5849 break;
5850 case MONO_TYPE_U2:
5851 *(guint16*)addr = decode_int (buf, &buf, limit);
5852 break;
5853 case MONO_TYPE_I4:
5854 *(gint32*)addr = decode_int (buf, &buf, limit);
5855 break;
5856 case MONO_TYPE_U4:
5857 *(guint32*)addr = decode_int (buf, &buf, limit);
5858 break;
5859 case MONO_TYPE_I8:
5860 *(gint64*)addr = decode_long (buf, &buf, limit);
5861 break;
5862 case MONO_TYPE_U8:
5863 *(guint64*)addr = decode_long (buf, &buf, limit);
5864 break;
5865 case MONO_TYPE_R4:
5866 *(guint32*)addr = decode_int (buf, &buf, limit);
5867 break;
5868 case MONO_TYPE_R8:
5869 *(guint64*)addr = decode_long (buf, &buf, limit);
5870 break;
5871 case MONO_TYPE_PTR:
5872 /* We send these as I8, so we get them back as such */
5873 g_assert (type == MONO_TYPE_I8);
5874 *(gssize*)addr = decode_long (buf, &buf, limit);
5875 break;
5876 case MONO_TYPE_GENERICINST:
5877 if (MONO_TYPE_ISSTRUCT (t)) {
5878 /* The client sends these as a valuetype */
5879 goto handle_vtype;
5880 } else {
5881 goto handle_ref;
5883 break;
5884 case MONO_TYPE_I:
5885 case MONO_TYPE_U:
5886 /* We send these as vtypes, so we get them back as such */
5887 g_assert (type == MONO_TYPE_VALUETYPE);
5888 /* Fall through */
5889 handle_vtype:
5890 case MONO_TYPE_VALUETYPE:
5891 if (type == MONO_TYPE_OBJECT) {
5892 /* Boxed vtype */
5893 int objid = decode_objid (buf, &buf, limit);
5894 ErrorCode err;
5895 MonoObject *obj;
5897 err = get_object (objid, (MonoObject**)&obj);
5898 if (err != ERR_NONE)
5899 return err;
5900 if (!obj)
5901 return ERR_INVALID_ARGUMENT;
5902 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5903 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5904 return ERR_INVALID_ARGUMENT;
5906 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5907 } else {
5908 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5909 if (err != ERR_NONE)
5910 return err;
5912 break;
5913 handle_ref:
5914 default:
5915 if (MONO_TYPE_IS_REFERENCE (t)) {
5916 if (type == MONO_TYPE_OBJECT) {
5917 int objid = decode_objid (buf, &buf, limit);
5918 ErrorCode err;
5919 MonoObject *obj;
5921 err = get_object (objid, (MonoObject**)&obj);
5922 if (err != ERR_NONE)
5923 return err;
5925 if (obj) {
5926 if (!obj_is_of_type (obj, t)) {
5927 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5928 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5929 return ERR_INVALID_ARGUMENT;
5933 if (obj && obj->vtable->domain != domain)
5934 return ERR_INVALID_ARGUMENT;
5936 mono_gc_wbarrier_generic_store_internal (addr, obj);
5937 } else if (type == VALUE_TYPE_ID_NULL) {
5938 *(MonoObject**)addr = NULL;
5939 } else if (type == MONO_TYPE_VALUETYPE) {
5940 ERROR_DECL (error);
5941 guint8 *buf2;
5942 gboolean is_enum;
5943 MonoClass *klass;
5944 MonoDomain *d;
5945 guint8 *vtype_buf;
5946 int vtype_buf_size;
5948 /* This can happen when round-tripping boxed vtypes */
5950 * Obtain vtype class.
5951 * Same as the beginning of the handle_vtype case above.
5953 buf2 = buf;
5954 is_enum = decode_byte (buf, &buf, limit);
5955 if (is_enum)
5956 return ERR_NOT_IMPLEMENTED;
5957 klass = decode_typeid (buf, &buf, limit, &d, &err);
5958 if (err != ERR_NONE)
5959 return err;
5961 /* Decode the vtype into a temporary buffer, then box it. */
5962 vtype_buf_size = mono_class_value_size (klass, NULL);
5963 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5964 g_assert (vtype_buf);
5966 buf = buf2;
5967 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5968 if (err != ERR_NONE) {
5969 g_free (vtype_buf);
5970 return err;
5972 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5973 mono_error_cleanup (error);
5974 g_free (vtype_buf);
5975 } else {
5976 char *name = mono_type_full_name (t);
5977 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5978 g_free (name);
5979 return ERR_INVALID_ARGUMENT;
5981 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5982 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5983 m_class_is_enumtype (t->data.generic_class->container_class)){
5984 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5985 if (err != ERR_NONE)
5986 return err;
5987 } else {
5988 NOT_IMPLEMENTED;
5990 break;
5994 *endbuf = buf;
5996 return ERR_NONE;
5999 static ErrorCode
6000 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
6002 guint8 *addr = (guint8*)void_addr;
6003 guint8 *buf = (guint8*)void_buf;
6005 ERROR_DECL (error);
6006 ErrorCode err;
6007 int type = decode_byte (buf, &buf, limit);
6009 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
6010 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6011 guint8 *nullable_buf;
6014 * First try decoding it as a Nullable`1
6016 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
6017 if (err == ERR_NONE)
6018 return err;
6021 * Then try decoding as a primitive value or null.
6023 if (targ->type == type) {
6024 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
6025 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
6026 if (err != ERR_NONE) {
6027 g_free (nullable_buf);
6028 return err;
6030 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
6031 if (!is_ok (error)) {
6032 mono_error_cleanup (error);
6033 return ERR_INVALID_OBJECT;
6035 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
6036 g_free (nullable_buf);
6037 *endbuf = buf;
6038 return ERR_NONE;
6039 } else if (type == VALUE_TYPE_ID_NULL) {
6040 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
6041 *endbuf = buf;
6042 return ERR_NONE;
6046 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
6049 static void
6050 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6052 guint32 flags;
6053 int reg;
6054 guint8 *addr, *gaddr;
6055 host_mgreg_t reg_val;
6057 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6058 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6060 switch (flags) {
6061 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6062 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6064 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
6065 break;
6066 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6067 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6068 addr += (gint32)var->offset;
6070 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6072 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6073 break;
6074 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6075 NOT_IMPLEMENTED;
6076 break;
6077 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6078 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6079 /* Same as regoffset, but with an indirection */
6080 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6081 addr += (gint32)var->offset;
6083 gaddr = (guint8 *)*(gpointer*)addr;
6084 g_assert (gaddr);
6085 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
6086 break;
6087 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6088 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6089 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6090 MonoGSharedVtMethodRuntimeInfo *info;
6091 guint8 *locals;
6092 int idx;
6094 idx = reg;
6096 g_assert (info_var);
6097 g_assert (locals_var);
6099 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6100 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6101 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6102 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6103 addr += (gint32)info_var->offset;
6104 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6105 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6106 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6107 } else {
6108 g_assert_not_reached ();
6110 g_assert (info);
6112 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6113 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6114 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6115 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6116 addr += (gint32)locals_var->offset;
6117 locals = (guint8 *)*(gpointer*)addr;
6118 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6119 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6120 } else {
6121 g_assert_not_reached ();
6123 g_assert (locals);
6125 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6127 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6128 break;
6131 default:
6132 g_assert_not_reached ();
6136 static void
6137 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
6139 guint32 flags;
6140 int reg, size;
6141 guint8 *addr, *gaddr;
6143 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6144 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6146 if (MONO_TYPE_IS_REFERENCE (t))
6147 size = sizeof (gpointer);
6148 else
6149 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6151 switch (flags) {
6152 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6153 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6154 host_mgreg_t v;
6155 gboolean is_signed = FALSE;
6157 if (t->byref) {
6158 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6160 if (addr) {
6161 // FIXME: Write barriers
6162 mono_gc_memmove_atomic (addr, val, size);
6164 break;
6167 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6168 is_signed = TRUE;
6170 switch (size) {
6171 case 1:
6172 v = is_signed ? *(gint8*)val : *(guint8*)val;
6173 break;
6174 case 2:
6175 v = is_signed ? *(gint16*)val : *(guint16*)val;
6176 break;
6177 case 4:
6178 v = is_signed ? *(gint32*)val : *(guint32*)val;
6179 break;
6180 case 8:
6181 v = is_signed ? *(gint64*)val : *(guint64*)val;
6182 break;
6183 default:
6184 g_assert_not_reached ();
6187 /* Set value on the stack or in the return ctx */
6188 if (reg_locations [reg]) {
6189 /* Saved on the stack */
6190 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6191 *(reg_locations [reg]) = v;
6192 } else {
6193 /* Not saved yet */
6194 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6195 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6198 // FIXME: Move these to mono-context.h/c.
6199 mono_arch_context_set_int_reg (ctx, reg, v);
6200 #else
6201 // FIXME: Can't set registers, so we disable linears
6202 NOT_IMPLEMENTED;
6203 #endif
6204 break;
6206 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6207 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6208 addr += (gint32)var->offset;
6210 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6212 if (t->byref) {
6213 addr = *(guint8**)addr;
6215 if (!addr)
6216 break;
6219 // FIXME: Write barriers
6220 mono_gc_memmove_atomic (addr, val, size);
6221 break;
6222 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6223 /* Same as regoffset, but with an indirection */
6224 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6225 addr += (gint32)var->offset;
6227 gaddr = (guint8 *)*(gpointer*)addr;
6228 g_assert (gaddr);
6229 // FIXME: Write barriers
6230 mono_gc_memmove_atomic (gaddr, val, size);
6231 break;
6232 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6233 NOT_IMPLEMENTED;
6234 break;
6235 default:
6236 g_assert_not_reached ();
6240 static void
6241 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6243 int size;
6245 if (t->byref) {
6246 addr = *(gpointer*)addr;
6247 g_assert (addr);
6250 if (MONO_TYPE_IS_REFERENCE (t))
6251 size = sizeof (gpointer);
6252 else
6253 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6255 memcpy (addr, val_buf, size);
6258 static void
6259 clear_event_request (int req_id, int etype)
6261 int i;
6263 mono_loader_lock ();
6264 for (i = 0; i < event_requests->len; ++i) {
6265 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6267 if (req->id == req_id && req->event_kind == etype) {
6268 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6269 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6270 if (req->event_kind == EVENT_KIND_STEP) {
6271 mono_de_cancel_ss ((SingleStepReq *)req->info);
6273 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6274 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6275 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6276 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6277 g_ptr_array_remove_index_fast (event_requests, i);
6278 g_free (req);
6279 break;
6282 mono_loader_unlock ();
6285 static void
6286 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6288 int i;
6290 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6291 m->kind = MOD_KIND_NONE;
6292 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6293 int count = 0, match_count = 0, pos;
6294 MonoAssembly **newassemblies;
6296 for (i = 0; m->data.assemblies [i]; ++i) {
6297 count ++;
6298 if (m->data.assemblies [i] == assembly)
6299 match_count ++;
6302 if (match_count) {
6303 // +1 because we don't know length and we use last element to check for end
6304 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6306 pos = 0;
6307 for (i = 0; i < count; ++i)
6308 if (m->data.assemblies [i] != assembly)
6309 newassemblies [pos ++] = m->data.assemblies [i];
6310 g_assert (pos == count - match_count);
6311 g_free (m->data.assemblies);
6312 m->data.assemblies = newassemblies;
6317 static void
6318 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6320 int i;
6322 for (i = 0; i < req->nmodifiers; ++i) {
6323 Modifier *m = &req->modifiers [i];
6325 clear_assembly_from_modifier (req, m, assembly);
6330 * clear_event_requests_for_assembly:
6332 * Clear all events requests which reference ASSEMBLY.
6334 static void
6335 clear_event_requests_for_assembly (MonoAssembly *assembly)
6337 int i;
6338 gboolean found;
6340 mono_loader_lock ();
6341 found = TRUE;
6342 while (found) {
6343 found = FALSE;
6344 for (i = 0; i < event_requests->len; ++i) {
6345 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6347 clear_assembly_from_modifiers (req, assembly);
6349 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6350 clear_event_request (req->id, req->event_kind);
6351 found = TRUE;
6352 break;
6355 if (req->event_kind == EVENT_KIND_STEP)
6356 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6359 mono_loader_unlock ();
6363 * type_comes_from_assembly:
6365 * GHRFunc that returns TRUE if klass comes from assembly
6367 static gboolean
6368 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6370 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6374 * clear_types_for_assembly:
6376 * Clears types from loaded_classes for a given assembly
6378 static void
6379 clear_types_for_assembly (MonoAssembly *assembly)
6381 MonoDomain *domain = mono_domain_get ();
6382 AgentDomainInfo *info = NULL;
6384 if (!domain || !domain_jit_info (domain))
6385 /* Can happen during shutdown */
6386 return;
6388 info = get_agent_domain_info (domain);
6390 mono_loader_lock ();
6391 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6392 mono_loader_unlock ();
6395 static void
6396 dispose_vm (void)
6398 /* Clear all event requests */
6399 mono_loader_lock ();
6400 while (event_requests->len > 0) {
6401 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6403 clear_event_request (req->id, req->event_kind);
6405 mono_loader_unlock ();
6407 while (suspend_count > 0)
6408 resume_vm ();
6409 disconnected = TRUE;
6410 vm_start_event_sent = FALSE;
6413 static void
6414 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6416 MonoThread *thread = (MonoThread *)value;
6417 gboolean *ret = (gboolean *)user_data;
6418 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6419 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6420 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6421 *ret = TRUE;
6422 return;
6427 static void
6428 add_thread (gpointer key, gpointer value, gpointer user_data)
6430 MonoThread *thread = (MonoThread *)value;
6431 Buffer *buf = (Buffer *)user_data;
6432 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6433 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6434 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6435 return;
6437 buffer_add_objid (buf, (MonoObject*)thread);
6441 static ErrorCode
6442 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6444 ERROR_DECL (error);
6445 guint8 *end = invoke->endp;
6446 MonoMethod *m;
6447 int i, nargs;
6448 ErrorCode err;
6449 MonoMethodSignature *sig;
6450 guint8 **arg_buf;
6451 void **args;
6452 MonoObject *this_arg, *res, *exc = NULL;
6453 MonoDomain *domain;
6454 guint8 *this_buf;
6455 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6456 MonoLMFExt ext;
6457 #endif
6458 MonoStopwatch watch;
6460 if (invoke->method) {
6462 * Invoke this method directly, currently only Environment.Exit () is supported.
6464 this_arg = NULL;
6465 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>");
6467 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6468 mono_error_assert_ok (error);
6469 g_assert_not_reached ();
6472 m = decode_methodid (p, &p, end, &domain, &err);
6473 if (err != ERR_NONE)
6474 return err;
6475 sig = mono_method_signature_internal (m);
6477 if (m_class_is_valuetype (m->klass))
6478 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6479 else
6480 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6482 if (m->is_generic) {
6483 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));
6484 return ERR_INVALID_ARGUMENT;
6485 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6486 /* Should be null */
6487 int type = decode_byte (p, &p, end);
6488 if (type != VALUE_TYPE_ID_NULL) {
6489 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6490 return ERR_INVALID_ARGUMENT;
6492 memset (this_buf, 0, mono_class_instance_size (m->klass));
6493 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6494 /* Could be null */
6495 guint8 *tmp_p;
6497 int type = decode_byte (p, &tmp_p, end);
6498 if (type == VALUE_TYPE_ID_NULL) {
6499 memset (this_buf, 0, mono_class_instance_size (m->klass));
6500 p = tmp_p;
6501 } else {
6502 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6503 if (err != ERR_NONE)
6504 return err;
6506 } else {
6507 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6508 if (err != ERR_NONE)
6509 return err;
6512 if (!m_class_is_valuetype (m->klass))
6513 this_arg = *(MonoObject**)this_buf;
6514 else
6515 this_arg = NULL;
6517 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6518 if (!this_arg) {
6519 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked 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 /* Transform this to the format the rest of the code expects it to be */
6524 if (m_class_is_valuetype (m->klass)) {
6525 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6526 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6528 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6529 if (!this_arg) {
6530 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6531 return ERR_INVALID_ARGUMENT;
6533 m = mono_object_get_virtual_method_internal (this_arg, m);
6534 if (m_class_is_valuetype (m->klass)) {
6535 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6536 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6540 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>");
6542 if (this_arg && this_arg->vtable->domain != domain)
6543 NOT_IMPLEMENTED;
6545 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6546 if (!strcmp (m->name, ".ctor")) {
6547 if (mono_class_is_abstract (m->klass))
6548 return ERR_INVALID_ARGUMENT;
6549 else {
6550 ERROR_DECL (error);
6551 this_arg = mono_object_new_checked (domain, m->klass, error);
6552 if (!is_ok (error)) {
6553 mono_error_cleanup (error);
6554 return ERR_INVALID_ARGUMENT;
6557 } else {
6558 return ERR_INVALID_ARGUMENT;
6562 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6563 return ERR_INVALID_ARGUMENT;
6565 nargs = decode_int (p, &p, end);
6566 if (nargs != sig->param_count)
6567 return ERR_INVALID_ARGUMENT;
6568 /* Use alloca to get gc tracking */
6569 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6570 memset (arg_buf, 0, nargs * sizeof (gpointer));
6571 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6572 for (i = 0; i < nargs; ++i) {
6573 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6574 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6575 if (err != ERR_NONE)
6576 break;
6577 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6578 NOT_IMPLEMENTED;
6580 if (sig->params [i]->byref) {
6581 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6582 *(gpointer*)arg_buf [i] = args [i];
6583 args [i] = arg_buf [i];
6585 } else {
6586 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6587 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6588 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6589 if (err != ERR_NONE)
6590 break;
6591 if (mono_class_is_nullable (arg_class)) {
6592 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6593 mono_error_assert_ok (error);
6594 } else {
6595 args [i] = arg_buf [i];
6600 if (i < nargs)
6601 return err;
6603 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6604 tls->disable_breakpoints = TRUE;
6605 else
6606 tls->disable_breakpoints = FALSE;
6609 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6611 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6612 if (invoke->has_ctx) {
6613 /* Setup our lmf */
6614 memset (&ext, 0, sizeof (ext));
6615 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6616 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6618 mono_push_lmf (&ext);
6620 #endif
6622 mono_stopwatch_start (&watch);
6623 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6624 if (!is_ok (error) && exc == NULL) {
6625 exc = (MonoObject*) mono_error_convert_to_exception (error);
6626 } else {
6627 mono_error_cleanup (error); /* FIXME report error */
6629 mono_stopwatch_stop (&watch);
6630 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));
6631 if (exc) {
6632 buffer_add_byte (buf, 0);
6633 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6634 } else {
6635 gboolean out_this = FALSE;
6636 gboolean out_args = FALSE;
6638 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6639 out_this = TRUE;
6640 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6641 out_args = TRUE;
6642 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6643 if (m->string_ctor) {
6644 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6645 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6646 if (!strcmp (m->name, ".ctor")) {
6647 if (!m_class_is_valuetype (m->klass))
6648 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6649 else
6650 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6651 } else {
6652 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6654 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6655 if (sig->ret->byref) {
6656 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6657 buffer_add_value (buf, ret_byval, &res, domain);
6658 } else {
6659 buffer_add_value (buf, sig->ret, &res, domain);
6661 } 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) {
6662 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6663 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6664 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6666 g_assert (nullable_buf);
6667 mono_nullable_init (nullable_buf, res, k);
6668 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6669 } else {
6670 g_assert (res);
6672 if (sig->ret->byref) {
6673 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6674 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6675 } else {
6676 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6679 } else {
6680 NOT_IMPLEMENTED;
6682 if (out_this)
6683 /* Return the new value of the receiver after the call */
6684 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6685 if (out_args) {
6686 buffer_add_int (buf, nargs);
6687 for (i = 0; i < nargs; ++i) {
6688 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6689 buffer_add_value (buf, sig->params [i], &args [i], domain);
6690 else if (sig->params [i]->byref)
6691 /* add_value () does an indirection */
6692 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6693 else
6694 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6699 tls->disable_breakpoints = FALSE;
6701 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6702 if (invoke->has_ctx)
6703 mono_pop_lmf ((MonoLMF*)&ext);
6704 #endif
6706 *endp = p;
6707 // FIXME: byref arguments
6708 // FIXME: varargs
6709 return ERR_NONE;
6713 * invoke_method:
6715 * Invoke the method given by tls->pending_invoke in the current thread.
6717 static void
6718 invoke_method (void)
6720 DebuggerTlsData *tls;
6721 InvokeData *invoke;
6722 int id;
6723 int i, mindex;
6724 ErrorCode err;
6725 Buffer buf;
6726 MonoContext restore_ctx;
6727 guint8 *p;
6729 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6730 g_assert (tls);
6733 * Store the `InvokeData *' in `tls->invoke' until we're done with
6734 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6737 mono_loader_lock ();
6739 invoke = tls->pending_invoke;
6740 g_assert (invoke);
6741 tls->pending_invoke = NULL;
6743 invoke->last_invoke = tls->invoke;
6744 tls->invoke = invoke;
6746 mono_loader_unlock ();
6748 tls->frames_up_to_date = FALSE;
6750 id = invoke->id;
6752 p = invoke->p;
6753 err = ERR_NONE;
6754 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6755 buffer_init (&buf, 128);
6757 if (err) {
6758 /* Fail the other invokes as well */
6759 } else {
6760 err = do_invoke_method (tls, &buf, invoke, p, &p);
6763 if (tls->abort_requested) {
6764 if (CHECK_PROTOCOL_VERSION (2, 42))
6765 err = ERR_INVOKE_ABORTED;
6768 /* Start suspending before sending the reply */
6769 if (mindex == invoke->nmethods - 1) {
6770 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6771 for (i = 0; i < invoke->suspend_count; ++i)
6772 suspend_vm ();
6776 send_reply_packet (id, err, &buf);
6778 buffer_free (&buf);
6781 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6783 if (invoke->has_ctx)
6784 save_thread_context (&restore_ctx);
6786 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6787 g_assert (tls->resume_count);
6788 tls->resume_count -= invoke->suspend_count;
6791 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6794 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6796 * It is possible that mono_thread_internal_abort () was called
6797 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6798 * because we reset the abort here.
6801 mono_loader_lock ();
6803 if (tls->abort_requested)
6804 mono_thread_internal_reset_abort (tls->thread);
6806 tls->invoke = tls->invoke->last_invoke;
6807 tls->abort_requested = FALSE;
6809 mono_loader_unlock ();
6811 g_free (invoke->p);
6812 g_free (invoke);
6815 static gboolean
6816 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6818 MonoThread *thread = (MonoThread *)value;
6819 DebuggerTlsData *tls;
6820 gboolean res;
6822 mono_loader_lock ();
6823 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6824 g_assert (tls);
6825 res = tls->really_suspended;
6826 mono_loader_unlock ();
6828 return res;
6831 static GPtrArray*
6832 get_source_files_for_type (MonoClass *klass)
6834 gpointer iter = NULL;
6835 MonoMethod *method;
6836 MonoDebugSourceInfo *sinfo;
6837 GPtrArray *files;
6838 int i, j;
6840 files = g_ptr_array_new ();
6842 while ((method = mono_class_get_methods (klass, &iter))) {
6843 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6844 GPtrArray *source_file_list;
6846 if (minfo) {
6847 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6848 for (j = 0; j < source_file_list->len; ++j) {
6849 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6850 for (i = 0; i < files->len; ++i)
6851 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6852 break;
6853 if (i == files->len)
6854 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6856 g_ptr_array_free (source_file_list, TRUE);
6860 return files;
6864 typedef struct {
6865 MonoTypeNameParse *info;
6866 gboolean ignore_case;
6867 GPtrArray *res_classes;
6868 GPtrArray *res_domains;
6869 } GetTypesArgs;
6871 static void
6872 get_types (gpointer key, gpointer value, gpointer user_data)
6874 MonoAssembly *ass;
6875 gboolean type_resolve;
6876 MonoType *t;
6877 GSList *tmp;
6878 MonoDomain *domain = (MonoDomain*)key;
6880 if (mono_domain_is_unloading (domain))
6881 return;
6883 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
6884 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6886 mono_domain_assemblies_lock (domain);
6887 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6888 ass = (MonoAssembly *)tmp->data;
6890 if (ass->image) {
6891 ERROR_DECL (probe_type_error);
6892 /* FIXME really okay to call while holding locks? */
6893 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6894 mono_error_cleanup (probe_type_error);
6895 if (t) {
6896 g_ptr_array_add (ud->res_classes, mono_type_get_class_internal (t));
6897 g_ptr_array_add (ud->res_domains, domain);
6901 mono_domain_assemblies_unlock (domain);
6904 typedef struct {
6905 gboolean ignore_case;
6906 char *basename;
6907 GPtrArray *res_classes;
6908 GPtrArray *res_domains;
6909 } GetTypesForSourceFileArgs;
6911 static void
6912 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6914 GHashTableIter iter;
6915 GSList *class_list = NULL;
6916 MonoClass *klass = NULL;
6917 GPtrArray *files = NULL;
6919 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6920 MonoDomain *domain = (MonoDomain*)key;
6922 if (mono_domain_is_unloading (domain))
6923 return;
6925 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6927 /* Update 'source_file_to_class' cache */
6928 g_hash_table_iter_init (&iter, info->loaded_classes);
6929 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6930 if (!g_hash_table_lookup (info->source_files, klass)) {
6931 files = get_source_files_for_type (klass);
6932 g_hash_table_insert (info->source_files, klass, files);
6934 for (int i = 0; i < files->len; ++i) {
6935 char *s = (char *)g_ptr_array_index (files, i);
6936 char *s2 = dbg_path_get_basename (s);
6937 char *s3;
6939 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6940 if (!class_list) {
6941 class_list = g_slist_prepend (class_list, klass);
6942 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6943 } else {
6944 class_list = g_slist_prepend (class_list, klass);
6945 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6948 /* The _ignorecase hash contains the lowercase path */
6949 s3 = strdup_tolower (s2);
6950 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6951 if (!class_list) {
6952 class_list = g_slist_prepend (class_list, klass);
6953 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6954 } else {
6955 class_list = g_slist_prepend (class_list, klass);
6956 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6959 g_free (s2);
6960 g_free (s3);
6965 if (ud->ignore_case) {
6966 char *s;
6968 s = strdup_tolower (ud->basename);
6969 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6970 g_free (s);
6971 } else {
6972 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6975 for (GSList *l = class_list; l; l = l->next) {
6976 klass = (MonoClass *)l->data;
6978 g_ptr_array_add (ud->res_classes, klass);
6979 g_ptr_array_add (ud->res_domains, domain);
6983 static void add_error_string (Buffer *buf, const char *str)
6985 if (CHECK_PROTOCOL_VERSION (2, 56))
6986 buffer_add_string (buf, str);
6989 static ErrorCode
6990 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6992 switch (command) {
6993 case CMD_VM_VERSION: {
6994 char *build_info, *version;
6996 build_info = mono_get_runtime_build_info ();
6997 version = g_strdup_printf ("mono %s", build_info);
6999 buffer_add_string (buf, version); /* vm version */
7000 buffer_add_int (buf, MAJOR_VERSION);
7001 buffer_add_int (buf, MINOR_VERSION);
7002 g_free (build_info);
7003 g_free (version);
7004 break;
7006 case CMD_VM_SET_PROTOCOL_VERSION: {
7007 major_version = decode_int (p, &p, end);
7008 minor_version = decode_int (p, &p, end);
7009 protocol_version_set = TRUE;
7010 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7011 break;
7013 case CMD_VM_ALL_THREADS: {
7014 // FIXME: Domains
7015 gboolean remove_gc_finalizing = FALSE;
7016 mono_loader_lock ();
7017 int count = mono_g_hash_table_size (tid_to_thread_obj);
7018 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
7019 if (remove_gc_finalizing)
7020 count--;
7021 buffer_add_int (buf, count);
7022 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7024 mono_loader_unlock ();
7025 break;
7027 case CMD_VM_SUSPEND:
7028 suspend_vm ();
7029 wait_for_suspend ();
7030 break;
7031 case CMD_VM_RESUME:
7032 if (suspend_count == 0)
7033 return ERR_NOT_SUSPENDED;
7034 resume_vm ();
7035 clear_suspended_objs ();
7036 break;
7037 case CMD_VM_DISPOSE:
7038 dispose_vm ();
7039 break;
7040 case CMD_VM_EXIT: {
7041 MonoInternalThread *thread;
7042 DebuggerTlsData *tls;
7043 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7044 MonoClass *env_class;
7045 #endif
7046 MonoMethod *exit_method = NULL;
7047 gpointer *args;
7048 int exit_code;
7050 exit_code = decode_int (p, &p, end);
7052 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7054 /* Have to send a reply before exiting */
7055 send_reply_packet (id, 0, buf);
7057 /* Clear all event requests */
7058 mono_loader_lock ();
7059 while (event_requests->len > 0) {
7060 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7062 clear_event_request (req->id, req->event_kind);
7064 mono_loader_unlock ();
7067 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7068 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7069 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7070 * better than doing the shutdown ourselves, since it avoids various races.
7073 suspend_vm ();
7074 wait_for_suspend ();
7076 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7077 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7078 if (env_class) {
7079 ERROR_DECL (error);
7080 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
7081 mono_error_assert_ok (error);
7083 #endif
7085 mono_loader_lock ();
7086 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7087 mono_loader_unlock ();
7089 if (thread && exit_method) {
7090 mono_loader_lock ();
7091 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7092 mono_loader_unlock ();
7094 args = g_new0 (gpointer, 1);
7095 args [0] = g_malloc (sizeof (int));
7096 *(int*)(args [0]) = exit_code;
7098 tls->pending_invoke = g_new0 (InvokeData, 1);
7099 tls->pending_invoke->method = exit_method;
7100 tls->pending_invoke->args = args;
7101 tls->pending_invoke->nmethods = 1;
7103 while (suspend_count > 0)
7104 resume_vm ();
7105 } else {
7107 * No thread found, do it ourselves.
7108 * FIXME: This can race with normal shutdown etc.
7110 while (suspend_count > 0)
7111 resume_vm ();
7113 if (!mono_runtime_try_shutdown ())
7114 break;
7116 mono_environment_exitcode_set (exit_code);
7118 /* Suspend all managed threads since the runtime is going away */
7119 #ifndef ENABLE_NETCORE
7120 DEBUG_PRINTF (1, "Suspending all threads...\n");
7121 mono_thread_suspend_all_other_threads ();
7122 #endif
7123 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7124 mono_runtime_quit_internal ();
7125 transport_close2 ();
7126 DEBUG_PRINTF (1, "Exiting...\n");
7128 exit (exit_code);
7130 break;
7132 case CMD_VM_INVOKE_METHOD:
7133 case CMD_VM_INVOKE_METHODS: {
7134 int objid = decode_objid (p, &p, end);
7135 MonoThread *thread;
7136 DebuggerTlsData *tls;
7137 int i, count, flags, nmethods;
7138 ErrorCode err;
7140 err = get_object (objid, (MonoObject**)&thread);
7141 if (err != ERR_NONE)
7142 return err;
7144 flags = decode_int (p, &p, end);
7146 if (command == CMD_VM_INVOKE_METHODS)
7147 nmethods = decode_int (p, &p, end);
7148 else
7149 nmethods = 1;
7151 // Wait for suspending if it already started
7152 if (suspend_count)
7153 wait_for_suspend ();
7154 if (!is_suspended ())
7155 return ERR_NOT_SUSPENDED;
7157 mono_loader_lock ();
7158 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7159 mono_loader_unlock ();
7160 g_assert (tls);
7162 if (!tls->really_suspended)
7163 /* The thread is still running native code, can't do invokes */
7164 return ERR_NOT_SUSPENDED;
7167 * Store the invoke data into tls, the thread will execute it after it is
7168 * resumed.
7170 if (tls->pending_invoke)
7171 return ERR_NOT_SUSPENDED;
7172 tls->pending_invoke = g_new0 (InvokeData, 1);
7173 tls->pending_invoke->id = id;
7174 tls->pending_invoke->flags = flags;
7175 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7176 memcpy (tls->pending_invoke->p, p, end - p);
7177 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7178 tls->pending_invoke->suspend_count = suspend_count;
7179 tls->pending_invoke->nmethods = nmethods;
7181 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7182 resume_thread (THREAD_TO_INTERNAL (thread));
7184 else {
7185 count = suspend_count;
7186 for (i = 0; i < count; ++i)
7187 resume_vm ();
7189 break;
7191 case CMD_VM_ABORT_INVOKE: {
7192 int objid = decode_objid (p, &p, end);
7193 MonoThread *thread;
7194 DebuggerTlsData *tls;
7195 int invoke_id;
7196 ErrorCode err;
7198 err = get_object (objid, (MonoObject**)&thread);
7199 if (err != ERR_NONE)
7200 return err;
7202 invoke_id = decode_int (p, &p, end);
7204 mono_loader_lock ();
7205 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7206 g_assert (tls);
7208 if (tls->abort_requested) {
7209 DEBUG_PRINTF (1, "Abort already requested.\n");
7210 mono_loader_unlock ();
7211 break;
7215 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7216 * actually the correct invocation.
7218 * Careful, we do not stop the thread that's doing the invocation, so we can't
7219 * inspect its stack. However, invoke_method() also acquires the loader lock
7220 * when it's done, so we're safe here.
7224 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7225 mono_loader_unlock ();
7226 return ERR_NO_INVOCATION;
7229 tls->abort_requested = TRUE;
7231 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7232 mono_loader_unlock ();
7233 break;
7236 case CMD_VM_SET_KEEPALIVE: {
7237 int timeout = decode_int (p, &p, end);
7238 agent_config.keepalive = timeout;
7239 // FIXME:
7240 #ifndef DISABLE_SOCKET_TRANSPORT
7241 set_keepalive ();
7242 #else
7243 NOT_IMPLEMENTED;
7244 #endif
7245 break;
7247 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7248 int i;
7249 char *fname, *basename;
7250 gboolean ignore_case;
7251 GPtrArray *res_classes, *res_domains;
7253 fname = decode_string (p, &p, end);
7254 ignore_case = decode_byte (p, &p, end);
7256 basename = dbg_path_get_basename (fname);
7258 res_classes = g_ptr_array_new ();
7259 res_domains = g_ptr_array_new ();
7261 mono_loader_lock ();
7262 GetTypesForSourceFileArgs args;
7263 memset (&args, 0, sizeof (args));
7264 args.ignore_case = ignore_case;
7265 args.basename = basename;
7266 args.res_classes = res_classes;
7267 args.res_domains = res_domains;
7268 mono_de_foreach_domain (get_types_for_source_file, &args);
7269 mono_loader_unlock ();
7271 g_free (fname);
7272 g_free (basename);
7274 buffer_add_int (buf, res_classes->len);
7275 for (i = 0; i < res_classes->len; ++i)
7276 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7277 g_ptr_array_free (res_classes, TRUE);
7278 g_ptr_array_free (res_domains, TRUE);
7279 break;
7281 case CMD_VM_GET_TYPES: {
7282 ERROR_DECL (error);
7283 int i;
7284 char *name;
7285 gboolean ignore_case;
7286 GPtrArray *res_classes, *res_domains;
7287 MonoTypeNameParse info;
7289 name = decode_string (p, &p, end);
7290 ignore_case = decode_byte (p, &p, end);
7292 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7293 add_error_string (buf, mono_error_get_message (error));
7294 mono_error_cleanup (error);
7295 g_free (name);
7296 mono_reflection_free_type_info (&info);
7297 return ERR_INVALID_ARGUMENT;
7300 res_classes = g_ptr_array_new ();
7301 res_domains = g_ptr_array_new ();
7303 mono_loader_lock ();
7305 GetTypesArgs args;
7306 memset (&args, 0, sizeof (args));
7307 args.info = &info;
7308 args.ignore_case = ignore_case;
7309 args.res_classes = res_classes;
7310 args.res_domains = res_domains;
7312 mono_de_foreach_domain (get_types, &args);
7314 mono_loader_unlock ();
7316 g_free (name);
7317 mono_reflection_free_type_info (&info);
7319 buffer_add_int (buf, res_classes->len);
7320 for (i = 0; i < res_classes->len; ++i)
7321 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7322 g_ptr_array_free (res_classes, TRUE);
7323 g_ptr_array_free (res_domains, TRUE);
7324 break;
7326 case CMD_VM_START_BUFFERING:
7327 case CMD_VM_STOP_BUFFERING:
7328 /* Handled in the main loop */
7329 break;
7330 default:
7331 return ERR_NOT_IMPLEMENTED;
7334 return ERR_NONE;
7337 static ErrorCode
7338 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7340 ErrorCode err;
7341 ERROR_DECL (error);
7343 switch (command) {
7344 case CMD_EVENT_REQUEST_SET: {
7345 EventRequest *req;
7346 int i, event_kind, suspend_policy, nmodifiers;
7347 ModifierKind mod;
7348 MonoMethod *method;
7349 long location = 0;
7350 MonoThread *step_thread;
7351 int step_thread_id = 0;
7352 StepDepth depth = STEP_DEPTH_INTO;
7353 StepSize size = STEP_SIZE_MIN;
7354 StepFilter filter = STEP_FILTER_NONE;
7355 MonoDomain *domain;
7356 Modifier *modifier;
7358 event_kind = decode_byte (p, &p, end);
7359 suspend_policy = decode_byte (p, &p, end);
7360 nmodifiers = decode_byte (p, &p, end);
7362 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7363 req->id = mono_atomic_inc_i32 (&event_request_id);
7364 req->event_kind = event_kind;
7365 req->suspend_policy = suspend_policy;
7366 req->nmodifiers = nmodifiers;
7368 method = NULL;
7369 for (i = 0; i < nmodifiers; ++i) {
7370 mod = (ModifierKind)decode_byte (p, &p, end);
7372 req->modifiers [i].kind = mod;
7373 if (mod == MOD_KIND_COUNT) {
7374 req->modifiers [i].data.count = decode_int (p, &p, end);
7375 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7376 method = decode_methodid (p, &p, end, &domain, &err);
7377 if (err != ERR_NONE)
7378 return err;
7379 location = decode_long (p, &p, end);
7380 } else if (mod == MOD_KIND_STEP) {
7381 step_thread_id = decode_id (p, &p, end);
7382 size = (StepSize)decode_int (p, &p, end);
7383 depth = (StepDepth)decode_int (p, &p, end);
7384 if (CHECK_PROTOCOL_VERSION (2, 16))
7385 filter = (StepFilter)decode_int (p, &p, end);
7386 req->modifiers [i].data.filter = filter;
7387 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7388 /* Treat STEP_THOUGH the same as HIDDEN */
7389 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7390 } else if (mod == MOD_KIND_THREAD_ONLY) {
7391 int id = decode_id (p, &p, end);
7393 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7394 if (err != ERR_NONE) {
7395 g_free (req);
7396 return err;
7398 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7399 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7401 if (err != ERR_NONE)
7402 return err;
7403 req->modifiers [i].caught = decode_byte (p, &p, end);
7404 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7405 if (CHECK_PROTOCOL_VERSION (2, 25))
7406 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7407 else
7408 req->modifiers [i].subclasses = TRUE;
7409 if (exc_class) {
7410 req->modifiers [i].data.exc_class = exc_class;
7412 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7413 g_free (req);
7414 return ERR_INVALID_ARGUMENT;
7417 if (CHECK_PROTOCOL_VERSION (2, 54)) {
7418 req->modifiers [i].not_filtered_feature = decode_byte (p, &p, end);
7419 req->modifiers [i].everything_else = decode_byte (p, &p, end);
7420 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" : "");
7421 } else {
7422 req->modifiers [i].not_filtered_feature = FALSE;
7423 req->modifiers [i].everything_else = FALSE;
7424 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" : "");
7427 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7428 int n = decode_int (p, &p, end);
7429 int j;
7431 // +1 because we don't know length and we use last element to check for end
7432 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7433 for (j = 0; j < n; ++j) {
7434 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7435 if (err != ERR_NONE) {
7436 g_free (req->modifiers [i].data.assemblies);
7437 return err;
7440 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7441 int n = decode_int (p, &p, end);
7442 int j;
7444 modifier = &req->modifiers [i];
7445 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7446 for (j = 0; j < n; ++j) {
7447 char *s = decode_string (p, &p, end);
7448 char *s2;
7450 if (s) {
7451 s2 = strdup_tolower (s);
7452 g_hash_table_insert (modifier->data.source_files, s2, s2);
7453 g_free (s);
7456 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7457 int n = decode_int (p, &p, end);
7458 int j;
7460 modifier = &req->modifiers [i];
7461 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7462 for (j = 0; j < n; ++j) {
7463 char *s = decode_string (p, &p, end);
7465 if (s)
7466 g_hash_table_insert (modifier->data.type_names, s, s);
7468 } else {
7469 g_free (req);
7470 return ERR_NOT_IMPLEMENTED;
7474 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7475 g_assert (method);
7477 req->info = mono_de_set_breakpoint (method, location, req, error);
7478 if (!is_ok (error)) {
7479 g_free (req);
7480 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7481 mono_error_cleanup (error);
7482 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7484 } else if (req->event_kind == EVENT_KIND_STEP) {
7485 g_assert (step_thread_id);
7487 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7488 if (err != ERR_NONE) {
7489 g_free (req);
7490 return err;
7493 mono_loader_lock ();
7494 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7495 mono_loader_unlock ();
7496 g_assert (tls);
7498 if (tls->terminated) {
7499 /* if the thread is already terminated ignore the single step */
7500 buffer_add_int (buf, req->id);
7501 return ERR_NONE;
7504 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7505 if (err != ERR_NONE) {
7506 g_free (req);
7507 return err;
7509 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7510 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7511 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7512 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7513 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7514 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7515 } else {
7516 if (req->nmodifiers) {
7517 g_free (req);
7518 return ERR_NOT_IMPLEMENTED;
7522 mono_loader_lock ();
7523 g_ptr_array_add (event_requests, req);
7525 if (agent_config.defer) {
7526 /* Transmit cached data to the client on receipt of the event request */
7527 switch (req->event_kind) {
7528 case EVENT_KIND_APPDOMAIN_CREATE:
7529 /* Emit load events for currently loaded domains */
7530 mono_de_foreach_domain (emit_appdomain_load, NULL);
7531 break;
7532 case EVENT_KIND_ASSEMBLY_LOAD:
7533 /* Emit load events for currently loaded assemblies */
7534 mono_domain_foreach (send_assemblies_for_domain, NULL);
7535 break;
7536 case EVENT_KIND_THREAD_START:
7537 /* Emit start events for currently started threads */
7538 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7539 break;
7540 case EVENT_KIND_TYPE_LOAD:
7541 /* Emit type load events for currently loaded types */
7542 mono_domain_foreach (send_types_for_domain, NULL);
7543 break;
7544 default:
7545 break;
7548 mono_loader_unlock ();
7550 buffer_add_int (buf, req->id);
7551 break;
7553 case CMD_EVENT_REQUEST_CLEAR: {
7554 int etype = decode_byte (p, &p, end);
7555 int req_id = decode_int (p, &p, end);
7557 // FIXME: Make a faster mapping from req_id to request
7558 mono_loader_lock ();
7559 clear_event_request (req_id, etype);
7560 mono_loader_unlock ();
7561 break;
7563 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7564 int i;
7566 mono_loader_lock ();
7567 i = 0;
7568 while (i < event_requests->len) {
7569 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7571 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7572 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7574 g_ptr_array_remove_index_fast (event_requests, i);
7575 g_free (req);
7576 } else {
7577 i ++;
7580 mono_loader_unlock ();
7581 break;
7583 default:
7584 return ERR_NOT_IMPLEMENTED;
7587 return ERR_NONE;
7590 static ErrorCode
7591 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7593 ErrorCode err;
7594 MonoDomain *domain;
7596 switch (command) {
7597 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7598 buffer_add_domainid (buf, mono_get_root_domain ());
7599 break;
7601 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7602 domain = decode_domainid (p, &p, end, NULL, &err);
7603 if (err != ERR_NONE)
7604 return err;
7605 buffer_add_string (buf, domain->friendly_name);
7606 break;
7608 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7609 GSList *tmp;
7610 MonoAssembly *ass;
7611 int count;
7613 domain = decode_domainid (p, &p, end, NULL, &err);
7614 if (err != ERR_NONE)
7615 return err;
7616 mono_domain_assemblies_lock (domain);
7617 count = 0;
7618 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7619 count ++;
7621 buffer_add_int (buf, count);
7622 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7623 ass = (MonoAssembly *)tmp->data;
7624 buffer_add_assemblyid (buf, domain, ass);
7626 mono_domain_assemblies_unlock (domain);
7627 break;
7629 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7630 domain = decode_domainid (p, &p, end, NULL, &err);
7631 if (err != ERR_NONE)
7632 return err;
7634 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7635 break;
7637 case CMD_APPDOMAIN_GET_CORLIB: {
7638 domain = decode_domainid (p, &p, end, NULL, &err);
7639 if (err != ERR_NONE)
7640 return err;
7642 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7643 break;
7645 case CMD_APPDOMAIN_CREATE_STRING: {
7646 char *s;
7647 MonoString *o;
7648 ERROR_DECL (error);
7650 domain = decode_domainid (p, &p, end, NULL, &err);
7651 if (err != ERR_NONE)
7652 return err;
7653 s = decode_string (p, &p, end);
7655 o = mono_string_new_checked (domain, s, error);
7656 if (!is_ok (error)) {
7657 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7658 mono_error_cleanup (error);
7659 return ERR_INVALID_OBJECT;
7661 buffer_add_objid (buf, (MonoObject*)o);
7662 break;
7664 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7665 ERROR_DECL (error);
7666 MonoArray *arr;
7667 gpointer elem;
7668 domain = decode_domainid (p, &p, end, NULL, &err);
7669 uintptr_t size = 0;
7670 int len = decode_int (p, &p, end);
7671 size = len;
7672 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7673 elem = mono_array_addr_internal (arr, guint8, 0);
7674 memcpy (elem, p, len);
7675 p += len;
7676 buffer_add_objid (buf, (MonoObject*) arr);
7677 break;
7679 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7680 ERROR_DECL (error);
7681 MonoClass *klass;
7682 MonoDomain *domain2;
7683 MonoObject *o;
7685 domain = decode_domainid (p, &p, end, NULL, &err);
7686 if (err != ERR_NONE)
7687 return err;
7688 klass = decode_typeid (p, &p, end, &domain2, &err);
7689 if (err != ERR_NONE)
7690 return err;
7692 // FIXME:
7693 g_assert (domain == domain2);
7695 o = mono_object_new_checked (domain, klass, error);
7696 mono_error_assert_ok (error);
7698 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7699 if (err != ERR_NONE)
7700 return err;
7702 buffer_add_objid (buf, o);
7703 break;
7705 default:
7706 return ERR_NOT_IMPLEMENTED;
7709 return ERR_NONE;
7712 static ErrorCode
7713 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7715 HANDLE_FUNCTION_ENTER();
7716 ErrorCode err = ERR_NONE;
7717 error_init (error);
7718 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7719 if (MONO_HANDLE_IS_NULL (o)) {
7720 err = ERR_INVALID_OBJECT;
7721 goto leave;
7723 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7724 leave:
7725 HANDLE_FUNCTION_RETURN_VAL (err);
7729 static ErrorCode
7730 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7732 ErrorCode err;
7733 MonoAssembly *ass;
7734 MonoDomain *domain;
7736 ass = decode_assemblyid (p, &p, end, &domain, &err);
7737 if (err != ERR_NONE)
7738 return err;
7740 switch (command) {
7741 case CMD_ASSEMBLY_GET_LOCATION: {
7742 buffer_add_string (buf, mono_image_get_filename (ass->image));
7743 break;
7745 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7746 guint32 token;
7747 MonoMethod *m;
7749 if (ass->image->dynamic) {
7750 buffer_add_id (buf, 0);
7751 } else {
7752 token = mono_image_get_entry_point (ass->image);
7753 if (token == 0) {
7754 buffer_add_id (buf, 0);
7755 } else {
7756 ERROR_DECL (error);
7757 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7758 if (!m)
7759 mono_error_cleanup (error); /* FIXME don't swallow the error */
7760 buffer_add_methodid (buf, domain, m);
7763 break;
7765 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7766 buffer_add_moduleid (buf, domain, ass->image);
7767 break;
7769 case CMD_ASSEMBLY_GET_OBJECT: {
7770 ERROR_DECL (error);
7771 err = get_assembly_object_command (domain, ass, buf, error);
7772 mono_error_cleanup (error);
7773 return err;
7775 case CMD_ASSEMBLY_GET_DOMAIN: {
7776 buffer_add_domainid (buf, domain);
7777 break;
7779 case CMD_ASSEMBLY_GET_TYPE: {
7780 ERROR_DECL (error);
7781 char *s = decode_string (p, &p, end);
7782 char* original_s = g_strdup_printf ("\"%s\"", s);
7784 gboolean ignorecase = decode_byte (p, &p, end);
7785 MonoTypeNameParse info;
7786 MonoType *t;
7787 gboolean type_resolve, res;
7788 MonoDomain *d = mono_domain_get ();
7789 MonoAssemblyLoadContext *alc = mono_domain_default_alc (d);
7791 /* This is needed to be able to find referenced assemblies */
7792 res = mono_domain_set_fast (domain, FALSE);
7793 g_assert (res);
7795 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7796 mono_error_cleanup (error);
7797 t = NULL;
7798 } else {
7799 if (info.assembly.name) {
7800 mono_reflection_free_type_info (&info);
7801 g_free (s);
7802 mono_domain_set_fast (d, TRUE);
7803 char* error_msg = g_strdup_printf ("Unexpected assembly-qualified type %s was provided", original_s);
7804 add_error_string (buf, error_msg);
7805 g_free (error_msg);
7806 g_free (original_s);
7807 return ERR_INVALID_ARGUMENT;
7809 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7810 if (!is_ok (error)) {
7811 mono_error_cleanup (error); /* FIXME don't swallow the error */
7812 mono_reflection_free_type_info (&info);
7813 g_free (s);
7814 mono_domain_set_fast (d, TRUE);
7815 char* error_msg = g_strdup_printf ("Invalid type name %s", original_s);
7816 add_error_string (buf, error_msg);
7817 g_free (error_msg);
7818 g_free (original_s);
7819 return ERR_INVALID_ARGUMENT;
7822 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7823 mono_reflection_free_type_info (&info);
7824 g_free (s);
7825 g_free (original_s);
7826 mono_domain_set_fast (d, TRUE);
7828 break;
7830 case CMD_ASSEMBLY_GET_NAME: {
7831 gchar *name;
7832 MonoAssembly *mass = ass;
7834 name = g_strdup_printf (
7835 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7836 mass->aname.name,
7837 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7838 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7839 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7840 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7842 buffer_add_string (buf, name);
7843 g_free (name);
7844 break;
7846 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7847 MonoImage* image = ass->image;
7848 if (ass->dynamic) {
7849 return ERR_NOT_IMPLEMENTED;
7851 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7852 break;
7854 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7855 buffer_add_byte (buf, ass->dynamic);
7856 break;
7858 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7859 MonoImage* image = ass->image;
7860 MonoDebugHandle* handle = mono_debug_get_handle (image);
7861 if (!handle) {
7862 return ERR_INVALID_ARGUMENT;
7864 MonoPPDBFile* ppdb = handle->ppdb;
7865 if (ppdb) {
7866 image = mono_ppdb_get_image (ppdb);
7867 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7868 } else {
7869 buffer_add_byte_array (buf, NULL, 0);
7871 break;
7873 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7874 if (ass->dynamic) {
7875 return ERR_NOT_IMPLEMENTED;
7877 guint32 token = decode_int (p, &p, end);
7878 ERROR_DECL (error);
7879 error_init (error);
7880 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7881 if (!is_ok (error)) {
7882 add_error_string (buf, mono_error_get_message (error));
7883 mono_error_cleanup (error);
7884 return ERR_INVALID_ARGUMENT;
7886 buffer_add_typeid (buf, domain, mono_class);
7887 mono_error_cleanup (error);
7888 break;
7890 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7891 if (ass->dynamic) {
7892 return ERR_NOT_IMPLEMENTED;
7894 guint32 token = decode_int (p, &p, end);
7895 ERROR_DECL (error);
7896 error_init (error);
7897 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7898 if (!is_ok (error)) {
7899 add_error_string (buf, mono_error_get_message (error));
7900 mono_error_cleanup (error);
7901 return ERR_INVALID_ARGUMENT;
7903 buffer_add_methodid (buf, domain, mono_method);
7904 mono_error_cleanup (error);
7905 break;
7907 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7908 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7909 break;
7911 default:
7912 return ERR_NOT_IMPLEMENTED;
7915 return ERR_NONE;
7918 static ErrorCode
7919 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7921 ErrorCode err;
7922 MonoDomain *domain;
7924 switch (command) {
7925 case CMD_MODULE_GET_INFO: {
7926 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7927 char *basename, *sourcelink = NULL;
7929 if (CHECK_PROTOCOL_VERSION (2, 48))
7930 sourcelink = mono_debug_image_get_sourcelink (image);
7932 basename = g_path_get_basename (image->name);
7933 buffer_add_string (buf, basename); // name
7934 buffer_add_string (buf, image->module_name); // scopename
7935 buffer_add_string (buf, image->name); // fqname
7936 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7937 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7938 if (CHECK_PROTOCOL_VERSION (2, 48))
7939 buffer_add_string (buf, sourcelink);
7940 g_free (basename);
7941 g_free (sourcelink);
7942 break;
7944 default:
7945 return ERR_NOT_IMPLEMENTED;
7948 return ERR_NONE;
7951 static ErrorCode
7952 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7954 ErrorCode err;
7955 MonoDomain *domain;
7957 switch (command) {
7958 case CMD_FIELD_GET_INFO: {
7959 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7961 buffer_add_string (buf, f->name);
7962 buffer_add_typeid (buf, domain, f->parent);
7963 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7964 buffer_add_int (buf, f->type->attrs);
7965 break;
7967 default:
7968 return ERR_NOT_IMPLEMENTED;
7971 return ERR_NONE;
7974 static void
7975 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7977 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7978 /* Special case these so the client doesn't have to handle Type objects */
7980 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7981 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
7982 } else if (MONO_TYPE_IS_REFERENCE (t))
7983 buffer_add_value (buf, t, &val, domain);
7984 else
7985 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
7988 static ErrorCode
7989 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7991 int i, j;
7992 int nattrs = 0;
7994 if (!cinfo) {
7995 buffer_add_int (buf, 0);
7996 return ERR_NONE;
7999 SETUP_ICALL_FUNCTION;
8001 for (i = 0; i < cinfo->num_attrs; ++i) {
8002 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8003 nattrs ++;
8005 buffer_add_int (buf, nattrs);
8007 for (i = 0; i < cinfo->num_attrs; ++i) {
8008 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8009 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8010 MonoArray *typed_args, *named_args;
8011 MonoArrayHandleOut typed_args_h, named_args_h;
8012 MonoObjectHandle val_h;
8013 MonoType *t;
8014 CattrNamedArg *arginfo = NULL;
8015 ERROR_DECL (error);
8017 SETUP_ICALL_FRAME;
8018 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
8019 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
8020 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
8022 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
8023 if (!is_ok (error)) {
8024 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
8025 mono_error_cleanup (error);
8026 CLEAR_ICALL_FRAME;
8027 return ERR_LOADER_ERROR;
8029 typed_args = MONO_HANDLE_RAW (typed_args_h);
8030 named_args = MONO_HANDLE_RAW (named_args_h);
8032 buffer_add_methodid (buf, domain, attr->ctor);
8034 /* Ctor args */
8035 if (typed_args) {
8036 buffer_add_int (buf, mono_array_length_internal (typed_args));
8037 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
8038 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
8039 MONO_HANDLE_ASSIGN_RAW (val_h, val);
8041 t = mono_method_signature_internal (attr->ctor)->params [j];
8043 buffer_add_cattr_arg (buf, t, domain, val);
8045 } else {
8046 buffer_add_int (buf, 0);
8049 /* Named args */
8050 if (named_args) {
8051 buffer_add_int (buf, mono_array_length_internal (named_args));
8053 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
8054 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
8055 MONO_HANDLE_ASSIGN_RAW (val_h, val);
8057 if (arginfo [j].prop) {
8058 buffer_add_byte (buf, 0x54);
8059 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8060 } else if (arginfo [j].field) {
8061 buffer_add_byte (buf, 0x53);
8062 buffer_add_fieldid (buf, domain, arginfo [j].field);
8063 } else {
8064 g_assert_not_reached ();
8067 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8069 } else {
8070 buffer_add_int (buf, 0);
8072 g_free (arginfo);
8074 CLEAR_ICALL_FRAME;
8078 return ERR_NONE;
8081 /* FIXME: Code duplication with icall.c */
8082 static void
8083 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8085 int i;
8086 MonoClass *ic;
8088 mono_class_setup_interfaces (klass, error);
8089 if (!is_ok (error))
8090 return;
8092 int klass_interface_count = m_class_get_interface_count (klass);
8093 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
8094 for (i = 0; i < klass_interface_count; i++) {
8095 ic = klass_interfaces [i];
8096 g_hash_table_insert (ifaces, ic, ic);
8098 collect_interfaces (ic, ifaces, error);
8099 if (!is_ok (error))
8100 return;
8104 static ErrorCode
8105 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8107 HANDLE_FUNCTION_ENTER ();
8109 ERROR_DECL (error);
8110 MonoClass *nested;
8111 MonoType *type;
8112 gpointer iter;
8113 guint8 b;
8114 int nnested;
8115 ErrorCode err;
8116 char *name;
8117 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
8119 switch (command) {
8120 case CMD_TYPE_GET_INFO: {
8121 buffer_add_string (buf, m_class_get_name_space (klass));
8122 buffer_add_string (buf, m_class_get_name (klass));
8123 // FIXME: byref
8124 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8125 buffer_add_string (buf, name);
8126 g_free (name);
8127 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
8128 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
8129 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
8130 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
8131 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
8132 else
8133 buffer_add_id (buf, 0);
8134 buffer_add_int (buf, m_class_get_type_token (klass));
8135 buffer_add_byte (buf, m_class_get_rank (klass));
8136 buffer_add_int (buf, mono_class_get_flags (klass));
8137 b = 0;
8138 type = m_class_get_byval_arg (klass);
8139 // FIXME: Can't decide whenever a class represents a byref type
8140 if (FALSE)
8141 b |= (1 << 0);
8142 if (type->type == MONO_TYPE_PTR)
8143 b |= (1 << 1);
8144 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8145 b |= (1 << 2);
8146 if (type->type == MONO_TYPE_VALUETYPE)
8147 b |= (1 << 3);
8148 if (m_class_is_enumtype (klass))
8149 b |= (1 << 4);
8150 if (mono_class_is_gtd (klass))
8151 b |= (1 << 5);
8152 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8153 b |= (1 << 6);
8154 buffer_add_byte (buf, b);
8155 nnested = 0;
8156 iter = NULL;
8157 while ((nested = mono_class_get_nested_types (klass, &iter)))
8158 nnested ++;
8159 buffer_add_int (buf, nnested);
8160 iter = NULL;
8161 while ((nested = mono_class_get_nested_types (klass, &iter)))
8162 buffer_add_typeid (buf, domain, nested);
8163 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8164 if (mono_class_is_gtd (klass))
8165 buffer_add_typeid (buf, domain, klass);
8166 else if (mono_class_is_ginst (klass))
8167 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8168 else
8169 buffer_add_id (buf, 0);
8171 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8172 int count, i;
8174 if (mono_class_is_ginst (klass)) {
8175 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8177 count = inst->type_argc;
8178 buffer_add_int (buf, count);
8179 for (i = 0; i < count; i++)
8180 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8181 } else if (mono_class_is_gtd (klass)) {
8182 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8183 MonoClass *pklass;
8185 count = container->type_argc;
8186 buffer_add_int (buf, count);
8187 for (i = 0; i < count; i++) {
8188 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8189 buffer_add_typeid (buf, domain, pklass);
8191 } else {
8192 buffer_add_int (buf, 0);
8195 break;
8197 case CMD_TYPE_GET_METHODS: {
8198 int nmethods;
8199 int i = 0;
8200 gpointer iter = NULL;
8201 MonoMethod *m;
8203 mono_class_setup_methods (klass);
8205 nmethods = mono_class_num_methods (klass);
8207 buffer_add_int (buf, nmethods);
8209 while ((m = mono_class_get_methods (klass, &iter))) {
8210 buffer_add_methodid (buf, domain, m);
8211 i ++;
8213 g_assert (i == nmethods);
8214 break;
8216 case CMD_TYPE_GET_FIELDS: {
8217 int nfields;
8218 int i = 0;
8219 gpointer iter = NULL;
8220 MonoClassField *f;
8222 nfields = mono_class_num_fields (klass);
8224 buffer_add_int (buf, nfields);
8226 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8227 buffer_add_fieldid (buf, domain, f);
8228 buffer_add_string (buf, f->name);
8229 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8230 buffer_add_int (buf, f->type->attrs);
8231 i ++;
8233 g_assert (i == nfields);
8234 break;
8236 case CMD_TYPE_GET_PROPERTIES: {
8237 int nprops;
8238 int i = 0;
8239 gpointer iter = NULL;
8240 MonoProperty *p;
8242 nprops = mono_class_num_properties (klass);
8244 buffer_add_int (buf, nprops);
8246 while ((p = mono_class_get_properties (klass, &iter))) {
8247 buffer_add_propertyid (buf, domain, p);
8248 buffer_add_string (buf, p->name);
8249 buffer_add_methodid (buf, domain, p->get);
8250 buffer_add_methodid (buf, domain, p->set);
8251 buffer_add_int (buf, p->attrs);
8252 i ++;
8254 g_assert (i == nprops);
8255 break;
8257 case CMD_TYPE_GET_CATTRS: {
8258 MonoClass *attr_klass;
8259 MonoCustomAttrInfo *cinfo;
8261 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8262 /* attr_klass can be NULL */
8263 if (err != ERR_NONE)
8264 goto exit;
8266 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8267 if (!is_ok (error)) {
8268 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8269 goto loader_error;
8272 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8273 if (err != ERR_NONE)
8274 goto exit;
8275 break;
8277 case CMD_TYPE_GET_FIELD_CATTRS: {
8278 MonoClass *attr_klass;
8279 MonoCustomAttrInfo *cinfo;
8280 MonoClassField *field;
8282 field = decode_fieldid (p, &p, end, NULL, &err);
8283 if (err != ERR_NONE)
8284 goto exit;
8285 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8286 if (err != ERR_NONE)
8287 goto exit;
8289 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8290 if (!is_ok (error)) {
8291 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8292 goto loader_error;
8295 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8296 if (err != ERR_NONE)
8297 goto exit;
8298 break;
8300 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8301 MonoClass *attr_klass;
8302 MonoCustomAttrInfo *cinfo;
8303 MonoProperty *prop;
8305 prop = decode_propertyid (p, &p, end, NULL, &err);
8306 if (err != ERR_NONE)
8307 goto exit;
8308 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8309 if (err != ERR_NONE)
8310 goto exit;
8312 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8313 if (!is_ok (error)) {
8314 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8315 goto loader_error;
8318 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8319 if (err != ERR_NONE)
8320 goto exit;
8321 break;
8323 case CMD_TYPE_GET_VALUES:
8324 case CMD_TYPE_GET_VALUES_2: {
8325 guint8 *val;
8326 MonoClassField *f;
8327 MonoVTable *vtable;
8328 MonoClass *k;
8329 int len, i;
8330 gboolean found;
8331 MonoThread *thread_obj;
8332 MonoInternalThread *thread = NULL;
8333 guint32 special_static_type;
8335 if (command == CMD_TYPE_GET_VALUES_2) {
8336 int objid = decode_objid (p, &p, end);
8338 err = get_object (objid, (MonoObject**)&thread_obj);
8339 if (err != ERR_NONE)
8340 goto exit;
8342 thread = THREAD_TO_INTERNAL (thread_obj);
8345 len = decode_int (p, &p, end);
8346 for (i = 0; i < len; ++i) {
8347 f = decode_fieldid (p, &p, end, NULL, &err);
8348 if (err != ERR_NONE)
8349 goto exit;
8351 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8352 goto invalid_fieldid;
8354 special_static_type = mono_class_field_get_special_static_type (f);
8355 if (special_static_type != SPECIAL_STATIC_NONE) {
8356 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8357 goto invalid_fieldid;
8360 /* Check that the field belongs to the object */
8361 found = FALSE;
8362 for (k = klass; k; k = m_class_get_parent (k)) {
8363 if (k == f->parent) {
8364 found = TRUE;
8365 break;
8368 if (!found)
8369 goto invalid_fieldid;
8371 vtable = mono_class_vtable_checked (domain, f->parent, error);
8372 goto_if_nok (error, invalid_fieldid);
8374 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8375 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, string_handle, error);
8376 goto_if_nok (error, invalid_fieldid);
8378 buffer_add_value (buf, f->type, val, domain);
8379 g_free (val);
8381 break;
8383 case CMD_TYPE_SET_VALUES: {
8384 guint8 *val;
8385 MonoClassField *f;
8386 MonoVTable *vtable;
8387 MonoClass *k;
8388 int len, i;
8389 gboolean found;
8391 len = decode_int (p, &p, end);
8392 for (i = 0; i < len; ++i) {
8393 f = decode_fieldid (p, &p, end, NULL, &err);
8394 if (err != ERR_NONE)
8395 goto exit;
8397 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8398 goto invalid_fieldid;
8400 if (mono_class_field_is_special_static (f))
8401 goto invalid_fieldid;
8403 /* Check that the field belongs to the object */
8404 found = FALSE;
8405 for (k = klass; k; k = m_class_get_parent (k)) {
8406 if (k == f->parent) {
8407 found = TRUE;
8408 break;
8411 if (!found)
8412 goto invalid_fieldid;
8414 // FIXME: Check for literal/const
8416 vtable = mono_class_vtable_checked (domain, f->parent, error);
8417 goto_if_nok (error, invalid_fieldid);
8419 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8420 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8421 if (err != ERR_NONE) {
8422 g_free (val);
8423 goto exit;
8425 if (MONO_TYPE_IS_REFERENCE (f->type))
8426 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8427 else
8428 mono_field_static_set_value_internal (vtable, f, val);
8429 g_free (val);
8431 break;
8433 case CMD_TYPE_GET_OBJECT: {
8434 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8435 if (!is_ok (error)) {
8436 mono_error_cleanup (error);
8437 goto invalid_object;
8439 buffer_add_objid (buf, o);
8440 break;
8442 case CMD_TYPE_GET_SOURCE_FILES:
8443 case CMD_TYPE_GET_SOURCE_FILES_2: {
8444 char *source_file, *base;
8445 GPtrArray *files;
8446 int i;
8448 files = get_source_files_for_type (klass);
8450 buffer_add_int (buf, files->len);
8451 for (i = 0; i < files->len; ++i) {
8452 source_file = (char *)g_ptr_array_index (files, i);
8453 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8454 buffer_add_string (buf, source_file);
8455 } else {
8456 base = dbg_path_get_basename (source_file);
8457 buffer_add_string (buf, base);
8458 g_free (base);
8460 g_free (source_file);
8462 g_ptr_array_free (files, TRUE);
8463 break;
8465 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8466 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8468 if (err != ERR_NONE)
8469 goto exit;
8470 if (mono_class_is_assignable_from_internal (klass, oklass))
8471 buffer_add_byte (buf, 1);
8472 else
8473 buffer_add_byte (buf, 0);
8474 break;
8476 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8477 char *name = decode_string (p, &p, end);
8478 int i, flags = decode_int (p, &p, end);
8479 int mlisttype;
8480 if (CHECK_PROTOCOL_VERSION (2, 48))
8481 mlisttype = decode_int (p, &p, end);
8482 else
8483 mlisttype = 0; // MLISTTYPE_All
8484 ERROR_DECL (error);
8485 GPtrArray *array;
8487 error_init (error);
8488 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8489 if (!is_ok (error)) {
8490 mono_error_cleanup (error);
8491 goto loader_error;
8493 buffer_add_int (buf, array->len);
8494 for (i = 0; i < array->len; ++i) {
8495 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8496 buffer_add_methodid (buf, domain, method);
8499 g_ptr_array_free (array, TRUE);
8500 g_free (name);
8501 break;
8503 case CMD_TYPE_GET_INTERFACES: {
8504 MonoClass *parent;
8505 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8506 MonoClass *tclass, *iface;
8507 GHashTableIter iter;
8509 tclass = klass;
8511 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8512 mono_class_setup_interfaces (parent, error);
8513 goto_if_nok (error, loader_error);
8515 collect_interfaces (parent, iface_hash, error);
8516 goto_if_nok (error, loader_error);
8519 buffer_add_int (buf, g_hash_table_size (iface_hash));
8521 g_hash_table_iter_init (&iter, iface_hash);
8522 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8523 buffer_add_typeid (buf, domain, iface);
8524 g_hash_table_destroy (iface_hash);
8525 break;
8527 case CMD_TYPE_GET_INTERFACE_MAP: {
8528 int tindex, ioffset;
8529 gboolean variance_used;
8530 MonoClass *iclass;
8531 int len, nmethods, i;
8532 gpointer iter;
8533 MonoMethod *method;
8535 len = decode_int (p, &p, end);
8536 mono_class_setup_vtable (klass);
8538 for (tindex = 0; tindex < len; ++tindex) {
8539 iclass = decode_typeid (p, &p, end, NULL, &err);
8540 if (err != ERR_NONE)
8541 goto exit;
8543 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8544 if (ioffset == -1)
8545 goto invalid_argument;
8547 nmethods = mono_class_num_methods (iclass);
8548 buffer_add_int (buf, nmethods);
8550 iter = NULL;
8551 while ((method = mono_class_get_methods (iclass, &iter))) {
8552 buffer_add_methodid (buf, domain, method);
8554 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8555 for (i = 0; i < nmethods; ++i)
8556 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8558 break;
8560 case CMD_TYPE_IS_INITIALIZED: {
8561 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8562 goto_if_nok (error, loader_error);
8564 if (vtable)
8565 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8566 else
8567 buffer_add_int (buf, 0);
8568 break;
8570 case CMD_TYPE_CREATE_INSTANCE: {
8571 ERROR_DECL (error);
8572 MonoObject *obj;
8574 obj = mono_object_new_checked (domain, klass, error);
8575 mono_error_assert_ok (error);
8576 buffer_add_objid (buf, obj);
8577 break;
8579 case CMD_TYPE_GET_VALUE_SIZE: {
8580 int32_t value_size;
8582 value_size = mono_class_value_size (klass, NULL);
8583 buffer_add_int (buf, value_size);
8584 break;
8586 default:
8587 err = ERR_NOT_IMPLEMENTED;
8588 goto exit;
8591 err = ERR_NONE;
8592 goto exit;
8593 invalid_argument:
8594 err = ERR_INVALID_ARGUMENT;
8595 goto exit;
8596 invalid_fieldid:
8597 err = ERR_INVALID_FIELDID;
8598 goto exit;
8599 invalid_object:
8600 err = ERR_INVALID_OBJECT;
8601 goto exit;
8602 loader_error:
8603 err = ERR_LOADER_ERROR;
8604 goto exit;
8605 exit:
8606 HANDLE_FUNCTION_RETURN_VAL (err);
8609 static ErrorCode
8610 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8612 MonoClass *klass;
8613 MonoDomain *old_domain;
8614 MonoDomain *domain;
8615 ErrorCode err;
8617 klass = decode_typeid (p, &p, end, &domain, &err);
8618 if (err != ERR_NONE)
8619 return err;
8621 old_domain = mono_domain_get ();
8623 mono_domain_set_fast (domain, TRUE);
8625 err = type_commands_internal (command, klass, domain, p, end, buf);
8627 mono_domain_set_fast (old_domain, TRUE);
8629 return err;
8632 static ErrorCode
8633 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8635 MonoMethodHeader *header;
8636 ErrorCode err;
8638 switch (command) {
8639 case CMD_METHOD_GET_NAME: {
8640 buffer_add_string (buf, method->name);
8641 break;
8643 case CMD_METHOD_GET_DECLARING_TYPE: {
8644 buffer_add_typeid (buf, domain, method->klass);
8645 break;
8647 case CMD_METHOD_GET_DEBUG_INFO: {
8648 ERROR_DECL (error);
8649 MonoDebugMethodInfo *minfo;
8650 char *source_file;
8651 int i, j, n_il_offsets;
8652 int *source_files;
8653 GPtrArray *source_file_list;
8654 MonoSymSeqPoint *sym_seq_points;
8656 header = mono_method_get_header_checked (method, error);
8657 if (!header) {
8658 mono_error_cleanup (error); /* FIXME don't swallow the error */
8659 buffer_add_int (buf, 0);
8660 buffer_add_string (buf, "");
8661 buffer_add_int (buf, 0);
8662 break;
8665 minfo = mono_debug_lookup_method (method);
8666 if (!minfo) {
8667 buffer_add_int (buf, header->code_size);
8668 buffer_add_string (buf, "");
8669 buffer_add_int (buf, 0);
8670 mono_metadata_free_mh (header);
8671 break;
8674 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8675 buffer_add_int (buf, header->code_size);
8676 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8677 buffer_add_int (buf, source_file_list->len);
8678 for (i = 0; i < source_file_list->len; ++i) {
8679 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8680 buffer_add_string (buf, sinfo->source_file);
8681 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8682 for (j = 0; j < 16; ++j)
8683 buffer_add_byte (buf, sinfo->hash [j]);
8686 } else {
8687 buffer_add_string (buf, source_file);
8689 buffer_add_int (buf, n_il_offsets);
8690 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8691 for (i = 0; i < n_il_offsets; ++i) {
8692 MonoSymSeqPoint *sp = &sym_seq_points [i];
8693 const char *srcfile = "";
8695 if (source_files [i] != -1) {
8696 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8697 srcfile = sinfo->source_file;
8699 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);
8700 buffer_add_int (buf, sp->il_offset);
8701 buffer_add_int (buf, sp->line);
8702 if (CHECK_PROTOCOL_VERSION (2, 13))
8703 buffer_add_int (buf, source_files [i]);
8704 if (CHECK_PROTOCOL_VERSION (2, 19))
8705 buffer_add_int (buf, sp->column);
8706 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8707 buffer_add_int (buf, sp->end_line);
8708 buffer_add_int (buf, sp->end_column);
8711 g_free (source_file);
8712 g_free (source_files);
8713 g_free (sym_seq_points);
8714 g_ptr_array_free (source_file_list, TRUE);
8715 mono_metadata_free_mh (header);
8716 break;
8718 case CMD_METHOD_GET_PARAM_INFO: {
8719 MonoMethodSignature *sig = mono_method_signature_internal (method);
8720 guint32 i;
8721 char **names;
8723 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8725 /* FIXME: Use a smaller encoding */
8726 buffer_add_int (buf, sig->call_convention);
8727 buffer_add_int (buf, sig->param_count);
8728 buffer_add_int (buf, sig->generic_param_count);
8729 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8730 for (i = 0; i < sig->param_count; ++i) {
8731 /* FIXME: vararg */
8732 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8735 /* Emit parameter names */
8736 names = g_new (char *, sig->param_count);
8737 mono_method_get_param_names (method, (const char **) names);
8738 for (i = 0; i < sig->param_count; ++i)
8739 buffer_add_string (buf, names [i]);
8740 g_free (names);
8742 break;
8744 case CMD_METHOD_GET_LOCALS_INFO: {
8745 ERROR_DECL (error);
8746 int i, num_locals;
8747 MonoDebugLocalsInfo *locals;
8748 int *locals_map = NULL;
8750 header = mono_method_get_header_checked (method, error);
8751 if (!header) {
8752 add_error_string (buf, mono_error_get_message (error));
8753 mono_error_cleanup (error); /* FIXME don't swallow the error */
8754 return ERR_INVALID_ARGUMENT;
8757 locals = mono_debug_lookup_locals (method);
8758 if (!locals) {
8759 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8760 /* Scopes */
8761 buffer_add_int (buf, 1);
8762 buffer_add_int (buf, 0);
8763 buffer_add_int (buf, header->code_size);
8765 buffer_add_int (buf, header->num_locals);
8766 /* Types */
8767 for (i = 0; i < header->num_locals; ++i) {
8768 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8770 /* Names */
8771 for (i = 0; i < header->num_locals; ++i) {
8772 char lname [128];
8773 sprintf (lname, "V_%d", i);
8774 buffer_add_string (buf, lname);
8776 /* Scopes */
8777 for (i = 0; i < header->num_locals; ++i) {
8778 buffer_add_int (buf, 0);
8779 buffer_add_int (buf, header->code_size);
8781 } else {
8782 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8783 /* Scopes */
8784 buffer_add_int (buf, locals->num_blocks);
8785 int last_start = 0;
8786 for (i = 0; i < locals->num_blocks; ++i) {
8787 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8788 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8789 last_start = locals->code_blocks [i].start_offset;
8793 num_locals = locals->num_locals;
8794 buffer_add_int (buf, num_locals);
8796 /* Types */
8797 for (i = 0; i < num_locals; ++i) {
8798 g_assert (locals->locals [i].index < header->num_locals);
8799 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8801 /* Names */
8802 for (i = 0; i < num_locals; ++i)
8803 buffer_add_string (buf, locals->locals [i].name);
8804 /* Scopes */
8805 for (i = 0; i < num_locals; ++i) {
8806 if (locals->locals [i].block) {
8807 buffer_add_int (buf, locals->locals [i].block->start_offset);
8808 buffer_add_int (buf, locals->locals [i].block->end_offset);
8809 } else {
8810 buffer_add_int (buf, 0);
8811 buffer_add_int (buf, header->code_size);
8815 mono_metadata_free_mh (header);
8817 if (locals)
8818 mono_debug_free_locals (locals);
8819 g_free (locals_map);
8821 break;
8823 case CMD_METHOD_GET_INFO:
8824 buffer_add_int (buf, method->flags);
8825 buffer_add_int (buf, method->iflags);
8826 buffer_add_int (buf, method->token);
8827 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8828 guint8 attrs = 0;
8829 if (method->is_generic)
8830 attrs |= (1 << 0);
8831 if (mono_method_signature_internal (method)->generic_param_count)
8832 attrs |= (1 << 1);
8833 buffer_add_byte (buf, attrs);
8834 if (method->is_generic || method->is_inflated) {
8835 MonoMethod *result;
8837 if (method->is_generic) {
8838 result = method;
8839 } else {
8840 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8842 result = imethod->declaring;
8843 if (imethod->context.class_inst) {
8844 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8845 /*Generic methods gets the context of the GTD.*/
8846 if (mono_class_get_context (klass)) {
8847 ERROR_DECL (error);
8848 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8849 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8854 buffer_add_methodid (buf, domain, result);
8855 } else {
8856 buffer_add_id (buf, 0);
8858 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8859 if (mono_method_signature_internal (method)->generic_param_count) {
8860 int count, i;
8862 if (method->is_inflated) {
8863 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8864 if (inst) {
8865 count = inst->type_argc;
8866 buffer_add_int (buf, count);
8868 for (i = 0; i < count; i++)
8869 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8870 } else {
8871 buffer_add_int (buf, 0);
8873 } else if (method->is_generic) {
8874 MonoGenericContainer *container = mono_method_get_generic_container (method);
8876 count = mono_method_signature_internal (method)->generic_param_count;
8877 buffer_add_int (buf, count);
8878 for (i = 0; i < count; i++) {
8879 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8880 MonoClass *pklass = mono_class_create_generic_parameter (param);
8881 buffer_add_typeid (buf, domain, pklass);
8883 } else {
8884 buffer_add_int (buf, 0);
8886 } else {
8887 buffer_add_int (buf, 0);
8891 break;
8892 case CMD_METHOD_GET_BODY: {
8893 ERROR_DECL (error);
8894 int i;
8896 header = mono_method_get_header_checked (method, error);
8897 if (!header) {
8898 mono_error_cleanup (error); /* FIXME don't swallow the error */
8899 buffer_add_int (buf, 0);
8901 if (CHECK_PROTOCOL_VERSION (2, 18))
8902 buffer_add_int (buf, 0);
8903 } else {
8904 buffer_add_int (buf, header->code_size);
8905 for (i = 0; i < header->code_size; ++i)
8906 buffer_add_byte (buf, header->code [i]);
8908 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8909 buffer_add_int (buf, header->num_clauses);
8910 for (i = 0; i < header->num_clauses; ++i) {
8911 MonoExceptionClause *clause = &header->clauses [i];
8913 buffer_add_int (buf, clause->flags);
8914 buffer_add_int (buf, clause->try_offset);
8915 buffer_add_int (buf, clause->try_len);
8916 buffer_add_int (buf, clause->handler_offset);
8917 buffer_add_int (buf, clause->handler_len);
8918 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8919 buffer_add_typeid (buf, domain, clause->data.catch_class);
8920 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8921 buffer_add_int (buf, clause->data.filter_offset);
8925 mono_metadata_free_mh (header);
8928 break;
8930 case CMD_METHOD_RESOLVE_TOKEN: {
8931 guint32 token = decode_int (p, &p, end);
8933 // FIXME: Generics
8934 switch (mono_metadata_token_code (token)) {
8935 case MONO_TOKEN_STRING: {
8936 ERROR_DECL (error);
8937 MonoString *s;
8938 char *s2;
8940 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8941 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8943 s2 = mono_string_to_utf8_checked_internal (s, error);
8944 mono_error_assert_ok (error);
8946 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8947 buffer_add_string (buf, s2);
8948 g_free (s2);
8949 break;
8951 default: {
8952 ERROR_DECL (error);
8953 gpointer val;
8954 MonoClass *handle_class;
8956 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8957 val = mono_method_get_wrapper_data (method, token);
8958 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8960 if (handle_class == NULL) {
8961 // Can't figure out the token type
8962 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8963 break;
8965 } else {
8966 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8967 if (!val)
8968 g_error ("Could not load token due to %s", mono_error_get_message (error));
8971 if (handle_class == mono_defaults.typehandle_class) {
8972 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8973 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8974 buffer_add_typeid (buf, domain, (MonoClass *) val);
8975 else
8976 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8977 } else if (handle_class == mono_defaults.fieldhandle_class) {
8978 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8979 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8980 } else if (handle_class == mono_defaults.methodhandle_class) {
8981 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8982 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8983 } else if (handle_class == mono_defaults.string_class) {
8984 char *s;
8986 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8987 mono_error_assert_ok (error);
8988 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8989 buffer_add_string (buf, s);
8990 g_free (s);
8991 } else {
8992 g_assert_not_reached ();
8994 break;
8997 break;
8999 case CMD_METHOD_GET_CATTRS: {
9000 ERROR_DECL (error);
9001 MonoClass *attr_klass;
9002 MonoCustomAttrInfo *cinfo;
9004 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9005 /* attr_klass can be NULL */
9006 if (err != ERR_NONE)
9007 return err;
9009 cinfo = mono_custom_attrs_from_method_checked (method, error);
9010 if (!is_ok (error)) {
9011 mono_error_cleanup (error); /* FIXME don't swallow the error message */
9012 return ERR_LOADER_ERROR;
9015 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
9016 if (err != ERR_NONE)
9017 return err;
9018 break;
9020 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9021 ERROR_DECL (error);
9022 MonoType **type_argv;
9023 int i, type_argc;
9024 MonoDomain *d;
9025 MonoClass *klass;
9026 MonoGenericInst *ginst;
9027 MonoGenericContext tmp_context;
9028 MonoMethod *inflated;
9030 type_argc = decode_int (p, &p, end);
9031 type_argv = g_new0 (MonoType*, type_argc);
9032 for (i = 0; i < type_argc; ++i) {
9033 klass = decode_typeid (p, &p, end, &d, &err);
9034 if (err != ERR_NONE) {
9035 g_free (type_argv);
9036 return err;
9038 if (domain != d) {
9039 g_free (type_argv);
9040 return ERR_INVALID_ARGUMENT;
9042 type_argv [i] = m_class_get_byval_arg (klass);
9044 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9045 g_free (type_argv);
9046 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9047 tmp_context.method_inst = ginst;
9049 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
9050 g_assert (is_ok (error)); /* FIXME don't swallow the error */
9051 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9052 return ERR_INVALID_ARGUMENT;
9053 buffer_add_methodid (buf, domain, inflated);
9054 break;
9056 default:
9057 return ERR_NOT_IMPLEMENTED;
9060 return ERR_NONE;
9063 static ErrorCode
9064 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9066 ErrorCode err;
9067 MonoDomain *old_domain;
9068 MonoDomain *domain;
9069 MonoMethod *method;
9071 method = decode_methodid (p, &p, end, &domain, &err);
9072 if (err != ERR_NONE)
9073 return err;
9075 old_domain = mono_domain_get ();
9077 mono_domain_set_fast (domain, TRUE);
9079 err = method_commands_internal (command, method, domain, p, end, buf);
9081 mono_domain_set_fast (old_domain, TRUE);
9083 return err;
9086 static ErrorCode
9087 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9089 int objid = decode_objid (p, &p, end);
9090 ErrorCode err;
9091 MonoThread *thread_obj;
9092 MonoInternalThread *thread;
9094 err = get_object (objid, (MonoObject**)&thread_obj);
9095 if (err != ERR_NONE)
9096 return err;
9098 thread = THREAD_TO_INTERNAL (thread_obj);
9100 switch (command) {
9101 case CMD_THREAD_GET_NAME: {
9102 char *s = mono_thread_get_name_utf8 (thread_obj);
9104 if (!s) {
9105 buffer_add_int (buf, 0);
9106 } else {
9107 const size_t len = strlen (s);
9108 buffer_add_int (buf, len);
9109 buffer_add_data (buf, (guint8*)s, len);
9110 g_free (s);
9112 break;
9114 case CMD_THREAD_GET_FRAME_INFO: {
9115 DebuggerTlsData *tls;
9116 int i, start_frame, length;
9118 // Wait for suspending if it already started
9119 // FIXME: Races with suspend_count
9120 while (!is_suspended ()) {
9121 if (suspend_count)
9122 wait_for_suspend ();
9125 if (suspend_count)
9126 wait_for_suspend ();
9127 if (!is_suspended ())
9128 return ERR_NOT_SUSPENDED;
9131 start_frame = decode_int (p, &p, end);
9132 length = decode_int (p, &p, end);
9134 if (start_frame != 0 || length != -1)
9135 return ERR_NOT_IMPLEMENTED;
9137 mono_loader_lock ();
9138 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9139 mono_loader_unlock ();
9140 if (tls == NULL)
9141 return ERR_UNLOADED;
9143 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
9145 buffer_add_int (buf, tls->frame_count);
9146 for (i = 0; i < tls->frame_count; ++i) {
9147 buffer_add_int (buf, tls->frames [i]->id);
9148 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
9149 buffer_add_int (buf, tls->frames [i]->il_offset);
9151 * Instead of passing the frame type directly to the client, we associate
9152 * it with the previous frame using a set of flags. This avoids lots of
9153 * conditional code in the client, since a frame whose type isn't
9154 * FRAME_TYPE_MANAGED has no method, location, etc.
9156 buffer_add_byte (buf, tls->frames [i]->flags);
9159 break;
9161 case CMD_THREAD_GET_STATE:
9162 buffer_add_int (buf, thread->state);
9163 break;
9164 case CMD_THREAD_GET_INFO:
9165 buffer_add_byte (buf, thread->threadpool_thread);
9166 break;
9167 case CMD_THREAD_GET_ID:
9168 buffer_add_long (buf, (guint64)(gsize)thread);
9169 break;
9170 case CMD_THREAD_GET_TID:
9171 buffer_add_long (buf, (guint64)thread->tid);
9172 break;
9173 case CMD_THREAD_SET_IP: {
9174 DebuggerTlsData *tls;
9175 MonoMethod *method;
9176 MonoDomain *domain;
9177 MonoSeqPointInfo *seq_points;
9178 SeqPoint sp;
9179 gboolean found_sp;
9180 gint64 il_offset;
9182 method = decode_methodid (p, &p, end, &domain, &err);
9183 if (err != ERR_NONE)
9184 return err;
9185 il_offset = decode_long (p, &p, end);
9187 while (!is_suspended ()) {
9188 if (suspend_count)
9189 wait_for_suspend ();
9192 mono_loader_lock ();
9193 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9194 mono_loader_unlock ();
9195 g_assert (tls);
9197 compute_frame_info (thread, tls, FALSE);
9198 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9199 return ERR_INVALID_ARGUMENT;
9201 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9203 g_assert (seq_points);
9205 if (!found_sp)
9206 return ERR_INVALID_ARGUMENT;
9208 // FIXME: Check that the ip change is safe
9210 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);
9212 if (tls->frames [0]->de.ji->is_interp) {
9213 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
9214 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);
9215 } else {
9216 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9218 break;
9220 case CMD_THREAD_ELAPSED_TIME: {
9221 DebuggerTlsData *tls;
9222 mono_loader_lock ();
9223 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9224 mono_loader_unlock ();
9225 g_assert (tls);
9226 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9227 break;
9229 default:
9230 return ERR_NOT_IMPLEMENTED;
9233 return ERR_NONE;
9236 static ErrorCode
9237 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9239 int objid;
9240 ErrorCode err;
9241 MonoThread *thread_obj;
9242 MonoInternalThread *thread;
9243 int pos, i, len, frame_idx;
9244 DebuggerTlsData *tls;
9245 StackFrame *frame;
9246 MonoDebugMethodJitInfo *jit;
9247 MonoMethodSignature *sig;
9248 gssize id;
9249 MonoMethodHeader *header;
9251 objid = decode_objid (p, &p, end);
9252 err = get_object (objid, (MonoObject**)&thread_obj);
9253 if (err != ERR_NONE)
9254 return err;
9256 thread = THREAD_TO_INTERNAL (thread_obj);
9258 id = decode_id (p, &p, end);
9260 mono_loader_lock ();
9261 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9262 mono_loader_unlock ();
9263 g_assert (tls);
9265 for (i = 0; i < tls->frame_count; ++i) {
9266 if (tls->frames [i]->id == id)
9267 break;
9269 if (i == tls->frame_count)
9270 return ERR_INVALID_FRAMEID;
9272 /* The thread is still running native code, can't get frame variables info */
9273 if (!tls->really_suspended && !tls->async_state.valid)
9274 return ERR_NOT_SUSPENDED;
9275 frame_idx = i;
9276 frame = tls->frames [frame_idx];
9278 /* This is supported for frames without has_ctx etc. set */
9279 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9280 if (CHECK_PROTOCOL_VERSION (2, 38))
9281 buffer_add_domainid (buf, frame->de.domain);
9282 return ERR_NONE;
9285 if (!frame->has_ctx)
9286 return ERR_ABSENT_INFORMATION;
9288 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9289 return ERR_ABSENT_INFORMATION;
9291 jit = frame->jit;
9293 sig = mono_method_signature_internal (frame->actual_method);
9295 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9297 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9299 return ERR_ABSENT_INFORMATION;
9301 switch (command) {
9302 case CMD_STACK_FRAME_GET_VALUES: {
9303 ERROR_DECL (error);
9304 len = decode_int (p, &p, end);
9305 header = mono_method_get_header_checked (frame->actual_method, error);
9306 mono_error_assert_ok (error); /* FIXME report error */
9308 for (i = 0; i < len; ++i) {
9309 pos = decode_int (p, &p, end);
9311 if (pos < 0) {
9312 pos = - pos - 1;
9314 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9316 if (frame->de.ji->is_interp) {
9317 guint8 *addr;
9319 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9321 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9322 } else {
9323 g_assert (pos >= 0 && pos < jit->num_params);
9325 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9327 } else {
9328 MonoDebugLocalsInfo *locals;
9330 locals = mono_debug_lookup_locals (frame->de.method);
9331 if (locals) {
9332 g_assert (pos < locals->num_locals);
9333 pos = locals->locals [pos].index;
9334 mono_debug_free_locals (locals);
9337 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9339 if (frame->de.ji->is_interp) {
9340 guint8 *addr;
9342 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9344 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9345 } else {
9346 g_assert (pos >= 0 && pos < jit->num_locals);
9348 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9352 mono_metadata_free_mh (header);
9353 break;
9355 case CMD_STACK_FRAME_GET_THIS: {
9356 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9357 return ERR_ABSENT_INFORMATION;
9358 if (m_class_is_valuetype (frame->api_method->klass)) {
9359 if (!sig->hasthis) {
9360 MonoObject *p = NULL;
9361 buffer_add_value (buf, mono_get_object_type (), &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_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9369 } else {
9370 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9373 } else {
9374 if (!sig->hasthis) {
9375 MonoObject *p = NULL;
9376 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9377 } else {
9378 if (frame->de.ji->is_interp) {
9379 guint8 *addr;
9381 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9383 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9384 } else {
9385 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9389 break;
9391 case CMD_STACK_FRAME_SET_VALUES: {
9392 ERROR_DECL (error);
9393 guint8 *val_buf;
9394 MonoType *t;
9395 MonoDebugVarInfo *var = NULL;
9396 gboolean is_arg = FALSE;
9398 len = decode_int (p, &p, end);
9399 header = mono_method_get_header_checked (frame->actual_method, error);
9400 mono_error_assert_ok (error); /* FIXME report error */
9402 for (i = 0; i < len; ++i) {
9403 pos = decode_int (p, &p, end);
9405 if (pos < 0) {
9406 pos = - pos - 1;
9408 g_assert (pos >= 0 && pos < jit->num_params);
9410 t = sig->params [pos];
9411 var = &jit->params [pos];
9412 is_arg = TRUE;
9413 } else {
9414 MonoDebugLocalsInfo *locals;
9416 locals = mono_debug_lookup_locals (frame->de.method);
9417 if (locals) {
9418 g_assert (pos < locals->num_locals);
9419 pos = locals->locals [pos].index;
9420 mono_debug_free_locals (locals);
9422 g_assert (pos >= 0 && pos < jit->num_locals);
9424 t = header->locals [pos];
9425 var = &jit->locals [pos];
9428 if (MONO_TYPE_IS_REFERENCE (t))
9429 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9430 else
9431 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9432 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9433 if (err != ERR_NONE)
9434 return err;
9436 if (frame->de.ji->is_interp) {
9437 guint8 *addr;
9439 if (is_arg)
9440 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9441 else
9442 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9443 set_interp_var (t, addr, val_buf);
9444 } else {
9445 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9448 mono_metadata_free_mh (header);
9449 break;
9451 case CMD_STACK_FRAME_GET_DOMAIN: {
9452 if (CHECK_PROTOCOL_VERSION (2, 38))
9453 buffer_add_domainid (buf, frame->de.domain);
9454 break;
9456 case CMD_STACK_FRAME_SET_THIS: {
9457 guint8 *val_buf;
9458 MonoType *t;
9459 MonoDebugVarInfo *var;
9461 t = m_class_get_byval_arg (frame->actual_method->klass);
9462 /* Checked by the sender */
9463 g_assert (MONO_TYPE_ISSTRUCT (t));
9465 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9466 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9467 if (err != ERR_NONE)
9468 return err;
9470 if (frame->de.ji->is_interp) {
9471 guint8 *addr;
9473 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9474 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9475 } else {
9476 var = jit->this_var;
9477 g_assert (var);
9479 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);
9481 break;
9483 default:
9484 return ERR_NOT_IMPLEMENTED;
9487 return ERR_NONE;
9490 static ErrorCode
9491 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9493 MonoArray *arr;
9494 int objid, index, len, i, esize;
9495 ErrorCode err;
9496 gpointer elem;
9498 objid = decode_objid (p, &p, end);
9499 err = get_object (objid, (MonoObject**)&arr);
9500 if (err != ERR_NONE)
9501 return err;
9503 switch (command) {
9504 case CMD_ARRAY_REF_GET_LENGTH:
9505 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9506 if (!arr->bounds) {
9507 buffer_add_int (buf, arr->max_length);
9508 buffer_add_int (buf, 0);
9509 } else {
9510 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9511 buffer_add_int (buf, arr->bounds [i].length);
9512 buffer_add_int (buf, arr->bounds [i].lower_bound);
9515 break;
9516 case CMD_ARRAY_REF_GET_VALUES:
9517 index = decode_int (p, &p, end);
9518 len = decode_int (p, &p, end);
9520 g_assert (index >= 0 && len >= 0);
9521 // Reordered to avoid integer overflow
9522 g_assert (!(index > arr->max_length - len));
9524 esize = mono_array_element_size (arr->obj.vtable->klass);
9525 for (i = index; i < index + len; ++i) {
9526 elem = (gpointer*)((char*)arr->vector + (i * esize));
9527 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9529 break;
9530 case CMD_ARRAY_REF_SET_VALUES:
9531 index = decode_int (p, &p, end);
9532 len = decode_int (p, &p, end);
9534 g_assert (index >= 0 && len >= 0);
9535 // Reordered to avoid integer overflow
9536 g_assert (!(index > arr->max_length - len));
9538 esize = mono_array_element_size (arr->obj.vtable->klass);
9539 for (i = index; i < index + len; ++i) {
9540 elem = (gpointer*)((char*)arr->vector + (i * esize));
9542 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);
9544 break;
9545 default:
9546 return ERR_NOT_IMPLEMENTED;
9549 return ERR_NONE;
9552 static ErrorCode
9553 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9555 int objid;
9556 ErrorCode err;
9557 MonoString *str;
9558 char *s;
9559 int i, index, length;
9560 gunichar2 *c;
9561 gboolean use_utf16 = FALSE;
9563 objid = decode_objid (p, &p, end);
9564 err = get_object (objid, (MonoObject**)&str);
9565 if (err != ERR_NONE)
9566 return err;
9568 switch (command) {
9569 case CMD_STRING_REF_GET_VALUE:
9570 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9571 for (i = 0; i < mono_string_length_internal (str); ++i)
9572 if (mono_string_chars_internal (str)[i] == 0)
9573 use_utf16 = TRUE;
9574 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9576 if (use_utf16) {
9577 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9578 buffer_add_data (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9579 } else {
9580 ERROR_DECL (error);
9581 s = mono_string_to_utf8_checked_internal (str, error);
9582 if (!is_ok (error)) {
9583 if (s)
9584 g_free (s);
9585 add_error_string (buf, mono_error_get_message (error));
9586 return ERR_INVALID_ARGUMENT;
9588 buffer_add_string (buf, s);
9589 g_free (s);
9591 break;
9592 case CMD_STRING_REF_GET_LENGTH:
9593 buffer_add_long (buf, mono_string_length_internal (str));
9594 break;
9595 case CMD_STRING_REF_GET_CHARS:
9596 index = decode_long (p, &p, end);
9597 length = decode_long (p, &p, end);
9598 if (index > mono_string_length_internal (str) - length)
9599 return ERR_INVALID_ARGUMENT;
9600 c = mono_string_chars_internal (str) + index;
9601 for (i = 0; i < length; ++i)
9602 buffer_add_short (buf, c [i]);
9603 break;
9604 default:
9605 return ERR_NOT_IMPLEMENTED;
9608 return ERR_NONE;
9611 static void
9612 create_file_to_check_memory_address (void)
9614 if (file_check_valid_memory != -1)
9615 return;
9616 char *file_name = g_strdup_printf ("debugger_check_valid_memory.%d", getpid());
9617 filename_check_valid_memory = g_build_filename (g_get_tmp_dir (), file_name, (const char*)NULL);
9618 file_check_valid_memory = open(filename_check_valid_memory, O_CREAT | O_WRONLY | O_APPEND, S_IWUSR);
9619 g_free (file_name);
9622 static gboolean
9623 valid_memory_address (gpointer addr, gint size)
9625 #ifndef _MSC_VER
9626 gboolean ret = TRUE;
9627 create_file_to_check_memory_address ();
9628 if(file_check_valid_memory < 0) {
9629 return TRUE;
9631 write (file_check_valid_memory, (gpointer)addr, 1);
9632 if (errno == EFAULT) {
9633 ret = FALSE;
9635 #else
9636 int i = 0;
9637 gboolean ret = FALSE;
9638 __try {
9639 for (i = 0; i < size; i++)
9640 *((volatile char*)addr+i);
9641 ret = TRUE;
9642 } __except(1) {
9643 return ret;
9645 #endif
9646 return ret;
9649 static ErrorCode
9650 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9652 ErrorCode err;
9653 gint64 addr;
9654 MonoClass* klass;
9655 MonoDomain* domain = NULL;
9656 MonoType *type = NULL;
9657 int align;
9658 int size = 0;
9660 switch (command) {
9661 case CMD_POINTER_GET_VALUE:
9662 addr = decode_long (p, &p, end);
9663 klass = decode_typeid (p, &p, end, &domain, &err);
9664 if (err != ERR_NONE)
9665 return err;
9667 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9668 return ERR_INVALID_ARGUMENT;
9670 type = m_class_get_byval_arg (m_class_get_element_class (klass));
9671 size = mono_type_size (type, &align);
9673 if (!valid_memory_address((gpointer)addr, size))
9674 return ERR_INVALID_ARGUMENT;
9676 buffer_add_value (buf, type, (gpointer)addr, domain);
9678 break;
9679 default:
9680 return ERR_NOT_IMPLEMENTED;
9683 return ERR_NONE;
9686 static ErrorCode
9687 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9689 HANDLE_FUNCTION_ENTER ();
9691 ERROR_DECL (error);
9692 int objid;
9693 ErrorCode err;
9694 MonoObject *obj;
9695 int len, i;
9696 MonoClassField *f;
9697 MonoClass *k;
9698 gboolean found;
9699 gboolean remote_obj = FALSE;
9700 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
9702 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9703 objid = decode_objid (p, &p, end);
9704 err = get_object (objid, &obj);
9705 if (err != ERR_NONE)
9706 buffer_add_int (buf, 1);
9707 else
9708 buffer_add_int (buf, 0);
9709 err = ERR_NONE;
9710 goto exit;
9713 objid = decode_objid (p, &p, end);
9714 err = get_object (objid, &obj);
9715 if (err != ERR_NONE)
9716 goto exit;
9718 MonoClass *obj_type;
9720 obj_type = obj->vtable->klass;
9721 if (mono_class_is_transparent_proxy (obj_type)) {
9722 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9723 remote_obj = TRUE;
9726 g_assert (obj_type);
9728 switch (command) {
9729 case CMD_OBJECT_REF_GET_TYPE:
9730 /* This handles transparent proxies too */
9731 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9732 break;
9733 case CMD_OBJECT_REF_GET_VALUES:
9734 len = decode_int (p, &p, end);
9736 for (i = 0; i < len; ++i) {
9737 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9738 if (err != ERR_NONE)
9739 goto exit;
9741 /* Check that the field belongs to the object */
9742 found = FALSE;
9743 for (k = obj_type; k; k = m_class_get_parent (k)) {
9744 if (k == f->parent) {
9745 found = TRUE;
9746 break;
9749 if (!found)
9750 goto invalid_fieldid;
9752 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9753 guint8 *val;
9754 MonoVTable *vtable;
9756 if (mono_class_field_is_special_static (f))
9757 goto invalid_fieldid;
9759 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9760 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9761 if (!is_ok (error)) {
9762 mono_error_cleanup (error);
9763 goto invalid_object;
9765 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9766 mono_field_static_get_value_checked (vtable, f, val, string_handle, error);
9767 if (!is_ok (error)) {
9768 mono_error_cleanup (error); /* FIXME report the error */
9769 goto invalid_object;
9771 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9772 g_free (val);
9773 } else {
9774 void *field_value = NULL;
9775 #ifndef DISABLE_REMOTING
9776 void *field_storage = NULL;
9777 #endif
9778 if (remote_obj) {
9779 #ifndef DISABLE_REMOTING
9780 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9781 if (!is_ok (error)) {
9782 mono_error_cleanup (error); /* FIXME report the error */
9783 goto invalid_object;
9785 #else
9786 g_assert_not_reached ();
9787 #endif
9788 } else
9789 field_value = (guint8*)obj + f->offset;
9791 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9794 break;
9795 case CMD_OBJECT_REF_SET_VALUES:
9796 len = decode_int (p, &p, end);
9798 for (i = 0; i < len; ++i) {
9799 f = decode_fieldid (p, &p, end, NULL, &err);
9800 if (err != ERR_NONE)
9801 goto exit;
9803 /* Check that the field belongs to the object */
9804 found = FALSE;
9805 for (k = obj_type; k; k = m_class_get_parent (k)) {
9806 if (k == f->parent) {
9807 found = TRUE;
9808 break;
9811 if (!found)
9812 goto invalid_fieldid;
9814 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9815 guint8 *val;
9816 MonoVTable *vtable;
9818 if (mono_class_field_is_special_static (f))
9819 goto invalid_fieldid;
9821 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9822 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9823 if (!is_ok (error)) {
9824 mono_error_cleanup (error);
9825 goto invalid_fieldid;
9828 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9829 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9830 if (err != ERR_NONE) {
9831 g_free (val);
9832 goto exit;
9834 mono_field_static_set_value_internal (vtable, f, val);
9835 g_free (val);
9836 } else {
9837 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9838 if (err != ERR_NONE)
9839 goto exit;
9842 break;
9843 case CMD_OBJECT_REF_GET_ADDRESS:
9844 buffer_add_long (buf, (gssize)obj);
9845 break;
9846 case CMD_OBJECT_REF_GET_DOMAIN:
9847 buffer_add_domainid (buf, obj->vtable->domain);
9848 break;
9849 case CMD_OBJECT_REF_GET_INFO:
9850 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9851 buffer_add_domainid (buf, obj->vtable->domain);
9852 break;
9853 default:
9854 err = ERR_NOT_IMPLEMENTED;
9855 goto exit;
9858 err = ERR_NONE;
9859 goto exit;
9860 invalid_fieldid:
9861 err = ERR_INVALID_FIELDID;
9862 goto exit;
9863 invalid_object:
9864 err = ERR_INVALID_OBJECT;
9865 goto exit;
9866 exit:
9867 HANDLE_FUNCTION_RETURN_VAL (err);
9870 static const char*
9871 command_set_to_string (CommandSet command_set)
9873 switch (command_set) {
9874 case CMD_SET_VM:
9875 return "VM";
9876 case CMD_SET_OBJECT_REF:
9877 return "OBJECT_REF";
9878 case CMD_SET_STRING_REF:
9879 return "STRING_REF";
9880 case CMD_SET_THREAD:
9881 return "THREAD";
9882 case CMD_SET_ARRAY_REF:
9883 return "ARRAY_REF";
9884 case CMD_SET_EVENT_REQUEST:
9885 return "EVENT_REQUEST";
9886 case CMD_SET_STACK_FRAME:
9887 return "STACK_FRAME";
9888 case CMD_SET_APPDOMAIN:
9889 return "APPDOMAIN";
9890 case CMD_SET_ASSEMBLY:
9891 return "ASSEMBLY";
9892 case CMD_SET_METHOD:
9893 return "METHOD";
9894 case CMD_SET_TYPE:
9895 return "TYPE";
9896 case CMD_SET_MODULE:
9897 return "MODULE";
9898 case CMD_SET_FIELD:
9899 return "FIELD";
9900 case CMD_SET_EVENT:
9901 return "EVENT";
9902 case CMD_SET_POINTER:
9903 return "POINTER";
9904 default:
9905 return "";
9909 static const char* vm_cmds_str [] = {
9910 "VERSION",
9911 "ALL_THREADS",
9912 "SUSPEND",
9913 "RESUME",
9914 "EXIT",
9915 "DISPOSE",
9916 "INVOKE_METHOD",
9917 "SET_PROTOCOL_VERSION",
9918 "ABORT_INVOKE",
9919 "SET_KEEPALIVE"
9920 "GET_TYPES_FOR_SOURCE_FILE",
9921 "GET_TYPES",
9922 "INVOKE_METHODS"
9925 static const char* thread_cmds_str[] = {
9926 "GET_FRAME_INFO",
9927 "GET_NAME",
9928 "GET_STATE",
9929 "GET_INFO",
9930 "GET_ID",
9931 "GET_TID",
9932 "SET_IP"
9935 static const char* event_cmds_str[] = {
9936 "REQUEST_SET",
9937 "REQUEST_CLEAR",
9938 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9941 static const char* appdomain_cmds_str[] = {
9942 "GET_ROOT_DOMAIN",
9943 "GET_FRIENDLY_NAME",
9944 "GET_ASSEMBLIES",
9945 "GET_ENTRY_ASSEMBLY",
9946 "CREATE_STRING",
9947 "GET_CORLIB",
9948 "CREATE_BOXED_VALUE",
9949 "CREATE_BYTE_ARRAY",
9952 static const char* assembly_cmds_str[] = {
9953 "GET_LOCATION",
9954 "GET_ENTRY_POINT",
9955 "GET_MANIFEST_MODULE",
9956 "GET_OBJECT",
9957 "GET_TYPE",
9958 "GET_NAME",
9959 "GET_DOMAIN",
9960 "HAS_DEBUG_INFO"
9963 static const char* module_cmds_str[] = {
9964 "GET_INFO",
9967 static const char* field_cmds_str[] = {
9968 "GET_INFO",
9971 static const char* method_cmds_str[] = {
9972 "GET_NAME",
9973 "GET_DECLARING_TYPE",
9974 "GET_DEBUG_INFO",
9975 "GET_PARAM_INFO",
9976 "GET_LOCALS_INFO",
9977 "GET_INFO",
9978 "GET_BODY",
9979 "RESOLVE_TOKEN",
9980 "GET_CATTRS ",
9981 "MAKE_GENERIC_METHOD"
9984 static const char* type_cmds_str[] = {
9985 "GET_INFO",
9986 "GET_METHODS",
9987 "GET_FIELDS",
9988 "GET_VALUES",
9989 "GET_OBJECT",
9990 "GET_SOURCE_FILES",
9991 "SET_VALUES",
9992 "IS_ASSIGNABLE_FROM",
9993 "GET_PROPERTIES ",
9994 "GET_CATTRS",
9995 "GET_FIELD_CATTRS",
9996 "GET_PROPERTY_CATTRS",
9997 "GET_SOURCE_FILES_2",
9998 "GET_VALUES_2",
9999 "GET_METHODS_BY_NAME_FLAGS",
10000 "GET_INTERFACES",
10001 "GET_INTERFACE_MAP",
10002 "IS_INITIALIZED",
10003 "CREATE_INSTANCE",
10004 "GET_VALUE_SIZE"
10007 static const char* stack_frame_cmds_str[] = {
10008 "GET_VALUES",
10009 "GET_THIS",
10010 "SET_VALUES",
10011 "GET_DOMAIN",
10012 "SET_THIS"
10015 static const char* array_cmds_str[] = {
10016 "GET_LENGTH",
10017 "GET_VALUES",
10018 "SET_VALUES",
10021 static const char* string_cmds_str[] = {
10022 "GET_VALUE",
10023 "GET_LENGTH",
10024 "GET_CHARS"
10027 static const char* pointer_cmds_str[] = {
10028 "GET_VALUE"
10031 static const char* object_cmds_str[] = {
10032 "GET_TYPE",
10033 "GET_VALUES",
10034 "IS_COLLECTED",
10035 "GET_ADDRESS",
10036 "GET_DOMAIN",
10037 "SET_VALUES",
10038 "GET_INFO",
10041 static const char*
10042 cmd_to_string (CommandSet set, int command)
10044 const char **cmds;
10045 int cmds_len = 0;
10047 switch (set) {
10048 case CMD_SET_VM:
10049 cmds = vm_cmds_str;
10050 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10051 break;
10052 case CMD_SET_OBJECT_REF:
10053 cmds = object_cmds_str;
10054 cmds_len = G_N_ELEMENTS (object_cmds_str);
10055 break;
10056 case CMD_SET_STRING_REF:
10057 cmds = string_cmds_str;
10058 cmds_len = G_N_ELEMENTS (string_cmds_str);
10059 break;
10060 case CMD_SET_THREAD:
10061 cmds = thread_cmds_str;
10062 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10063 break;
10064 case CMD_SET_ARRAY_REF:
10065 cmds = array_cmds_str;
10066 cmds_len = G_N_ELEMENTS (array_cmds_str);
10067 break;
10068 case CMD_SET_EVENT_REQUEST:
10069 cmds = event_cmds_str;
10070 cmds_len = G_N_ELEMENTS (event_cmds_str);
10071 break;
10072 case CMD_SET_STACK_FRAME:
10073 cmds = stack_frame_cmds_str;
10074 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10075 break;
10076 case CMD_SET_APPDOMAIN:
10077 cmds = appdomain_cmds_str;
10078 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10079 break;
10080 case CMD_SET_ASSEMBLY:
10081 cmds = assembly_cmds_str;
10082 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10083 break;
10084 case CMD_SET_METHOD:
10085 cmds = method_cmds_str;
10086 cmds_len = G_N_ELEMENTS (method_cmds_str);
10087 break;
10088 case CMD_SET_TYPE:
10089 cmds = type_cmds_str;
10090 cmds_len = G_N_ELEMENTS (type_cmds_str);
10091 break;
10092 case CMD_SET_MODULE:
10093 cmds = module_cmds_str;
10094 cmds_len = G_N_ELEMENTS (module_cmds_str);
10095 break;
10096 case CMD_SET_FIELD:
10097 cmds = field_cmds_str;
10098 cmds_len = G_N_ELEMENTS (field_cmds_str);
10099 break;
10100 case CMD_SET_EVENT:
10101 cmds = event_cmds_str;
10102 cmds_len = G_N_ELEMENTS (event_cmds_str);
10103 break;
10104 case CMD_SET_POINTER:
10105 cmds = pointer_cmds_str;
10106 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
10107 break;
10108 default:
10109 return NULL;
10111 if (command > 0 && command <= cmds_len)
10112 return cmds [command - 1];
10113 else
10114 return NULL;
10117 static gboolean
10118 wait_for_attach (void)
10120 #ifndef DISABLE_SOCKET_TRANSPORT
10121 if (listen_fd == -1) {
10122 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10123 return FALSE;
10126 /* Block and wait for client connection */
10127 conn_fd = socket_transport_accept (listen_fd);
10129 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10130 if (conn_fd == -1) {
10131 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10132 return FALSE;
10134 #else
10135 g_assert_not_reached ();
10136 #endif
10138 /* Handshake */
10139 disconnected = !transport_handshake ();
10140 if (disconnected) {
10141 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10142 return FALSE;
10145 return TRUE;
10149 * debugger_thread:
10151 * This thread handles communication with the debugger client using a JDWP
10152 * like protocol.
10154 static gsize WINAPI
10155 debugger_thread (void *arg)
10157 int res, len, id, flags, command = 0;
10158 CommandSet command_set = (CommandSet)0;
10159 guint8 header [HEADER_LENGTH];
10160 guint8 *data, *p, *end;
10161 Buffer buf;
10162 ErrorCode err;
10163 gboolean no_reply;
10164 gboolean attach_failed = FALSE;
10166 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10168 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
10170 debugger_thread_id = mono_native_thread_id_get ();
10172 MonoInternalThread *internal = mono_thread_internal_current ();
10173 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
10175 internal->state |= ThreadState_Background;
10176 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10178 if (agent_config.defer) {
10179 if (!wait_for_attach ()) {
10180 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10181 attach_failed = TRUE; // Don't abort process when we can't listen
10182 } else {
10183 mono_set_is_debugger_attached (TRUE);
10184 /* Send start event to client */
10185 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10187 } else {
10188 mono_set_is_debugger_attached (TRUE);
10191 while (!attach_failed) {
10192 res = transport_recv (header, HEADER_LENGTH);
10194 /* This will break if the socket is closed during shutdown too */
10195 if (res != HEADER_LENGTH) {
10196 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10197 command_set = (CommandSet)0;
10198 command = 0;
10199 dispose_vm ();
10200 break;
10201 } else {
10202 p = header;
10203 end = header + HEADER_LENGTH;
10205 len = decode_int (p, &p, end);
10206 id = decode_int (p, &p, end);
10207 flags = decode_byte (p, &p, end);
10208 command_set = (CommandSet)decode_byte (p, &p, end);
10209 command = decode_byte (p, &p, end);
10212 g_assert (flags == 0);
10213 const char *cmd_str;
10214 char cmd_num [256];
10216 cmd_str = cmd_to_string (command_set, command);
10217 if (!cmd_str) {
10218 sprintf (cmd_num, "%d", command);
10219 cmd_str = cmd_num;
10222 if (log_level) {
10223 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);
10226 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10227 if (len - HEADER_LENGTH > 0)
10229 res = transport_recv (data, len - HEADER_LENGTH);
10230 if (res != len - HEADER_LENGTH) {
10231 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10232 break;
10236 p = data;
10237 end = data + (len - HEADER_LENGTH);
10239 buffer_init (&buf, 128);
10241 err = ERR_NONE;
10242 no_reply = FALSE;
10244 /* Process the request */
10245 switch (command_set) {
10246 case CMD_SET_VM:
10247 err = vm_commands (command, id, p, end, &buf);
10248 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10249 /* Sent after the invoke is complete */
10250 no_reply = TRUE;
10251 break;
10252 case CMD_SET_EVENT_REQUEST:
10253 err = event_commands (command, p, end, &buf);
10254 break;
10255 case CMD_SET_APPDOMAIN:
10256 err = domain_commands (command, p, end, &buf);
10257 break;
10258 case CMD_SET_ASSEMBLY:
10259 err = assembly_commands (command, p, end, &buf);
10260 break;
10261 case CMD_SET_MODULE:
10262 err = module_commands (command, p, end, &buf);
10263 break;
10264 case CMD_SET_FIELD:
10265 err = field_commands (command, p, end, &buf);
10266 break;
10267 case CMD_SET_TYPE:
10268 err = type_commands (command, p, end, &buf);
10269 break;
10270 case CMD_SET_METHOD:
10271 err = method_commands (command, p, end, &buf);
10272 break;
10273 case CMD_SET_THREAD:
10274 err = thread_commands (command, p, end, &buf);
10275 break;
10276 case CMD_SET_STACK_FRAME:
10277 err = frame_commands (command, p, end, &buf);
10278 break;
10279 case CMD_SET_ARRAY_REF:
10280 err = array_commands (command, p, end, &buf);
10281 break;
10282 case CMD_SET_STRING_REF:
10283 err = string_commands (command, p, end, &buf);
10284 break;
10285 case CMD_SET_POINTER:
10286 err = pointer_commands (command, p, end, &buf);
10287 break;
10288 case CMD_SET_OBJECT_REF:
10289 err = object_commands (command, p, end, &buf);
10290 break;
10291 default:
10292 err = ERR_NOT_IMPLEMENTED;
10295 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10296 buffer_replies = TRUE;
10299 if (!no_reply) {
10300 if (buffer_replies) {
10301 buffer_reply_packet (id, err, &buf);
10302 } else {
10303 send_reply_packet (id, err, &buf);
10304 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10308 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10310 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10311 send_buffered_reply_packets ();
10312 buffer_replies = FALSE;
10315 g_free (data);
10316 buffer_free (&buf);
10318 if (log_each_step) {
10319 char *debugger_log = mono_debugger_state_str ();
10320 if (debugger_log) {
10321 fprintf (stderr, "Debugger state: %s\n", debugger_log);
10322 g_free (debugger_log);
10326 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10327 break;
10330 mono_set_is_debugger_attached (FALSE);
10332 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10333 debugger_thread_exited = TRUE;
10334 mono_coop_cond_signal (&debugger_thread_exited_cond);
10335 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10337 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10339 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10340 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10341 ERROR_DECL (error);
10342 start_debugger_thread (error);
10343 mono_error_cleanup (error);
10346 return 0;
10349 void
10350 mono_debugger_agent_init (void)
10352 MonoDebuggerCallbacks cbs;
10354 memset (&cbs, 0, sizeof (cbs));
10355 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10356 cbs.parse_options = debugger_agent_parse_options;
10357 cbs.init = debugger_agent_init;
10358 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10359 cbs.single_step_event = debugger_agent_single_step_event;
10360 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10361 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10362 cbs.free_domain_info = debugger_agent_free_domain_info;
10363 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10364 cbs.handle_exception = debugger_agent_handle_exception;
10365 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10366 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10367 cbs.user_break = debugger_agent_user_break;
10368 cbs.debug_log = debugger_agent_debug_log;
10369 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10370 cbs.send_crash = mono_debugger_agent_send_crash;
10372 mini_install_dbg_callbacks (&cbs);
10375 void
10376 mono_debugger_agent_parse_options (char *options)
10378 sdb_options = options;
10381 #endif /* DISABLE_SDB */