[metadata] Fix leaks when handling a few attributes (#16675)
[mono-project.git] / mono / mini / debugger-agent.c
blob9cdd5d1268b851e582b8625a5130a30c66e6590b
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 #endif
50 #ifdef HOST_ANDROID
51 #include <linux/in.h>
52 #include <linux/tcp.h>
53 #include <sys/endian.h>
54 #endif
56 #include <mono/metadata/mono-debug.h>
57 #include <mono/metadata/debug-internals.h>
58 #include <mono/metadata/domain-internals.h>
59 #include <mono/metadata/gc-internals.h>
60 #include <mono/metadata/environment.h>
61 #include <mono/metadata/mono-hash-internals.h>
62 #include <mono/metadata/threads-types.h>
63 #include <mono/metadata/threadpool.h>
64 #include <mono/metadata/assembly.h>
65 #include <mono/metadata/assembly-internals.h>
66 #include <mono/metadata/runtime.h>
67 #include <mono/metadata/verify-internals.h>
68 #include <mono/metadata/reflection-internals.h>
69 #include <mono/metadata/w32socket.h>
70 #include <mono/utils/mono-coop-mutex.h>
71 #include <mono/utils/mono-coop-semaphore.h>
72 #include <mono/utils/mono-error-internals.h>
73 #include <mono/utils/mono-stack-unwinding.h>
74 #include <mono/utils/mono-time.h>
75 #include <mono/utils/mono-threads.h>
76 #include <mono/utils/networking.h>
77 #include <mono/utils/mono-proclib.h>
78 #include <mono/utils/w32api.h>
79 #include "debugger-state-machine.h"
80 #include "debugger-agent.h"
81 #include "mini.h"
82 #include "seq-points.h"
83 #include "aot-runtime.h"
84 #include "mini-runtime.h"
85 #include "interp/interp.h"
86 #include "debugger-engine.h"
87 #include "mono/metadata/debug-mono-ppdb.h"
88 #include "mono/metadata/custom-attrs-internals.h"
91 * On iOS we can't use System.Environment.Exit () as it will do the wrong
92 * shutdown sequence.
94 #if !defined (TARGET_IOS)
95 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
96 #endif
98 #if DISABLE_SOCKETS
99 #define DISABLE_SOCKET_TRANSPORT
100 #endif
102 #ifndef DISABLE_SDB
104 #include <mono/utils/mono-os-mutex.h>
106 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
108 typedef struct {
109 gboolean enabled;
110 char *transport;
111 char *address;
112 int log_level;
113 char *log_file;
114 gboolean suspend;
115 gboolean server;
116 gboolean onuncaught;
117 GSList *onthrow;
118 int timeout;
119 char *launch;
120 gboolean embedding;
121 gboolean defer;
122 int keepalive;
123 gboolean setpgid;
124 } AgentConfig;
126 typedef struct
128 //Must be the first field to ensure pointer equivalence
129 DbgEngineStackFrame de;
130 int id;
131 guint32 il_offset;
133 * If method is gshared, this is the actual instance, otherwise this is equal to
134 * method.
136 MonoMethod *actual_method;
138 * This is the method which is visible to debugger clients. Same as method,
139 * except for native-to-managed wrappers.
141 MonoMethod *api_method;
142 MonoContext ctx;
143 MonoDebugMethodJitInfo *jit;
144 MonoInterpFrameHandle interp_frame;
145 gpointer frame_addr;
146 int flags;
147 host_mgreg_t *reg_locations [MONO_MAX_IREGS];
149 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
150 * the frame can become invalid.
152 gboolean has_ctx;
153 } StackFrame;
155 typedef struct _InvokeData InvokeData;
157 struct _InvokeData
159 int id;
160 int flags;
161 guint8 *p;
162 guint8 *endp;
163 /* This is the context which needs to be restored after the invoke */
164 MonoContext ctx;
165 gboolean has_ctx;
167 * If this is set, invoke this method with the arguments given by ARGS.
169 MonoMethod *method;
170 gpointer *args;
171 guint32 suspend_count;
172 int nmethods;
174 InvokeData *last_invoke;
177 struct _DebuggerTlsData {
178 MonoThreadUnwindState context;
180 /* This is computed on demand when it is requested using the wire protocol */
181 /* It is freed up when the thread is resumed */
182 int frame_count;
183 StackFrame **frames;
185 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
186 * re-compute it.
188 gboolean frames_up_to_date;
190 * Points to data about a pending invoke which needs to be executed after the thread
191 * resumes.
193 InvokeData *pending_invoke;
195 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
196 * native code.
198 gboolean suspended;
200 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
201 * within a finite amount of time.
203 gboolean suspending;
205 * Set to TRUE if this thread is suspended in suspend_current ().
207 gboolean really_suspended;
208 /* Used to pass the context to the breakpoint/single step handler */
209 MonoContext handler_ctx;
210 /* Whenever thread_stop () was called for this thread */
211 gboolean terminated;
213 /* Whenever to disable breakpoints (used during invokes) */
214 gboolean disable_breakpoints;
217 * Number of times this thread has been resumed using resume_thread ().
219 guint32 resume_count;
221 MonoInternalThread *thread;
222 intptr_t thread_id;
225 * Information about the frame which transitioned to native code for running
226 * threads.
228 StackFrameInfo async_last_frame;
231 * The context where the stack walk can be started for running threads.
233 MonoThreadUnwindState async_state;
236 * The context used for filter clauses
238 MonoThreadUnwindState filter_state;
240 gboolean abort_requested;
243 * The current mono_runtime_invoke_checked invocation.
245 InvokeData *invoke;
247 StackFrameInfo catch_frame;
248 gboolean has_catch_frame;
251 * The context which needs to be restored after handling a single step/breakpoint
252 * event. This is the same as the ctx at step/breakpoint site, but includes changes
253 * to caller saved registers done by set_var ().
255 MonoThreadUnwindState restore_state;
256 /* Frames computed from restore_state */
257 int restore_frame_count;
258 StackFrame **restore_frames;
260 /* The currently unloading appdomain */
261 MonoDomain *domain_unloading;
263 // The state that the debugger expects the thread to be in
264 MonoDebuggerThreadState thread_state;
265 MonoStopwatch step_time;
267 gboolean gc_finalizing;
270 typedef struct {
271 const char *name;
272 void (*connect) (const char *address);
273 void (*close1) (void);
274 void (*close2) (void);
275 gboolean (*send) (void *buf, int len);
276 int (*recv) (void *buf, int len);
277 } DebuggerTransport;
280 * Wire Protocol definitions
283 #define HEADER_LENGTH 11
285 #define MAJOR_VERSION 2
286 #define MINOR_VERSION 53
288 typedef enum {
289 CMD_SET_VM = 1,
290 CMD_SET_OBJECT_REF = 9,
291 CMD_SET_STRING_REF = 10,
292 CMD_SET_THREAD = 11,
293 CMD_SET_ARRAY_REF = 13,
294 CMD_SET_EVENT_REQUEST = 15,
295 CMD_SET_STACK_FRAME = 16,
296 CMD_SET_APPDOMAIN = 20,
297 CMD_SET_ASSEMBLY = 21,
298 CMD_SET_METHOD = 22,
299 CMD_SET_TYPE = 23,
300 CMD_SET_MODULE = 24,
301 CMD_SET_FIELD = 25,
302 CMD_SET_EVENT = 64,
303 CMD_SET_POINTER = 65
304 } CommandSet;
306 typedef enum {
307 SUSPEND_POLICY_NONE = 0,
308 SUSPEND_POLICY_EVENT_THREAD = 1,
309 SUSPEND_POLICY_ALL = 2
310 } SuspendPolicy;
312 typedef enum {
313 ERR_NONE = 0,
314 ERR_INVALID_OBJECT = 20,
315 ERR_INVALID_FIELDID = 25,
316 ERR_INVALID_FRAMEID = 30,
317 ERR_NOT_IMPLEMENTED = 100,
318 ERR_NOT_SUSPENDED = 101,
319 ERR_INVALID_ARGUMENT = 102,
320 ERR_UNLOADED = 103,
321 ERR_NO_INVOCATION = 104,
322 ERR_ABSENT_INFORMATION = 105,
323 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
324 ERR_INVOKE_ABORTED = 107,
325 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
326 } ErrorCode;
328 typedef enum {
329 TOKEN_TYPE_STRING = 0,
330 TOKEN_TYPE_TYPE = 1,
331 TOKEN_TYPE_FIELD = 2,
332 TOKEN_TYPE_METHOD = 3,
333 TOKEN_TYPE_UNKNOWN = 4
334 } DebuggerTokenType;
336 typedef enum {
337 VALUE_TYPE_ID_NULL = 0xf0,
338 VALUE_TYPE_ID_TYPE = 0xf1,
339 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2,
340 VALUE_TYPE_ID_FIXED_ARRAY = 0xf3
341 } ValueTypeId;
343 typedef enum {
344 FRAME_FLAG_DEBUGGER_INVOKE = 1,
345 FRAME_FLAG_NATIVE_TRANSITION = 2
346 } StackFrameFlags;
348 typedef enum {
349 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
350 INVOKE_FLAG_SINGLE_THREADED = 2,
351 INVOKE_FLAG_RETURN_OUT_THIS = 4,
352 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
353 INVOKE_FLAG_VIRTUAL = 16
354 } InvokeFlags;
356 typedef enum {
357 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
358 } BindingFlagsExtensions;
360 typedef enum {
361 CMD_VM_VERSION = 1,
362 CMD_VM_ALL_THREADS = 2,
363 CMD_VM_SUSPEND = 3,
364 CMD_VM_RESUME = 4,
365 CMD_VM_EXIT = 5,
366 CMD_VM_DISPOSE = 6,
367 CMD_VM_INVOKE_METHOD = 7,
368 CMD_VM_SET_PROTOCOL_VERSION = 8,
369 CMD_VM_ABORT_INVOKE = 9,
370 CMD_VM_SET_KEEPALIVE = 10,
371 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
372 CMD_VM_GET_TYPES = 12,
373 CMD_VM_INVOKE_METHODS = 13,
374 CMD_VM_START_BUFFERING = 14,
375 CMD_VM_STOP_BUFFERING = 15
376 } CmdVM;
378 typedef enum {
379 CMD_THREAD_GET_FRAME_INFO = 1,
380 CMD_THREAD_GET_NAME = 2,
381 CMD_THREAD_GET_STATE = 3,
382 CMD_THREAD_GET_INFO = 4,
383 CMD_THREAD_GET_ID = 5,
384 CMD_THREAD_GET_TID = 6,
385 CMD_THREAD_SET_IP = 7,
386 CMD_THREAD_ELAPSED_TIME = 8
387 } CmdThread;
389 typedef enum {
390 CMD_EVENT_REQUEST_SET = 1,
391 CMD_EVENT_REQUEST_CLEAR = 2,
392 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
393 } CmdEvent;
395 typedef enum {
396 CMD_COMPOSITE = 100
397 } CmdComposite;
399 typedef enum {
400 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
401 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
402 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
403 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
404 CMD_APPDOMAIN_CREATE_STRING = 5,
405 CMD_APPDOMAIN_GET_CORLIB = 6,
406 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
407 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
408 } CmdAppDomain;
410 typedef enum {
411 CMD_ASSEMBLY_GET_LOCATION = 1,
412 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
413 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
414 CMD_ASSEMBLY_GET_OBJECT = 4,
415 CMD_ASSEMBLY_GET_TYPE = 5,
416 CMD_ASSEMBLY_GET_NAME = 6,
417 CMD_ASSEMBLY_GET_DOMAIN = 7,
418 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
419 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
420 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
421 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
422 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
423 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13
424 } CmdAssembly;
426 typedef enum {
427 CMD_MODULE_GET_INFO = 1,
428 } CmdModule;
430 typedef enum {
431 CMD_FIELD_GET_INFO = 1,
432 } CmdField;
434 typedef enum {
435 CMD_METHOD_GET_NAME = 1,
436 CMD_METHOD_GET_DECLARING_TYPE = 2,
437 CMD_METHOD_GET_DEBUG_INFO = 3,
438 CMD_METHOD_GET_PARAM_INFO = 4,
439 CMD_METHOD_GET_LOCALS_INFO = 5,
440 CMD_METHOD_GET_INFO = 6,
441 CMD_METHOD_GET_BODY = 7,
442 CMD_METHOD_RESOLVE_TOKEN = 8,
443 CMD_METHOD_GET_CATTRS = 9,
444 CMD_METHOD_MAKE_GENERIC_METHOD = 10
445 } CmdMethod;
447 typedef enum {
448 CMD_TYPE_GET_INFO = 1,
449 CMD_TYPE_GET_METHODS = 2,
450 CMD_TYPE_GET_FIELDS = 3,
451 CMD_TYPE_GET_VALUES = 4,
452 CMD_TYPE_GET_OBJECT = 5,
453 CMD_TYPE_GET_SOURCE_FILES = 6,
454 CMD_TYPE_SET_VALUES = 7,
455 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
456 CMD_TYPE_GET_PROPERTIES = 9,
457 CMD_TYPE_GET_CATTRS = 10,
458 CMD_TYPE_GET_FIELD_CATTRS = 11,
459 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
460 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
461 CMD_TYPE_GET_VALUES_2 = 14,
462 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
463 CMD_TYPE_GET_INTERFACES = 16,
464 CMD_TYPE_GET_INTERFACE_MAP = 17,
465 CMD_TYPE_IS_INITIALIZED = 18,
466 CMD_TYPE_CREATE_INSTANCE = 19,
467 CMD_TYPE_GET_VALUE_SIZE = 20
468 } CmdType;
470 typedef enum {
471 CMD_STACK_FRAME_GET_VALUES = 1,
472 CMD_STACK_FRAME_GET_THIS = 2,
473 CMD_STACK_FRAME_SET_VALUES = 3,
474 CMD_STACK_FRAME_GET_DOMAIN = 4,
475 CMD_STACK_FRAME_SET_THIS = 5,
476 } CmdStackFrame;
478 typedef enum {
479 CMD_ARRAY_REF_GET_LENGTH = 1,
480 CMD_ARRAY_REF_GET_VALUES = 2,
481 CMD_ARRAY_REF_SET_VALUES = 3,
482 } CmdArray;
484 typedef enum {
485 CMD_STRING_REF_GET_VALUE = 1,
486 CMD_STRING_REF_GET_LENGTH = 2,
487 CMD_STRING_REF_GET_CHARS = 3
488 } CmdString;
490 typedef enum {
491 CMD_POINTER_GET_VALUE = 1
492 } CmdPointer;
494 typedef enum {
495 CMD_OBJECT_REF_GET_TYPE = 1,
496 CMD_OBJECT_REF_GET_VALUES = 2,
497 CMD_OBJECT_REF_IS_COLLECTED = 3,
498 CMD_OBJECT_REF_GET_ADDRESS = 4,
499 CMD_OBJECT_REF_GET_DOMAIN = 5,
500 CMD_OBJECT_REF_SET_VALUES = 6,
501 CMD_OBJECT_REF_GET_INFO = 7,
502 } CmdObject;
505 * Contains additional information for an event
507 typedef struct {
508 /* For EVENT_KIND_EXCEPTION */
509 MonoObject *exc;
510 MonoContext catch_ctx;
511 gboolean caught;
512 /* For EVENT_KIND_USER_LOG */
513 int level;
514 char *category, *message;
515 /* For EVENT_KIND_TYPE_LOAD */
516 MonoClass *klass;
517 /* For EVENT_KIND_CRASH */
518 char *dump;
519 MonoStackHash *hashes;
520 } EventInfo;
522 typedef struct {
523 guint8 *buf, *p, *end;
524 } Buffer;
526 typedef struct ReplyPacket {
527 int id;
528 int error;
529 Buffer *data;
530 } ReplyPacket;
532 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
534 #ifdef HOST_ANDROID
535 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
536 #else
537 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
538 #endif
540 #ifdef HOST_WIN32
541 #define get_last_sock_error() WSAGetLastError()
542 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
543 #define MONO_EINTR WSAEINTR
544 #else
545 #define get_last_sock_error() errno
546 #define MONO_EWOULDBLOCK EWOULDBLOCK
547 #define MONO_EINTR EINTR
548 #endif
550 #define CHECK_PROTOCOL_VERSION(major,minor) \
551 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
554 * Globals
557 static AgentConfig agent_config;
560 * Whenever the agent is fully initialized.
561 * When using the onuncaught or onthrow options, only some parts of the agent are
562 * initialized on startup, and the full initialization which includes connection
563 * establishment and the startup of the agent thread is only done in response to
564 * an event.
566 static gint32 inited;
568 #ifndef DISABLE_SOCKET_TRANSPORT
569 static int conn_fd;
570 static int listen_fd;
571 #endif
573 static int packet_id = 0;
575 static int objref_id = 0;
577 static int event_request_id = 0;
579 static int frame_id = 0;
581 static GPtrArray *event_requests;
583 static MonoNativeTlsKey debugger_tls_id;
585 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
587 /* Maps MonoInternalThread -> DebuggerTlsData */
588 /* Protected by the loader lock */
589 static MonoGHashTable *thread_to_tls;
591 /* Maps tid -> MonoInternalThread */
592 /* Protected by the loader lock */
593 static MonoGHashTable *tid_to_thread;
595 /* Maps tid -> MonoThread (not MonoInternalThread) */
596 /* Protected by the loader lock */
597 static MonoGHashTable *tid_to_thread_obj;
599 static MonoNativeThreadId debugger_thread_id;
601 static MonoThreadHandle *debugger_thread_handle;
603 static int log_level;
605 static gboolean embedding;
607 static FILE *log_file;
609 /* Assemblies whose assembly load event has no been sent yet */
610 /* Protected by the dbg lock */
611 static GPtrArray *pending_assembly_loads;
613 /* Whenever the debugger thread has exited */
614 static gboolean debugger_thread_exited;
616 /* Cond variable used to wait for debugger_thread_exited becoming true */
617 static MonoCoopCond debugger_thread_exited_cond;
619 /* Mutex for the cond var above */
620 static MonoCoopMutex debugger_thread_exited_mutex;
622 /* The protocol version of the client */
623 static int major_version, minor_version;
625 /* Whenever the variables above are set by the client */
626 static gboolean protocol_version_set;
628 /* The number of times the runtime is suspended */
629 static gint32 suspend_count;
631 /* Whenever to buffer reply messages and send them together */
632 static gboolean buffer_replies;
634 /* Buffered reply packets */
635 static ReplyPacket reply_packets [128];
636 static int nreply_packets;
638 #define dbg_lock mono_de_lock
639 #define dbg_unlock mono_de_unlock
641 static void transport_init (void);
642 static void transport_connect (const char *address);
643 static gboolean transport_handshake (void);
644 static void register_transport (DebuggerTransport *trans);
646 static gsize WINAPI debugger_thread (void *arg);
648 static void runtime_initialized (MonoProfiler *prof);
650 static void runtime_shutdown (MonoProfiler *prof);
652 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
654 static void thread_end (MonoProfiler *prof, uintptr_t tid);
656 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
658 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
660 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
662 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
664 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
666 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
668 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
670 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
672 static void gc_finalizing (MonoProfiler *prof);
674 static void gc_finalized (MonoProfiler *prof);
676 static void emit_assembly_load (gpointer assembly, gpointer user_data);
678 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
680 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
682 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
684 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
686 static void suspend_current (void);
688 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
690 static void clear_types_for_assembly (MonoAssembly *assembly);
692 static void process_profiler_event (EventKind event, gpointer arg);
694 /* Submodule init/cleanup */
695 static void event_requests_cleanup (void);
697 static void objrefs_init (void);
698 static void objrefs_cleanup (void);
700 static void ids_init (void);
701 static void ids_cleanup (void);
703 static void suspend_init (void);
705 static void start_debugger_thread (MonoError *error);
706 static void stop_debugger_thread (void);
708 static void finish_agent_init (gboolean on_startup);
710 static void process_profiler_event (EventKind event, gpointer arg);
712 static void invalidate_frames (DebuggerTlsData *tls);
714 /* Callbacks used by debugger-engine */
715 static MonoContext* tls_get_restore_state (void *the_tls);
716 static gboolean try_process_suspend (void *tls, MonoContext *ctx);
717 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
718 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
719 static void ss_discard_frame_context (void *the_tls);
720 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
721 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
722 static int ensure_runtime_is_suspended (void);
723 static int get_this_async_id (DbgEngineStackFrame *frame);
724 static gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame);
725 static MonoMethod* get_notify_debugger_of_wait_completion_method (void);
726 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
727 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
728 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
729 static void ss_args_destroy (SingleStepArgs *ss_args);
731 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
733 #ifndef DISABLE_SOCKET_TRANSPORT
734 static void
735 register_socket_transport (void);
736 #endif
738 static gboolean
739 is_debugger_thread (void)
741 MonoInternalThread *internal;
743 internal = mono_thread_internal_current ();
744 if (!internal)
745 return FALSE;
747 return internal->debugger_thread;
750 static int
751 parse_address (char *address, char **host, int *port)
753 char *pos = strchr (address, ':');
755 if (pos == NULL || pos == address)
756 return 1;
758 size_t len = pos - address;
759 *host = (char *)g_malloc (len + 1);
760 memcpy (*host, address, len);
761 (*host) [len] = '\0';
763 *port = atoi (pos + 1);
765 return 0;
768 static void
769 print_usage (void)
771 g_printerr ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
772 g_printerr ("Available options:\n");
773 g_printerr (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
774 g_printerr (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
775 g_printerr (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
776 g_printerr (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
777 g_printerr (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
778 g_printerr (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
779 g_printerr (" server=y/n\t\t\tWhether to listen for a client connection.\n");
780 g_printerr (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
781 g_printerr (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
782 g_printerr (" help\t\t\t\tPrint this help.\n");
785 static gboolean
786 parse_flag (const char *option, char *flag)
788 if (!strcmp (flag, "y"))
789 return TRUE;
790 else if (!strcmp (flag, "n"))
791 return FALSE;
792 else {
793 g_printerr ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
794 exit (1);
795 return FALSE;
799 static void
800 debugger_agent_parse_options (char *options)
802 char **args, **ptr;
803 char *host;
804 int port;
805 char *extra;
807 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
808 g_printerr ("--debugger-agent is not supported on this platform.\n");
809 exit (1);
810 #endif
812 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
813 if (extra) {
814 options = g_strdup_printf ("%s,%s", options, extra);
815 g_free (extra);
818 agent_config.enabled = TRUE;
819 agent_config.suspend = TRUE;
820 agent_config.server = FALSE;
821 agent_config.defer = FALSE;
822 agent_config.address = NULL;
824 //agent_config.log_level = 10;
826 args = g_strsplit (options, ",", -1);
827 for (ptr = args; ptr && *ptr; ptr ++) {
828 char *arg = *ptr;
830 if (strncmp (arg, "transport=", 10) == 0) {
831 agent_config.transport = g_strdup (arg + 10);
832 } else if (strncmp (arg, "address=", 8) == 0) {
833 agent_config.address = g_strdup (arg + 8);
834 } else if (strncmp (arg, "loglevel=", 9) == 0) {
835 agent_config.log_level = atoi (arg + 9);
836 } else if (strncmp (arg, "logfile=", 8) == 0) {
837 agent_config.log_file = g_strdup (arg + 8);
838 } else if (strncmp (arg, "suspend=", 8) == 0) {
839 agent_config.suspend = parse_flag ("suspend", arg + 8);
840 } else if (strncmp (arg, "server=", 7) == 0) {
841 agent_config.server = parse_flag ("server", arg + 7);
842 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
843 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
844 } else if (strncmp (arg, "onthrow=", 8) == 0) {
845 /* We support multiple onthrow= options */
846 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
847 } else if (strncmp (arg, "onthrow", 7) == 0) {
848 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
849 } else if (strncmp (arg, "help", 4) == 0) {
850 print_usage ();
851 exit (0);
852 } else if (strncmp (arg, "timeout=", 8) == 0) {
853 agent_config.timeout = atoi (arg + 8);
854 } else if (strncmp (arg, "launch=", 7) == 0) {
855 agent_config.launch = g_strdup (arg + 7);
856 } else if (strncmp (arg, "embedding=", 10) == 0) {
857 agent_config.embedding = atoi (arg + 10) == 1;
858 } else if (strncmp (arg, "keepalive=", 10) == 0) {
859 agent_config.keepalive = atoi (arg + 10);
860 } else if (strncmp (arg, "setpgid=", 8) == 0) {
861 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
862 } else {
863 print_usage ();
864 exit (1);
868 if (agent_config.server && !agent_config.suspend) {
869 /* Waiting for deferred attachment */
870 agent_config.defer = TRUE;
871 if (agent_config.address == NULL) {
872 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
876 //agent_config.log_level = 0;
878 if (agent_config.transport == NULL) {
879 g_printerr ("debugger-agent: The 'transport' option is mandatory.\n");
880 exit (1);
883 if (agent_config.address == NULL && !agent_config.server) {
884 g_printerr ("debugger-agent: The 'address' option is mandatory.\n");
885 exit (1);
888 // FIXME:
889 if (!strcmp (agent_config.transport, "dt_socket")) {
890 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
891 g_printerr ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
892 exit (1);
897 void
898 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
900 g_assertf (tls, "Cannot get state of null thread", NULL);
902 g_assert (tls->thread_state == expected);
904 tls->thread_state = set;
906 return;
909 MonoDebuggerThreadState
910 mono_debugger_get_thread_state (DebuggerTlsData *tls)
912 g_assertf (tls, "Cannot get state of null thread", NULL);
914 return tls->thread_state;
917 gsize
918 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
920 if (!tls)
921 return 0;
923 return tls->thread_id;
926 // Only call this function with the loader lock held
927 MonoGHashTable *
928 mono_debugger_get_thread_states (void)
930 return thread_to_tls;
933 gboolean
934 mono_debugger_is_disconnected (void)
936 return disconnected;
939 static void
940 debugger_agent_init (void)
942 if (!agent_config.enabled)
943 return;
945 DebuggerEngineCallbacks cbs;
946 memset (&cbs, 0, sizeof (cbs));
947 cbs.tls_get_restore_state = tls_get_restore_state;
948 cbs.try_process_suspend = try_process_suspend;
949 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
950 cbs.begin_single_step_processing = begin_single_step_processing;
951 cbs.ss_discard_frame_context = ss_discard_frame_context;
952 cbs.ss_calculate_framecount = ss_calculate_framecount;
953 cbs.ensure_jit = ensure_jit;
954 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
955 cbs.get_this_async_id = get_this_async_id;
956 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
957 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
958 cbs.create_breakpoint_events = create_breakpoint_events;
959 cbs.process_breakpoint_events = process_breakpoint_events;
960 cbs.ss_create_init_args = ss_create_init_args;
961 cbs.ss_args_destroy = ss_args_destroy;
963 mono_de_init (&cbs);
965 transport_init ();
967 /* Need to know whenever a thread has acquired the loader mutex */
968 mono_loader_lock_track_ownership (TRUE);
970 event_requests = g_ptr_array_new ();
972 mono_coop_mutex_init (&debugger_thread_exited_mutex);
973 mono_coop_cond_init (&debugger_thread_exited_cond);
975 MonoProfilerHandle prof = mono_profiler_create (NULL);
976 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
977 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
978 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
979 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
980 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
981 mono_profiler_set_thread_started_callback (prof, thread_startup);
982 mono_profiler_set_thread_stopped_callback (prof, thread_end);
983 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
984 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
985 mono_profiler_set_jit_done_callback (prof, jit_done);
986 mono_profiler_set_jit_failed_callback (prof, jit_failed);
987 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
988 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
990 mono_native_tls_alloc (&debugger_tls_id, NULL);
992 /* Needed by the hash_table_new_type () call below */
993 mono_gc_base_init ();
995 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");
997 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
999 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");
1001 pending_assembly_loads = g_ptr_array_new ();
1003 log_level = agent_config.log_level;
1005 embedding = agent_config.embedding;
1006 disconnected = TRUE;
1008 if (agent_config.log_file) {
1009 log_file = fopen (agent_config.log_file, "w+");
1010 if (!log_file) {
1011 g_printerr ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1012 exit (1);
1014 } else {
1015 log_file = stdout;
1017 mono_de_set_log_level (log_level, log_file);
1019 ids_init ();
1020 objrefs_init ();
1021 suspend_init ();
1023 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1025 * This is needed because currently we don't handle liveness info.
1027 mini_get_debug_options ()->mdb_optimizations = TRUE;
1029 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1030 /* This is needed because we can't set local variables in registers yet */
1031 mono_disable_optimizations (MONO_OPT_LINEARS);
1032 #endif
1035 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1036 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1037 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1038 * workaround.
1040 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1042 #ifdef HAVE_SETPGID
1043 if (agent_config.setpgid)
1044 setpgid (0, 0);
1045 #endif
1047 if (!agent_config.onuncaught && !agent_config.onthrow)
1048 finish_agent_init (TRUE);
1052 * finish_agent_init:
1054 * Finish the initialization of the agent. This involves connecting the transport
1055 * and starting the agent thread. This is either done at startup, or
1056 * in response to some event like an unhandled exception.
1058 static void
1059 finish_agent_init (gboolean on_startup)
1061 int res;
1063 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1064 return;
1066 if (agent_config.launch) {
1067 char *argv [16];
1069 // FIXME: Generated address
1070 // FIXME: Races with transport_connect ()
1072 argv [0] = agent_config.launch;
1073 argv [1] = agent_config.transport;
1074 argv [2] = agent_config.address;
1075 argv [3] = NULL;
1077 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1078 if (!res) {
1079 g_printerr ("Failed to execute '%s'.\n", agent_config.launch);
1080 exit (1);
1084 transport_connect (agent_config.address);
1086 if (!on_startup) {
1087 /* Do some which is usually done after sending the VMStart () event */
1088 vm_start_event_sent = TRUE;
1089 ERROR_DECL (error);
1090 start_debugger_thread (error);
1091 mono_error_assert_ok (error);
1095 static void
1096 mono_debugger_agent_cleanup (void)
1098 if (!inited)
1099 return;
1101 stop_debugger_thread ();
1103 event_requests_cleanup ();
1104 objrefs_cleanup ();
1105 ids_cleanup ();
1107 mono_de_cleanup ();
1111 * SOCKET TRANSPORT
1114 #ifndef DISABLE_SOCKET_TRANSPORT
1117 * recv_length:
1119 * recv() + handle incomplete reads and EINTR
1121 static int
1122 socket_transport_recv (void *buf, int len)
1124 int res;
1125 int total = 0;
1126 int fd = conn_fd;
1127 int flags = 0;
1128 static gint64 last_keepalive;
1129 gint64 msecs;
1131 MONO_ENTER_GC_SAFE;
1133 do {
1134 again:
1135 res = recv (fd, (char *) buf + total, len - total, flags);
1136 if (res > 0)
1137 total += res;
1138 if (agent_config.keepalive) {
1139 gboolean need_keepalive = FALSE;
1140 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1141 need_keepalive = TRUE;
1142 } else if (res == -1) {
1143 /* This could happen if recv () is interrupted repeatedly */
1144 msecs = mono_msec_ticks ();
1145 if (msecs - last_keepalive >= agent_config.keepalive) {
1146 need_keepalive = TRUE;
1147 last_keepalive = msecs;
1150 if (need_keepalive) {
1151 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1152 goto again;
1155 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1157 MONO_EXIT_GC_SAFE;
1159 return total;
1162 static void
1163 set_keepalive (void)
1165 struct timeval tv;
1166 int result;
1168 if (!agent_config.keepalive || !conn_fd)
1169 return;
1171 tv.tv_sec = agent_config.keepalive / 1000;
1172 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1174 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1175 g_assert (result >= 0);
1178 static int
1179 socket_transport_accept (int socket_fd)
1181 MONO_ENTER_GC_SAFE;
1182 conn_fd = accept (socket_fd, NULL, NULL);
1183 MONO_EXIT_GC_SAFE;
1185 if (conn_fd == -1) {
1186 g_printerr ("debugger-agent: Unable to listen on %d\n", socket_fd);
1187 } else {
1188 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1191 return conn_fd;
1194 static gboolean
1195 socket_transport_send (void *data, int len)
1197 int res;
1199 MONO_ENTER_GC_SAFE;
1201 do {
1202 res = send (conn_fd, (const char*)data, len, 0);
1203 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1205 MONO_EXIT_GC_SAFE;
1207 if (res != len)
1208 return FALSE;
1209 else
1210 return TRUE;
1214 * socket_transport_connect:
1216 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1218 static void
1219 socket_transport_connect (const char *address)
1221 MonoAddressInfo *result;
1222 MonoAddressEntry *rp;
1223 int sfd = -1, s, res;
1224 char *host;
1225 int port;
1227 if (agent_config.address) {
1228 res = parse_address (agent_config.address, &host, &port);
1229 g_assert (res == 0);
1230 } else {
1231 host = NULL;
1232 port = 0;
1235 conn_fd = -1;
1236 listen_fd = -1;
1238 if (host) {
1240 mono_network_init ();
1242 /* Obtain address(es) matching host/port */
1243 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1244 if (s != 0) {
1245 g_printerr ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1246 exit (1);
1250 if (agent_config.server) {
1251 /* Wait for a connection */
1252 if (!host) {
1253 struct sockaddr_in addr;
1254 socklen_t addrlen;
1256 /* No address, generate one */
1257 sfd = socket (AF_INET, SOCK_STREAM, 0);
1258 if (sfd == -1) {
1259 g_printerr ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1260 exit (1);
1263 /* This will bind the socket to a random port */
1264 res = listen (sfd, 16);
1265 if (res == -1) {
1266 g_printerr ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1267 exit (1);
1269 listen_fd = sfd;
1271 addrlen = sizeof (addr);
1272 memset (&addr, 0, sizeof (addr));
1273 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1274 g_assert (res == 0);
1276 host = (char*)"127.0.0.1";
1277 port = ntohs (addr.sin_port);
1279 /* Emit the address to stdout */
1280 /* FIXME: Should print another interface, not localhost */
1281 printf ("%s:%d\n", host, port);
1282 } else {
1283 /* Listen on the provided address */
1284 for (rp = result->entries; rp != NULL; rp = rp->next) {
1285 MonoSocketAddress sockaddr;
1286 socklen_t sock_len;
1287 int n = 1;
1289 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1291 sfd = socket (rp->family, rp->socktype,
1292 rp->protocol);
1293 if (sfd == -1)
1294 continue;
1296 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1297 continue;
1299 res = bind (sfd, &sockaddr.addr, sock_len);
1300 if (res == -1)
1301 continue;
1303 res = listen (sfd, 16);
1304 if (res == -1)
1305 continue;
1306 listen_fd = sfd;
1307 break;
1310 mono_free_address_info (result);
1313 if (agent_config.defer)
1314 return;
1316 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1318 if (agent_config.timeout) {
1319 fd_set readfds;
1320 struct timeval tv;
1322 tv.tv_sec = 0;
1323 tv.tv_usec = agent_config.timeout * 1000;
1324 FD_ZERO (&readfds);
1325 FD_SET (sfd, &readfds);
1327 MONO_ENTER_GC_SAFE;
1328 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1329 MONO_EXIT_GC_SAFE;
1331 if (res == 0) {
1332 g_printerr ("debugger-agent: Timed out waiting to connect.\n");
1333 exit (1);
1337 conn_fd = socket_transport_accept (sfd);
1338 if (conn_fd == -1)
1339 exit (1);
1341 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1342 } else {
1343 /* Connect to the specified address */
1344 /* FIXME: Respect the timeout */
1345 for (rp = result->entries; rp != NULL; rp = rp->next) {
1346 MonoSocketAddress sockaddr;
1347 socklen_t sock_len;
1349 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1351 sfd = socket (rp->family, rp->socktype,
1352 rp->protocol);
1353 if (sfd == -1)
1354 continue;
1356 MONO_ENTER_GC_SAFE;
1357 res = connect (sfd, &sockaddr.addr, sock_len);
1358 MONO_EXIT_GC_SAFE;
1360 if (res != -1)
1361 break; /* Success */
1363 MONO_ENTER_GC_SAFE;
1364 #ifdef HOST_WIN32
1365 closesocket (sfd);
1366 #else
1367 close (sfd);
1368 #endif
1369 MONO_EXIT_GC_SAFE;
1372 if (rp == 0) {
1373 g_printerr ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1374 exit (1);
1377 conn_fd = sfd;
1379 mono_free_address_info (result);
1382 if (!transport_handshake ())
1383 exit (1);
1386 static void
1387 socket_transport_close1 (void)
1389 /* This will interrupt the agent thread */
1390 /* Close the read part only so it can still send back replies */
1391 /* Also shut down the connection listener so that we can exit normally */
1392 #ifdef HOST_WIN32
1393 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1394 shutdown (conn_fd, SD_BOTH);
1395 shutdown (listen_fd, SD_BOTH);
1396 closesocket (listen_fd);
1397 #else
1398 shutdown (conn_fd, SHUT_RD);
1399 shutdown (listen_fd, SHUT_RDWR);
1400 MONO_ENTER_GC_SAFE;
1401 close (listen_fd);
1402 MONO_EXIT_GC_SAFE;
1403 #endif
1406 static void
1407 socket_transport_close2 (void)
1409 #ifdef HOST_WIN32
1410 shutdown (conn_fd, SD_BOTH);
1411 #else
1412 shutdown (conn_fd, SHUT_RDWR);
1413 #endif
1416 static void
1417 register_socket_transport (void)
1419 DebuggerTransport trans;
1421 trans.name = "dt_socket";
1422 trans.connect = socket_transport_connect;
1423 trans.close1 = socket_transport_close1;
1424 trans.close2 = socket_transport_close2;
1425 trans.send = socket_transport_send;
1426 trans.recv = socket_transport_recv;
1428 register_transport (&trans);
1432 * socket_fd_transport_connect:
1435 static void
1436 socket_fd_transport_connect (const char *address)
1438 int res;
1440 res = sscanf (address, "%d", &conn_fd);
1441 if (res != 1) {
1442 g_printerr ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1443 exit (1);
1446 if (!transport_handshake ())
1447 exit (1);
1450 static void
1451 register_socket_fd_transport (void)
1453 DebuggerTransport trans;
1455 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1456 trans.name = "socket-fd";
1457 trans.connect = socket_fd_transport_connect;
1458 trans.close1 = socket_transport_close1;
1459 trans.close2 = socket_transport_close2;
1460 trans.send = socket_transport_send;
1461 trans.recv = socket_transport_recv;
1463 register_transport (&trans);
1466 #endif /* DISABLE_SOCKET_TRANSPORT */
1469 * TRANSPORT CODE
1472 #define MAX_TRANSPORTS 16
1474 static DebuggerTransport *transport;
1476 static DebuggerTransport transports [MAX_TRANSPORTS];
1477 static int ntransports;
1479 MONO_API void
1480 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1482 void
1483 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1485 register_transport (trans);
1488 static void
1489 register_transport (DebuggerTransport *trans)
1491 g_assert (ntransports < MAX_TRANSPORTS);
1493 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1494 ntransports ++;
1497 static void
1498 transport_init (void)
1500 int i;
1502 #ifndef DISABLE_SOCKET_TRANSPORT
1503 register_socket_transport ();
1504 register_socket_fd_transport ();
1505 #endif
1507 for (i = 0; i < ntransports; ++i) {
1508 if (!strcmp (agent_config.transport, transports [i].name))
1509 break;
1511 if (i == ntransports) {
1512 g_printerr ("debugger-agent: The supported values for the 'transport' option are: ");
1513 for (i = 0; i < ntransports; ++i)
1514 g_printerr ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1515 g_printerr ("\n");
1516 exit (1);
1518 transport = &transports [i];
1521 void
1522 transport_connect (const char *address)
1524 transport->connect (address);
1527 static void
1528 transport_close1 (void)
1530 transport->close1 ();
1533 static void
1534 transport_close2 (void)
1536 transport->close2 ();
1539 static int
1540 transport_send (void *buf, int len)
1542 return transport->send (buf, len);
1545 static int
1546 transport_recv (void *buf, int len)
1548 return transport->recv (buf, len);
1551 gboolean
1552 mono_debugger_agent_transport_handshake (void)
1554 return transport_handshake ();
1557 static gboolean
1558 transport_handshake (void)
1560 char handshake_msg [128];
1561 guint8 buf [128];
1562 int res;
1564 disconnected = TRUE;
1566 /* Write handshake message */
1567 sprintf (handshake_msg, "DWP-Handshake");
1569 do {
1570 res = transport_send (handshake_msg, strlen (handshake_msg));
1571 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1573 g_assert (res != -1);
1575 /* Read answer */
1576 res = transport_recv (buf, strlen (handshake_msg));
1577 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1578 g_printerr ("debugger-agent: DWP handshake failed.\n");
1579 return FALSE;
1583 * To support older clients, the client sends its protocol version after connecting
1584 * using a command. Until that is received, default to our protocol version.
1586 major_version = MAJOR_VERSION;
1587 minor_version = MINOR_VERSION;
1588 protocol_version_set = FALSE;
1590 #ifndef DISABLE_SOCKET_TRANSPORT
1591 // FIXME: Move this somewhere else
1593 * Set TCP_NODELAY on the socket so the client receives events/command
1594 * results immediately.
1596 if (conn_fd) {
1597 int flag = 1;
1598 int result = setsockopt (conn_fd,
1599 IPPROTO_TCP,
1600 TCP_NODELAY,
1601 (char *) &flag,
1602 sizeof(int));
1603 g_assert (result >= 0);
1606 set_keepalive ();
1607 #endif
1609 disconnected = FALSE;
1610 return TRUE;
1613 static void
1614 stop_debugger_thread (void)
1616 if (!inited)
1617 return;
1619 transport_close1 ();
1622 * Wait for the thread to exit.
1624 * If we continue with the shutdown without waiting for it, then the client might
1625 * not receive an answer to its last command like a resume.
1627 if (!is_debugger_thread ()) {
1628 do {
1629 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1630 if (!debugger_thread_exited)
1631 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1632 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1633 } while (!debugger_thread_exited);
1635 if (debugger_thread_handle)
1636 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1639 transport_close2 ();
1642 static void
1643 start_debugger_thread (MonoError *error)
1645 MonoInternalThread *thread;
1647 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1648 return_if_nok (error);
1650 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1651 g_assert (debugger_thread_handle);
1656 * Functions to decode protocol data
1659 static int
1660 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1662 *endbuf = buf + 1;
1663 g_assert (*endbuf <= limit);
1664 return buf [0];
1667 static int
1668 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1670 *endbuf = buf + 4;
1671 g_assert (*endbuf <= limit);
1673 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1676 static gint64
1677 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1679 guint32 high = decode_int (buf, &buf, limit);
1680 guint32 low = decode_int (buf, &buf, limit);
1682 *endbuf = buf;
1684 return ((((guint64)high) << 32) | ((guint64)low));
1687 static int
1688 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1690 return decode_int (buf, endbuf, limit);
1693 static char*
1694 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1696 int len = decode_int (buf, &buf, limit);
1697 char *s;
1699 if (len < 0) {
1700 *endbuf = buf;
1701 return NULL;
1704 s = (char *)g_malloc (len + 1);
1705 g_assert (s);
1707 memcpy (s, buf, len);
1708 s [len] = '\0';
1709 buf += len;
1710 *endbuf = buf;
1712 return s;
1716 * Functions to encode protocol data
1719 static void
1720 buffer_init (Buffer *buf, int size)
1722 buf->buf = (guint8 *)g_malloc (size);
1723 buf->p = buf->buf;
1724 buf->end = buf->buf + size;
1727 static int
1728 buffer_len (Buffer *buf)
1730 return buf->p - buf->buf;
1733 static void
1734 buffer_make_room (Buffer *buf, int size)
1736 if (buf->end - buf->p < size) {
1737 int new_size = buf->end - buf->buf + size + 32;
1738 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1739 size = buf->p - buf->buf;
1740 buf->buf = p;
1741 buf->p = p + size;
1742 buf->end = buf->buf + new_size;
1746 static void
1747 buffer_add_byte (Buffer *buf, guint8 val)
1749 buffer_make_room (buf, 1);
1750 buf->p [0] = val;
1751 buf->p++;
1754 static void
1755 buffer_add_short (Buffer *buf, guint32 val)
1757 buffer_make_room (buf, 2);
1758 buf->p [0] = (val >> 8) & 0xff;
1759 buf->p [1] = (val >> 0) & 0xff;
1760 buf->p += 2;
1763 static void
1764 buffer_add_int (Buffer *buf, guint32 val)
1766 buffer_make_room (buf, 4);
1767 buf->p [0] = (val >> 24) & 0xff;
1768 buf->p [1] = (val >> 16) & 0xff;
1769 buf->p [2] = (val >> 8) & 0xff;
1770 buf->p [3] = (val >> 0) & 0xff;
1771 buf->p += 4;
1774 static void
1775 buffer_add_long (Buffer *buf, guint64 l)
1777 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1778 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1781 static void
1782 buffer_add_id (Buffer *buf, int id)
1784 buffer_add_int (buf, (guint64)id);
1787 static void
1788 buffer_add_data (Buffer *buf, guint8 *data, int len)
1790 buffer_make_room (buf, len);
1791 memcpy (buf->p, data, len);
1792 buf->p += len;
1795 static void
1796 buffer_add_string (Buffer *buf, const char *str)
1798 int len;
1800 if (str == NULL) {
1801 buffer_add_int (buf, 0);
1802 } else {
1803 len = strlen (str);
1804 buffer_add_int (buf, len);
1805 buffer_add_data (buf, (guint8*)str, len);
1809 static void
1810 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1812 buffer_add_int (buf, arr_len);
1813 buffer_add_data (buf, bytes, arr_len);
1816 static void
1817 buffer_add_buffer (Buffer *buf, Buffer *data)
1819 buffer_add_data (buf, data->buf, buffer_len (data));
1822 static void
1823 buffer_free (Buffer *buf)
1825 g_free (buf->buf);
1828 static gboolean
1829 send_packet (int command_set, int command, Buffer *data)
1831 Buffer buf;
1832 int len, id;
1833 gboolean res;
1835 id = mono_atomic_inc_i32 (&packet_id);
1837 len = data->p - data->buf + 11;
1838 buffer_init (&buf, len);
1839 buffer_add_int (&buf, len);
1840 buffer_add_int (&buf, id);
1841 buffer_add_byte (&buf, 0); /* flags */
1842 buffer_add_byte (&buf, command_set);
1843 buffer_add_byte (&buf, command);
1844 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1846 res = transport_send (buf.buf, len);
1848 buffer_free (&buf);
1850 return res;
1853 static gboolean
1854 send_reply_packets (int npackets, ReplyPacket *packets)
1856 Buffer buf;
1857 int i, len;
1858 gboolean res;
1860 len = 0;
1861 for (i = 0; i < npackets; ++i)
1862 len += buffer_len (packets [i].data) + 11;
1863 buffer_init (&buf, len);
1864 for (i = 0; i < npackets; ++i) {
1865 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1866 buffer_add_int (&buf, packets [i].id);
1867 buffer_add_byte (&buf, 0x80); /* flags */
1868 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1869 buffer_add_byte (&buf, packets [i].error);
1870 buffer_add_buffer (&buf, packets [i].data);
1873 res = transport_send (buf.buf, len);
1875 buffer_free (&buf);
1877 return res;
1880 static gboolean
1881 send_reply_packet (int id, int error, Buffer *data)
1883 ReplyPacket packet;
1885 memset (&packet, 0, sizeof (ReplyPacket));
1886 packet.id = id;
1887 packet.error = error;
1888 packet.data = data;
1890 return send_reply_packets (1, &packet);
1893 static void
1894 send_buffered_reply_packets (void)
1896 int i;
1898 send_reply_packets (nreply_packets, reply_packets);
1899 for (i = 0; i < nreply_packets; ++i)
1900 buffer_free (reply_packets [i].data);
1901 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1902 nreply_packets = 0;
1905 static void
1906 buffer_reply_packet (int id, int error, Buffer *data)
1908 ReplyPacket *p;
1910 if (nreply_packets == 128)
1911 send_buffered_reply_packets ();
1913 p = &reply_packets [nreply_packets];
1914 p->id = id;
1915 p->error = error;
1916 p->data = g_new0 (Buffer, 1);
1917 buffer_init (p->data, buffer_len (data));
1918 buffer_add_buffer (p->data, data);
1919 nreply_packets ++;
1923 /* Maps objid -> ObjRef */
1924 /* Protected by the loader lock */
1925 static GHashTable *objrefs;
1926 /* Protected by the loader lock */
1927 static GHashTable *obj_to_objref;
1928 /* Protected by the dbg lock */
1929 static MonoGHashTable *suspended_objs;
1933 static void
1934 objrefs_init (void)
1936 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1937 obj_to_objref = g_hash_table_new (NULL, NULL);
1938 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");
1941 static void
1942 objrefs_cleanup (void)
1944 g_hash_table_destroy (objrefs);
1945 objrefs = NULL;
1949 * Return an ObjRef for OBJ.
1951 static ObjRef*
1952 get_objref (MonoObject *obj)
1954 ObjRef *ref;
1955 GSList *reflist = NULL, *l;
1956 int hash = 0;
1958 if (obj == NULL)
1959 return NULL;
1961 if (suspend_count) {
1963 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1965 dbg_lock ();
1966 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
1967 dbg_unlock ();
1970 mono_loader_lock ();
1972 /* FIXME: The tables can grow indefinitely */
1974 if (mono_gc_is_moving ()) {
1976 * Objects can move, so use a hash table mapping hash codes to lists of
1977 * ObjRef structures.
1979 hash = mono_object_hash_internal (obj);
1981 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1982 for (l = reflist; l; l = l->next) {
1983 ref = (ObjRef *)l->data;
1984 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1985 mono_loader_unlock ();
1986 return ref;
1989 } else {
1990 /* Use a hash table with masked pointers to internalize object references */
1991 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1992 /* ref might refer to a different object with the same addr which was GCd */
1993 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1994 mono_loader_unlock ();
1995 return ref;
1999 ref = g_new0 (ObjRef, 1);
2000 ref->id = mono_atomic_inc_i32 (&objref_id);
2001 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2003 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2005 if (mono_gc_is_moving ()) {
2006 reflist = g_slist_append (reflist, ref);
2007 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2008 } else {
2009 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2012 mono_loader_unlock ();
2014 return ref;
2017 static gboolean
2018 true_pred (gpointer key, gpointer value, gpointer user_data)
2020 return TRUE;
2023 static void
2024 clear_suspended_objs (void)
2026 dbg_lock ();
2027 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2028 dbg_unlock ();
2031 static int
2032 get_objid (MonoObject *obj)
2034 if (!obj)
2035 return 0;
2036 else
2037 return get_objref (obj)->id;
2041 * Set OBJ to the object identified by OBJID.
2042 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2043 * collected.
2045 static ErrorCode
2046 get_object_allow_null (int objid, MonoObject **obj)
2048 ObjRef *ref;
2050 if (objid == 0) {
2051 *obj = NULL;
2052 return ERR_NONE;
2055 if (!objrefs)
2056 return ERR_INVALID_OBJECT;
2058 mono_loader_lock ();
2060 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2062 if (ref) {
2063 *obj = mono_gchandle_get_target_internal (ref->handle);
2064 mono_loader_unlock ();
2065 if (!(*obj))
2066 return ERR_INVALID_OBJECT;
2067 return ERR_NONE;
2068 } else {
2069 mono_loader_unlock ();
2070 return ERR_INVALID_OBJECT;
2074 static ErrorCode
2075 get_object (int objid, MonoObject **obj)
2077 ErrorCode err = get_object_allow_null (objid, obj);
2079 if (err != ERR_NONE)
2080 return err;
2081 if (!(*obj))
2082 return ERR_INVALID_OBJECT;
2083 return ERR_NONE;
2086 static int
2087 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2089 return decode_id (buf, endbuf, limit);
2092 static void
2093 buffer_add_objid (Buffer *buf, MonoObject *o)
2095 buffer_add_id (buf, get_objid (o));
2099 * IDS
2102 typedef enum {
2103 ID_ASSEMBLY = 0,
2104 ID_MODULE = 1,
2105 ID_TYPE = 2,
2106 ID_METHOD = 3,
2107 ID_FIELD = 4,
2108 ID_DOMAIN = 5,
2109 ID_PROPERTY = 6,
2110 ID_NUM
2111 } IdType;
2114 * Represents a runtime structure accessible to the debugger client
2116 typedef struct {
2117 /* Unique id used in the wire protocol */
2118 int id;
2119 /* Domain of the runtime structure, NULL if the domain was unloaded */
2120 MonoDomain *domain;
2121 union {
2122 gpointer val;
2123 MonoClass *klass;
2124 MonoMethod *method;
2125 MonoImage *image;
2126 MonoAssembly *assembly;
2127 MonoClassField *field;
2128 MonoDomain *domain;
2129 MonoProperty *property;
2130 } data;
2131 } Id;
2133 typedef struct {
2134 /* Maps runtime structure -> Id */
2135 /* Protected by the dbg lock */
2136 GHashTable *val_to_id [ID_NUM];
2137 /* Classes whose class load event has been sent */
2138 /* Protected by the loader lock */
2139 GHashTable *loaded_classes;
2140 /* Maps MonoClass->GPtrArray of file names */
2141 GHashTable *source_files;
2142 /* Maps source file basename -> GSList of classes */
2143 GHashTable *source_file_to_class;
2144 /* Same with ignore-case */
2145 GHashTable *source_file_to_class_ignorecase;
2146 } AgentDomainInfo;
2148 /* Maps id -> Id */
2149 /* Protected by the dbg lock */
2150 static GPtrArray *ids [ID_NUM];
2152 static void
2153 ids_init (void)
2155 int i;
2157 for (i = 0; i < ID_NUM; ++i)
2158 ids [i] = g_ptr_array_new ();
2161 static void
2162 ids_cleanup (void)
2164 int i, j;
2166 for (i = 0; i < ID_NUM; ++i) {
2167 if (ids [i]) {
2168 for (j = 0; j < ids [i]->len; ++j)
2169 g_free (g_ptr_array_index (ids [i], j));
2170 g_ptr_array_free (ids [i], TRUE);
2172 ids [i] = NULL;
2176 static void
2177 debugger_agent_free_domain_info (MonoDomain *domain)
2179 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2180 int i, j;
2181 GHashTableIter iter;
2182 GPtrArray *file_names;
2183 char *basename;
2184 GSList *l;
2186 if (info) {
2187 for (i = 0; i < ID_NUM; ++i)
2188 g_hash_table_destroy (info->val_to_id [i]);
2189 g_hash_table_destroy (info->loaded_classes);
2191 g_hash_table_iter_init (&iter, info->source_files);
2192 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2193 for (i = 0; i < file_names->len; ++i)
2194 g_free (g_ptr_array_index (file_names, i));
2195 g_ptr_array_free (file_names, TRUE);
2198 g_hash_table_iter_init (&iter, info->source_file_to_class);
2199 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2200 g_free (basename);
2201 g_slist_free (l);
2204 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2205 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2206 g_free (basename);
2207 g_slist_free (l);
2210 g_free (info);
2213 domain_jit_info (domain)->agent_info = NULL;
2215 /* Clear ids referencing structures in the domain */
2216 dbg_lock ();
2217 for (i = 0; i < ID_NUM; ++i) {
2218 if (ids [i]) {
2219 for (j = 0; j < ids [i]->len; ++j) {
2220 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2221 if (id->domain == domain)
2222 id->domain = NULL;
2226 dbg_unlock ();
2228 mono_de_domain_remove (domain);
2231 static AgentDomainInfo*
2232 get_agent_domain_info (MonoDomain *domain)
2234 AgentDomainInfo *info = NULL;
2235 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2237 info = (AgentDomainInfo *)jit_info->agent_info;
2239 if (info) {
2240 mono_memory_read_barrier ();
2241 return info;
2244 info = g_new0 (AgentDomainInfo, 1);
2245 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2246 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2247 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2248 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2250 mono_memory_write_barrier ();
2252 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2254 if (other_info != NULL) {
2255 g_hash_table_destroy (info->loaded_classes);
2256 g_hash_table_destroy (info->source_files);
2257 g_hash_table_destroy (info->source_file_to_class);
2258 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2259 g_free (info);
2262 return (AgentDomainInfo *)jit_info->agent_info;
2265 static int
2266 get_id (MonoDomain *domain, IdType type, gpointer val)
2268 Id *id;
2269 AgentDomainInfo *info;
2271 if (val == NULL)
2272 return 0;
2274 info = get_agent_domain_info (domain);
2276 dbg_lock ();
2278 if (info->val_to_id [type] == NULL)
2279 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2281 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2282 if (id) {
2283 dbg_unlock ();
2284 return id->id;
2287 id = g_new0 (Id, 1);
2288 /* Reserve id 0 */
2289 id->id = ids [type]->len + 1;
2290 id->domain = domain;
2291 id->data.val = val;
2293 g_hash_table_insert (info->val_to_id [type], val, id);
2294 g_ptr_array_add (ids [type], id);
2296 dbg_unlock ();
2298 return id->id;
2301 static gpointer
2302 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2304 Id *res;
2306 int id = decode_id (buf, endbuf, limit);
2308 *err = ERR_NONE;
2309 if (domain)
2310 *domain = NULL;
2312 if (id == 0)
2313 return NULL;
2315 // FIXME: error handling
2316 dbg_lock ();
2317 g_assert (id > 0 && id <= ids [type]->len);
2319 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2320 dbg_unlock ();
2322 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2323 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2324 *err = ERR_UNLOADED;
2325 return NULL;
2328 if (domain)
2329 *domain = res->domain;
2331 return res->data.val;
2334 static int
2335 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2337 int id = get_id (domain, type, val);
2339 buffer_add_id (buf, id);
2340 return id;
2343 static MonoClass*
2344 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2346 MonoClass *klass;
2348 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2349 if (G_UNLIKELY (log_level >= 2) && klass) {
2350 char *s;
2352 s = mono_type_full_name (m_class_get_byval_arg (klass));
2353 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2354 g_free (s);
2356 return klass;
2359 static MonoAssembly*
2360 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2362 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2365 static MonoImage*
2366 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2368 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2371 static MonoMethod*
2372 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2374 MonoMethod *m;
2376 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2377 if (G_UNLIKELY (log_level >= 2) && m) {
2378 char *s;
2380 s = mono_method_full_name (m, TRUE);
2381 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2382 g_free (s);
2384 return m;
2387 static MonoClassField*
2388 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2390 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2393 static MonoDomain*
2394 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2396 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2399 static MonoProperty*
2400 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2402 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2405 static void
2406 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2408 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2409 if (G_UNLIKELY (log_level >= 2) && klass) {
2410 char *s;
2412 s = mono_type_full_name (m_class_get_byval_arg (klass));
2413 if (is_debugger_thread ())
2414 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2415 else
2416 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2417 g_free (s);
2421 static void
2422 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2424 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2425 if (G_UNLIKELY (log_level >= 2) && method) {
2426 char *s;
2428 s = mono_method_full_name (method, 1);
2429 if (is_debugger_thread ())
2430 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2431 else
2432 DEBUG_PRINTF (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2433 g_free (s);
2437 static void
2438 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2440 int id;
2442 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2443 if (G_UNLIKELY (log_level >= 2) && assembly)
2444 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2447 static void
2448 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2450 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2453 static void
2454 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2456 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2459 static void
2460 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2462 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2465 static void
2466 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2468 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2471 static void invoke_method (void);
2474 * SUSPEND/RESUME
2477 static MonoJitInfo*
2478 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2480 MonoJitInfo *ji;
2482 if (out_ip)
2483 *out_ip = ip;
2485 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2486 if (!ji) {
2487 /* Could be an interpreter method */
2489 MonoLMF *lmf = mono_get_lmf ();
2490 MonoInterpFrameHandle *frame;
2492 g_assert (((gsize)lmf->previous_lmf) & 2);
2493 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2495 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2496 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2497 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2498 if (domain)
2499 *domain = mono_domain_get ();
2500 if (out_ip)
2501 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2503 return ji;
2507 * save_thread_context:
2509 * Set CTX as the current threads context which is used for computing stack traces.
2510 * This function is signal-safe.
2512 static void
2513 save_thread_context (MonoContext *ctx)
2515 DebuggerTlsData *tls;
2517 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2518 g_assert (tls);
2520 if (ctx)
2521 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2522 else
2523 mono_thread_state_init_from_current (&tls->context);
2526 /* Number of threads suspended */
2528 * If this is equal to the size of thread_to_tls, the runtime is considered
2529 * suspended.
2531 static gint32 threads_suspend_count;
2533 static MonoCoopMutex suspend_mutex;
2535 /* Cond variable used to wait for suspend_count becoming 0 */
2536 static MonoCoopCond suspend_cond;
2538 /* Semaphore used to wait for a thread becoming suspended */
2539 static MonoCoopSem suspend_sem;
2541 static void
2542 suspend_init (void)
2544 mono_coop_mutex_init (&suspend_mutex);
2545 mono_coop_cond_init (&suspend_cond);
2546 mono_coop_sem_init (&suspend_sem, 0);
2549 typedef struct
2551 StackFrameInfo last_frame;
2552 gboolean last_frame_set;
2553 MonoContext ctx;
2554 gpointer lmf;
2555 MonoDomain *domain;
2556 } GetLastFrameUserData;
2558 static gboolean
2559 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2561 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2563 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2564 return FALSE;
2566 if (!data->last_frame_set) {
2567 /* Store the last frame */
2568 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2569 data->last_frame_set = TRUE;
2570 return FALSE;
2571 } else {
2572 /* Store the context/lmf for the frame above the last frame */
2573 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2574 data->lmf = info->lmf;
2575 data->domain = info->domain;
2576 return TRUE;
2580 static void
2581 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2583 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2585 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2586 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2587 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2588 to->valid = TRUE;
2592 * thread_interrupt:
2594 * Process interruption of a thread. This should be signal safe.
2596 * This always runs in the debugger thread.
2598 static void
2599 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2601 gpointer ip;
2602 MonoNativeThreadId tid;
2604 g_assert (info);
2606 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2607 tid = mono_thread_info_get_tid (info);
2609 // FIXME: Races when the thread leaves managed code before hitting a single step
2610 // event.
2612 if (ji && !ji->is_trampoline) {
2613 /* Running managed code, will be suspended by the single step code */
2614 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2615 } else {
2617 * Running native code, will be suspended when it returns to/enters
2618 * managed code. Treat it as already suspended.
2619 * This might interrupt the code in mono_de_process_single_step (), we use the
2620 * tls->suspending flag to avoid races when that happens.
2622 if (!tls->suspended && !tls->suspending) {
2623 GetLastFrameUserData data;
2625 // FIXME: printf is not signal safe, but this is only used during
2626 // debugger debugging
2627 if (ip)
2628 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2629 //save_thread_context (&ctx);
2631 if (!tls->thread)
2632 /* Already terminated */
2633 return;
2636 * We are in a difficult position: we want to be able to provide stack
2637 * traces for this thread, but we can't use the current ctx+lmf, since
2638 * the thread is still running, so it might return to managed code,
2639 * making these invalid.
2640 * So we start a stack walk and save the first frame, along with the
2641 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2642 * suspended when it returns to managed code, so the parent's ctx should
2643 * remain valid.
2645 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2647 data.last_frame_set = FALSE;
2648 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2649 if (data.last_frame_set) {
2650 gpointer jit_tls = tls->thread->thread_info->jit_data;
2652 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2654 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2656 * Store the current lmf instead of the parent one, since that
2657 * contains the interp exit data.
2659 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2662 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2663 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2664 } else {
2665 tls->async_state.valid = FALSE;
2668 mono_memory_barrier ();
2670 tls->suspended = TRUE;
2671 mono_coop_sem_post (&suspend_sem);
2677 * reset_native_thread_suspend_state:
2679 * Reset the suspended flag and state on native threads
2681 static void
2682 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2684 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2686 if (!tls->really_suspended && tls->suspended) {
2687 tls->suspended = FALSE;
2689 * The thread might still be running if it was executing native code, so the state won't be invalided by
2690 * suspend_current ().
2692 tls->context.valid = FALSE;
2693 tls->async_state.valid = FALSE;
2694 invalidate_frames (tls);
2698 typedef struct {
2699 DebuggerTlsData *tls;
2700 gboolean valid_info;
2701 } InterruptData;
2703 static SuspendThreadResult
2704 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2706 InterruptData *data = (InterruptData *)user_data;
2707 MonoJitInfo *ji;
2709 data->valid_info = TRUE;
2710 ji = mono_jit_info_table_find_internal (
2711 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2712 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2713 TRUE,
2714 TRUE);
2716 /* This is signal safe */
2717 thread_interrupt (data->tls, info, ji);
2718 return MonoResumeThread;
2722 * notify_thread:
2724 * Notify a thread that it needs to suspend.
2726 static void
2727 notify_thread (gpointer key, gpointer value, gpointer user_data)
2729 MonoInternalThread *thread = (MonoInternalThread *)key;
2730 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2731 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2733 if (mono_thread_internal_is_current (thread) || tls->terminated)
2734 return;
2736 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2738 /* This is _not_ equivalent to mono_thread_internal_abort () */
2739 InterruptData interrupt_data = { 0 };
2740 interrupt_data.tls = tls;
2742 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2743 if (!interrupt_data.valid_info) {
2744 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2746 * Attached thread which died without detaching.
2748 tls->terminated = TRUE;
2752 static void
2753 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2755 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2756 MonoJitInfo *ji;
2757 MonoMethod *method;
2759 if (mono_loader_lock_is_owned_by_self ()) {
2761 * Shortcut for the check in suspend_current (). This speeds up processing
2762 * when executing long running code inside the loader lock, i.e. assembly load
2763 * hooks.
2765 return;
2768 if (is_debugger_thread ())
2769 return;
2771 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2772 if (suspend_count - tls->resume_count > 0)
2773 tls->suspending = TRUE;
2775 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2777 if (suspend_count - tls->resume_count == 0) {
2779 * We are executing a single threaded invoke but the single step for
2780 * suspending is still active.
2781 * FIXME: This slows down single threaded invokes.
2783 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2784 return;
2787 ji = get_top_method_ji (ip, NULL, NULL);
2788 g_assert (ji);
2789 /* Can't suspend in these methods */
2790 method = jinfo_get_method (ji);
2791 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2792 return;
2794 save_thread_context (ctx);
2796 suspend_current ();
2800 /* Conditionally call process_suspend depending oh the current state */
2801 static gboolean
2802 try_process_suspend (void *the_tls, MonoContext *ctx)
2804 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2806 if (suspend_count > 0) {
2807 /* Fastpath during invokes, see in process_suspend () */
2808 if (suspend_count - tls->resume_count == 0)
2809 return FALSE;
2810 if (tls->invoke)
2811 return FALSE;
2812 process_suspend (tls, ctx);
2813 return TRUE;
2815 return FALSE;
2819 * suspend_vm:
2821 * Increase the suspend count of the VM. While the suspend count is greater
2822 * than 0, runtime threads are suspended at certain points during execution.
2824 static void
2825 suspend_vm (void)
2827 gboolean tp_suspend = FALSE;
2828 mono_loader_lock ();
2830 mono_coop_mutex_lock (&suspend_mutex);
2832 suspend_count ++;
2834 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2836 if (suspend_count == 1) {
2837 // FIXME: Is it safe to call this inside the lock ?
2838 mono_de_start_single_stepping ();
2839 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2842 mono_coop_mutex_unlock (&suspend_mutex);
2844 if (suspend_count == 1)
2846 * Suspend creation of new threadpool threads, since they cannot run
2848 tp_suspend = TRUE;
2849 mono_loader_unlock ();
2851 if (tp_suspend)
2852 mono_threadpool_suspend ();
2856 * resume_vm:
2858 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2859 * are resumed.
2861 static void
2862 resume_vm (void)
2864 g_assert (is_debugger_thread ());
2865 gboolean tp_resume = FALSE;
2867 mono_loader_lock ();
2869 mono_coop_mutex_lock (&suspend_mutex);
2871 g_assert (suspend_count > 0);
2872 suspend_count --;
2874 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2876 if (suspend_count == 0) {
2877 // FIXME: Is it safe to call this inside the lock ?
2878 mono_de_stop_single_stepping ();
2879 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2882 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2883 mono_coop_cond_broadcast (&suspend_cond);
2885 mono_coop_mutex_unlock (&suspend_mutex);
2886 //g_assert (err == 0);
2888 if (suspend_count == 0)
2889 tp_resume = TRUE;
2890 mono_loader_unlock ();
2892 if (tp_resume)
2893 mono_threadpool_resume ();
2897 * resume_thread:
2899 * Resume just one thread.
2901 static void
2902 resume_thread (MonoInternalThread *thread)
2904 DebuggerTlsData *tls;
2906 g_assert (is_debugger_thread ());
2908 mono_loader_lock ();
2910 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2911 g_assert (tls);
2913 mono_coop_mutex_lock (&suspend_mutex);
2915 g_assert (suspend_count > 0);
2917 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2919 tls->resume_count += suspend_count;
2922 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2923 * but only the one whose resume_count field is > 0 will be resumed.
2925 mono_coop_cond_broadcast (&suspend_cond);
2927 mono_coop_mutex_unlock (&suspend_mutex);
2928 //g_assert (err == 0);
2930 mono_loader_unlock ();
2933 static void
2934 free_frames (StackFrame **frames, int nframes)
2936 int i;
2938 for (i = 0; i < nframes; ++i) {
2939 if (frames [i]->jit)
2940 mono_debug_free_method_jit_info (frames [i]->jit);
2941 g_free (frames [i]);
2943 g_free (frames);
2946 static void
2947 invalidate_frames (DebuggerTlsData *tls)
2949 mono_loader_lock ();
2951 if (!tls)
2952 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2953 g_assert (tls);
2955 free_frames (tls->frames, tls->frame_count);
2956 tls->frame_count = 0;
2957 tls->frames = NULL;
2959 free_frames (tls->restore_frames, tls->restore_frame_count);
2960 tls->restore_frame_count = 0;
2961 tls->restore_frames = NULL;
2963 mono_loader_unlock ();
2967 * suspend_current:
2969 * Suspend the current thread until the runtime is resumed. If the thread has a
2970 * pending invoke, then the invoke is executed before this function returns.
2972 static void
2973 suspend_current (void)
2975 DebuggerTlsData *tls;
2977 g_assert (!is_debugger_thread ());
2979 if (mono_loader_lock_is_owned_by_self ()) {
2981 * If we own the loader mutex, can't suspend until we release it, since the
2982 * whole runtime can deadlock otherwise.
2984 return;
2987 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2988 g_assert (tls);
2990 gboolean do_resume = FALSE;
2991 while (!do_resume) {
2992 mono_coop_mutex_lock (&suspend_mutex);
2994 tls->suspending = FALSE;
2995 tls->really_suspended = TRUE;
2997 if (!tls->suspended) {
2998 tls->suspended = TRUE;
2999 mono_coop_sem_post (&suspend_sem);
3002 mono_debugger_log_suspend (tls);
3003 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3005 while (suspend_count - tls->resume_count > 0) {
3006 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
3009 tls->suspended = FALSE;
3010 tls->really_suspended = FALSE;
3012 threads_suspend_count --;
3014 mono_coop_mutex_unlock (&suspend_mutex);
3016 mono_debugger_log_resume (tls);
3017 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3019 if (tls->pending_invoke) {
3020 /* Save the original context */
3021 tls->pending_invoke->has_ctx = TRUE;
3022 tls->pending_invoke->ctx = tls->context.ctx;
3024 invoke_method ();
3026 /* Have to suspend again */
3027 } else {
3028 do_resume = TRUE;
3032 /* The frame info becomes invalid after a resume */
3033 tls->context.valid = FALSE;
3034 tls->async_state.valid = FALSE;
3035 invalidate_frames (tls);
3036 mono_stopwatch_start (&tls->step_time);
3039 static void
3040 count_thread (gpointer key, gpointer value, gpointer user_data)
3042 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3044 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3045 *(int*)user_data = *(int*)user_data + 1;
3048 static int
3049 count_threads_to_wait_for (void)
3051 int count = 0;
3053 mono_loader_lock ();
3054 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3055 mono_loader_unlock ();
3057 return count;
3061 * wait_for_suspend:
3063 * Wait until the runtime is completely suspended.
3065 static void
3066 wait_for_suspend (void)
3068 int nthreads, nwait, err;
3069 gboolean waited = FALSE;
3071 // FIXME: Threads starting/stopping ?
3072 mono_loader_lock ();
3073 nthreads = mono_g_hash_table_size (thread_to_tls);
3074 mono_loader_unlock ();
3076 while (TRUE) {
3077 nwait = count_threads_to_wait_for ();
3078 if (nwait) {
3079 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3080 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3081 g_assert (err == 0);
3082 waited = TRUE;
3083 } else {
3084 break;
3088 if (waited)
3089 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3093 * is_suspended:
3095 * Return whenever the runtime is suspended.
3097 static gboolean
3098 is_suspended (void)
3100 return count_threads_to_wait_for () == 0;
3103 static void
3104 no_seq_points_found (MonoMethod *method, int offset)
3107 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3109 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3112 static int
3113 calc_il_offset (MonoDomain *domain, MonoMethod *method, int native_offset, gboolean is_top_frame)
3115 int ret = -1;
3116 if (is_top_frame) {
3117 SeqPoint sp;
3118 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3119 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
3120 ret = sp.il_offset;
3122 if (ret == -1)
3123 ret = mono_debug_il_offset_from_address (method, domain, native_offset);
3124 return ret;
3127 typedef struct {
3128 DebuggerTlsData *tls;
3129 GSList *frames;
3130 gboolean set_debugger_flag;
3131 } ComputeFramesUserData;
3133 static gboolean
3134 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3136 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3137 StackFrame *frame;
3138 MonoMethod *method, *actual_method, *api_method;
3139 int flags = 0;
3141 mono_loader_lock ();
3142 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3143 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3144 /* Mark the last frame as an invoke frame */
3145 if (ud->frames)
3146 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3147 else
3148 ud->set_debugger_flag = TRUE;
3150 mono_loader_unlock ();
3151 return FALSE;
3154 if (info->ji)
3155 method = jinfo_get_method (info->ji);
3156 else
3157 method = info->method;
3158 actual_method = info->actual_method;
3159 api_method = method;
3161 if (!method) {
3162 mono_loader_unlock ();
3163 return FALSE;
3166 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3167 mono_loader_unlock ();
3168 return FALSE;
3171 if (info->il_offset == -1) {
3172 info->il_offset = calc_il_offset (info->domain, method, info->native_offset, ud->frames == NULL);
3175 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);
3177 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3178 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3179 /* Older clients can't handle this flag */
3180 mono_loader_unlock ();
3181 return FALSE;
3183 api_method = mono_marshal_method_from_wrapper (method);
3184 if (!api_method) {
3185 mono_loader_unlock ();
3186 return FALSE;
3188 actual_method = api_method;
3189 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3192 if (ud->set_debugger_flag) {
3193 g_assert (g_slist_length (ud->frames) == 0);
3194 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3195 ud->set_debugger_flag = FALSE;
3198 frame = g_new0 (StackFrame, 1);
3199 frame->de.ji = info->ji;
3200 frame->de.domain = info->domain;
3201 frame->de.method = method;
3202 frame->de.native_offset = info->native_offset;
3204 frame->actual_method = actual_method;
3205 frame->api_method = api_method;
3206 frame->il_offset = info->il_offset;
3207 frame->flags = flags;
3208 frame->interp_frame = info->interp_frame;
3209 frame->frame_addr = info->frame_addr;
3210 if (info->reg_locations)
3211 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3212 if (ctx) {
3213 frame->ctx = *ctx;
3214 frame->has_ctx = TRUE;
3217 ud->frames = g_slist_append (ud->frames, frame);
3219 mono_loader_unlock ();
3220 return FALSE;
3223 static gint32 isFixedSizeArray (MonoClassField *f)
3225 ERROR_DECL (error);
3226 if (!CHECK_PROTOCOL_VERSION (2, 53) || f->type->type != MONO_TYPE_VALUETYPE) {
3227 return 1;
3229 MonoCustomAttrInfo *cinfo;
3230 MonoCustomAttrEntry *attr;
3231 int aindex;
3232 gint32 ret = 1;
3233 cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error);
3234 goto_if_nok (error, leave);
3235 attr = NULL;
3236 if (cinfo) {
3237 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
3238 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
3239 MonoClass *fixed_size_class = mono_class_try_get_fixed_buffer_class ();
3240 if (fixed_size_class != NULL && mono_class_has_parent (ctor_class, fixed_size_class)) {
3241 attr = &cinfo->attrs [aindex];
3242 gpointer *typed_args, *named_args;
3243 CattrNamedArg *arginfo;
3244 int num_named_args;
3246 mono_reflection_create_custom_attr_data_args_noalloc (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size,
3247 &typed_args, &named_args, &num_named_args, &arginfo, error);
3248 if (!is_ok (error)) {
3249 ret = 0;
3250 goto leave;
3252 ret = *(gint32*)typed_args [1];
3253 g_free (typed_args [1]);
3254 g_free (typed_args);
3255 g_free (named_args);
3256 g_free (arginfo);
3257 return ret;
3261 leave:
3262 mono_error_cleanup (error);
3263 return ret;
3266 static gboolean
3267 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3269 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3272 * 'tls->filter_ctx' is the location of the throw site.
3274 * mono_walk_stack() will never actually hit the throw site, but unwind
3275 * directly from the filter to the call site; we abort stack unwinding here
3276 * once this happens and resume from the throw site.
3278 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3279 return TRUE;
3281 return process_frame (info, ctx, user_data);
3285 * Return a malloc-ed list of StackFrame structures.
3287 static StackFrame**
3288 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3290 ComputeFramesUserData user_data;
3291 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3292 StackFrame **res;
3293 int i, nframes;
3294 GSList *l;
3296 user_data.tls = tls;
3297 user_data.frames = NULL;
3299 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3301 nframes = g_slist_length (user_data.frames);
3302 res = g_new0 (StackFrame*, nframes);
3303 l = user_data.frames;
3304 for (i = 0; i < nframes; ++i) {
3305 res [i] = (StackFrame *)l->data;
3306 l = l->next;
3308 *out_nframes = nframes;
3310 return res;
3313 static void
3314 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3316 ComputeFramesUserData user_data;
3317 GSList *tmp;
3318 int i, findex, new_frame_count;
3319 StackFrame **new_frames, *f;
3320 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3322 // FIXME: Locking on tls
3323 if (tls->frames && tls->frames_up_to_date && !force_update)
3324 return;
3326 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3328 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3329 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
3330 new_frames = compute_frame_info_from (thread, tls, &tls->restore_state, &new_frame_count);
3331 invalidate_frames (tls);
3333 tls->frames = new_frames;
3334 tls->frame_count = new_frame_count;
3335 tls->frames_up_to_date = TRUE;
3336 return;
3340 user_data.tls = tls;
3341 user_data.frames = NULL;
3342 if (tls->terminated) {
3343 tls->frame_count = 0;
3344 return;
3345 } if (!tls->really_suspended && tls->async_state.valid) {
3346 /* Have to use the state saved by the signal handler */
3347 process_frame (&tls->async_last_frame, NULL, &user_data);
3348 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3349 } else if (tls->filter_state.valid) {
3351 * We are inside an exception filter.
3353 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3355 if (tls->context.valid) {
3356 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3357 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3360 * After that, we resume unwinding from the location where the exception has been thrown.
3362 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3363 } else if (tls->context.valid) {
3364 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3365 } else {
3366 // FIXME:
3367 tls->frame_count = 0;
3368 return;
3371 new_frame_count = g_slist_length (user_data.frames);
3372 new_frames = g_new0 (StackFrame*, new_frame_count);
3373 findex = 0;
3374 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3375 f = (StackFrame *)tmp->data;
3378 * Reuse the id for already existing stack frames, so invokes don't invalidate
3379 * the still valid stack frames.
3381 for (i = 0; i < tls->frame_count; ++i) {
3382 if (tls->frames [i]->frame_addr == f->frame_addr) {
3383 f->id = tls->frames [i]->id;
3384 break;
3388 if (i >= tls->frame_count)
3389 f->id = mono_atomic_inc_i32 (&frame_id);
3391 new_frames [findex ++] = f;
3394 g_slist_free (user_data.frames);
3396 invalidate_frames (tls);
3398 tls->frames = new_frames;
3399 tls->frame_count = new_frame_count;
3400 tls->frames_up_to_date = TRUE;
3402 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3403 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
3404 gboolean has_interp_resume_state = FALSE;
3405 MonoInterpFrameHandle interp_resume_frame = NULL;
3406 gpointer interp_resume_ip = 0;
3407 mini_get_interp_callbacks ()->get_resume_state (jit_data, &has_interp_resume_state, &interp_resume_frame, &interp_resume_ip);
3408 if (has_interp_resume_state && tls->frame_count > 0) {
3409 StackFrame *top_frame = tls->frames [0];
3410 if (interp_resume_frame == top_frame->interp_frame) {
3411 int native_offset = (int) ((uintptr_t) interp_resume_ip - (uintptr_t) top_frame->de.ji->code_start);
3412 top_frame->il_offset = calc_il_offset (top_frame->de.domain, top_frame->de.method, native_offset, TRUE);
3419 * GHFunc to emit an appdomain creation event
3420 * @param key Don't care
3421 * @param value A loaded appdomain
3422 * @param user_data Don't care
3424 static void
3425 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3427 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3428 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3432 * GHFunc to emit a thread start event
3433 * @param key A thread id
3434 * @param value A thread object
3435 * @param user_data Don't care
3437 static void
3438 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3440 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3441 process_profiler_event (EVENT_KIND_THREAD_START, value);
3445 * GFunc to emit an assembly load event
3446 * @param value A loaded assembly
3447 * @param user_data Don't care
3449 static void
3450 emit_assembly_load (gpointer value, gpointer user_data)
3452 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3456 * GFunc to emit a type load event
3457 * @param value A loaded type
3458 * @param user_data Don't care
3460 static void
3461 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3463 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3467 static void gc_finalizing (MonoProfiler *prof)
3469 DebuggerTlsData *tls;
3471 if (is_debugger_thread ())
3472 return;
3474 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3475 g_assert (tls);
3476 tls->gc_finalizing = TRUE;
3479 static void gc_finalized (MonoProfiler *prof)
3481 DebuggerTlsData *tls;
3483 if (is_debugger_thread ())
3484 return;
3486 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3487 g_assert (tls);
3488 tls->gc_finalizing = FALSE;
3492 static char*
3493 strdup_tolower (char *s)
3495 char *s2, *p;
3497 s2 = g_strdup (s);
3498 for (p = s2; *p; ++p)
3499 *p = tolower (*p);
3500 return s2;
3504 * Same as g_path_get_basename () but handles windows paths as well,
3505 * which can occur in .mdb files created by pdb2mdb.
3507 static char*
3508 dbg_path_get_basename (const char *filename)
3510 char *r;
3512 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3513 return g_path_get_basename (filename);
3515 /* From gpath.c */
3517 /* No separator -> filename */
3518 r = (char*)strrchr (filename, '\\');
3519 if (r == NULL)
3520 return g_strdup (filename);
3522 /* Trailing slash, remove component */
3523 if (r [1] == 0){
3524 char *copy = g_strdup (filename);
3525 copy [r-filename] = 0;
3526 r = strrchr (copy, '\\');
3528 if (r == NULL){
3529 g_free (copy);
3530 return g_strdup ("/");
3532 r = g_strdup (&r[1]);
3533 g_free (copy);
3534 return r;
3537 return g_strdup (&r[1]);
3540 static void
3541 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3543 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3544 ERROR_DECL (error);
3545 MonoCustomAttrInfo *ainfo;
3547 if (ji->dbg_attrs_inited)
3548 return;
3550 if (!hidden_klass)
3551 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3553 if (!step_through_klass)
3554 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3556 if (!non_user_klass)
3557 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3559 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3560 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3561 if (ainfo) {
3562 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3563 ji->dbg_hidden = TRUE;
3564 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3565 ji->dbg_step_through = TRUE;
3566 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3567 ji->dbg_non_user_code = TRUE;
3568 mono_custom_attrs_free (ainfo);
3571 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3572 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3573 if (ainfo) {
3574 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3575 ji->dbg_step_through = TRUE;
3576 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3577 ji->dbg_non_user_code = TRUE;
3578 mono_custom_attrs_free (ainfo);
3581 mono_memory_barrier ();
3582 ji->dbg_attrs_inited = TRUE;
3586 * EVENT HANDLING
3590 * create_event_list:
3592 * Return a list of event request ids matching EVENT, starting from REQS, which
3593 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3594 * policy.
3595 * We return request ids, instead of requests, to simplify threading, since
3596 * requests could be deleted anytime when the loader lock is not held.
3597 * LOCKING: Assumes the loader lock is held.
3599 static GSList*
3600 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3602 int i, j;
3603 GSList *events = NULL;
3605 *suspend_policy = SUSPEND_POLICY_NONE;
3607 if (!reqs)
3608 reqs = event_requests;
3610 if (!reqs)
3611 return NULL;
3613 for (i = 0; i < reqs->len; ++i) {
3614 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3615 if (req->event_kind == event) {
3616 gboolean filtered = FALSE;
3618 /* Apply filters */
3619 for (j = 0; j < req->nmodifiers; ++j) {
3620 Modifier *mod = &req->modifiers [j];
3622 if (mod->kind == MOD_KIND_COUNT) {
3623 filtered = TRUE;
3624 if (mod->data.count > 0) {
3625 if (mod->data.count > 0) {
3626 mod->data.count --;
3627 if (mod->data.count == 0)
3628 filtered = FALSE;
3631 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3632 if (mod->data.thread != mono_thread_internal_current ())
3633 filtered = TRUE;
3634 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3635 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3636 filtered = TRUE;
3637 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3638 filtered = TRUE;
3639 if (ei->caught && !mod->caught)
3640 filtered = TRUE;
3641 if (!ei->caught && !mod->uncaught)
3642 filtered = TRUE;
3643 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3644 int k;
3645 gboolean found = FALSE;
3646 MonoAssembly **assemblies = mod->data.assemblies;
3648 if (assemblies) {
3649 for (k = 0; assemblies [k]; ++k)
3650 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3651 found = TRUE;
3653 if (!found)
3654 filtered = TRUE;
3655 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3656 gpointer iter = NULL;
3657 MonoMethod *method;
3658 MonoDebugSourceInfo *sinfo;
3659 char *s;
3660 gboolean found = FALSE;
3661 int i;
3662 GPtrArray *source_file_list;
3664 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3665 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3667 if (minfo) {
3668 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
3669 for (i = 0; i < source_file_list->len; ++i) {
3670 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3672 * Do a case-insesitive match by converting the file name to
3673 * lowercase.
3675 s = strdup_tolower (sinfo->source_file);
3676 if (g_hash_table_lookup (mod->data.source_files, s))
3677 found = TRUE;
3678 else {
3679 char *s2 = dbg_path_get_basename (sinfo->source_file);
3680 char *s3 = strdup_tolower (s2);
3682 if (g_hash_table_lookup (mod->data.source_files, s3))
3683 found = TRUE;
3684 g_free (s2);
3685 g_free (s3);
3687 g_free (s);
3689 g_ptr_array_free (source_file_list, TRUE);
3692 if (!found)
3693 filtered = TRUE;
3694 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3695 char *s;
3697 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3698 if (!g_hash_table_lookup (mod->data.type_names, s))
3699 filtered = TRUE;
3700 g_free (s);
3701 } else if (mod->kind == MOD_KIND_STEP) {
3702 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3703 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3704 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3705 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3706 filtered = TRUE;
3707 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3708 init_jit_info_dbg_attrs (ji);
3709 if (ji->dbg_hidden)
3710 filtered = TRUE;
3712 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3713 init_jit_info_dbg_attrs (ji);
3714 if (ji->dbg_step_through)
3715 filtered = TRUE;
3717 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3718 init_jit_info_dbg_attrs (ji);
3719 if (ji->dbg_non_user_code)
3720 filtered = TRUE;
3725 if (!filtered) {
3726 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3727 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3732 /* Send a VM START/DEATH event by default */
3733 if (event == EVENT_KIND_VM_START)
3734 events = g_slist_append (events, GINT_TO_POINTER (0));
3735 if (event == EVENT_KIND_VM_DEATH)
3736 events = g_slist_append (events, GINT_TO_POINTER (0));
3738 return events;
3741 static G_GNUC_UNUSED const char*
3742 event_to_string (EventKind event)
3744 switch (event) {
3745 case EVENT_KIND_VM_START: return "VM_START";
3746 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3747 case EVENT_KIND_THREAD_START: return "THREAD_START";
3748 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3749 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3750 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3751 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3752 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3753 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3754 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3755 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3756 case EVENT_KIND_STEP: return "STEP";
3757 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3758 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3759 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3760 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3761 case EVENT_KIND_USER_LOG: return "USER_LOG";
3762 case EVENT_KIND_CRASH: return "CRASH";
3763 default:
3764 g_assert_not_reached ();
3765 return "";
3770 * process_event:
3772 * Send an event to the client, suspending the vm if needed.
3773 * LOCKING: Since this can suspend the calling thread, no locks should be held
3774 * by the caller.
3775 * The EVENTS list is freed by this function.
3777 static void
3778 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3780 Buffer buf;
3781 GSList *l;
3782 MonoDomain *domain = mono_domain_get ();
3783 MonoThread *thread = NULL;
3784 MonoObject *keepalive_obj = NULL;
3785 gboolean send_success = FALSE;
3786 static int ecount;
3787 int nevents;
3789 if (!inited) {
3790 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3791 return;
3794 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3795 // FIXME: We miss those events
3796 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3797 return;
3800 if (vm_death_event_sent) {
3801 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3802 return;
3805 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3806 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3807 return;
3810 if (disconnected) {
3811 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3812 return;
3815 if (event == EVENT_KIND_KEEPALIVE)
3816 suspend_policy = SUSPEND_POLICY_NONE;
3817 else {
3818 if (events == NULL)
3819 return;
3821 if (agent_config.defer) {
3822 if (is_debugger_thread ()) {
3823 /* Don't suspend on events from the debugger thread */
3824 suspend_policy = SUSPEND_POLICY_NONE;
3826 } else {
3827 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3828 // FIXME: Send these with a NULL thread, don't suspend the current thread
3829 return;
3833 nevents = g_slist_length (events);
3834 buffer_init (&buf, 128);
3835 buffer_add_byte (&buf, suspend_policy);
3836 buffer_add_int (&buf, nevents);
3838 for (l = events; l; l = l->next) {
3839 buffer_add_byte (&buf, event); // event kind
3840 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3842 ecount ++;
3844 if (event == EVENT_KIND_VM_DEATH) {
3845 thread = NULL;
3846 } else {
3847 if (!thread)
3848 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3850 if (event == EVENT_KIND_VM_START && arg != NULL)
3851 thread = (MonoThread *)arg;
3854 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3856 switch (event) {
3857 case EVENT_KIND_THREAD_START:
3858 case EVENT_KIND_THREAD_DEATH:
3859 break;
3860 case EVENT_KIND_APPDOMAIN_CREATE:
3861 case EVENT_KIND_APPDOMAIN_UNLOAD:
3862 buffer_add_domainid (&buf, (MonoDomain *)arg);
3863 break;
3864 case EVENT_KIND_METHOD_ENTRY:
3865 case EVENT_KIND_METHOD_EXIT:
3866 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3867 break;
3868 case EVENT_KIND_ASSEMBLY_LOAD:
3869 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3870 break;
3871 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3872 DebuggerTlsData *tls;
3874 /* The domain the assembly belonged to is not equal to the current domain */
3875 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3876 g_assert (tls);
3877 g_assert (tls->domain_unloading);
3879 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3880 break;
3882 case EVENT_KIND_TYPE_LOAD:
3883 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3884 break;
3885 case EVENT_KIND_BREAKPOINT:
3886 case EVENT_KIND_STEP: {
3887 DebuggerTlsData *tls;
3888 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3889 g_assert (tls);
3890 mono_stopwatch_stop (&tls->step_time);
3891 MonoMethod *method = (MonoMethod *)arg;
3893 buffer_add_methodid (&buf, domain, method);
3894 buffer_add_long (&buf, il_offset);
3895 break;
3897 case EVENT_KIND_VM_START:
3898 buffer_add_domainid (&buf, mono_get_root_domain ());
3899 break;
3900 case EVENT_KIND_VM_DEATH:
3901 if (CHECK_PROTOCOL_VERSION (2, 27))
3902 buffer_add_int (&buf, mono_environment_exitcode_get ());
3903 break;
3904 case EVENT_KIND_CRASH: {
3905 EventInfo *ei = (EventInfo *)arg;
3906 buffer_add_long (&buf, ei->hashes->offset_free_hash);
3907 buffer_add_string (&buf, ei->dump);
3908 break;
3910 case EVENT_KIND_EXCEPTION: {
3911 EventInfo *ei = (EventInfo *)arg;
3912 buffer_add_objid (&buf, ei->exc);
3914 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3915 * later after the suspension. (#12494).
3917 keepalive_obj = ei->exc;
3918 break;
3920 case EVENT_KIND_USER_BREAK: {
3921 DebuggerTlsData *tls;
3922 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3923 g_assert (tls);
3924 mono_stopwatch_stop (&tls->step_time);
3925 break;
3927 case EVENT_KIND_USER_LOG: {
3928 EventInfo *ei = (EventInfo *)arg;
3929 buffer_add_int (&buf, ei->level);
3930 buffer_add_string (&buf, ei->category ? ei->category : "");
3931 buffer_add_string (&buf, ei->message ? ei->message : "");
3932 break;
3934 case EVENT_KIND_KEEPALIVE:
3935 suspend_policy = SUSPEND_POLICY_NONE;
3936 break;
3937 default:
3938 g_assert_not_reached ();
3942 if (event == EVENT_KIND_VM_START) {
3943 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3944 if (!agent_config.defer) {
3945 ERROR_DECL (error);
3946 start_debugger_thread (error);
3947 mono_error_assert_ok (error);
3951 if (event == EVENT_KIND_VM_DEATH) {
3952 vm_death_event_sent = TRUE;
3953 suspend_policy = SUSPEND_POLICY_NONE;
3956 if (mono_runtime_is_shutting_down ())
3957 suspend_policy = SUSPEND_POLICY_NONE;
3959 if (suspend_policy != SUSPEND_POLICY_NONE) {
3961 * Save the thread context and start suspending before sending the packet,
3962 * since we could be receiving the resume request before send_packet ()
3963 * returns.
3965 save_thread_context (ctx);
3966 suspend_vm ();
3968 if (keepalive_obj)
3969 /* This will keep this object alive */
3970 get_objref (keepalive_obj);
3973 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3975 if (send_success) {
3976 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3977 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
3980 buffer_free (&buf);
3982 g_slist_free (events);
3983 events = NULL;
3985 if (!send_success) {
3986 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3987 return;
3990 if (event == EVENT_KIND_VM_START) {
3991 vm_start_event_sent = TRUE;
3994 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);
3996 switch (suspend_policy) {
3997 case SUSPEND_POLICY_NONE:
3998 break;
3999 case SUSPEND_POLICY_ALL:
4000 suspend_current ();
4001 break;
4002 case SUSPEND_POLICY_EVENT_THREAD:
4003 NOT_IMPLEMENTED;
4004 break;
4005 default:
4006 g_assert_not_reached ();
4010 static void
4011 process_profiler_event (EventKind event, gpointer arg)
4013 int suspend_policy;
4014 GSList *events;
4015 EventInfo ei, *ei_arg = NULL;
4017 if (event == EVENT_KIND_TYPE_LOAD) {
4018 ei.klass = (MonoClass *)arg;
4019 ei_arg = &ei;
4022 mono_loader_lock ();
4023 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
4024 mono_loader_unlock ();
4026 process_event (event, arg, 0, NULL, events, suspend_policy);
4029 static void
4030 runtime_initialized (MonoProfiler *prof)
4032 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
4033 if (agent_config.defer) {
4034 ERROR_DECL (error);
4035 start_debugger_thread (error);
4036 mono_error_assert_ok (error);
4040 static void
4041 runtime_shutdown (MonoProfiler *prof)
4043 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
4045 mono_debugger_agent_cleanup ();
4048 static void
4049 thread_startup (MonoProfiler *prof, uintptr_t tid)
4051 MonoInternalThread *thread = mono_thread_internal_current ();
4052 MonoInternalThread *old_thread;
4053 DebuggerTlsData *tls;
4055 if (is_debugger_thread ())
4056 return;
4058 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
4060 mono_loader_lock ();
4061 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4062 mono_loader_unlock ();
4063 if (old_thread) {
4064 if (thread == old_thread) {
4066 * For some reason, thread_startup () might be called for the same thread
4067 * multiple times (attach ?).
4069 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4070 return;
4071 } else {
4073 * thread_end () might not be called for some threads, and the tid could
4074 * get reused.
4076 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4077 mono_loader_lock ();
4078 mono_g_hash_table_remove (thread_to_tls, old_thread);
4079 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
4080 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4081 mono_loader_unlock ();
4085 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4086 g_assert (!tls);
4087 // FIXME: Free this somewhere
4088 tls = g_new0 (DebuggerTlsData, 1);
4089 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
4090 tls->thread = thread;
4091 // Do so we have thread id even after termination
4092 tls->thread_id = (intptr_t) thread->tid;
4093 mono_native_tls_set_value (debugger_tls_id, tls);
4095 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4097 mono_loader_lock ();
4098 mono_g_hash_table_insert_internal (thread_to_tls, thread, tls);
4099 mono_g_hash_table_insert_internal (tid_to_thread, (gpointer)tid, thread);
4100 mono_g_hash_table_insert_internal (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
4101 mono_loader_unlock ();
4103 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4106 * suspend_vm () could have missed this thread, so wait for a resume.
4109 suspend_current ();
4112 static void
4113 thread_end (MonoProfiler *prof, uintptr_t tid)
4115 MonoInternalThread *thread;
4116 DebuggerTlsData *tls = NULL;
4118 mono_loader_lock ();
4119 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4120 if (thread) {
4121 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4122 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4123 if (tls) {
4124 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4125 tls->terminated = TRUE;
4126 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4127 MONO_GC_UNREGISTER_ROOT (tls->thread);
4128 tls->thread = NULL;
4131 mono_loader_unlock ();
4133 /* We might be called for threads started before we registered the start callback */
4134 if (thread) {
4135 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p (domain=%p).\n", (gpointer)tid, thread, tls, (gpointer)mono_domain_get ());
4137 if (mono_thread_internal_is_current (thread) &&
4138 (!mono_native_tls_get_value (debugger_tls_id) ||
4139 !mono_domain_get ())
4142 * This can happen on darwin and android since we
4143 * deregister threads using pthread dtors.
4144 * process_profiler_event () and the code it calls
4145 * cannot handle a null TLS value.
4147 return;
4150 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4154 static void
4155 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4157 mono_de_domain_add (domain);
4159 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4162 static void
4163 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4165 DebuggerTlsData *tls;
4167 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4168 if (is_debugger_thread ())
4169 return;
4172 * Remember the currently unloading appdomain as it is needed to generate
4173 * proper ids for unloading assemblies.
4175 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4176 g_assert (tls);
4177 tls->domain_unloading = domain;
4180 static void
4181 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4183 DebuggerTlsData *tls;
4185 if (is_debugger_thread ())
4186 return;
4188 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4189 g_assert (tls);
4190 tls->domain_unloading = NULL;
4192 mono_de_clear_breakpoints_for_domain (domain);
4194 mono_loader_lock ();
4195 /* Invalidate each thread's frame stack */
4196 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4197 mono_loader_unlock ();
4199 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4203 * invalidate_each_thread:
4205 * A GHFunc to invalidate frames.
4206 * value must be a DebuggerTlsData*
4208 static void
4209 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4211 invalidate_frames ((DebuggerTlsData *)value);
4214 static void
4215 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4217 /* Sent later in jit_end () */
4218 dbg_lock ();
4219 g_ptr_array_add (pending_assembly_loads, assembly);
4220 dbg_unlock ();
4223 static void
4224 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4226 if (is_debugger_thread ())
4227 return;
4229 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4231 clear_event_requests_for_assembly (assembly);
4232 clear_types_for_assembly (assembly);
4235 static void
4236 send_type_load (MonoClass *klass)
4238 gboolean type_load = FALSE;
4239 MonoDomain *domain = mono_domain_get ();
4240 AgentDomainInfo *info = NULL;
4242 info = get_agent_domain_info (domain);
4244 mono_loader_lock ();
4246 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4247 type_load = TRUE;
4248 g_hash_table_insert (info->loaded_classes, klass, klass);
4251 mono_loader_unlock ();
4253 if (type_load)
4254 emit_type_load (klass, klass, NULL);
4258 * Emit load events for all types currently loaded in the domain.
4259 * Takes the loader and domain locks.
4260 * user_data is unused.
4262 static void
4263 send_types_for_domain (MonoDomain *domain, void *user_data)
4265 MonoDomain* old_domain;
4266 AgentDomainInfo *info = NULL;
4268 info = get_agent_domain_info (domain);
4269 g_assert (info);
4271 old_domain = mono_domain_get ();
4273 mono_domain_set_fast (domain, TRUE);
4275 mono_loader_lock ();
4276 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4277 mono_loader_unlock ();
4279 mono_domain_set_fast (old_domain, TRUE);
4282 static void
4283 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4285 GSList *tmp;
4286 MonoDomain* old_domain;
4288 old_domain = mono_domain_get ();
4290 mono_domain_set_fast (domain, TRUE);
4292 mono_domain_assemblies_lock (domain);
4293 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4294 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4295 emit_assembly_load (ass, NULL);
4297 mono_domain_assemblies_unlock (domain);
4299 mono_domain_set_fast (old_domain, TRUE);
4302 static void
4303 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4305 jit_end (prof, method, jinfo);
4308 static void
4309 jit_failed (MonoProfiler *prof, MonoMethod *method)
4311 jit_end (prof, method, NULL);
4314 static void
4315 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4318 * We emit type load events when the first method of the type is JITted,
4319 * since the class load profiler callbacks might be called with the
4320 * loader lock held. They could also occur in the debugger thread.
4321 * Same for assembly load events.
4323 while (TRUE) {
4324 MonoAssembly *assembly = NULL;
4326 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4327 dbg_lock ();
4328 if (pending_assembly_loads->len > 0) {
4329 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4330 g_ptr_array_remove_index (pending_assembly_loads, 0);
4332 dbg_unlock ();
4334 if (assembly) {
4335 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4336 } else {
4337 break;
4341 send_type_load (method->klass);
4343 if (jinfo)
4344 mono_de_add_pending_breakpoints (method, jinfo);
4348 * SINGLE STEPPING
4351 static void
4352 event_requests_cleanup (void)
4354 mono_loader_lock ();
4355 int i = 0;
4356 while (i < event_requests->len) {
4357 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4359 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4360 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4361 g_ptr_array_remove_index_fast (event_requests, i);
4362 g_free (req);
4363 } else {
4364 i ++;
4367 mono_loader_unlock ();
4371 * ss_calculate_framecount:
4373 * Ensure DebuggerTlsData fields are filled out.
4375 static void
4376 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4378 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4380 if (force_use_ctx || !tls->context.valid)
4381 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4382 compute_frame_info (tls->thread, tls, FALSE);
4383 if (frames)
4384 *frames = (DbgEngineStackFrame**)tls->frames;
4385 if (nframes)
4386 *nframes = tls->frame_count;
4390 * ss_discard_frame_data:
4392 * Discard frame data and invalidate any context
4394 static void
4395 ss_discard_frame_context (void *the_tls)
4397 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4398 tls->context.valid = FALSE;
4399 tls->async_state.valid = FALSE;
4400 invalidate_frames (tls);
4403 static MonoContext*
4404 tls_get_restore_state (void *the_tls)
4406 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4408 return &tls->restore_state.ctx;
4411 static gboolean
4412 ensure_jit (DbgEngineStackFrame* the_frame)
4414 StackFrame *frame = (StackFrame*)the_frame;
4415 if (!frame->jit) {
4416 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4417 if (!frame->jit && frame->api_method->is_inflated)
4418 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4419 if (!frame->jit) {
4420 char *s;
4422 /* This could happen for aot images with no jit debug info */
4423 s = mono_method_full_name (frame->api_method, TRUE);
4424 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4425 g_free (s);
4426 return FALSE;
4429 return TRUE;
4432 static gboolean
4433 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4435 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4438 static gpointer
4439 get_this_addr (DbgEngineStackFrame *the_frame)
4441 StackFrame *frame = (StackFrame *)the_frame;
4442 if (frame->de.ji->is_interp)
4443 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4445 MonoDebugVarInfo *var = frame->jit->this_var;
4446 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4447 return NULL;
4449 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4450 addr += (gint32)var->offset;
4451 return addr;
4454 static MonoMethod*
4455 get_set_notification_method (MonoClass* async_builder_class)
4457 ERROR_DECL (error);
4458 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, 1, FALSE, error);
4459 mono_error_assert_ok (error);
4460 if (array->len == 0) {
4461 g_ptr_array_free (array, TRUE);
4462 return NULL;
4464 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4465 g_ptr_array_free (array, TRUE);
4466 return set_notification_method;
4469 static MonoMethod*
4470 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4472 ERROR_DECL (error);
4473 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, 1, FALSE, error);
4474 mono_error_assert_ok (error);
4475 g_assert (array->len == 1);
4476 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4477 g_ptr_array_free (array, TRUE);
4478 return method;
4481 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4482 static gpointer
4483 get_async_method_builder (DbgEngineStackFrame *frame)
4485 MonoObject *this_obj;
4486 MonoClassField *builder_field;
4487 gpointer builder;
4488 gpointer this_addr;
4490 builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4491 g_assert (builder_field);
4493 this_addr = get_this_addr (frame);
4494 if (!this_addr)
4495 return NULL;
4497 if (m_class_is_valuetype (frame->method->klass)) {
4498 builder = mono_vtype_get_field_addr (*(guint8**)this_addr, builder_field);
4499 } else {
4500 this_obj = *(MonoObject**)this_addr;
4501 builder = (char*)this_obj + builder_field->offset;
4504 return builder;
4507 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4508 //since thread probably changed...
4509 static int
4510 get_this_async_id (DbgEngineStackFrame *frame)
4512 MonoClassField *builder_field;
4513 gpointer builder;
4514 MonoMethod *method;
4515 MonoObject *ex;
4516 ERROR_DECL (error);
4517 MonoObject *obj;
4518 gboolean old_disable_breakpoints = FALSE;
4519 DebuggerTlsData *tls;
4522 * FRAME points to a method in a state machine class/struct.
4523 * Call the ObjectIdForDebugger method of the associated method builder type.
4525 builder = get_async_method_builder (frame);
4526 if (!builder)
4527 return 0;
4529 builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4530 g_assert (builder_field);
4532 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4533 if (tls) {
4534 old_disable_breakpoints = tls->disable_breakpoints;
4535 tls->disable_breakpoints = TRUE;
4538 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4539 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4540 mono_error_assert_ok (error);
4542 if (tls)
4543 tls->disable_breakpoints = old_disable_breakpoints;
4545 return get_objid (obj);
4548 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4549 // false if not(AsyncVoidBuilder)
4550 static gboolean
4551 set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame)
4553 MonoClassField *builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4554 g_assert (builder_field);
4555 gpointer builder = get_async_method_builder (frame);
4556 g_assert (builder);
4558 void* args [1];
4559 gboolean arg = TRUE;
4560 ERROR_DECL (error);
4561 args [0] = &arg;
4562 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type_internal (builder_field->type));
4563 if (method == NULL)
4564 return FALSE;
4565 mono_runtime_invoke_checked (method, builder, args, error);
4566 mono_error_assert_ok (error);
4567 return TRUE;
4570 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4572 static MonoMethod*
4573 get_notify_debugger_of_wait_completion_method (void)
4575 if (notify_debugger_of_wait_completion_method_cache != NULL)
4576 return notify_debugger_of_wait_completion_method_cache;
4577 ERROR_DECL (error);
4578 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4579 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error);
4580 mono_error_assert_ok (error);
4581 g_assert (array->len == 1);
4582 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4583 g_ptr_array_free (array, TRUE);
4584 return notify_debugger_of_wait_completion_method_cache;
4587 static gboolean
4588 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4590 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4593 * Skip the instruction causing the breakpoint signal.
4595 if (from_signal)
4596 mono_arch_skip_breakpoint (ctx, ji);
4598 if (tls->disable_breakpoints)
4599 return FALSE;
4600 return TRUE;
4603 typedef struct {
4604 GSList *bp_events, *ss_events, *enter_leave_events;
4605 EventKind kind;
4606 int suspend_policy;
4607 } BreakPointEvents;
4609 static void*
4610 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4612 int suspend_policy = 0;
4613 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4614 if (ss_reqs && ss_reqs->len > 0)
4615 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4616 else if (bp_reqs && bp_reqs->len > 0)
4617 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4618 else if (kind != EVENT_KIND_BREAKPOINT)
4619 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4621 evts->kind = kind;
4622 evts->suspend_policy = suspend_policy;
4623 return evts;
4626 static void
4627 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4629 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4631 * FIXME: The first event will suspend, so the second will only be sent after the
4632 * resume.
4634 if (evts->ss_events)
4635 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4636 if (evts->bp_events)
4637 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4638 if (evts->enter_leave_events)
4639 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4641 g_free (evts);
4644 /* Process a breakpoint/single step event after resuming from a signal handler */
4645 static void
4646 process_signal_event (void (*func) (void*, gboolean))
4648 DebuggerTlsData *tls;
4649 MonoThreadUnwindState orig_restore_state;
4650 MonoContext ctx;
4652 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4653 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4654 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4655 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4657 func (tls, TRUE);
4659 /* This is called when resuming from a signal handler, so it shouldn't return */
4660 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4661 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4662 mono_restore_context (&ctx);
4663 g_assert_not_reached ();
4666 static void
4667 process_breakpoint_from_signal (void)
4669 process_signal_event (mono_de_process_breakpoint);
4672 static void
4673 resume_from_signal_handler (void *sigctx, void *func)
4675 DebuggerTlsData *tls;
4676 MonoContext ctx;
4678 /* Save the original context in TLS */
4679 // FIXME: This might not work on an altstack ?
4680 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4681 if (!tls)
4682 g_printerr ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4683 g_assert (tls);
4685 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4686 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4687 // clob:c could be added to op_seq_point.
4689 mono_sigctx_to_monoctx (sigctx, &ctx);
4690 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4691 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4692 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4693 #else
4694 MONO_CONTEXT_SET_IP (&ctx, func);
4695 #endif
4696 mono_monoctx_to_sigctx (&ctx, sigctx);
4699 static void
4700 debugger_agent_breakpoint_hit (void *sigctx)
4703 * We are called from a signal handler, and running code there causes all kinds of
4704 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4705 * So set up the signal context to return to the real breakpoint handler function.
4707 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4710 typedef struct {
4711 gboolean found;
4712 MonoContext *ctx;
4713 } UserBreakCbData;
4715 static gboolean
4716 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4718 UserBreakCbData *data = (UserBreakCbData*)user_data;
4720 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4721 data->found = TRUE;
4722 return TRUE;
4724 if (frame->managed) {
4725 data->found = TRUE;
4726 *data->ctx = *ctx;
4728 return TRUE;
4730 return FALSE;
4734 * Called by System.Diagnostics.Debugger:Break ().
4736 static void
4737 debugger_agent_user_break (void)
4739 if (agent_config.enabled) {
4740 MonoContext ctx;
4741 int suspend_policy;
4742 GSList *events;
4743 UserBreakCbData data;
4745 memset (&data, 0, sizeof (UserBreakCbData));
4746 data.ctx = &ctx;
4748 /* Obtain a context */
4749 MONO_CONTEXT_SET_IP (&ctx, NULL);
4750 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4751 g_assert (data.found);
4753 mono_loader_lock ();
4754 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4755 mono_loader_unlock ();
4757 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4758 } else if (mini_debug_options.native_debugger_break) {
4759 G_BREAKPOINT ();
4763 static void
4764 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4766 if (from_signal)
4767 mono_arch_skip_single_step (ctx);
4770 static void
4771 process_single_step (void)
4773 process_signal_event (mono_de_process_single_step);
4777 * debugger_agent_single_step_event:
4779 * Called from a signal handler to handle a single step event.
4781 static void
4782 debugger_agent_single_step_event (void *sigctx)
4784 /* Resume to process_single_step through the signal context */
4786 // FIXME: Since step out/over is implemented using step in, the step in case should
4787 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4788 // here
4790 if (is_debugger_thread ()) {
4792 * This could happen despite our best effors when the runtime calls
4793 * assembly/type resolve hooks.
4794 * FIXME: Breakpoints too.
4796 MonoContext ctx;
4798 mono_sigctx_to_monoctx (sigctx, &ctx);
4799 mono_arch_skip_single_step (&ctx);
4800 mono_monoctx_to_sigctx (&ctx, sigctx);
4801 return;
4804 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4807 static void
4808 debugger_agent_single_step_from_context (MonoContext *ctx)
4810 DebuggerTlsData *tls;
4811 MonoThreadUnwindState orig_restore_state;
4813 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4814 /* Fastpath during invokes, see in process_suspend () */
4815 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4816 return;
4818 if (is_debugger_thread ())
4819 return;
4821 g_assert (tls);
4823 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4824 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4825 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4826 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4828 mono_de_process_single_step (tls, FALSE);
4830 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4831 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4834 static void
4835 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4837 DebuggerTlsData *tls;
4838 MonoThreadUnwindState orig_restore_state;
4839 guint8 *orig_ip;
4841 if (is_debugger_thread ())
4842 return;
4844 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4845 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4847 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4848 g_assert (tls);
4849 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4850 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4851 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4853 mono_de_process_breakpoint (tls, FALSE);
4855 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4856 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4857 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4858 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4861 static void
4862 ss_args_destroy (SingleStepArgs *ss_args)
4864 if (ss_args->frames)
4865 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
4868 static int
4869 ensure_runtime_is_suspended (void)
4871 if (suspend_count == 0)
4872 return ERR_NOT_SUSPENDED;
4874 wait_for_suspend ();
4876 return ERR_NONE;
4879 static int
4880 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
4882 MonoSeqPointInfo *info = NULL;
4883 gboolean found_sp;
4884 MonoMethod *method = NULL;
4885 MonoDebugMethodInfo *minfo;
4886 gboolean step_to_catch = FALSE;
4887 gboolean set_ip = FALSE;
4888 StackFrame **frames = NULL;
4889 int nframes = 0;
4891 mono_loader_lock ();
4892 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4893 mono_loader_unlock ();
4894 g_assert (tls);
4895 if (!tls->context.valid) {
4896 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
4897 return ERR_INVALID_ARGUMENT;
4900 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
4902 * Need to start single stepping from restore_state and not from the current state
4904 set_ip = TRUE;
4905 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
4908 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4910 if (tls->has_catch_frame) {
4911 StackFrameInfo frame;
4914 * We are stopped at a throw site. Stepping should go to the catch site.
4916 frame = tls->catch_frame;
4917 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
4920 * Find the seq point corresponding to the landing site ip, which is the first seq
4921 * point after ip.
4923 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
4924 if (!found_sp)
4925 no_seq_points_found (frame.method, frame.native_offset);
4926 g_assert (found_sp);
4928 method = frame.method;
4930 step_to_catch = TRUE;
4931 /* This make sure the seq point is not skipped by process_single_step () */
4932 ss_req->last_sp = NULL;
4935 if (!step_to_catch) {
4936 StackFrame *frame = NULL;
4938 if (set_ip) {
4939 if (frames && nframes)
4940 frame = frames [0];
4941 } else {
4942 compute_frame_info (ss_req->thread, tls, FALSE);
4944 if (tls->frame_count)
4945 frame = tls->frames [0];
4948 if (ss_req->size == STEP_SIZE_LINE) {
4949 if (frame) {
4950 ss_req->last_method = frame->de.method;
4951 ss_req->last_line = -1;
4953 minfo = mono_debug_lookup_method (frame->de.method);
4954 if (minfo && frame->il_offset != -1) {
4955 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
4957 if (loc) {
4958 ss_req->last_line = loc->row;
4959 g_free (loc);
4965 if (frame) {
4966 if (!method && frame->il_offset != -1) {
4967 /* FIXME: Sort the table and use a binary search */
4968 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
4969 if (!found_sp)
4970 no_seq_points_found (frame->de.method, frame->de.native_offset);
4971 g_assert (found_sp);
4972 method = frame->de.method;
4977 ss_req->start_method = method;
4979 args->method = method;
4980 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
4981 args->tls = tls;
4982 args->step_to_catch = step_to_catch;
4983 args->info = info;
4984 args->frames = (DbgEngineStackFrame**)frames;
4985 args->nframes = nframes;
4987 return ERR_NONE;
4990 static void
4991 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
4993 GSList *l;
4994 gboolean found = TRUE;
4996 while (found) {
4997 found = FALSE;
4998 for (l = req->bps; l; l = l->next) {
4999 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5000 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
5001 req->bps = g_slist_delete_link (req->bps, l);
5002 found = TRUE;
5003 break;
5010 * This takes a lot of locks and stuff. Do this at the end, after
5011 * other things have dumped us, so that getting stuck here won't
5012 * prevent seeing other crash information
5014 static void
5015 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
5017 #ifndef DISABLE_CRASH_REPORTING
5018 int suspend_policy;
5019 GSList *events;
5020 EventInfo ei;
5022 if (!agent_config.enabled)
5023 return;
5025 // Don't send the event if the client doesn't expect it
5026 if (!CHECK_PROTOCOL_VERSION (2, 49))
5027 return;
5029 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5030 // actually enabled. Therefore we do the wait here.
5031 sleep (pause);
5033 // Don't heap allocate when we can avoid it
5034 EventRequest request;
5035 memset (&request, 0, sizeof (request));
5036 request.event_kind = EVENT_KIND_CRASH;
5038 gpointer pdata [1];
5039 pdata [0] = &request;
5040 GPtrArray array;
5041 memset (&array, 0, sizeof (array));
5042 array.pdata = pdata;
5043 array.len = 1;
5045 mono_loader_lock ();
5046 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5047 mono_loader_unlock ();
5049 ei.dump = json_dump;
5050 ei.hashes = hashes;
5052 g_assert (events != NULL);
5054 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5056 // Don't die before it is sent.
5057 sleep (4);
5058 #endif
5062 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5064 static void
5065 debugger_agent_debug_log (int level, MonoStringHandle category, MonoStringHandle message)
5067 ERROR_DECL (error);
5068 int suspend_policy;
5069 GSList *events;
5070 EventInfo ei;
5072 if (!agent_config.enabled)
5073 return;
5075 mono_loader_lock ();
5076 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5077 mono_loader_unlock ();
5079 ei.level = level;
5080 ei.category = NULL;
5081 if (!MONO_HANDLE_IS_NULL (category)) {
5082 ei.category = mono_string_handle_to_utf8 (category, error);
5083 mono_error_cleanup (error);
5085 ei.message = NULL;
5086 if (!MONO_HANDLE_IS_NULL (message)) {
5087 ei.message = mono_string_handle_to_utf8 (message, error);
5088 mono_error_cleanup (error);
5091 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5093 g_free (ei.category);
5094 g_free (ei.message);
5097 static gboolean
5098 debugger_agent_debug_log_is_enabled (void)
5100 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5101 return agent_config.enabled;
5104 static void
5105 debugger_agent_unhandled_exception (MonoException *exc)
5107 int suspend_policy;
5108 GSList *events;
5109 EventInfo ei;
5111 if (!inited)
5112 return;
5114 memset (&ei, 0, sizeof (EventInfo));
5115 ei.exc = (MonoObject*)exc;
5117 mono_loader_lock ();
5118 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5119 mono_loader_unlock ();
5121 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5124 static void
5125 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5126 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5128 int i, j, suspend_policy;
5129 GSList *events;
5130 MonoJitInfo *ji, *catch_ji;
5131 EventInfo ei;
5132 DebuggerTlsData *tls = NULL;
5134 if (thread_to_tls != NULL) {
5135 MonoInternalThread *thread = mono_thread_internal_current ();
5137 mono_loader_lock ();
5138 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5139 mono_loader_unlock ();
5141 if (tls && tls->abort_requested)
5142 return;
5143 if (tls && tls->disable_breakpoints)
5144 return;
5147 memset (&ei, 0, sizeof (EventInfo));
5149 /* Just-In-Time debugging */
5150 if (!catch_ctx) {
5151 if (agent_config.onuncaught && !inited) {
5152 finish_agent_init (FALSE);
5155 * Send an unsolicited EXCEPTION event with a dummy request id.
5157 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5158 ei.exc = (MonoObject*)exc;
5159 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5160 return;
5162 } else if (agent_config.onthrow && !inited) {
5163 GSList *l;
5164 gboolean found = FALSE;
5166 for (l = agent_config.onthrow; l; l = l->next) {
5167 char *ex_type = (char *)l->data;
5168 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5170 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5171 found = TRUE;
5173 g_free (f);
5176 if (found) {
5177 finish_agent_init (FALSE);
5180 * Send an unsolicited EXCEPTION event with a dummy request id.
5182 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5183 ei.exc = (MonoObject*)exc;
5184 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5185 return;
5189 if (!inited)
5190 return;
5192 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5193 if (catch_frame)
5194 catch_ji = catch_frame->ji;
5195 else
5196 catch_ji = NULL;
5198 ei.exc = (MonoObject*)exc;
5199 ei.caught = catch_ctx != NULL;
5201 mono_loader_lock ();
5203 /* Treat exceptions which are caught in non-user code as unhandled */
5204 for (i = 0; i < event_requests->len; ++i) {
5205 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5206 if (req->event_kind != EVENT_KIND_EXCEPTION)
5207 continue;
5209 for (j = 0; j < req->nmodifiers; ++j) {
5210 Modifier *mod = &req->modifiers [j];
5212 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5213 int k;
5214 gboolean found = FALSE;
5215 MonoAssembly **assemblies = mod->data.assemblies;
5217 if (assemblies) {
5218 for (k = 0; assemblies [k]; ++k)
5219 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5220 found = TRUE;
5222 if (!found)
5223 ei.caught = FALSE;
5228 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5229 mono_loader_unlock ();
5231 if (tls && ei.caught && catch_ctx) {
5232 if (catch_frame) {
5233 tls->has_catch_frame = TRUE;
5234 tls->catch_frame = *catch_frame;
5235 } else {
5236 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5240 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5242 if (tls)
5243 tls->has_catch_frame = FALSE;
5246 static void
5247 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5249 DebuggerTlsData *tls;
5251 if (!inited)
5252 return;
5254 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5255 if (!tls)
5256 return;
5259 * We're about to invoke an exception filter during the first pass of exception handling.
5261 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5262 * 'orig_ctx' is the context where the exception has been thrown.
5265 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5267 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5268 * the call site (line 37) and then continue to Main(), but it would never
5269 * include the throw site (line 32).
5271 * Since exception filters are invoked during the first pass of exception handling,
5272 * the stack frames of the throw site are still intact, so we should include them
5273 * in a stack trace.
5275 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5277 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5278 * but report the location of the 'throw' to the user.
5282 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5285 static void
5286 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5288 DebuggerTlsData *tls;
5290 if (!inited)
5291 return;
5293 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5294 if (!tls)
5295 return;
5297 tls->filter_state.valid = FALSE;
5300 static void
5301 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5302 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5304 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5305 buffer_add_byte (buf, t->type);
5306 buffer_add_int (buf, len_fixed_array );
5307 for (int i = 0; i < len_fixed_array; i++) {
5308 switch (t->type) {
5309 case MONO_TYPE_BOOLEAN:
5310 case MONO_TYPE_I1:
5311 case MONO_TYPE_U1:
5312 buffer_add_int (buf, ((gint8*)addr)[i]);
5313 break;
5314 case MONO_TYPE_CHAR:
5315 case MONO_TYPE_I2:
5316 case MONO_TYPE_U2:
5317 buffer_add_int (buf, ((gint16*)addr)[i]);
5318 break;
5319 case MONO_TYPE_I4:
5320 case MONO_TYPE_U4:
5321 case MONO_TYPE_R4:
5322 buffer_add_int (buf, ((gint32*)addr)[i]);
5323 break;
5324 case MONO_TYPE_I8:
5325 case MONO_TYPE_U8:
5326 case MONO_TYPE_R8:
5327 buffer_add_long (buf, ((gint64*)addr)[i]);
5328 break;
5329 case MONO_TYPE_PTR: {
5330 gssize val = *(gssize*)addr;
5332 buffer_add_byte (buf, t->type);
5333 buffer_add_long (buf, val);
5334 if (CHECK_PROTOCOL_VERSION(2, 46))
5335 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5336 break;
5342 * buffer_add_value_full:
5344 * Add the encoding of the value at ADDR described by T to the buffer.
5345 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5346 * vtypes.
5348 static void
5349 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5350 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5352 MonoObject *obj;
5353 gboolean boxed_vtype = FALSE;
5355 if (t->byref) {
5356 if (!(*(void**)addr)) {
5357 /* This can happen with compiler generated locals */
5358 //printf ("%s\n", mono_type_full_name (t));
5359 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5360 return;
5362 g_assert (*(void**)addr);
5363 addr = *(void**)addr;
5366 if (as_vtype) {
5367 switch (t->type) {
5368 case MONO_TYPE_BOOLEAN:
5369 case MONO_TYPE_I1:
5370 case MONO_TYPE_U1:
5371 case MONO_TYPE_CHAR:
5372 case MONO_TYPE_I2:
5373 case MONO_TYPE_U2:
5374 case MONO_TYPE_I4:
5375 case MONO_TYPE_U4:
5376 case MONO_TYPE_R4:
5377 case MONO_TYPE_I8:
5378 case MONO_TYPE_U8:
5379 case MONO_TYPE_R8:
5380 case MONO_TYPE_I:
5381 case MONO_TYPE_U:
5382 case MONO_TYPE_PTR:
5383 goto handle_vtype;
5384 break;
5385 default:
5386 break;
5390 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5392 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5393 return;
5395 switch (t->type) {
5396 case MONO_TYPE_VOID:
5397 buffer_add_byte (buf, t->type);
5398 break;
5399 case MONO_TYPE_BOOLEAN:
5400 case MONO_TYPE_I1:
5401 case MONO_TYPE_U1:
5402 buffer_add_byte (buf, t->type);
5403 buffer_add_int (buf, *(gint8*)addr);
5404 break;
5405 case MONO_TYPE_CHAR:
5406 case MONO_TYPE_I2:
5407 case MONO_TYPE_U2:
5408 buffer_add_byte (buf, t->type);
5409 buffer_add_int (buf, *(gint16*)addr);
5410 break;
5411 case MONO_TYPE_I4:
5412 case MONO_TYPE_U4:
5413 case MONO_TYPE_R4:
5414 buffer_add_byte (buf, t->type);
5415 buffer_add_int (buf, *(gint32*)addr);
5416 break;
5417 case MONO_TYPE_I8:
5418 case MONO_TYPE_U8:
5419 case MONO_TYPE_R8:
5420 buffer_add_byte (buf, t->type);
5421 buffer_add_long (buf, *(gint64*)addr);
5422 break;
5423 case MONO_TYPE_I:
5424 case MONO_TYPE_U:
5425 /* Treat it as a vtype */
5426 goto handle_vtype;
5427 case MONO_TYPE_PTR: {
5428 gssize val = *(gssize*)addr;
5430 buffer_add_byte (buf, t->type);
5431 buffer_add_long (buf, val);
5432 if (CHECK_PROTOCOL_VERSION(2, 46))
5433 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5434 break;
5436 handle_ref:
5437 case MONO_TYPE_STRING:
5438 case MONO_TYPE_SZARRAY:
5439 case MONO_TYPE_OBJECT:
5440 case MONO_TYPE_CLASS:
5441 case MONO_TYPE_ARRAY:
5442 obj = *(MonoObject**)addr;
5444 if (!obj) {
5445 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5446 } else {
5447 if (m_class_is_valuetype (obj->vtable->klass)) {
5448 t = m_class_get_byval_arg (obj->vtable->klass);
5449 addr = mono_object_unbox_internal (obj);
5450 boxed_vtype = TRUE;
5451 goto handle_vtype;
5452 } else if (m_class_get_rank (obj->vtable->klass)) {
5453 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5454 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5455 buffer_add_byte (buf, MONO_TYPE_CLASS);
5456 } else {
5457 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5459 buffer_add_objid (buf, obj);
5461 break;
5462 handle_vtype:
5463 case MONO_TYPE_VALUETYPE:
5464 case MONO_TYPE_TYPEDBYREF: {
5465 int nfields;
5466 gpointer iter;
5467 MonoClassField *f;
5468 MonoClass *klass = mono_class_from_mono_type_internal (t);
5469 int vtype_index;
5471 if (boxed_vtype) {
5473 * Handle boxed vtypes recursively referencing themselves using fields.
5475 if (!parent_vtypes)
5476 parent_vtypes = g_hash_table_new (NULL, NULL);
5477 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5478 if (vtype_index) {
5479 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5480 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5481 buffer_add_int (buf, vtype_index - 1);
5482 } else {
5483 /* The client can't handle PARENT_VTYPE */
5484 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5486 break;
5487 } else {
5488 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5492 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5493 buffer_add_byte (buf, m_class_is_enumtype (klass));
5494 buffer_add_typeid (buf, domain, klass);
5496 nfields = 0;
5497 iter = NULL;
5498 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5499 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5500 continue;
5501 if (mono_field_is_deleted (f))
5502 continue;
5503 nfields ++;
5505 buffer_add_int (buf, nfields);
5507 iter = NULL;
5508 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5509 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5510 continue;
5511 if (mono_field_is_deleted (f))
5512 continue;
5513 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));
5516 if (boxed_vtype) {
5517 g_hash_table_remove (parent_vtypes, addr);
5518 if (g_hash_table_size (parent_vtypes) == 0) {
5519 g_hash_table_destroy (parent_vtypes);
5520 parent_vtypes = NULL;
5523 break;
5525 case MONO_TYPE_GENERICINST:
5526 if (mono_type_generic_inst_is_valuetype (t)) {
5527 goto handle_vtype;
5528 } else {
5529 goto handle_ref;
5531 break;
5532 default:
5533 NOT_IMPLEMENTED;
5537 static void
5538 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5540 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5543 static gboolean
5544 obj_is_of_type (MonoObject *obj, MonoType *t)
5546 MonoClass *klass = obj->vtable->klass;
5547 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5548 if (mono_class_is_transparent_proxy (klass)) {
5549 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5550 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5551 return TRUE;
5554 return FALSE;
5556 return TRUE;
5559 static ErrorCode
5560 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5562 static ErrorCode
5563 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5565 guint8 *addr = (guint8*)void_addr;
5566 guint8 *buf = (guint8*)void_buf;
5567 gboolean is_enum;
5568 MonoClass *klass;
5569 MonoClassField *f;
5570 int nfields;
5571 gpointer iter = NULL;
5572 MonoDomain *d;
5573 ErrorCode err;
5575 is_enum = decode_byte (buf, &buf, limit);
5576 /* Enums are sent as a normal vtype */
5577 if (is_enum)
5578 return ERR_NOT_IMPLEMENTED;
5579 klass = decode_typeid (buf, &buf, limit, &d, &err);
5580 if (err != ERR_NONE)
5581 return err;
5583 if (t && klass != mono_class_from_mono_type_internal (t)) {
5584 char *name = mono_type_full_name (t);
5585 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5586 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5587 g_free (name);
5588 g_free (name2);
5589 return ERR_INVALID_ARGUMENT;
5592 nfields = decode_int (buf, &buf, limit);
5593 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5594 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5595 continue;
5596 if (mono_field_is_deleted (f))
5597 continue;
5598 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5599 if (err != ERR_NONE)
5600 return err;
5601 nfields --;
5603 g_assert (nfields == 0);
5605 *endbuf = buf;
5607 return ERR_NONE;
5609 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)
5611 ErrorCode err = ERR_NONE;
5612 int fixedSizeLen = 1;
5613 int newType = MONO_TYPE_END;
5614 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5615 newType = decode_byte (buf, &buf, limit);
5616 fixedSizeLen = decode_int (buf, &buf, limit);
5617 //t->type = newType;
5619 for (int i = 0 ; i < fixedSizeLen; i++) {
5620 switch (newType) {
5621 case MONO_TYPE_BOOLEAN:
5622 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5623 break;
5624 case MONO_TYPE_CHAR:
5625 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5626 break;
5627 case MONO_TYPE_I1:
5628 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5629 break;
5630 case MONO_TYPE_U1:
5631 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5632 break;
5633 case MONO_TYPE_I2:
5634 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5635 break;
5636 case MONO_TYPE_U2:
5637 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5638 break;
5639 case MONO_TYPE_I4:
5640 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5641 break;
5642 case MONO_TYPE_U4:
5643 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5644 break;
5645 case MONO_TYPE_I8:
5646 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5647 break;
5648 case MONO_TYPE_U8:
5649 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5650 break;
5651 case MONO_TYPE_R4:
5652 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5653 break;
5654 case MONO_TYPE_R8:
5655 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5656 break;
5659 *endbuf = buf;
5660 return err;
5662 static ErrorCode
5663 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5665 ErrorCode err;
5666 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5667 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5668 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5669 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5670 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5671 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5672 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5673 char *name = mono_type_full_name (t);
5674 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5675 g_free (name);
5676 return ERR_INVALID_ARGUMENT;
5678 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5679 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5680 return ERR_NONE;
5683 switch (t->type) {
5684 case MONO_TYPE_BOOLEAN:
5685 *(guint8*)addr = decode_int (buf, &buf, limit);
5686 break;
5687 case MONO_TYPE_CHAR:
5688 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5689 break;
5690 case MONO_TYPE_I1:
5691 *(gint8*)addr = decode_int (buf, &buf, limit);
5692 break;
5693 case MONO_TYPE_U1:
5694 *(guint8*)addr = decode_int (buf, &buf, limit);
5695 break;
5696 case MONO_TYPE_I2:
5697 *(gint16*)addr = decode_int (buf, &buf, limit);
5698 break;
5699 case MONO_TYPE_U2:
5700 *(guint16*)addr = decode_int (buf, &buf, limit);
5701 break;
5702 case MONO_TYPE_I4:
5703 *(gint32*)addr = decode_int (buf, &buf, limit);
5704 break;
5705 case MONO_TYPE_U4:
5706 *(guint32*)addr = decode_int (buf, &buf, limit);
5707 break;
5708 case MONO_TYPE_I8:
5709 *(gint64*)addr = decode_long (buf, &buf, limit);
5710 break;
5711 case MONO_TYPE_U8:
5712 *(guint64*)addr = decode_long (buf, &buf, limit);
5713 break;
5714 case MONO_TYPE_R4:
5715 *(guint32*)addr = decode_int (buf, &buf, limit);
5716 break;
5717 case MONO_TYPE_R8:
5718 *(guint64*)addr = decode_long (buf, &buf, limit);
5719 break;
5720 case MONO_TYPE_PTR:
5721 /* We send these as I8, so we get them back as such */
5722 g_assert (type == MONO_TYPE_I8);
5723 *(gssize*)addr = decode_long (buf, &buf, limit);
5724 break;
5725 case MONO_TYPE_GENERICINST:
5726 if (MONO_TYPE_ISSTRUCT (t)) {
5727 /* The client sends these as a valuetype */
5728 goto handle_vtype;
5729 } else {
5730 goto handle_ref;
5732 break;
5733 case MONO_TYPE_I:
5734 case MONO_TYPE_U:
5735 /* We send these as vtypes, so we get them back as such */
5736 g_assert (type == MONO_TYPE_VALUETYPE);
5737 /* Fall through */
5738 handle_vtype:
5739 case MONO_TYPE_VALUETYPE:
5740 if (type == MONO_TYPE_OBJECT) {
5741 /* Boxed vtype */
5742 int objid = decode_objid (buf, &buf, limit);
5743 ErrorCode err;
5744 MonoObject *obj;
5746 err = get_object (objid, (MonoObject**)&obj);
5747 if (err != ERR_NONE)
5748 return err;
5749 if (!obj)
5750 return ERR_INVALID_ARGUMENT;
5751 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5752 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5753 return ERR_INVALID_ARGUMENT;
5755 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5756 } else {
5757 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5758 if (err != ERR_NONE)
5759 return err;
5761 break;
5762 handle_ref:
5763 default:
5764 if (MONO_TYPE_IS_REFERENCE (t)) {
5765 if (type == MONO_TYPE_OBJECT) {
5766 int objid = decode_objid (buf, &buf, limit);
5767 ErrorCode err;
5768 MonoObject *obj;
5770 err = get_object (objid, (MonoObject**)&obj);
5771 if (err != ERR_NONE)
5772 return err;
5774 if (obj) {
5775 if (!obj_is_of_type (obj, t)) {
5776 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5777 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5778 return ERR_INVALID_ARGUMENT;
5782 if (obj && obj->vtable->domain != domain)
5783 return ERR_INVALID_ARGUMENT;
5785 mono_gc_wbarrier_generic_store_internal (addr, obj);
5786 } else if (type == VALUE_TYPE_ID_NULL) {
5787 *(MonoObject**)addr = NULL;
5788 } else if (type == MONO_TYPE_VALUETYPE) {
5789 ERROR_DECL (error);
5790 guint8 *buf2;
5791 gboolean is_enum;
5792 MonoClass *klass;
5793 MonoDomain *d;
5794 guint8 *vtype_buf;
5795 int vtype_buf_size;
5797 /* This can happen when round-tripping boxed vtypes */
5799 * Obtain vtype class.
5800 * Same as the beginning of the handle_vtype case above.
5802 buf2 = buf;
5803 is_enum = decode_byte (buf, &buf, limit);
5804 if (is_enum)
5805 return ERR_NOT_IMPLEMENTED;
5806 klass = decode_typeid (buf, &buf, limit, &d, &err);
5807 if (err != ERR_NONE)
5808 return err;
5810 /* Decode the vtype into a temporary buffer, then box it. */
5811 vtype_buf_size = mono_class_value_size (klass, NULL);
5812 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5813 g_assert (vtype_buf);
5815 buf = buf2;
5816 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5817 if (err != ERR_NONE) {
5818 g_free (vtype_buf);
5819 return err;
5821 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5822 mono_error_cleanup (error);
5823 g_free (vtype_buf);
5824 } else {
5825 char *name = mono_type_full_name (t);
5826 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5827 g_free (name);
5828 return ERR_INVALID_ARGUMENT;
5830 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5831 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5832 m_class_is_enumtype (t->data.generic_class->container_class)){
5833 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5834 if (err != ERR_NONE)
5835 return err;
5836 } else {
5837 NOT_IMPLEMENTED;
5839 break;
5843 *endbuf = buf;
5845 return ERR_NONE;
5848 static ErrorCode
5849 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5851 guint8 *addr = (guint8*)void_addr;
5852 guint8 *buf = (guint8*)void_buf;
5854 ERROR_DECL (error);
5855 ErrorCode err;
5856 int type = decode_byte (buf, &buf, limit);
5858 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5859 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5860 guint8 *nullable_buf;
5863 * First try decoding it as a Nullable`1
5865 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5866 if (err == ERR_NONE)
5867 return err;
5870 * Then try decoding as a primitive value or null.
5872 if (targ->type == type) {
5873 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
5874 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
5875 if (err != ERR_NONE) {
5876 g_free (nullable_buf);
5877 return err;
5879 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
5880 if (!is_ok (error)) {
5881 mono_error_cleanup (error);
5882 return ERR_INVALID_OBJECT;
5884 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
5885 g_free (nullable_buf);
5886 *endbuf = buf;
5887 return ERR_NONE;
5888 } else if (type == VALUE_TYPE_ID_NULL) {
5889 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
5890 *endbuf = buf;
5891 return ERR_NONE;
5895 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5898 static void
5899 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5901 guint32 flags;
5902 int reg;
5903 guint8 *addr, *gaddr;
5904 host_mgreg_t reg_val;
5906 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5907 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5909 switch (flags) {
5910 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5911 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5913 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
5914 break;
5915 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5916 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5917 addr += (gint32)var->offset;
5919 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5921 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
5922 break;
5923 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5924 NOT_IMPLEMENTED;
5925 break;
5926 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5927 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5928 /* Same as regoffset, but with an indirection */
5929 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5930 addr += (gint32)var->offset;
5932 gaddr = (guint8 *)*(gpointer*)addr;
5933 g_assert (gaddr);
5934 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
5935 break;
5936 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5937 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5938 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5939 MonoGSharedVtMethodRuntimeInfo *info;
5940 guint8 *locals;
5941 int idx;
5943 idx = reg;
5945 g_assert (info_var);
5946 g_assert (locals_var);
5948 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5949 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5950 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5951 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5952 addr += (gint32)info_var->offset;
5953 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
5954 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5955 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
5956 } else {
5957 g_assert_not_reached ();
5959 g_assert (info);
5961 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5962 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5963 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5964 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5965 addr += (gint32)locals_var->offset;
5966 locals = (guint8 *)*(gpointer*)addr;
5967 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5968 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5969 } else {
5970 g_assert_not_reached ();
5972 g_assert (locals);
5974 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5976 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
5977 break;
5980 default:
5981 g_assert_not_reached ();
5985 static void
5986 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
5988 guint32 flags;
5989 int reg, size;
5990 guint8 *addr, *gaddr;
5992 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5993 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5995 if (MONO_TYPE_IS_REFERENCE (t))
5996 size = sizeof (gpointer);
5997 else
5998 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6000 switch (flags) {
6001 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6002 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6003 host_mgreg_t v;
6004 gboolean is_signed = FALSE;
6006 if (t->byref) {
6007 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6009 if (addr) {
6010 // FIXME: Write barriers
6011 mono_gc_memmove_atomic (addr, val, size);
6013 break;
6016 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6017 is_signed = TRUE;
6019 switch (size) {
6020 case 1:
6021 v = is_signed ? *(gint8*)val : *(guint8*)val;
6022 break;
6023 case 2:
6024 v = is_signed ? *(gint16*)val : *(guint16*)val;
6025 break;
6026 case 4:
6027 v = is_signed ? *(gint32*)val : *(guint32*)val;
6028 break;
6029 case 8:
6030 v = is_signed ? *(gint64*)val : *(guint64*)val;
6031 break;
6032 default:
6033 g_assert_not_reached ();
6036 /* Set value on the stack or in the return ctx */
6037 if (reg_locations [reg]) {
6038 /* Saved on the stack */
6039 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6040 *(reg_locations [reg]) = v;
6041 } else {
6042 /* Not saved yet */
6043 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6044 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6047 // FIXME: Move these to mono-context.h/c.
6048 mono_arch_context_set_int_reg (ctx, reg, v);
6049 #else
6050 // FIXME: Can't set registers, so we disable linears
6051 NOT_IMPLEMENTED;
6052 #endif
6053 break;
6055 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6056 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6057 addr += (gint32)var->offset;
6059 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6061 if (t->byref) {
6062 addr = *(guint8**)addr;
6064 if (!addr)
6065 break;
6068 // FIXME: Write barriers
6069 mono_gc_memmove_atomic (addr, val, size);
6070 break;
6071 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6072 /* Same as regoffset, but with an indirection */
6073 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6074 addr += (gint32)var->offset;
6076 gaddr = (guint8 *)*(gpointer*)addr;
6077 g_assert (gaddr);
6078 // FIXME: Write barriers
6079 mono_gc_memmove_atomic (gaddr, val, size);
6080 break;
6081 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6082 NOT_IMPLEMENTED;
6083 break;
6084 default:
6085 g_assert_not_reached ();
6089 static void
6090 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6092 int size;
6094 if (t->byref) {
6095 addr = *(gpointer*)addr;
6096 g_assert (addr);
6099 if (MONO_TYPE_IS_REFERENCE (t))
6100 size = sizeof (gpointer);
6101 else
6102 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6104 memcpy (addr, val_buf, size);
6107 static void
6108 clear_event_request (int req_id, int etype)
6110 int i;
6112 mono_loader_lock ();
6113 for (i = 0; i < event_requests->len; ++i) {
6114 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6116 if (req->id == req_id && req->event_kind == etype) {
6117 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6118 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6119 if (req->event_kind == EVENT_KIND_STEP) {
6120 mono_de_cancel_ss ();
6122 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6123 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6124 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6125 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6126 g_ptr_array_remove_index_fast (event_requests, i);
6127 g_free (req);
6128 break;
6131 mono_loader_unlock ();
6134 static void
6135 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6137 int i;
6139 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6140 m->kind = MOD_KIND_NONE;
6141 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6142 int count = 0, match_count = 0, pos;
6143 MonoAssembly **newassemblies;
6145 for (i = 0; m->data.assemblies [i]; ++i) {
6146 count ++;
6147 if (m->data.assemblies [i] == assembly)
6148 match_count ++;
6151 if (match_count) {
6152 // +1 because we don't know length and we use last element to check for end
6153 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6155 pos = 0;
6156 for (i = 0; i < count; ++i)
6157 if (m->data.assemblies [i] != assembly)
6158 newassemblies [pos ++] = m->data.assemblies [i];
6159 g_assert (pos == count - match_count);
6160 g_free (m->data.assemblies);
6161 m->data.assemblies = newassemblies;
6166 static void
6167 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6169 int i;
6171 for (i = 0; i < req->nmodifiers; ++i) {
6172 Modifier *m = &req->modifiers [i];
6174 clear_assembly_from_modifier (req, m, assembly);
6179 * clear_event_requests_for_assembly:
6181 * Clear all events requests which reference ASSEMBLY.
6183 static void
6184 clear_event_requests_for_assembly (MonoAssembly *assembly)
6186 int i;
6187 gboolean found;
6189 mono_loader_lock ();
6190 found = TRUE;
6191 while (found) {
6192 found = FALSE;
6193 for (i = 0; i < event_requests->len; ++i) {
6194 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6196 clear_assembly_from_modifiers (req, assembly);
6198 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6199 clear_event_request (req->id, req->event_kind);
6200 found = TRUE;
6201 break;
6204 if (req->event_kind == EVENT_KIND_STEP)
6205 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6208 mono_loader_unlock ();
6212 * type_comes_from_assembly:
6214 * GHRFunc that returns TRUE if klass comes from assembly
6216 static gboolean
6217 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6219 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6223 * clear_types_for_assembly:
6225 * Clears types from loaded_classes for a given assembly
6227 static void
6228 clear_types_for_assembly (MonoAssembly *assembly)
6230 MonoDomain *domain = mono_domain_get ();
6231 AgentDomainInfo *info = NULL;
6233 if (!domain || !domain_jit_info (domain))
6234 /* Can happen during shutdown */
6235 return;
6237 info = get_agent_domain_info (domain);
6239 mono_loader_lock ();
6240 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6241 mono_loader_unlock ();
6245 static void
6246 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6248 MonoThread *thread = (MonoThread *)value;
6249 gboolean *ret = (gboolean *)user_data;
6250 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6251 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6252 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6253 *ret = TRUE;
6254 return;
6259 static void
6260 add_thread (gpointer key, gpointer value, gpointer user_data)
6262 MonoThread *thread = (MonoThread *)value;
6263 Buffer *buf = (Buffer *)user_data;
6264 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6265 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6266 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6267 return;
6269 buffer_add_objid (buf, (MonoObject*)thread);
6273 static ErrorCode
6274 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6276 ERROR_DECL (error);
6277 guint8 *end = invoke->endp;
6278 MonoMethod *m;
6279 int i, nargs;
6280 ErrorCode err;
6281 MonoMethodSignature *sig;
6282 guint8 **arg_buf;
6283 void **args;
6284 MonoObject *this_arg, *res, *exc = NULL;
6285 MonoDomain *domain;
6286 guint8 *this_buf;
6287 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6288 MonoLMFExt ext;
6289 #endif
6290 MonoStopwatch watch;
6292 if (invoke->method) {
6294 * Invoke this method directly, currently only Environment.Exit () is supported.
6296 this_arg = NULL;
6297 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>");
6299 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6300 mono_error_assert_ok (error);
6301 g_assert_not_reached ();
6304 m = decode_methodid (p, &p, end, &domain, &err);
6305 if (err != ERR_NONE)
6306 return err;
6307 sig = mono_method_signature_internal (m);
6309 if (m_class_is_valuetype (m->klass))
6310 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6311 else
6312 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6314 if (m->is_generic) {
6315 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));
6316 return ERR_INVALID_ARGUMENT;
6317 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6318 /* Should be null */
6319 int type = decode_byte (p, &p, end);
6320 if (type != VALUE_TYPE_ID_NULL) {
6321 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6322 return ERR_INVALID_ARGUMENT;
6324 memset (this_buf, 0, mono_class_instance_size (m->klass));
6325 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6326 /* Could be null */
6327 guint8 *tmp_p;
6329 int type = decode_byte (p, &tmp_p, end);
6330 if (type == VALUE_TYPE_ID_NULL) {
6331 memset (this_buf, 0, mono_class_instance_size (m->klass));
6332 p = tmp_p;
6333 } else {
6334 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6335 if (err != ERR_NONE)
6336 return err;
6338 } else {
6339 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6340 if (err != ERR_NONE)
6341 return err;
6344 if (!m_class_is_valuetype (m->klass))
6345 this_arg = *(MonoObject**)this_buf;
6346 else
6347 this_arg = NULL;
6349 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6350 if (!this_arg) {
6351 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6352 return ERR_INVALID_ARGUMENT;
6354 m = mono_object_get_virtual_method_internal (this_arg, m);
6355 /* Transform this to the format the rest of the code expects it to be */
6356 if (m_class_is_valuetype (m->klass)) {
6357 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6358 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6360 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6361 if (!this_arg) {
6362 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6363 return ERR_INVALID_ARGUMENT;
6365 m = mono_object_get_virtual_method_internal (this_arg, m);
6366 if (m_class_is_valuetype (m->klass)) {
6367 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6368 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6372 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>");
6374 if (this_arg && this_arg->vtable->domain != domain)
6375 NOT_IMPLEMENTED;
6377 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6378 if (!strcmp (m->name, ".ctor")) {
6379 if (mono_class_is_abstract (m->klass))
6380 return ERR_INVALID_ARGUMENT;
6381 else {
6382 ERROR_DECL (error);
6383 this_arg = mono_object_new_checked (domain, m->klass, error);
6384 mono_error_assert_ok (error);
6386 } else {
6387 return ERR_INVALID_ARGUMENT;
6391 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6392 return ERR_INVALID_ARGUMENT;
6394 nargs = decode_int (p, &p, end);
6395 if (nargs != sig->param_count)
6396 return ERR_INVALID_ARGUMENT;
6397 /* Use alloca to get gc tracking */
6398 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6399 memset (arg_buf, 0, nargs * sizeof (gpointer));
6400 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6401 for (i = 0; i < nargs; ++i) {
6402 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6403 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6404 if (err != ERR_NONE)
6405 break;
6406 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6407 NOT_IMPLEMENTED;
6409 if (sig->params [i]->byref) {
6410 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6411 *(gpointer*)arg_buf [i] = args [i];
6412 args [i] = arg_buf [i];
6414 } else {
6415 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6416 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6417 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6418 if (err != ERR_NONE)
6419 break;
6420 if (mono_class_is_nullable (arg_class)) {
6421 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6422 mono_error_assert_ok (error);
6423 } else {
6424 args [i] = arg_buf [i];
6429 if (i < nargs)
6430 return err;
6432 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6433 tls->disable_breakpoints = TRUE;
6434 else
6435 tls->disable_breakpoints = FALSE;
6438 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6440 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6441 if (invoke->has_ctx) {
6442 /* Setup our lmf */
6443 memset (&ext, 0, sizeof (ext));
6444 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6445 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6447 mono_push_lmf (&ext);
6449 #endif
6451 mono_stopwatch_start (&watch);
6452 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6453 if (!is_ok (error) && exc == NULL) {
6454 exc = (MonoObject*) mono_error_convert_to_exception (error);
6455 } else {
6456 mono_error_cleanup (error); /* FIXME report error */
6458 mono_stopwatch_stop (&watch);
6459 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));
6460 if (exc) {
6461 buffer_add_byte (buf, 0);
6462 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6463 } else {
6464 gboolean out_this = FALSE;
6465 gboolean out_args = FALSE;
6467 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6468 out_this = TRUE;
6469 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6470 out_args = TRUE;
6471 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6472 if (m->string_ctor) {
6473 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6474 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6475 if (!strcmp (m->name, ".ctor")) {
6476 if (!m_class_is_valuetype (m->klass))
6477 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6478 else
6479 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6480 } else {
6481 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6483 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6484 if (sig->ret->byref) {
6485 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6486 buffer_add_value (buf, ret_byval, &res, domain);
6487 } else {
6488 buffer_add_value (buf, sig->ret, &res, domain);
6490 } 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) {
6491 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6492 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6493 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6495 g_assert (nullable_buf);
6496 mono_nullable_init (nullable_buf, res, k);
6497 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6498 } else {
6499 g_assert (res);
6501 if (sig->ret->byref) {
6502 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6503 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6504 } else {
6505 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6508 } else {
6509 NOT_IMPLEMENTED;
6511 if (out_this)
6512 /* Return the new value of the receiver after the call */
6513 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6514 if (out_args) {
6515 buffer_add_int (buf, nargs);
6516 for (i = 0; i < nargs; ++i) {
6517 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6518 buffer_add_value (buf, sig->params [i], &args [i], domain);
6519 else if (sig->params [i]->byref)
6520 /* add_value () does an indirection */
6521 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6522 else
6523 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6528 tls->disable_breakpoints = FALSE;
6530 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6531 if (invoke->has_ctx)
6532 mono_pop_lmf ((MonoLMF*)&ext);
6533 #endif
6535 *endp = p;
6536 // FIXME: byref arguments
6537 // FIXME: varargs
6538 return ERR_NONE;
6542 * invoke_method:
6544 * Invoke the method given by tls->pending_invoke in the current thread.
6546 static void
6547 invoke_method (void)
6549 DebuggerTlsData *tls;
6550 InvokeData *invoke;
6551 int id;
6552 int i, mindex;
6553 ErrorCode err;
6554 Buffer buf;
6555 MonoContext restore_ctx;
6556 guint8 *p;
6558 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6559 g_assert (tls);
6562 * Store the `InvokeData *' in `tls->invoke' until we're done with
6563 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6566 mono_loader_lock ();
6568 invoke = tls->pending_invoke;
6569 g_assert (invoke);
6570 tls->pending_invoke = NULL;
6572 invoke->last_invoke = tls->invoke;
6573 tls->invoke = invoke;
6575 mono_loader_unlock ();
6577 tls->frames_up_to_date = FALSE;
6579 id = invoke->id;
6581 p = invoke->p;
6582 err = ERR_NONE;
6583 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6584 buffer_init (&buf, 128);
6586 if (err) {
6587 /* Fail the other invokes as well */
6588 } else {
6589 err = do_invoke_method (tls, &buf, invoke, p, &p);
6592 if (tls->abort_requested) {
6593 if (CHECK_PROTOCOL_VERSION (2, 42))
6594 err = ERR_INVOKE_ABORTED;
6597 /* Start suspending before sending the reply */
6598 if (mindex == invoke->nmethods - 1) {
6599 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6600 for (i = 0; i < invoke->suspend_count; ++i)
6601 suspend_vm ();
6605 send_reply_packet (id, err, &buf);
6607 buffer_free (&buf);
6610 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6612 if (invoke->has_ctx)
6613 save_thread_context (&restore_ctx);
6615 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6616 g_assert (tls->resume_count);
6617 tls->resume_count -= invoke->suspend_count;
6620 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6623 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6625 * It is possible that mono_thread_internal_abort () was called
6626 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6627 * because we reset the abort here.
6630 mono_loader_lock ();
6632 if (tls->abort_requested)
6633 mono_thread_internal_reset_abort (tls->thread);
6635 tls->invoke = tls->invoke->last_invoke;
6636 tls->abort_requested = FALSE;
6638 mono_loader_unlock ();
6640 g_free (invoke->p);
6641 g_free (invoke);
6644 static gboolean
6645 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6647 MonoThread *thread = (MonoThread *)value;
6648 DebuggerTlsData *tls;
6649 gboolean res;
6651 mono_loader_lock ();
6652 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6653 g_assert (tls);
6654 res = tls->really_suspended;
6655 mono_loader_unlock ();
6657 return res;
6660 static GPtrArray*
6661 get_source_files_for_type (MonoClass *klass)
6663 gpointer iter = NULL;
6664 MonoMethod *method;
6665 MonoDebugSourceInfo *sinfo;
6666 GPtrArray *files;
6667 int i, j;
6669 files = g_ptr_array_new ();
6671 while ((method = mono_class_get_methods (klass, &iter))) {
6672 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6673 GPtrArray *source_file_list;
6675 if (minfo) {
6676 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6677 for (j = 0; j < source_file_list->len; ++j) {
6678 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6679 for (i = 0; i < files->len; ++i)
6680 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6681 break;
6682 if (i == files->len)
6683 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6685 g_ptr_array_free (source_file_list, TRUE);
6689 return files;
6693 typedef struct {
6694 MonoTypeNameParse *info;
6695 gboolean ignore_case;
6696 GPtrArray *res_classes;
6697 GPtrArray *res_domains;
6698 } GetTypesArgs;
6700 static void
6701 get_types (gpointer key, gpointer value, gpointer user_data)
6703 MonoAssembly *ass;
6704 gboolean type_resolve;
6705 MonoType *t;
6706 GSList *tmp;
6707 MonoDomain *domain = (MonoDomain*)key;
6708 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6710 mono_domain_assemblies_lock (domain);
6711 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6712 ass = (MonoAssembly *)tmp->data;
6714 if (ass->image) {
6715 ERROR_DECL (probe_type_error);
6716 /* FIXME really okay to call while holding locks? */
6717 t = mono_reflection_get_type_checked (ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6718 mono_error_cleanup (probe_type_error);
6719 if (t) {
6720 g_ptr_array_add (ud->res_classes, mono_type_get_class (t));
6721 g_ptr_array_add (ud->res_domains, domain);
6725 mono_domain_assemblies_unlock (domain);
6728 typedef struct {
6729 gboolean ignore_case;
6730 char *basename;
6731 GPtrArray *res_classes;
6732 GPtrArray *res_domains;
6733 } GetTypesForSourceFileArgs;
6735 static void
6736 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6738 GHashTableIter iter;
6739 GSList *class_list = NULL;
6740 MonoClass *klass = NULL;
6741 GPtrArray *files = NULL;
6743 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6744 MonoDomain *domain = (MonoDomain*)key;
6746 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6748 /* Update 'source_file_to_class' cache */
6749 g_hash_table_iter_init (&iter, info->loaded_classes);
6750 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6751 if (!g_hash_table_lookup (info->source_files, klass)) {
6752 files = get_source_files_for_type (klass);
6753 g_hash_table_insert (info->source_files, klass, files);
6755 for (int i = 0; i < files->len; ++i) {
6756 char *s = (char *)g_ptr_array_index (files, i);
6757 char *s2 = dbg_path_get_basename (s);
6758 char *s3;
6760 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6761 if (!class_list) {
6762 class_list = g_slist_prepend (class_list, klass);
6763 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6764 } else {
6765 class_list = g_slist_prepend (class_list, klass);
6766 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6769 /* The _ignorecase hash contains the lowercase path */
6770 s3 = strdup_tolower (s2);
6771 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6772 if (!class_list) {
6773 class_list = g_slist_prepend (class_list, klass);
6774 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6775 } else {
6776 class_list = g_slist_prepend (class_list, klass);
6777 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6780 g_free (s2);
6781 g_free (s3);
6786 if (ud->ignore_case) {
6787 char *s;
6789 s = strdup_tolower (ud->basename);
6790 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6791 g_free (s);
6792 } else {
6793 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6796 for (GSList *l = class_list; l; l = l->next) {
6797 klass = (MonoClass *)l->data;
6799 g_ptr_array_add (ud->res_classes, klass);
6800 g_ptr_array_add (ud->res_domains, domain);
6804 static ErrorCode
6805 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6807 switch (command) {
6808 case CMD_VM_VERSION: {
6809 char *build_info, *version;
6811 build_info = mono_get_runtime_build_info ();
6812 version = g_strdup_printf ("mono %s", build_info);
6814 buffer_add_string (buf, version); /* vm version */
6815 buffer_add_int (buf, MAJOR_VERSION);
6816 buffer_add_int (buf, MINOR_VERSION);
6817 g_free (build_info);
6818 g_free (version);
6819 break;
6821 case CMD_VM_SET_PROTOCOL_VERSION: {
6822 major_version = decode_int (p, &p, end);
6823 minor_version = decode_int (p, &p, end);
6824 protocol_version_set = TRUE;
6825 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6826 break;
6828 case CMD_VM_ALL_THREADS: {
6829 // FIXME: Domains
6830 gboolean remove_gc_finalizing;
6831 mono_loader_lock ();
6832 int count = mono_g_hash_table_size (tid_to_thread_obj);
6833 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
6834 if (remove_gc_finalizing)
6835 count--;
6836 buffer_add_int (buf, count);
6837 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6839 mono_loader_unlock ();
6840 break;
6842 case CMD_VM_SUSPEND:
6843 suspend_vm ();
6844 wait_for_suspend ();
6845 break;
6846 case CMD_VM_RESUME:
6847 if (suspend_count == 0)
6848 return ERR_NOT_SUSPENDED;
6849 resume_vm ();
6850 clear_suspended_objs ();
6851 break;
6852 case CMD_VM_DISPOSE:
6853 /* Clear all event requests */
6854 mono_loader_lock ();
6855 while (event_requests->len > 0) {
6856 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6858 clear_event_request (req->id, req->event_kind);
6860 mono_loader_unlock ();
6862 while (suspend_count > 0)
6863 resume_vm ();
6864 disconnected = TRUE;
6865 vm_start_event_sent = FALSE;
6866 break;
6867 case CMD_VM_EXIT: {
6868 MonoInternalThread *thread;
6869 DebuggerTlsData *tls;
6870 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6871 MonoClass *env_class;
6872 #endif
6873 MonoMethod *exit_method = NULL;
6874 gpointer *args;
6875 int exit_code;
6877 exit_code = decode_int (p, &p, end);
6879 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6881 /* Have to send a reply before exiting */
6882 send_reply_packet (id, 0, buf);
6884 /* Clear all event requests */
6885 mono_loader_lock ();
6886 while (event_requests->len > 0) {
6887 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6889 clear_event_request (req->id, req->event_kind);
6891 mono_loader_unlock ();
6894 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6895 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6896 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6897 * better than doing the shutdown ourselves, since it avoids various races.
6900 suspend_vm ();
6901 wait_for_suspend ();
6903 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6904 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6905 if (env_class) {
6906 ERROR_DECL (error);
6907 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
6908 mono_error_assert_ok (error);
6910 #endif
6912 mono_loader_lock ();
6913 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6914 mono_loader_unlock ();
6916 if (thread && exit_method) {
6917 mono_loader_lock ();
6918 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6919 mono_loader_unlock ();
6921 args = g_new0 (gpointer, 1);
6922 args [0] = g_malloc (sizeof (int));
6923 *(int*)(args [0]) = exit_code;
6925 tls->pending_invoke = g_new0 (InvokeData, 1);
6926 tls->pending_invoke->method = exit_method;
6927 tls->pending_invoke->args = args;
6928 tls->pending_invoke->nmethods = 1;
6930 while (suspend_count > 0)
6931 resume_vm ();
6932 } else {
6934 * No thread found, do it ourselves.
6935 * FIXME: This can race with normal shutdown etc.
6937 while (suspend_count > 0)
6938 resume_vm ();
6940 if (!mono_runtime_try_shutdown ())
6941 break;
6943 mono_environment_exitcode_set (exit_code);
6945 /* Suspend all managed threads since the runtime is going away */
6946 DEBUG_PRINTF (1, "Suspending all threads...\n");
6947 mono_thread_suspend_all_other_threads ();
6948 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6949 mono_runtime_quit ();
6950 transport_close2 ();
6951 DEBUG_PRINTF (1, "Exiting...\n");
6953 exit (exit_code);
6955 break;
6957 case CMD_VM_INVOKE_METHOD:
6958 case CMD_VM_INVOKE_METHODS: {
6959 int objid = decode_objid (p, &p, end);
6960 MonoThread *thread;
6961 DebuggerTlsData *tls;
6962 int i, count, flags, nmethods;
6963 ErrorCode err;
6965 err = get_object (objid, (MonoObject**)&thread);
6966 if (err != ERR_NONE)
6967 return err;
6969 flags = decode_int (p, &p, end);
6971 if (command == CMD_VM_INVOKE_METHODS)
6972 nmethods = decode_int (p, &p, end);
6973 else
6974 nmethods = 1;
6976 // Wait for suspending if it already started
6977 if (suspend_count)
6978 wait_for_suspend ();
6979 if (!is_suspended ())
6980 return ERR_NOT_SUSPENDED;
6982 mono_loader_lock ();
6983 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6984 mono_loader_unlock ();
6985 g_assert (tls);
6987 if (!tls->really_suspended)
6988 /* The thread is still running native code, can't do invokes */
6989 return ERR_NOT_SUSPENDED;
6992 * Store the invoke data into tls, the thread will execute it after it is
6993 * resumed.
6995 if (tls->pending_invoke)
6996 return ERR_NOT_SUSPENDED;
6997 tls->pending_invoke = g_new0 (InvokeData, 1);
6998 tls->pending_invoke->id = id;
6999 tls->pending_invoke->flags = flags;
7000 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7001 memcpy (tls->pending_invoke->p, p, end - p);
7002 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7003 tls->pending_invoke->suspend_count = suspend_count;
7004 tls->pending_invoke->nmethods = nmethods;
7006 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7007 resume_thread (THREAD_TO_INTERNAL (thread));
7009 else {
7010 count = suspend_count;
7011 for (i = 0; i < count; ++i)
7012 resume_vm ();
7014 break;
7016 case CMD_VM_ABORT_INVOKE: {
7017 int objid = decode_objid (p, &p, end);
7018 MonoThread *thread;
7019 DebuggerTlsData *tls;
7020 int invoke_id;
7021 ErrorCode err;
7023 err = get_object (objid, (MonoObject**)&thread);
7024 if (err != ERR_NONE)
7025 return err;
7027 invoke_id = decode_int (p, &p, end);
7029 mono_loader_lock ();
7030 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7031 g_assert (tls);
7033 if (tls->abort_requested) {
7034 DEBUG_PRINTF (1, "Abort already requested.\n");
7035 mono_loader_unlock ();
7036 break;
7040 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7041 * actually the correct invocation.
7043 * Careful, we do not stop the thread that's doing the invocation, so we can't
7044 * inspect its stack. However, invoke_method() also acquires the loader lock
7045 * when it's done, so we're safe here.
7049 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7050 mono_loader_unlock ();
7051 return ERR_NO_INVOCATION;
7054 tls->abort_requested = TRUE;
7056 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7057 mono_loader_unlock ();
7058 break;
7061 case CMD_VM_SET_KEEPALIVE: {
7062 int timeout = decode_int (p, &p, end);
7063 agent_config.keepalive = timeout;
7064 // FIXME:
7065 #ifndef DISABLE_SOCKET_TRANSPORT
7066 set_keepalive ();
7067 #else
7068 NOT_IMPLEMENTED;
7069 #endif
7070 break;
7072 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7073 int i;
7074 char *fname, *basename;
7075 gboolean ignore_case;
7076 GPtrArray *res_classes, *res_domains;
7078 fname = decode_string (p, &p, end);
7079 ignore_case = decode_byte (p, &p, end);
7081 basename = dbg_path_get_basename (fname);
7083 res_classes = g_ptr_array_new ();
7084 res_domains = g_ptr_array_new ();
7086 mono_loader_lock ();
7087 GetTypesForSourceFileArgs args;
7088 memset (&args, 0, sizeof (args));
7089 args.ignore_case = ignore_case;
7090 args.basename = basename;
7091 args.res_classes = res_classes;
7092 args.res_domains = res_domains;
7093 mono_de_foreach_domain (get_types_for_source_file, &args);
7094 mono_loader_unlock ();
7096 g_free (fname);
7097 g_free (basename);
7099 buffer_add_int (buf, res_classes->len);
7100 for (i = 0; i < res_classes->len; ++i)
7101 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7102 g_ptr_array_free (res_classes, TRUE);
7103 g_ptr_array_free (res_domains, TRUE);
7104 break;
7106 case CMD_VM_GET_TYPES: {
7107 ERROR_DECL (error);
7108 int i;
7109 char *name;
7110 gboolean ignore_case;
7111 GPtrArray *res_classes, *res_domains;
7112 MonoTypeNameParse info;
7114 name = decode_string (p, &p, end);
7115 ignore_case = decode_byte (p, &p, end);
7117 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7118 mono_error_cleanup (error);
7119 g_free (name);
7120 mono_reflection_free_type_info (&info);
7121 return ERR_INVALID_ARGUMENT;
7124 res_classes = g_ptr_array_new ();
7125 res_domains = g_ptr_array_new ();
7127 mono_loader_lock ();
7129 GetTypesArgs args;
7130 memset (&args, 0, sizeof (args));
7131 args.info = &info;
7132 args.ignore_case = ignore_case;
7133 args.res_classes = res_classes;
7134 args.res_domains = res_domains;
7136 mono_de_foreach_domain (get_types, &args);
7138 mono_loader_unlock ();
7140 g_free (name);
7141 mono_reflection_free_type_info (&info);
7143 buffer_add_int (buf, res_classes->len);
7144 for (i = 0; i < res_classes->len; ++i)
7145 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7146 g_ptr_array_free (res_classes, TRUE);
7147 g_ptr_array_free (res_domains, TRUE);
7148 break;
7150 case CMD_VM_START_BUFFERING:
7151 case CMD_VM_STOP_BUFFERING:
7152 /* Handled in the main loop */
7153 break;
7154 default:
7155 return ERR_NOT_IMPLEMENTED;
7158 return ERR_NONE;
7161 static ErrorCode
7162 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7164 ErrorCode err;
7165 ERROR_DECL (error);
7167 switch (command) {
7168 case CMD_EVENT_REQUEST_SET: {
7169 EventRequest *req;
7170 int i, event_kind, suspend_policy, nmodifiers;
7171 ModifierKind mod;
7172 MonoMethod *method;
7173 long location = 0;
7174 MonoThread *step_thread;
7175 int step_thread_id = 0;
7176 StepDepth depth = STEP_DEPTH_INTO;
7177 StepSize size = STEP_SIZE_MIN;
7178 StepFilter filter = STEP_FILTER_NONE;
7179 MonoDomain *domain;
7180 Modifier *modifier;
7182 event_kind = decode_byte (p, &p, end);
7183 suspend_policy = decode_byte (p, &p, end);
7184 nmodifiers = decode_byte (p, &p, end);
7186 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7187 req->id = mono_atomic_inc_i32 (&event_request_id);
7188 req->event_kind = event_kind;
7189 req->suspend_policy = suspend_policy;
7190 req->nmodifiers = nmodifiers;
7192 method = NULL;
7193 for (i = 0; i < nmodifiers; ++i) {
7194 mod = (ModifierKind)decode_byte (p, &p, end);
7196 req->modifiers [i].kind = mod;
7197 if (mod == MOD_KIND_COUNT) {
7198 req->modifiers [i].data.count = decode_int (p, &p, end);
7199 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7200 method = decode_methodid (p, &p, end, &domain, &err);
7201 if (err != ERR_NONE)
7202 return err;
7203 location = decode_long (p, &p, end);
7204 } else if (mod == MOD_KIND_STEP) {
7205 step_thread_id = decode_id (p, &p, end);
7206 size = (StepSize)decode_int (p, &p, end);
7207 depth = (StepDepth)decode_int (p, &p, end);
7208 if (CHECK_PROTOCOL_VERSION (2, 16))
7209 filter = (StepFilter)decode_int (p, &p, end);
7210 req->modifiers [i].data.filter = filter;
7211 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7212 /* Treat STEP_THOUGH the same as HIDDEN */
7213 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7214 } else if (mod == MOD_KIND_THREAD_ONLY) {
7215 int id = decode_id (p, &p, end);
7217 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7218 if (err != ERR_NONE) {
7219 g_free (req);
7220 return err;
7222 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7223 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7225 if (err != ERR_NONE)
7226 return err;
7227 req->modifiers [i].caught = decode_byte (p, &p, end);
7228 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7229 if (CHECK_PROTOCOL_VERSION (2, 25))
7230 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7231 else
7232 req->modifiers [i].subclasses = TRUE;
7233 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" : "");
7234 if (exc_class) {
7235 req->modifiers [i].data.exc_class = exc_class;
7237 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7238 g_free (req);
7239 return ERR_INVALID_ARGUMENT;
7242 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7243 int n = decode_int (p, &p, end);
7244 int j;
7246 // +1 because we don't know length and we use last element to check for end
7247 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7248 for (j = 0; j < n; ++j) {
7249 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7250 if (err != ERR_NONE) {
7251 g_free (req->modifiers [i].data.assemblies);
7252 return err;
7255 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7256 int n = decode_int (p, &p, end);
7257 int j;
7259 modifier = &req->modifiers [i];
7260 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7261 for (j = 0; j < n; ++j) {
7262 char *s = decode_string (p, &p, end);
7263 char *s2;
7265 if (s) {
7266 s2 = strdup_tolower (s);
7267 g_hash_table_insert (modifier->data.source_files, s2, s2);
7268 g_free (s);
7271 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7272 int n = decode_int (p, &p, end);
7273 int j;
7275 modifier = &req->modifiers [i];
7276 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7277 for (j = 0; j < n; ++j) {
7278 char *s = decode_string (p, &p, end);
7280 if (s)
7281 g_hash_table_insert (modifier->data.type_names, s, s);
7283 } else {
7284 g_free (req);
7285 return ERR_NOT_IMPLEMENTED;
7289 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7290 g_assert (method);
7292 req->info = mono_de_set_breakpoint (method, location, req, error);
7293 if (!is_ok (error)) {
7294 g_free (req);
7295 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7296 mono_error_cleanup (error);
7297 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7299 } else if (req->event_kind == EVENT_KIND_STEP) {
7300 g_assert (step_thread_id);
7302 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7303 if (err != ERR_NONE) {
7304 g_free (req);
7305 return err;
7308 mono_loader_lock ();
7309 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7310 mono_loader_unlock ();
7311 g_assert (tls);
7313 if (tls->terminated) {
7314 /* if the thread is already terminated ignore the single step */
7315 buffer_add_int (buf, req->id);
7316 return ERR_NONE;
7319 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7320 if (err != ERR_NONE) {
7321 g_free (req);
7322 return err;
7324 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7325 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7326 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7327 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7328 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7329 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7330 } else {
7331 if (req->nmodifiers) {
7332 g_free (req);
7333 return ERR_NOT_IMPLEMENTED;
7337 mono_loader_lock ();
7338 g_ptr_array_add (event_requests, req);
7340 if (agent_config.defer) {
7341 /* Transmit cached data to the client on receipt of the event request */
7342 switch (req->event_kind) {
7343 case EVENT_KIND_APPDOMAIN_CREATE:
7344 /* Emit load events for currently loaded domains */
7345 mono_de_foreach_domain (emit_appdomain_load, NULL);
7346 break;
7347 case EVENT_KIND_ASSEMBLY_LOAD:
7348 /* Emit load events for currently loaded assemblies */
7349 mono_domain_foreach (send_assemblies_for_domain, NULL);
7350 break;
7351 case EVENT_KIND_THREAD_START:
7352 /* Emit start events for currently started threads */
7353 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7354 break;
7355 case EVENT_KIND_TYPE_LOAD:
7356 /* Emit type load events for currently loaded types */
7357 mono_domain_foreach (send_types_for_domain, NULL);
7358 break;
7359 default:
7360 break;
7363 mono_loader_unlock ();
7365 buffer_add_int (buf, req->id);
7366 break;
7368 case CMD_EVENT_REQUEST_CLEAR: {
7369 int etype = decode_byte (p, &p, end);
7370 int req_id = decode_int (p, &p, end);
7372 // FIXME: Make a faster mapping from req_id to request
7373 mono_loader_lock ();
7374 clear_event_request (req_id, etype);
7375 mono_loader_unlock ();
7376 break;
7378 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7379 int i;
7381 mono_loader_lock ();
7382 i = 0;
7383 while (i < event_requests->len) {
7384 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7386 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7387 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7389 g_ptr_array_remove_index_fast (event_requests, i);
7390 g_free (req);
7391 } else {
7392 i ++;
7395 mono_loader_unlock ();
7396 break;
7398 default:
7399 return ERR_NOT_IMPLEMENTED;
7402 return ERR_NONE;
7405 static ErrorCode
7406 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7408 ErrorCode err;
7409 MonoDomain *domain;
7411 switch (command) {
7412 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7413 buffer_add_domainid (buf, mono_get_root_domain ());
7414 break;
7416 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7417 domain = decode_domainid (p, &p, end, NULL, &err);
7418 if (err != ERR_NONE)
7419 return err;
7420 buffer_add_string (buf, domain->friendly_name);
7421 break;
7423 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7424 GSList *tmp;
7425 MonoAssembly *ass;
7426 int count;
7428 domain = decode_domainid (p, &p, end, NULL, &err);
7429 if (err != ERR_NONE)
7430 return err;
7431 mono_domain_assemblies_lock (domain);
7432 count = 0;
7433 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7434 count ++;
7436 buffer_add_int (buf, count);
7437 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7438 ass = (MonoAssembly *)tmp->data;
7439 buffer_add_assemblyid (buf, domain, ass);
7441 mono_domain_assemblies_unlock (domain);
7442 break;
7444 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7445 domain = decode_domainid (p, &p, end, NULL, &err);
7446 if (err != ERR_NONE)
7447 return err;
7449 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7450 break;
7452 case CMD_APPDOMAIN_GET_CORLIB: {
7453 domain = decode_domainid (p, &p, end, NULL, &err);
7454 if (err != ERR_NONE)
7455 return err;
7457 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7458 break;
7460 case CMD_APPDOMAIN_CREATE_STRING: {
7461 char *s;
7462 MonoString *o;
7463 ERROR_DECL (error);
7465 domain = decode_domainid (p, &p, end, NULL, &err);
7466 if (err != ERR_NONE)
7467 return err;
7468 s = decode_string (p, &p, end);
7470 o = mono_string_new_checked (domain, s, error);
7471 if (!is_ok (error)) {
7472 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7473 mono_error_cleanup (error);
7474 return ERR_INVALID_OBJECT;
7476 buffer_add_objid (buf, (MonoObject*)o);
7477 break;
7479 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7480 ERROR_DECL (error);
7481 MonoArray *arr;
7482 gpointer elem;
7483 domain = decode_domainid (p, &p, end, NULL, &err);
7484 uintptr_t size = 0;
7485 int len = decode_int (p, &p, end);
7486 size = len;
7487 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7488 elem = mono_array_addr_internal (arr, guint8, 0);
7489 memcpy (elem, p, len);
7490 p += len;
7491 buffer_add_objid (buf, (MonoObject*) arr);
7492 break;
7494 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7495 ERROR_DECL (error);
7496 MonoClass *klass;
7497 MonoDomain *domain2;
7498 MonoObject *o;
7500 domain = decode_domainid (p, &p, end, NULL, &err);
7501 if (err != ERR_NONE)
7502 return err;
7503 klass = decode_typeid (p, &p, end, &domain2, &err);
7504 if (err != ERR_NONE)
7505 return err;
7507 // FIXME:
7508 g_assert (domain == domain2);
7510 o = mono_object_new_checked (domain, klass, error);
7511 mono_error_assert_ok (error);
7513 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7514 if (err != ERR_NONE)
7515 return err;
7517 buffer_add_objid (buf, o);
7518 break;
7520 default:
7521 return ERR_NOT_IMPLEMENTED;
7524 return ERR_NONE;
7527 static ErrorCode
7528 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7530 HANDLE_FUNCTION_ENTER();
7531 ErrorCode err = ERR_NONE;
7532 error_init (error);
7533 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7534 if (MONO_HANDLE_IS_NULL (o)) {
7535 err = ERR_INVALID_OBJECT;
7536 goto leave;
7538 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7539 leave:
7540 HANDLE_FUNCTION_RETURN_VAL (err);
7544 static ErrorCode
7545 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7547 ErrorCode err;
7548 MonoAssembly *ass;
7549 MonoDomain *domain;
7551 ass = decode_assemblyid (p, &p, end, &domain, &err);
7552 if (err != ERR_NONE)
7553 return err;
7555 switch (command) {
7556 case CMD_ASSEMBLY_GET_LOCATION: {
7557 buffer_add_string (buf, mono_image_get_filename (ass->image));
7558 break;
7560 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7561 guint32 token;
7562 MonoMethod *m;
7564 if (ass->image->dynamic) {
7565 buffer_add_id (buf, 0);
7566 } else {
7567 token = mono_image_get_entry_point (ass->image);
7568 if (token == 0) {
7569 buffer_add_id (buf, 0);
7570 } else {
7571 ERROR_DECL (error);
7572 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7573 if (!m)
7574 mono_error_cleanup (error); /* FIXME don't swallow the error */
7575 buffer_add_methodid (buf, domain, m);
7578 break;
7580 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7581 buffer_add_moduleid (buf, domain, ass->image);
7582 break;
7584 case CMD_ASSEMBLY_GET_OBJECT: {
7585 ERROR_DECL (error);
7586 err = get_assembly_object_command (domain, ass, buf, error);
7587 mono_error_cleanup (error);
7588 return err;
7590 case CMD_ASSEMBLY_GET_DOMAIN: {
7591 buffer_add_domainid (buf, domain);
7592 break;
7594 case CMD_ASSEMBLY_GET_TYPE: {
7595 ERROR_DECL (error);
7596 char *s = decode_string (p, &p, end);
7597 gboolean ignorecase = decode_byte (p, &p, end);
7598 MonoTypeNameParse info;
7599 MonoType *t;
7600 gboolean type_resolve, res;
7601 MonoDomain *d = mono_domain_get ();
7603 /* This is needed to be able to find referenced assemblies */
7604 res = mono_domain_set_fast (domain, FALSE);
7605 g_assert (res);
7607 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7608 mono_error_cleanup (error);
7609 t = NULL;
7610 } else {
7611 if (info.assembly.name)
7612 NOT_IMPLEMENTED;
7613 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7614 if (!is_ok (error)) {
7615 mono_error_cleanup (error); /* FIXME don't swallow the error */
7616 mono_reflection_free_type_info (&info);
7617 g_free (s);
7618 return ERR_INVALID_ARGUMENT;
7621 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7622 mono_reflection_free_type_info (&info);
7623 g_free (s);
7625 mono_domain_set_fast (d, TRUE);
7627 break;
7629 case CMD_ASSEMBLY_GET_NAME: {
7630 gchar *name;
7631 MonoAssembly *mass = ass;
7633 name = g_strdup_printf (
7634 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7635 mass->aname.name,
7636 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7637 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7638 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7639 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7641 buffer_add_string (buf, name);
7642 g_free (name);
7643 break;
7645 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7646 MonoImage* image = ass->image;
7647 if (ass->dynamic) {
7648 return ERR_NOT_IMPLEMENTED;
7650 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7651 break;
7653 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7654 buffer_add_byte (buf, ass->dynamic);
7655 break;
7657 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7658 MonoImage* image = ass->image;
7659 MonoDebugHandle* handle = mono_debug_get_handle (image);
7660 if (!handle) {
7661 return ERR_INVALID_ARGUMENT;
7663 MonoPPDBFile* ppdb = handle->ppdb;
7664 if (ppdb) {
7665 image = mono_ppdb_get_image (ppdb);
7666 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7667 } else {
7668 buffer_add_byte_array (buf, NULL, 0);
7670 break;
7672 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7673 if (ass->dynamic) {
7674 return ERR_NOT_IMPLEMENTED;
7676 guint32 token = decode_int (p, &p, end);
7677 ERROR_DECL (error);
7678 error_init (error);
7679 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7680 if (!is_ok (error)) {
7681 mono_error_cleanup (error);
7682 return ERR_INVALID_ARGUMENT;
7684 buffer_add_typeid (buf, domain, mono_class);
7685 mono_error_cleanup (error);
7686 break;
7688 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7689 if (ass->dynamic) {
7690 return ERR_NOT_IMPLEMENTED;
7692 guint32 token = decode_int (p, &p, end);
7693 ERROR_DECL (error);
7694 error_init (error);
7695 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7696 if (!is_ok (error)) {
7697 mono_error_cleanup (error);
7698 return ERR_INVALID_ARGUMENT;
7700 buffer_add_methodid (buf, domain, mono_method);
7701 mono_error_cleanup (error);
7702 break;
7704 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7705 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7706 break;
7708 default:
7709 return ERR_NOT_IMPLEMENTED;
7712 return ERR_NONE;
7715 static ErrorCode
7716 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7718 ErrorCode err;
7719 MonoDomain *domain;
7721 switch (command) {
7722 case CMD_MODULE_GET_INFO: {
7723 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7724 char *basename, *sourcelink = NULL;
7726 if (CHECK_PROTOCOL_VERSION (2, 48))
7727 sourcelink = mono_debug_image_get_sourcelink (image);
7729 basename = g_path_get_basename (image->name);
7730 buffer_add_string (buf, basename); // name
7731 buffer_add_string (buf, image->module_name); // scopename
7732 buffer_add_string (buf, image->name); // fqname
7733 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7734 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7735 if (CHECK_PROTOCOL_VERSION (2, 48))
7736 buffer_add_string (buf, sourcelink);
7737 g_free (basename);
7738 g_free (sourcelink);
7739 break;
7741 default:
7742 return ERR_NOT_IMPLEMENTED;
7745 return ERR_NONE;
7748 static ErrorCode
7749 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7751 ErrorCode err;
7752 MonoDomain *domain;
7754 switch (command) {
7755 case CMD_FIELD_GET_INFO: {
7756 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7758 buffer_add_string (buf, f->name);
7759 buffer_add_typeid (buf, domain, f->parent);
7760 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7761 buffer_add_int (buf, f->type->attrs);
7762 break;
7764 default:
7765 return ERR_NOT_IMPLEMENTED;
7768 return ERR_NONE;
7771 static void
7772 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7774 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7775 /* Special case these so the client doesn't have to handle Type objects */
7777 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7778 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
7779 } else if (MONO_TYPE_IS_REFERENCE (t))
7780 buffer_add_value (buf, t, &val, domain);
7781 else
7782 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
7785 static ErrorCode
7786 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7788 int i, j;
7789 int nattrs = 0;
7791 if (!cinfo) {
7792 buffer_add_int (buf, 0);
7793 return ERR_NONE;
7796 SETUP_ICALL_FUNCTION;
7798 for (i = 0; i < cinfo->num_attrs; ++i) {
7799 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7800 nattrs ++;
7802 buffer_add_int (buf, nattrs);
7804 for (i = 0; i < cinfo->num_attrs; ++i) {
7805 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7806 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7807 MonoArray *typed_args, *named_args;
7808 MonoArrayHandleOut typed_args_h, named_args_h;
7809 MonoObjectHandle val_h;
7810 MonoType *t;
7811 CattrNamedArg *arginfo = NULL;
7812 ERROR_DECL (error);
7814 SETUP_ICALL_FRAME;
7815 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
7816 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
7817 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
7819 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
7820 if (!is_ok (error)) {
7821 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
7822 mono_error_cleanup (error);
7823 CLEAR_ICALL_FRAME;
7824 return ERR_LOADER_ERROR;
7826 typed_args = MONO_HANDLE_RAW (typed_args_h);
7827 named_args = MONO_HANDLE_RAW (named_args_h);
7829 buffer_add_methodid (buf, domain, attr->ctor);
7831 /* Ctor args */
7832 if (typed_args) {
7833 buffer_add_int (buf, mono_array_length_internal (typed_args));
7834 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
7835 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
7836 MONO_HANDLE_ASSIGN_RAW (val_h, val);
7838 t = mono_method_signature_internal (attr->ctor)->params [j];
7840 buffer_add_cattr_arg (buf, t, domain, val);
7842 } else {
7843 buffer_add_int (buf, 0);
7846 /* Named args */
7847 if (named_args) {
7848 buffer_add_int (buf, mono_array_length_internal (named_args));
7850 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
7851 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
7852 MONO_HANDLE_ASSIGN_RAW (val_h, val);
7854 if (arginfo [j].prop) {
7855 buffer_add_byte (buf, 0x54);
7856 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7857 } else if (arginfo [j].field) {
7858 buffer_add_byte (buf, 0x53);
7859 buffer_add_fieldid (buf, domain, arginfo [j].field);
7860 } else {
7861 g_assert_not_reached ();
7864 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7866 } else {
7867 buffer_add_int (buf, 0);
7869 g_free (arginfo);
7871 CLEAR_ICALL_FRAME;
7875 return ERR_NONE;
7878 /* FIXME: Code duplication with icall.c */
7879 static void
7880 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7882 int i;
7883 MonoClass *ic;
7885 mono_class_setup_interfaces (klass, error);
7886 if (!is_ok (error))
7887 return;
7889 int klass_interface_count = m_class_get_interface_count (klass);
7890 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
7891 for (i = 0; i < klass_interface_count; i++) {
7892 ic = klass_interfaces [i];
7893 g_hash_table_insert (ifaces, ic, ic);
7895 collect_interfaces (ic, ifaces, error);
7896 if (!is_ok (error))
7897 return;
7901 static ErrorCode
7902 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7904 ERROR_DECL (error);
7905 MonoClass *nested;
7906 MonoType *type;
7907 gpointer iter;
7908 guint8 b;
7909 int nnested;
7910 ErrorCode err;
7911 char *name;
7913 switch (command) {
7914 case CMD_TYPE_GET_INFO: {
7915 buffer_add_string (buf, m_class_get_name_space (klass));
7916 buffer_add_string (buf, m_class_get_name (klass));
7917 // FIXME: byref
7918 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7919 buffer_add_string (buf, name);
7920 g_free (name);
7921 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
7922 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
7923 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
7924 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
7925 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
7926 else
7927 buffer_add_id (buf, 0);
7928 buffer_add_int (buf, m_class_get_type_token (klass));
7929 buffer_add_byte (buf, m_class_get_rank (klass));
7930 buffer_add_int (buf, mono_class_get_flags (klass));
7931 b = 0;
7932 type = m_class_get_byval_arg (klass);
7933 // FIXME: Can't decide whenever a class represents a byref type
7934 if (FALSE)
7935 b |= (1 << 0);
7936 if (type->type == MONO_TYPE_PTR)
7937 b |= (1 << 1);
7938 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7939 b |= (1 << 2);
7940 if (type->type == MONO_TYPE_VALUETYPE)
7941 b |= (1 << 3);
7942 if (m_class_is_enumtype (klass))
7943 b |= (1 << 4);
7944 if (mono_class_is_gtd (klass))
7945 b |= (1 << 5);
7946 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
7947 b |= (1 << 6);
7948 buffer_add_byte (buf, b);
7949 nnested = 0;
7950 iter = NULL;
7951 while ((nested = mono_class_get_nested_types (klass, &iter)))
7952 nnested ++;
7953 buffer_add_int (buf, nnested);
7954 iter = NULL;
7955 while ((nested = mono_class_get_nested_types (klass, &iter)))
7956 buffer_add_typeid (buf, domain, nested);
7957 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7958 if (mono_class_is_gtd (klass))
7959 buffer_add_typeid (buf, domain, klass);
7960 else if (mono_class_is_ginst (klass))
7961 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
7962 else
7963 buffer_add_id (buf, 0);
7965 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7966 int count, i;
7968 if (mono_class_is_ginst (klass)) {
7969 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
7971 count = inst->type_argc;
7972 buffer_add_int (buf, count);
7973 for (i = 0; i < count; i++)
7974 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
7975 } else if (mono_class_is_gtd (klass)) {
7976 MonoGenericContainer *container = mono_class_get_generic_container (klass);
7977 MonoClass *pklass;
7979 count = container->type_argc;
7980 buffer_add_int (buf, count);
7981 for (i = 0; i < count; i++) {
7982 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
7983 buffer_add_typeid (buf, domain, pklass);
7985 } else {
7986 buffer_add_int (buf, 0);
7989 break;
7991 case CMD_TYPE_GET_METHODS: {
7992 int nmethods;
7993 int i = 0;
7994 gpointer iter = NULL;
7995 MonoMethod *m;
7997 mono_class_setup_methods (klass);
7999 nmethods = mono_class_num_methods (klass);
8001 buffer_add_int (buf, nmethods);
8003 while ((m = mono_class_get_methods (klass, &iter))) {
8004 buffer_add_methodid (buf, domain, m);
8005 i ++;
8007 g_assert (i == nmethods);
8008 break;
8010 case CMD_TYPE_GET_FIELDS: {
8011 int nfields;
8012 int i = 0;
8013 gpointer iter = NULL;
8014 MonoClassField *f;
8016 nfields = mono_class_num_fields (klass);
8018 buffer_add_int (buf, nfields);
8020 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8021 buffer_add_fieldid (buf, domain, f);
8022 buffer_add_string (buf, f->name);
8023 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8024 buffer_add_int (buf, f->type->attrs);
8025 i ++;
8027 g_assert (i == nfields);
8028 break;
8030 case CMD_TYPE_GET_PROPERTIES: {
8031 int nprops;
8032 int i = 0;
8033 gpointer iter = NULL;
8034 MonoProperty *p;
8036 nprops = mono_class_num_properties (klass);
8038 buffer_add_int (buf, nprops);
8040 while ((p = mono_class_get_properties (klass, &iter))) {
8041 buffer_add_propertyid (buf, domain, p);
8042 buffer_add_string (buf, p->name);
8043 buffer_add_methodid (buf, domain, p->get);
8044 buffer_add_methodid (buf, domain, p->set);
8045 buffer_add_int (buf, p->attrs);
8046 i ++;
8048 g_assert (i == nprops);
8049 break;
8051 case CMD_TYPE_GET_CATTRS: {
8052 MonoClass *attr_klass;
8053 MonoCustomAttrInfo *cinfo;
8055 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8056 /* attr_klass can be NULL */
8057 if (err != ERR_NONE)
8058 return err;
8060 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8061 if (!is_ok (error)) {
8062 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8063 return ERR_LOADER_ERROR;
8066 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8067 if (err != ERR_NONE)
8068 return err;
8069 break;
8071 case CMD_TYPE_GET_FIELD_CATTRS: {
8072 MonoClass *attr_klass;
8073 MonoCustomAttrInfo *cinfo;
8074 MonoClassField *field;
8076 field = decode_fieldid (p, &p, end, NULL, &err);
8077 if (err != ERR_NONE)
8078 return err;
8079 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8080 if (err != ERR_NONE)
8081 return err;
8083 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8084 if (!is_ok (error)) {
8085 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8086 return ERR_LOADER_ERROR;
8089 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8090 if (err != ERR_NONE)
8091 return err;
8092 break;
8094 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8095 MonoClass *attr_klass;
8096 MonoCustomAttrInfo *cinfo;
8097 MonoProperty *prop;
8099 prop = decode_propertyid (p, &p, end, NULL, &err);
8100 if (err != ERR_NONE)
8101 return err;
8102 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8103 if (err != ERR_NONE)
8104 return err;
8106 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8107 if (!is_ok (error)) {
8108 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8109 return ERR_LOADER_ERROR;
8112 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8113 if (err != ERR_NONE)
8114 return err;
8115 break;
8117 case CMD_TYPE_GET_VALUES:
8118 case CMD_TYPE_GET_VALUES_2: {
8119 guint8 *val;
8120 MonoClassField *f;
8121 MonoVTable *vtable;
8122 MonoClass *k;
8123 int len, i;
8124 gboolean found;
8125 MonoThread *thread_obj;
8126 MonoInternalThread *thread = NULL;
8127 guint32 special_static_type;
8129 if (command == CMD_TYPE_GET_VALUES_2) {
8130 int objid = decode_objid (p, &p, end);
8131 ErrorCode err;
8133 err = get_object (objid, (MonoObject**)&thread_obj);
8134 if (err != ERR_NONE)
8135 return err;
8137 thread = THREAD_TO_INTERNAL (thread_obj);
8140 len = decode_int (p, &p, end);
8141 for (i = 0; i < len; ++i) {
8142 f = decode_fieldid (p, &p, end, NULL, &err);
8143 if (err != ERR_NONE)
8144 return err;
8146 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8147 return ERR_INVALID_FIELDID;
8148 special_static_type = mono_class_field_get_special_static_type (f);
8149 if (special_static_type != SPECIAL_STATIC_NONE) {
8150 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8151 return ERR_INVALID_FIELDID;
8154 /* Check that the field belongs to the object */
8155 found = FALSE;
8156 for (k = klass; k; k = m_class_get_parent (k)) {
8157 if (k == f->parent) {
8158 found = TRUE;
8159 break;
8162 if (!found)
8163 return ERR_INVALID_FIELDID;
8165 vtable = mono_class_vtable_checked (domain, f->parent, error);
8166 if (!is_ok (error))
8167 return ERR_INVALID_FIELDID;
8168 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8169 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, error);
8170 if (!is_ok (error))
8171 return ERR_INVALID_FIELDID;
8172 buffer_add_value (buf, f->type, val, domain);
8173 g_free (val);
8175 break;
8177 case CMD_TYPE_SET_VALUES: {
8178 guint8 *val;
8179 MonoClassField *f;
8180 MonoVTable *vtable;
8181 MonoClass *k;
8182 int len, i;
8183 gboolean found;
8185 len = decode_int (p, &p, end);
8186 for (i = 0; i < len; ++i) {
8187 f = decode_fieldid (p, &p, end, NULL, &err);
8188 if (err != ERR_NONE)
8189 return err;
8191 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8192 return ERR_INVALID_FIELDID;
8193 if (mono_class_field_is_special_static (f))
8194 return ERR_INVALID_FIELDID;
8196 /* Check that the field belongs to the object */
8197 found = FALSE;
8198 for (k = klass; k; k = m_class_get_parent (k)) {
8199 if (k == f->parent) {
8200 found = TRUE;
8201 break;
8204 if (!found)
8205 return ERR_INVALID_FIELDID;
8207 // FIXME: Check for literal/const
8209 vtable = mono_class_vtable_checked (domain, f->parent, error);
8210 if (!is_ok (error))
8211 return ERR_INVALID_FIELDID;
8212 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8213 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8214 if (err != ERR_NONE) {
8215 g_free (val);
8216 return err;
8218 if (MONO_TYPE_IS_REFERENCE (f->type))
8219 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8220 else
8221 mono_field_static_set_value_internal (vtable, f, val);
8222 g_free (val);
8224 break;
8226 case CMD_TYPE_GET_OBJECT: {
8227 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8228 if (!is_ok (error)) {
8229 mono_error_cleanup (error);
8230 return ERR_INVALID_OBJECT;
8232 buffer_add_objid (buf, o);
8233 break;
8235 case CMD_TYPE_GET_SOURCE_FILES:
8236 case CMD_TYPE_GET_SOURCE_FILES_2: {
8237 char *source_file, *base;
8238 GPtrArray *files;
8239 int i;
8241 files = get_source_files_for_type (klass);
8243 buffer_add_int (buf, files->len);
8244 for (i = 0; i < files->len; ++i) {
8245 source_file = (char *)g_ptr_array_index (files, i);
8246 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8247 buffer_add_string (buf, source_file);
8248 } else {
8249 base = dbg_path_get_basename (source_file);
8250 buffer_add_string (buf, base);
8251 g_free (base);
8253 g_free (source_file);
8255 g_ptr_array_free (files, TRUE);
8256 break;
8258 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8259 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8261 if (err != ERR_NONE)
8262 return err;
8263 if (mono_class_is_assignable_from_internal (klass, oklass))
8264 buffer_add_byte (buf, 1);
8265 else
8266 buffer_add_byte (buf, 0);
8267 break;
8269 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8270 char *name = decode_string (p, &p, end);
8271 int i, flags = decode_int (p, &p, end);
8272 int mlisttype;
8273 if (CHECK_PROTOCOL_VERSION (2, 48))
8274 mlisttype = decode_int (p, &p, end);
8275 else
8276 mlisttype = 0; // MLISTTYPE_All
8277 ERROR_DECL (error);
8278 GPtrArray *array;
8280 error_init (error);
8281 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8282 if (!is_ok (error)) {
8283 mono_error_cleanup (error);
8284 return ERR_LOADER_ERROR;
8286 buffer_add_int (buf, array->len);
8287 for (i = 0; i < array->len; ++i) {
8288 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8289 buffer_add_methodid (buf, domain, method);
8292 g_ptr_array_free (array, TRUE);
8293 g_free (name);
8294 break;
8296 case CMD_TYPE_GET_INTERFACES: {
8297 MonoClass *parent;
8298 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8299 MonoClass *tclass, *iface;
8300 GHashTableIter iter;
8302 tclass = klass;
8304 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8305 mono_class_setup_interfaces (parent, error);
8306 if (!is_ok (error))
8307 return ERR_LOADER_ERROR;
8308 collect_interfaces (parent, iface_hash, error);
8309 if (!is_ok (error))
8310 return ERR_LOADER_ERROR;
8313 buffer_add_int (buf, g_hash_table_size (iface_hash));
8315 g_hash_table_iter_init (&iter, iface_hash);
8316 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8317 buffer_add_typeid (buf, domain, iface);
8318 g_hash_table_destroy (iface_hash);
8319 break;
8321 case CMD_TYPE_GET_INTERFACE_MAP: {
8322 int tindex, ioffset;
8323 gboolean variance_used;
8324 MonoClass *iclass;
8325 int len, nmethods, i;
8326 gpointer iter;
8327 MonoMethod *method;
8329 len = decode_int (p, &p, end);
8330 mono_class_setup_vtable (klass);
8332 for (tindex = 0; tindex < len; ++tindex) {
8333 iclass = decode_typeid (p, &p, end, NULL, &err);
8334 if (err != ERR_NONE)
8335 return err;
8337 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8338 if (ioffset == -1)
8339 return ERR_INVALID_ARGUMENT;
8341 nmethods = mono_class_num_methods (iclass);
8342 buffer_add_int (buf, nmethods);
8344 iter = NULL;
8345 while ((method = mono_class_get_methods (iclass, &iter))) {
8346 buffer_add_methodid (buf, domain, method);
8348 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8349 for (i = 0; i < nmethods; ++i)
8350 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8352 break;
8354 case CMD_TYPE_IS_INITIALIZED: {
8355 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8356 if (!is_ok (error))
8357 return ERR_LOADER_ERROR;
8359 if (vtable)
8360 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8361 else
8362 buffer_add_int (buf, 0);
8363 break;
8365 case CMD_TYPE_CREATE_INSTANCE: {
8366 ERROR_DECL (error);
8367 MonoObject *obj;
8369 obj = mono_object_new_checked (domain, klass, error);
8370 mono_error_assert_ok (error);
8371 buffer_add_objid (buf, obj);
8372 break;
8374 case CMD_TYPE_GET_VALUE_SIZE: {
8375 int32_t value_size;
8377 value_size = mono_class_value_size (klass, NULL);
8378 buffer_add_int (buf, value_size);
8379 break;
8381 default:
8382 return ERR_NOT_IMPLEMENTED;
8385 return ERR_NONE;
8388 static ErrorCode
8389 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8391 MonoClass *klass;
8392 MonoDomain *old_domain;
8393 MonoDomain *domain;
8394 ErrorCode err;
8396 klass = decode_typeid (p, &p, end, &domain, &err);
8397 if (err != ERR_NONE)
8398 return err;
8400 old_domain = mono_domain_get ();
8402 mono_domain_set_fast (domain, TRUE);
8404 err = type_commands_internal (command, klass, domain, p, end, buf);
8406 mono_domain_set_fast (old_domain, TRUE);
8408 return err;
8411 static ErrorCode
8412 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8414 MonoMethodHeader *header;
8415 ErrorCode err;
8417 switch (command) {
8418 case CMD_METHOD_GET_NAME: {
8419 buffer_add_string (buf, method->name);
8420 break;
8422 case CMD_METHOD_GET_DECLARING_TYPE: {
8423 buffer_add_typeid (buf, domain, method->klass);
8424 break;
8426 case CMD_METHOD_GET_DEBUG_INFO: {
8427 ERROR_DECL (error);
8428 MonoDebugMethodInfo *minfo;
8429 char *source_file;
8430 int i, j, n_il_offsets;
8431 int *source_files;
8432 GPtrArray *source_file_list;
8433 MonoSymSeqPoint *sym_seq_points;
8435 header = mono_method_get_header_checked (method, error);
8436 if (!header) {
8437 mono_error_cleanup (error); /* FIXME don't swallow the error */
8438 buffer_add_int (buf, 0);
8439 buffer_add_string (buf, "");
8440 buffer_add_int (buf, 0);
8441 break;
8444 minfo = mono_debug_lookup_method (method);
8445 if (!minfo) {
8446 buffer_add_int (buf, header->code_size);
8447 buffer_add_string (buf, "");
8448 buffer_add_int (buf, 0);
8449 mono_metadata_free_mh (header);
8450 break;
8453 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8454 buffer_add_int (buf, header->code_size);
8455 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8456 buffer_add_int (buf, source_file_list->len);
8457 for (i = 0; i < source_file_list->len; ++i) {
8458 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8459 buffer_add_string (buf, sinfo->source_file);
8460 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8461 for (j = 0; j < 16; ++j)
8462 buffer_add_byte (buf, sinfo->hash [j]);
8465 } else {
8466 buffer_add_string (buf, source_file);
8468 buffer_add_int (buf, n_il_offsets);
8469 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8470 for (i = 0; i < n_il_offsets; ++i) {
8471 MonoSymSeqPoint *sp = &sym_seq_points [i];
8472 const char *srcfile = "";
8474 if (source_files [i] != -1) {
8475 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8476 srcfile = sinfo->source_file;
8478 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);
8479 buffer_add_int (buf, sp->il_offset);
8480 buffer_add_int (buf, sp->line);
8481 if (CHECK_PROTOCOL_VERSION (2, 13))
8482 buffer_add_int (buf, source_files [i]);
8483 if (CHECK_PROTOCOL_VERSION (2, 19))
8484 buffer_add_int (buf, sp->column);
8485 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8486 buffer_add_int (buf, sp->end_line);
8487 buffer_add_int (buf, sp->end_column);
8490 g_free (source_file);
8491 g_free (source_files);
8492 g_free (sym_seq_points);
8493 g_ptr_array_free (source_file_list, TRUE);
8494 mono_metadata_free_mh (header);
8495 break;
8497 case CMD_METHOD_GET_PARAM_INFO: {
8498 MonoMethodSignature *sig = mono_method_signature_internal (method);
8499 guint32 i;
8500 char **names;
8502 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8504 /* FIXME: Use a smaller encoding */
8505 buffer_add_int (buf, sig->call_convention);
8506 buffer_add_int (buf, sig->param_count);
8507 buffer_add_int (buf, sig->generic_param_count);
8508 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8509 for (i = 0; i < sig->param_count; ++i) {
8510 /* FIXME: vararg */
8511 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8514 /* Emit parameter names */
8515 names = g_new (char *, sig->param_count);
8516 mono_method_get_param_names (method, (const char **) names);
8517 for (i = 0; i < sig->param_count; ++i)
8518 buffer_add_string (buf, names [i]);
8519 g_free (names);
8521 break;
8523 case CMD_METHOD_GET_LOCALS_INFO: {
8524 ERROR_DECL (error);
8525 int i, num_locals;
8526 MonoDebugLocalsInfo *locals;
8527 int *locals_map = NULL;
8529 header = mono_method_get_header_checked (method, error);
8530 if (!header) {
8531 mono_error_cleanup (error); /* FIXME don't swallow the error */
8532 return ERR_INVALID_ARGUMENT;
8535 locals = mono_debug_lookup_locals (method);
8536 if (!locals) {
8537 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8538 /* Scopes */
8539 buffer_add_int (buf, 1);
8540 buffer_add_int (buf, 0);
8541 buffer_add_int (buf, header->code_size);
8543 buffer_add_int (buf, header->num_locals);
8544 /* Types */
8545 for (i = 0; i < header->num_locals; ++i) {
8546 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8548 /* Names */
8549 for (i = 0; i < header->num_locals; ++i) {
8550 char lname [128];
8551 sprintf (lname, "V_%d", i);
8552 buffer_add_string (buf, lname);
8554 /* Scopes */
8555 for (i = 0; i < header->num_locals; ++i) {
8556 buffer_add_int (buf, 0);
8557 buffer_add_int (buf, header->code_size);
8559 } else {
8560 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8561 /* Scopes */
8562 buffer_add_int (buf, locals->num_blocks);
8563 int last_start = 0;
8564 for (i = 0; i < locals->num_blocks; ++i) {
8565 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8566 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8567 last_start = locals->code_blocks [i].start_offset;
8571 num_locals = locals->num_locals;
8572 buffer_add_int (buf, num_locals);
8574 /* Types */
8575 for (i = 0; i < num_locals; ++i) {
8576 g_assert (locals->locals [i].index < header->num_locals);
8577 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8579 /* Names */
8580 for (i = 0; i < num_locals; ++i)
8581 buffer_add_string (buf, locals->locals [i].name);
8582 /* Scopes */
8583 for (i = 0; i < num_locals; ++i) {
8584 if (locals->locals [i].block) {
8585 buffer_add_int (buf, locals->locals [i].block->start_offset);
8586 buffer_add_int (buf, locals->locals [i].block->end_offset);
8587 } else {
8588 buffer_add_int (buf, 0);
8589 buffer_add_int (buf, header->code_size);
8593 mono_metadata_free_mh (header);
8595 if (locals)
8596 mono_debug_free_locals (locals);
8597 g_free (locals_map);
8599 break;
8601 case CMD_METHOD_GET_INFO:
8602 buffer_add_int (buf, method->flags);
8603 buffer_add_int (buf, method->iflags);
8604 buffer_add_int (buf, method->token);
8605 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8606 guint8 attrs = 0;
8607 if (method->is_generic)
8608 attrs |= (1 << 0);
8609 if (mono_method_signature_internal (method)->generic_param_count)
8610 attrs |= (1 << 1);
8611 buffer_add_byte (buf, attrs);
8612 if (method->is_generic || method->is_inflated) {
8613 MonoMethod *result;
8615 if (method->is_generic) {
8616 result = method;
8617 } else {
8618 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8620 result = imethod->declaring;
8621 if (imethod->context.class_inst) {
8622 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8623 /*Generic methods gets the context of the GTD.*/
8624 if (mono_class_get_context (klass)) {
8625 ERROR_DECL (error);
8626 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8627 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8632 buffer_add_methodid (buf, domain, result);
8633 } else {
8634 buffer_add_id (buf, 0);
8636 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8637 if (mono_method_signature_internal (method)->generic_param_count) {
8638 int count, i;
8640 if (method->is_inflated) {
8641 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8642 if (inst) {
8643 count = inst->type_argc;
8644 buffer_add_int (buf, count);
8646 for (i = 0; i < count; i++)
8647 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8648 } else {
8649 buffer_add_int (buf, 0);
8651 } else if (method->is_generic) {
8652 MonoGenericContainer *container = mono_method_get_generic_container (method);
8654 count = mono_method_signature_internal (method)->generic_param_count;
8655 buffer_add_int (buf, count);
8656 for (i = 0; i < count; i++) {
8657 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8658 MonoClass *pklass = mono_class_create_generic_parameter (param);
8659 buffer_add_typeid (buf, domain, pklass);
8661 } else {
8662 buffer_add_int (buf, 0);
8664 } else {
8665 buffer_add_int (buf, 0);
8669 break;
8670 case CMD_METHOD_GET_BODY: {
8671 ERROR_DECL (error);
8672 int i;
8674 header = mono_method_get_header_checked (method, error);
8675 if (!header) {
8676 mono_error_cleanup (error); /* FIXME don't swallow the error */
8677 buffer_add_int (buf, 0);
8679 if (CHECK_PROTOCOL_VERSION (2, 18))
8680 buffer_add_int (buf, 0);
8681 } else {
8682 buffer_add_int (buf, header->code_size);
8683 for (i = 0; i < header->code_size; ++i)
8684 buffer_add_byte (buf, header->code [i]);
8686 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8687 buffer_add_int (buf, header->num_clauses);
8688 for (i = 0; i < header->num_clauses; ++i) {
8689 MonoExceptionClause *clause = &header->clauses [i];
8691 buffer_add_int (buf, clause->flags);
8692 buffer_add_int (buf, clause->try_offset);
8693 buffer_add_int (buf, clause->try_len);
8694 buffer_add_int (buf, clause->handler_offset);
8695 buffer_add_int (buf, clause->handler_len);
8696 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8697 buffer_add_typeid (buf, domain, clause->data.catch_class);
8698 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8699 buffer_add_int (buf, clause->data.filter_offset);
8703 mono_metadata_free_mh (header);
8706 break;
8708 case CMD_METHOD_RESOLVE_TOKEN: {
8709 guint32 token = decode_int (p, &p, end);
8711 // FIXME: Generics
8712 switch (mono_metadata_token_code (token)) {
8713 case MONO_TOKEN_STRING: {
8714 ERROR_DECL (error);
8715 MonoString *s;
8716 char *s2;
8718 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8719 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8721 s2 = mono_string_to_utf8_checked_internal (s, error);
8722 mono_error_assert_ok (error);
8724 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8725 buffer_add_string (buf, s2);
8726 g_free (s2);
8727 break;
8729 default: {
8730 ERROR_DECL (error);
8731 gpointer val;
8732 MonoClass *handle_class;
8734 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8735 val = mono_method_get_wrapper_data (method, token);
8736 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8738 if (handle_class == NULL) {
8739 // Can't figure out the token type
8740 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8741 break;
8743 } else {
8744 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8745 if (!val)
8746 g_error ("Could not load token due to %s", mono_error_get_message (error));
8749 if (handle_class == mono_defaults.typehandle_class) {
8750 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8751 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8752 buffer_add_typeid (buf, domain, (MonoClass *) val);
8753 else
8754 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8755 } else if (handle_class == mono_defaults.fieldhandle_class) {
8756 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8757 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8758 } else if (handle_class == mono_defaults.methodhandle_class) {
8759 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8760 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8761 } else if (handle_class == mono_defaults.string_class) {
8762 char *s;
8764 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8765 mono_error_assert_ok (error);
8766 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8767 buffer_add_string (buf, s);
8768 g_free (s);
8769 } else {
8770 g_assert_not_reached ();
8772 break;
8775 break;
8777 case CMD_METHOD_GET_CATTRS: {
8778 ERROR_DECL (error);
8779 MonoClass *attr_klass;
8780 MonoCustomAttrInfo *cinfo;
8782 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8783 /* attr_klass can be NULL */
8784 if (err != ERR_NONE)
8785 return err;
8787 cinfo = mono_custom_attrs_from_method_checked (method, error);
8788 if (!is_ok (error)) {
8789 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8790 return ERR_LOADER_ERROR;
8793 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
8794 if (err != ERR_NONE)
8795 return err;
8796 break;
8798 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8799 ERROR_DECL (error);
8800 MonoType **type_argv;
8801 int i, type_argc;
8802 MonoDomain *d;
8803 MonoClass *klass;
8804 MonoGenericInst *ginst;
8805 MonoGenericContext tmp_context;
8806 MonoMethod *inflated;
8808 type_argc = decode_int (p, &p, end);
8809 type_argv = g_new0 (MonoType*, type_argc);
8810 for (i = 0; i < type_argc; ++i) {
8811 klass = decode_typeid (p, &p, end, &d, &err);
8812 if (err != ERR_NONE) {
8813 g_free (type_argv);
8814 return err;
8816 if (domain != d) {
8817 g_free (type_argv);
8818 return ERR_INVALID_ARGUMENT;
8820 type_argv [i] = m_class_get_byval_arg (klass);
8822 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8823 g_free (type_argv);
8824 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8825 tmp_context.method_inst = ginst;
8827 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
8828 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8829 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8830 return ERR_INVALID_ARGUMENT;
8831 buffer_add_methodid (buf, domain, inflated);
8832 break;
8834 default:
8835 return ERR_NOT_IMPLEMENTED;
8838 return ERR_NONE;
8841 static ErrorCode
8842 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8844 ErrorCode err;
8845 MonoDomain *old_domain;
8846 MonoDomain *domain;
8847 MonoMethod *method;
8849 method = decode_methodid (p, &p, end, &domain, &err);
8850 if (err != ERR_NONE)
8851 return err;
8853 old_domain = mono_domain_get ();
8855 mono_domain_set_fast (domain, TRUE);
8857 err = method_commands_internal (command, method, domain, p, end, buf);
8859 mono_domain_set_fast (old_domain, TRUE);
8861 return err;
8864 static ErrorCode
8865 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8867 int objid = decode_objid (p, &p, end);
8868 ErrorCode err;
8869 MonoThread *thread_obj;
8870 MonoInternalThread *thread;
8872 err = get_object (objid, (MonoObject**)&thread_obj);
8873 if (err != ERR_NONE)
8874 return err;
8876 thread = THREAD_TO_INTERNAL (thread_obj);
8878 switch (command) {
8879 case CMD_THREAD_GET_NAME: {
8880 char *s = mono_thread_get_name_utf8 (thread_obj);
8882 if (!s) {
8883 buffer_add_int (buf, 0);
8884 } else {
8885 const size_t len = strlen (s);
8886 buffer_add_int (buf, len);
8887 buffer_add_data (buf, (guint8*)s, len);
8888 g_free (s);
8890 break;
8892 case CMD_THREAD_GET_FRAME_INFO: {
8893 DebuggerTlsData *tls;
8894 int i, start_frame, length;
8896 // Wait for suspending if it already started
8897 // FIXME: Races with suspend_count
8898 while (!is_suspended ()) {
8899 if (suspend_count)
8900 wait_for_suspend ();
8903 if (suspend_count)
8904 wait_for_suspend ();
8905 if (!is_suspended ())
8906 return ERR_NOT_SUSPENDED;
8909 start_frame = decode_int (p, &p, end);
8910 length = decode_int (p, &p, end);
8912 if (start_frame != 0 || length != -1)
8913 return ERR_NOT_IMPLEMENTED;
8915 mono_loader_lock ();
8916 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8917 mono_loader_unlock ();
8918 g_assert (tls);
8920 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
8922 buffer_add_int (buf, tls->frame_count);
8923 for (i = 0; i < tls->frame_count; ++i) {
8924 buffer_add_int (buf, tls->frames [i]->id);
8925 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
8926 buffer_add_int (buf, tls->frames [i]->il_offset);
8928 * Instead of passing the frame type directly to the client, we associate
8929 * it with the previous frame using a set of flags. This avoids lots of
8930 * conditional code in the client, since a frame whose type isn't
8931 * FRAME_TYPE_MANAGED has no method, location, etc.
8933 buffer_add_byte (buf, tls->frames [i]->flags);
8936 break;
8938 case CMD_THREAD_GET_STATE:
8939 buffer_add_int (buf, thread->state);
8940 break;
8941 case CMD_THREAD_GET_INFO:
8942 buffer_add_byte (buf, thread->threadpool_thread);
8943 break;
8944 case CMD_THREAD_GET_ID:
8945 buffer_add_long (buf, (guint64)(gsize)thread);
8946 break;
8947 case CMD_THREAD_GET_TID:
8948 buffer_add_long (buf, (guint64)thread->tid);
8949 break;
8950 case CMD_THREAD_SET_IP: {
8951 DebuggerTlsData *tls;
8952 MonoMethod *method;
8953 MonoDomain *domain;
8954 MonoSeqPointInfo *seq_points;
8955 SeqPoint sp;
8956 gboolean found_sp;
8957 gint64 il_offset;
8959 method = decode_methodid (p, &p, end, &domain, &err);
8960 if (err != ERR_NONE)
8961 return err;
8962 il_offset = decode_long (p, &p, end);
8964 while (!is_suspended ()) {
8965 if (suspend_count)
8966 wait_for_suspend ();
8969 mono_loader_lock ();
8970 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8971 mono_loader_unlock ();
8972 g_assert (tls);
8974 compute_frame_info (thread, tls, FALSE);
8975 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8976 return ERR_INVALID_ARGUMENT;
8978 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8980 g_assert (seq_points);
8982 if (!found_sp)
8983 return ERR_INVALID_ARGUMENT;
8985 // FIXME: Check that the ip change is safe
8987 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);
8989 if (tls->frames [0]->de.ji->is_interp) {
8990 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
8991 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);
8992 } else {
8993 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
8995 break;
8997 case CMD_THREAD_ELAPSED_TIME: {
8998 DebuggerTlsData *tls;
8999 mono_loader_lock ();
9000 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9001 mono_loader_unlock ();
9002 g_assert (tls);
9003 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9004 break;
9006 default:
9007 return ERR_NOT_IMPLEMENTED;
9010 return ERR_NONE;
9013 static ErrorCode
9014 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9016 int objid;
9017 ErrorCode err;
9018 MonoThread *thread_obj;
9019 MonoInternalThread *thread;
9020 int pos, i, len, frame_idx;
9021 DebuggerTlsData *tls;
9022 StackFrame *frame;
9023 MonoDebugMethodJitInfo *jit;
9024 MonoMethodSignature *sig;
9025 gssize id;
9026 MonoMethodHeader *header;
9028 objid = decode_objid (p, &p, end);
9029 err = get_object (objid, (MonoObject**)&thread_obj);
9030 if (err != ERR_NONE)
9031 return err;
9033 thread = THREAD_TO_INTERNAL (thread_obj);
9035 id = decode_id (p, &p, end);
9037 mono_loader_lock ();
9038 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9039 mono_loader_unlock ();
9040 g_assert (tls);
9042 for (i = 0; i < tls->frame_count; ++i) {
9043 if (tls->frames [i]->id == id)
9044 break;
9046 if (i == tls->frame_count)
9047 return ERR_INVALID_FRAMEID;
9049 /* The thread is still running native code, can't get frame variables info */
9050 if (!tls->really_suspended && !tls->async_state.valid)
9051 return ERR_NOT_SUSPENDED;
9052 frame_idx = i;
9053 frame = tls->frames [frame_idx];
9055 /* This is supported for frames without has_ctx etc. set */
9056 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9057 if (CHECK_PROTOCOL_VERSION (2, 38))
9058 buffer_add_domainid (buf, frame->de.domain);
9059 return ERR_NONE;
9062 if (!frame->has_ctx)
9063 return ERR_ABSENT_INFORMATION;
9065 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9066 return ERR_ABSENT_INFORMATION;
9068 jit = frame->jit;
9070 sig = mono_method_signature_internal (frame->actual_method);
9072 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9074 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9076 return ERR_ABSENT_INFORMATION;
9078 switch (command) {
9079 case CMD_STACK_FRAME_GET_VALUES: {
9080 ERROR_DECL (error);
9081 len = decode_int (p, &p, end);
9082 header = mono_method_get_header_checked (frame->actual_method, error);
9083 mono_error_assert_ok (error); /* FIXME report error */
9085 for (i = 0; i < len; ++i) {
9086 pos = decode_int (p, &p, end);
9088 if (pos < 0) {
9089 pos = - pos - 1;
9091 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9093 if (frame->de.ji->is_interp) {
9094 guint8 *addr;
9096 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9098 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9099 } else {
9100 g_assert (pos >= 0 && pos < jit->num_params);
9102 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9104 } else {
9105 MonoDebugLocalsInfo *locals;
9107 locals = mono_debug_lookup_locals (frame->de.method);
9108 if (locals) {
9109 g_assert (pos < locals->num_locals);
9110 pos = locals->locals [pos].index;
9111 mono_debug_free_locals (locals);
9114 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9116 if (frame->de.ji->is_interp) {
9117 guint8 *addr;
9119 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9121 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9122 } else {
9123 g_assert (pos >= 0 && pos < jit->num_locals);
9125 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9129 mono_metadata_free_mh (header);
9130 break;
9132 case CMD_STACK_FRAME_GET_THIS: {
9133 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9134 return ERR_ABSENT_INFORMATION;
9135 if (m_class_is_valuetype (frame->api_method->klass)) {
9136 if (!sig->hasthis) {
9137 MonoObject *p = NULL;
9138 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
9139 } else {
9140 if (frame->de.ji->is_interp) {
9141 guint8 *addr;
9143 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9145 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9146 } else {
9147 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9150 } else {
9151 if (!sig->hasthis) {
9152 MonoObject *p = NULL;
9153 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9154 } else {
9155 if (frame->de.ji->is_interp) {
9156 guint8 *addr;
9158 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9160 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9161 } else {
9162 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9166 break;
9168 case CMD_STACK_FRAME_SET_VALUES: {
9169 ERROR_DECL (error);
9170 guint8 *val_buf;
9171 MonoType *t;
9172 MonoDebugVarInfo *var = NULL;
9173 gboolean is_arg = FALSE;
9175 len = decode_int (p, &p, end);
9176 header = mono_method_get_header_checked (frame->actual_method, error);
9177 mono_error_assert_ok (error); /* FIXME report error */
9179 for (i = 0; i < len; ++i) {
9180 pos = decode_int (p, &p, end);
9182 if (pos < 0) {
9183 pos = - pos - 1;
9185 g_assert (pos >= 0 && pos < jit->num_params);
9187 t = sig->params [pos];
9188 var = &jit->params [pos];
9189 is_arg = TRUE;
9190 } else {
9191 MonoDebugLocalsInfo *locals;
9193 locals = mono_debug_lookup_locals (frame->de.method);
9194 if (locals) {
9195 g_assert (pos < locals->num_locals);
9196 pos = locals->locals [pos].index;
9197 mono_debug_free_locals (locals);
9199 g_assert (pos >= 0 && pos < jit->num_locals);
9201 t = header->locals [pos];
9202 var = &jit->locals [pos];
9205 if (MONO_TYPE_IS_REFERENCE (t))
9206 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9207 else
9208 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9209 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9210 if (err != ERR_NONE)
9211 return err;
9213 if (frame->de.ji->is_interp) {
9214 guint8 *addr;
9216 if (is_arg)
9217 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9218 else
9219 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9220 set_interp_var (t, addr, val_buf);
9221 } else {
9222 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9225 mono_metadata_free_mh (header);
9226 break;
9228 case CMD_STACK_FRAME_GET_DOMAIN: {
9229 if (CHECK_PROTOCOL_VERSION (2, 38))
9230 buffer_add_domainid (buf, frame->de.domain);
9231 break;
9233 case CMD_STACK_FRAME_SET_THIS: {
9234 guint8 *val_buf;
9235 MonoType *t;
9236 MonoDebugVarInfo *var;
9238 t = m_class_get_byval_arg (frame->actual_method->klass);
9239 /* Checked by the sender */
9240 g_assert (MONO_TYPE_ISSTRUCT (t));
9242 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9243 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9244 if (err != ERR_NONE)
9245 return err;
9247 if (frame->de.ji->is_interp) {
9248 guint8 *addr;
9250 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9251 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9252 } else {
9253 var = jit->this_var;
9254 g_assert (var);
9256 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);
9258 break;
9260 default:
9261 return ERR_NOT_IMPLEMENTED;
9264 return ERR_NONE;
9267 static ErrorCode
9268 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9270 MonoArray *arr;
9271 int objid, index, len, i, esize;
9272 ErrorCode err;
9273 gpointer elem;
9275 objid = decode_objid (p, &p, end);
9276 err = get_object (objid, (MonoObject**)&arr);
9277 if (err != ERR_NONE)
9278 return err;
9280 switch (command) {
9281 case CMD_ARRAY_REF_GET_LENGTH:
9282 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9283 if (!arr->bounds) {
9284 buffer_add_int (buf, arr->max_length);
9285 buffer_add_int (buf, 0);
9286 } else {
9287 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9288 buffer_add_int (buf, arr->bounds [i].length);
9289 buffer_add_int (buf, arr->bounds [i].lower_bound);
9292 break;
9293 case CMD_ARRAY_REF_GET_VALUES:
9294 index = decode_int (p, &p, end);
9295 len = decode_int (p, &p, end);
9297 g_assert (index >= 0 && len >= 0);
9298 // Reordered to avoid integer overflow
9299 g_assert (!(index > arr->max_length - len));
9301 esize = mono_array_element_size (arr->obj.vtable->klass);
9302 for (i = index; i < index + len; ++i) {
9303 elem = (gpointer*)((char*)arr->vector + (i * esize));
9304 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9306 break;
9307 case CMD_ARRAY_REF_SET_VALUES:
9308 index = decode_int (p, &p, end);
9309 len = decode_int (p, &p, end);
9311 g_assert (index >= 0 && len >= 0);
9312 // Reordered to avoid integer overflow
9313 g_assert (!(index > arr->max_length - len));
9315 esize = mono_array_element_size (arr->obj.vtable->klass);
9316 for (i = index; i < index + len; ++i) {
9317 elem = (gpointer*)((char*)arr->vector + (i * esize));
9319 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);
9321 break;
9322 default:
9323 return ERR_NOT_IMPLEMENTED;
9326 return ERR_NONE;
9329 static ErrorCode
9330 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9332 int objid;
9333 ErrorCode err;
9334 MonoString *str;
9335 char *s;
9336 int i, index, length;
9337 gunichar2 *c;
9338 gboolean use_utf16 = FALSE;
9340 objid = decode_objid (p, &p, end);
9341 err = get_object (objid, (MonoObject**)&str);
9342 if (err != ERR_NONE)
9343 return err;
9345 switch (command) {
9346 case CMD_STRING_REF_GET_VALUE:
9347 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9348 for (i = 0; i < mono_string_length_internal (str); ++i)
9349 if (mono_string_chars_internal (str)[i] == 0)
9350 use_utf16 = TRUE;
9351 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9353 if (use_utf16) {
9354 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9355 buffer_add_data (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9356 } else {
9357 ERROR_DECL (error);
9358 s = mono_string_to_utf8_checked_internal (str, error);
9359 if (!is_ok (error)) {
9360 if (s)
9361 g_free (s);
9363 return ERR_INVALID_ARGUMENT;
9365 buffer_add_string (buf, s);
9366 g_free (s);
9368 break;
9369 case CMD_STRING_REF_GET_LENGTH:
9370 buffer_add_long (buf, mono_string_length_internal (str));
9371 break;
9372 case CMD_STRING_REF_GET_CHARS:
9373 index = decode_long (p, &p, end);
9374 length = decode_long (p, &p, end);
9375 if (index > mono_string_length_internal (str) - length)
9376 return ERR_INVALID_ARGUMENT;
9377 c = mono_string_chars_internal (str) + index;
9378 for (i = 0; i < length; ++i)
9379 buffer_add_short (buf, c [i]);
9380 break;
9381 default:
9382 return ERR_NOT_IMPLEMENTED;
9385 return ERR_NONE;
9388 static ErrorCode
9389 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9391 ErrorCode err;
9392 gint64 addr;
9393 MonoClass* klass;
9394 MonoDomain* domain = NULL;
9396 switch (command) {
9397 case CMD_POINTER_GET_VALUE:
9398 addr = decode_long (p, &p, end);
9399 klass = decode_typeid (p, &p, end, &domain, &err);
9400 if (err != ERR_NONE)
9401 return err;
9403 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9404 return ERR_INVALID_ARGUMENT;
9406 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (klass)), (gpointer)addr, domain);
9408 break;
9409 default:
9410 return ERR_NOT_IMPLEMENTED;
9413 return ERR_NONE;
9416 static ErrorCode
9417 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9419 ERROR_DECL (error);
9420 int objid;
9421 ErrorCode err;
9422 MonoObject *obj;
9423 int len, i;
9424 MonoClassField *f;
9425 MonoClass *k;
9426 gboolean found;
9428 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9429 objid = decode_objid (p, &p, end);
9430 err = get_object (objid, &obj);
9431 if (err != ERR_NONE)
9432 buffer_add_int (buf, 1);
9433 else
9434 buffer_add_int (buf, 0);
9435 return ERR_NONE;
9438 objid = decode_objid (p, &p, end);
9439 err = get_object (objid, &obj);
9440 if (err != ERR_NONE)
9441 return err;
9443 MonoClass *obj_type;
9444 gboolean remote_obj = FALSE;
9446 obj_type = obj->vtable->klass;
9447 if (mono_class_is_transparent_proxy (obj_type)) {
9448 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9449 remote_obj = TRUE;
9452 g_assert (obj_type);
9454 switch (command) {
9455 case CMD_OBJECT_REF_GET_TYPE:
9456 /* This handles transparent proxies too */
9457 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9458 break;
9459 case CMD_OBJECT_REF_GET_VALUES:
9460 len = decode_int (p, &p, end);
9462 for (i = 0; i < len; ++i) {
9463 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9464 if (err != ERR_NONE)
9465 return err;
9467 /* Check that the field belongs to the object */
9468 found = FALSE;
9469 for (k = obj_type; k; k = m_class_get_parent (k)) {
9470 if (k == f->parent) {
9471 found = TRUE;
9472 break;
9475 if (!found)
9476 return ERR_INVALID_FIELDID;
9478 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9479 guint8 *val;
9480 MonoVTable *vtable;
9482 if (mono_class_field_is_special_static (f))
9483 return ERR_INVALID_FIELDID;
9485 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9486 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9487 if (!is_ok (error)) {
9488 mono_error_cleanup (error);
9489 return ERR_INVALID_OBJECT;
9491 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9492 mono_field_static_get_value_checked (vtable, f, val, error);
9493 if (!is_ok (error)) {
9494 mono_error_cleanup (error); /* FIXME report the error */
9495 return ERR_INVALID_OBJECT;
9497 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9498 g_free (val);
9499 } else {
9500 void *field_value = NULL;
9501 #ifndef DISABLE_REMOTING
9502 void *field_storage = NULL;
9503 #endif
9504 if (remote_obj) {
9505 #ifndef DISABLE_REMOTING
9506 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9507 if (!is_ok (error)) {
9508 mono_error_cleanup (error); /* FIXME report the error */
9509 return ERR_INVALID_OBJECT;
9511 #else
9512 g_assert_not_reached ();
9513 #endif
9514 } else
9515 field_value = (guint8*)obj + f->offset;
9517 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9520 break;
9521 case CMD_OBJECT_REF_SET_VALUES:
9522 len = decode_int (p, &p, end);
9524 for (i = 0; i < len; ++i) {
9525 f = decode_fieldid (p, &p, end, NULL, &err);
9526 if (err != ERR_NONE)
9527 return err;
9529 /* Check that the field belongs to the object */
9530 found = FALSE;
9531 for (k = obj_type; k; k = m_class_get_parent (k)) {
9532 if (k == f->parent) {
9533 found = TRUE;
9534 break;
9537 if (!found)
9538 return ERR_INVALID_FIELDID;
9540 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9541 guint8 *val;
9542 MonoVTable *vtable;
9544 if (mono_class_field_is_special_static (f))
9545 return ERR_INVALID_FIELDID;
9547 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9548 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9549 if (!is_ok (error)) {
9550 mono_error_cleanup (error);
9551 return ERR_INVALID_FIELDID;
9554 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9555 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9556 if (err != ERR_NONE) {
9557 g_free (val);
9558 return err;
9560 mono_field_static_set_value_internal (vtable, f, val);
9561 g_free (val);
9562 } else {
9563 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9564 if (err != ERR_NONE)
9565 return err;
9568 break;
9569 case CMD_OBJECT_REF_GET_ADDRESS:
9570 buffer_add_long (buf, (gssize)obj);
9571 break;
9572 case CMD_OBJECT_REF_GET_DOMAIN:
9573 buffer_add_domainid (buf, obj->vtable->domain);
9574 break;
9575 case CMD_OBJECT_REF_GET_INFO:
9576 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9577 buffer_add_domainid (buf, obj->vtable->domain);
9578 break;
9579 default:
9580 return ERR_NOT_IMPLEMENTED;
9583 return ERR_NONE;
9586 static const char*
9587 command_set_to_string (CommandSet command_set)
9589 switch (command_set) {
9590 case CMD_SET_VM:
9591 return "VM";
9592 case CMD_SET_OBJECT_REF:
9593 return "OBJECT_REF";
9594 case CMD_SET_STRING_REF:
9595 return "STRING_REF";
9596 case CMD_SET_THREAD:
9597 return "THREAD";
9598 case CMD_SET_ARRAY_REF:
9599 return "ARRAY_REF";
9600 case CMD_SET_EVENT_REQUEST:
9601 return "EVENT_REQUEST";
9602 case CMD_SET_STACK_FRAME:
9603 return "STACK_FRAME";
9604 case CMD_SET_APPDOMAIN:
9605 return "APPDOMAIN";
9606 case CMD_SET_ASSEMBLY:
9607 return "ASSEMBLY";
9608 case CMD_SET_METHOD:
9609 return "METHOD";
9610 case CMD_SET_TYPE:
9611 return "TYPE";
9612 case CMD_SET_MODULE:
9613 return "MODULE";
9614 case CMD_SET_FIELD:
9615 return "FIELD";
9616 case CMD_SET_EVENT:
9617 return "EVENT";
9618 case CMD_SET_POINTER:
9619 return "POINTER";
9620 default:
9621 return "";
9625 static const char* vm_cmds_str [] = {
9626 "VERSION",
9627 "ALL_THREADS",
9628 "SUSPEND",
9629 "RESUME",
9630 "EXIT",
9631 "DISPOSE",
9632 "INVOKE_METHOD",
9633 "SET_PROTOCOL_VERSION",
9634 "ABORT_INVOKE",
9635 "SET_KEEPALIVE"
9636 "GET_TYPES_FOR_SOURCE_FILE",
9637 "GET_TYPES",
9638 "INVOKE_METHODS"
9641 static const char* thread_cmds_str[] = {
9642 "GET_FRAME_INFO",
9643 "GET_NAME",
9644 "GET_STATE",
9645 "GET_INFO",
9646 "GET_ID",
9647 "GET_TID",
9648 "SET_IP"
9651 static const char* event_cmds_str[] = {
9652 "REQUEST_SET",
9653 "REQUEST_CLEAR",
9654 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9657 static const char* appdomain_cmds_str[] = {
9658 "GET_ROOT_DOMAIN",
9659 "GET_FRIENDLY_NAME",
9660 "GET_ASSEMBLIES",
9661 "GET_ENTRY_ASSEMBLY",
9662 "CREATE_STRING",
9663 "GET_CORLIB",
9664 "CREATE_BOXED_VALUE",
9665 "CREATE_BYTE_ARRAY",
9668 static const char* assembly_cmds_str[] = {
9669 "GET_LOCATION",
9670 "GET_ENTRY_POINT",
9671 "GET_MANIFEST_MODULE",
9672 "GET_OBJECT",
9673 "GET_TYPE",
9674 "GET_NAME",
9675 "GET_DOMAIN",
9676 "HAS_DEBUG_INFO"
9679 static const char* module_cmds_str[] = {
9680 "GET_INFO",
9683 static const char* field_cmds_str[] = {
9684 "GET_INFO",
9687 static const char* method_cmds_str[] = {
9688 "GET_NAME",
9689 "GET_DECLARING_TYPE",
9690 "GET_DEBUG_INFO",
9691 "GET_PARAM_INFO",
9692 "GET_LOCALS_INFO",
9693 "GET_INFO",
9694 "GET_BODY",
9695 "RESOLVE_TOKEN",
9696 "GET_CATTRS ",
9697 "MAKE_GENERIC_METHOD"
9700 static const char* type_cmds_str[] = {
9701 "GET_INFO",
9702 "GET_METHODS",
9703 "GET_FIELDS",
9704 "GET_VALUES",
9705 "GET_OBJECT",
9706 "GET_SOURCE_FILES",
9707 "SET_VALUES",
9708 "IS_ASSIGNABLE_FROM",
9709 "GET_PROPERTIES ",
9710 "GET_CATTRS",
9711 "GET_FIELD_CATTRS",
9712 "GET_PROPERTY_CATTRS",
9713 "GET_SOURCE_FILES_2",
9714 "GET_VALUES_2",
9715 "GET_METHODS_BY_NAME_FLAGS",
9716 "GET_INTERFACES",
9717 "GET_INTERFACE_MAP",
9718 "IS_INITIALIZED",
9719 "CREATE_INSTANCE",
9720 "GET_VALUE_SIZE"
9723 static const char* stack_frame_cmds_str[] = {
9724 "GET_VALUES",
9725 "GET_THIS",
9726 "SET_VALUES",
9727 "GET_DOMAIN",
9728 "SET_THIS"
9731 static const char* array_cmds_str[] = {
9732 "GET_LENGTH",
9733 "GET_VALUES",
9734 "SET_VALUES",
9737 static const char* string_cmds_str[] = {
9738 "GET_VALUE",
9739 "GET_LENGTH",
9740 "GET_CHARS"
9743 static const char* pointer_cmds_str[] = {
9744 "GET_VALUE"
9747 static const char* object_cmds_str[] = {
9748 "GET_TYPE",
9749 "GET_VALUES",
9750 "IS_COLLECTED",
9751 "GET_ADDRESS",
9752 "GET_DOMAIN",
9753 "SET_VALUES",
9754 "GET_INFO",
9757 static const char*
9758 cmd_to_string (CommandSet set, int command)
9760 const char **cmds;
9761 int cmds_len = 0;
9763 switch (set) {
9764 case CMD_SET_VM:
9765 cmds = vm_cmds_str;
9766 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9767 break;
9768 case CMD_SET_OBJECT_REF:
9769 cmds = object_cmds_str;
9770 cmds_len = G_N_ELEMENTS (object_cmds_str);
9771 break;
9772 case CMD_SET_STRING_REF:
9773 cmds = string_cmds_str;
9774 cmds_len = G_N_ELEMENTS (string_cmds_str);
9775 break;
9776 case CMD_SET_THREAD:
9777 cmds = thread_cmds_str;
9778 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9779 break;
9780 case CMD_SET_ARRAY_REF:
9781 cmds = array_cmds_str;
9782 cmds_len = G_N_ELEMENTS (array_cmds_str);
9783 break;
9784 case CMD_SET_EVENT_REQUEST:
9785 cmds = event_cmds_str;
9786 cmds_len = G_N_ELEMENTS (event_cmds_str);
9787 break;
9788 case CMD_SET_STACK_FRAME:
9789 cmds = stack_frame_cmds_str;
9790 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9791 break;
9792 case CMD_SET_APPDOMAIN:
9793 cmds = appdomain_cmds_str;
9794 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9795 break;
9796 case CMD_SET_ASSEMBLY:
9797 cmds = assembly_cmds_str;
9798 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9799 break;
9800 case CMD_SET_METHOD:
9801 cmds = method_cmds_str;
9802 cmds_len = G_N_ELEMENTS (method_cmds_str);
9803 break;
9804 case CMD_SET_TYPE:
9805 cmds = type_cmds_str;
9806 cmds_len = G_N_ELEMENTS (type_cmds_str);
9807 break;
9808 case CMD_SET_MODULE:
9809 cmds = module_cmds_str;
9810 cmds_len = G_N_ELEMENTS (module_cmds_str);
9811 break;
9812 case CMD_SET_FIELD:
9813 cmds = field_cmds_str;
9814 cmds_len = G_N_ELEMENTS (field_cmds_str);
9815 break;
9816 case CMD_SET_EVENT:
9817 cmds = event_cmds_str;
9818 cmds_len = G_N_ELEMENTS (event_cmds_str);
9819 break;
9820 case CMD_SET_POINTER:
9821 cmds = pointer_cmds_str;
9822 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
9823 break;
9824 default:
9825 return NULL;
9827 if (command > 0 && command <= cmds_len)
9828 return cmds [command - 1];
9829 else
9830 return NULL;
9833 static gboolean
9834 wait_for_attach (void)
9836 #ifndef DISABLE_SOCKET_TRANSPORT
9837 if (listen_fd == -1) {
9838 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9839 return FALSE;
9842 /* Block and wait for client connection */
9843 conn_fd = socket_transport_accept (listen_fd);
9845 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9846 if (conn_fd == -1) {
9847 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9848 return FALSE;
9850 #else
9851 g_assert_not_reached ();
9852 #endif
9854 /* Handshake */
9855 disconnected = !transport_handshake ();
9856 if (disconnected) {
9857 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9858 return FALSE;
9861 return TRUE;
9865 * debugger_thread:
9867 * This thread handles communication with the debugger client using a JDWP
9868 * like protocol.
9870 static gsize WINAPI
9871 debugger_thread (void *arg)
9873 int res, len, id, flags, command = 0;
9874 CommandSet command_set = (CommandSet)0;
9875 guint8 header [HEADER_LENGTH];
9876 guint8 *data, *p, *end;
9877 Buffer buf;
9878 ErrorCode err;
9879 gboolean no_reply;
9880 gboolean attach_failed = FALSE;
9882 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9884 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
9886 debugger_thread_id = mono_native_thread_id_get ();
9888 MonoInternalThread *internal = mono_thread_internal_current ();
9889 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
9891 internal->state |= ThreadState_Background;
9892 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9894 if (agent_config.defer) {
9895 if (!wait_for_attach ()) {
9896 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9897 attach_failed = TRUE; // Don't abort process when we can't listen
9898 } else {
9899 mono_set_is_debugger_attached (TRUE);
9900 /* Send start event to client */
9901 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9903 } else {
9904 mono_set_is_debugger_attached (TRUE);
9907 while (!attach_failed) {
9908 res = transport_recv (header, HEADER_LENGTH);
9910 /* This will break if the socket is closed during shutdown too */
9911 if (res != HEADER_LENGTH) {
9912 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9913 len = HEADER_LENGTH;
9914 id = 0;
9915 flags = 0;
9916 command_set = CMD_SET_VM;
9917 command = CMD_VM_DISPOSE;
9918 } else {
9919 p = header;
9920 end = header + HEADER_LENGTH;
9922 len = decode_int (p, &p, end);
9923 id = decode_int (p, &p, end);
9924 flags = decode_byte (p, &p, end);
9925 command_set = (CommandSet)decode_byte (p, &p, end);
9926 command = decode_byte (p, &p, end);
9929 g_assert (flags == 0);
9930 const char *cmd_str;
9931 char cmd_num [256];
9933 cmd_str = cmd_to_string (command_set, command);
9934 if (!cmd_str) {
9935 sprintf (cmd_num, "%d", command);
9936 cmd_str = cmd_num;
9939 if (log_level) {
9940 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);
9943 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9944 if (len - HEADER_LENGTH > 0)
9946 res = transport_recv (data, len - HEADER_LENGTH);
9947 if (res != len - HEADER_LENGTH) {
9948 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9949 break;
9953 p = data;
9954 end = data + (len - HEADER_LENGTH);
9956 buffer_init (&buf, 128);
9958 err = ERR_NONE;
9959 no_reply = FALSE;
9961 /* Process the request */
9962 switch (command_set) {
9963 case CMD_SET_VM:
9964 err = vm_commands (command, id, p, end, &buf);
9965 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9966 /* Sent after the invoke is complete */
9967 no_reply = TRUE;
9968 break;
9969 case CMD_SET_EVENT_REQUEST:
9970 err = event_commands (command, p, end, &buf);
9971 break;
9972 case CMD_SET_APPDOMAIN:
9973 err = domain_commands (command, p, end, &buf);
9974 break;
9975 case CMD_SET_ASSEMBLY:
9976 err = assembly_commands (command, p, end, &buf);
9977 break;
9978 case CMD_SET_MODULE:
9979 err = module_commands (command, p, end, &buf);
9980 break;
9981 case CMD_SET_FIELD:
9982 err = field_commands (command, p, end, &buf);
9983 break;
9984 case CMD_SET_TYPE:
9985 err = type_commands (command, p, end, &buf);
9986 break;
9987 case CMD_SET_METHOD:
9988 err = method_commands (command, p, end, &buf);
9989 break;
9990 case CMD_SET_THREAD:
9991 err = thread_commands (command, p, end, &buf);
9992 break;
9993 case CMD_SET_STACK_FRAME:
9994 err = frame_commands (command, p, end, &buf);
9995 break;
9996 case CMD_SET_ARRAY_REF:
9997 err = array_commands (command, p, end, &buf);
9998 break;
9999 case CMD_SET_STRING_REF:
10000 err = string_commands (command, p, end, &buf);
10001 break;
10002 case CMD_SET_POINTER:
10003 err = pointer_commands (command, p, end, &buf);
10004 break;
10005 case CMD_SET_OBJECT_REF:
10006 err = object_commands (command, p, end, &buf);
10007 break;
10008 default:
10009 err = ERR_NOT_IMPLEMENTED;
10012 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10013 buffer_replies = TRUE;
10016 if (!no_reply) {
10017 if (buffer_replies) {
10018 buffer_reply_packet (id, err, &buf);
10019 } else {
10020 send_reply_packet (id, err, &buf);
10021 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10025 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10027 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10028 send_buffered_reply_packets ();
10029 buffer_replies = FALSE;
10032 g_free (data);
10033 buffer_free (&buf);
10035 if (log_each_step) {
10036 char *debugger_log = mono_debugger_state_str ();
10037 if (debugger_log) {
10038 fprintf (stderr, "Debugger state: %s\n", debugger_log);
10039 g_free (debugger_log);
10043 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10044 break;
10047 mono_set_is_debugger_attached (FALSE);
10049 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10050 debugger_thread_exited = TRUE;
10051 mono_coop_cond_signal (&debugger_thread_exited_cond);
10052 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10054 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10056 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10057 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10058 ERROR_DECL (error);
10059 start_debugger_thread (error);
10060 mono_error_cleanup (error);
10063 return 0;
10066 void
10067 mono_debugger_agent_init (void)
10069 MonoDebuggerCallbacks cbs;
10071 memset (&cbs, 0, sizeof (MonoDebuggerCallbacks));
10072 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10073 cbs.parse_options = debugger_agent_parse_options;
10074 cbs.init = debugger_agent_init;
10075 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10076 cbs.single_step_event = debugger_agent_single_step_event;
10077 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10078 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10079 cbs.free_domain_info = debugger_agent_free_domain_info;
10080 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10081 cbs.handle_exception = debugger_agent_handle_exception;
10082 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10083 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10084 cbs.user_break = debugger_agent_user_break;
10085 cbs.debug_log = debugger_agent_debug_log;
10086 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10087 cbs.send_crash = mono_debugger_agent_send_crash;
10089 mini_install_dbg_callbacks (&cbs);
10092 void
10093 mono_debugger_agent_parse_options (char *options)
10095 sdb_options = options;
10098 #endif /* DISABLE_SDB */