[wasm] Improve virtualenv installation script (#18470)
[mono-project.git] / mono / mini / debugger-agent.c
blobf6f4098422af50d6f9c4c20b58c164ca7102932b
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 <mono/utils/mono-logger-internals.h>
80 #include "debugger-state-machine.h"
81 #include "debugger-agent.h"
82 #include "mini.h"
83 #include "seq-points.h"
84 #include "aot-runtime.h"
85 #include "mini-runtime.h"
86 #include "interp/interp.h"
87 #include "debugger-engine.h"
88 #include "mono/metadata/debug-mono-ppdb.h"
89 #include "mono/metadata/custom-attrs-internals.h"
92 * On iOS we can't use System.Environment.Exit () as it will do the wrong
93 * shutdown sequence.
95 #if !defined (TARGET_IOS)
96 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
97 #endif
99 #if DISABLE_SOCKETS
100 #define DISABLE_SOCKET_TRANSPORT
101 #endif
103 #ifndef DISABLE_SDB
105 #include <mono/utils/mono-os-mutex.h>
107 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
109 typedef struct {
110 gboolean enabled;
111 char *transport;
112 char *address;
113 int log_level;
114 char *log_file;
115 gboolean suspend;
116 gboolean server;
117 gboolean onuncaught;
118 GSList *onthrow;
119 int timeout;
120 char *launch;
121 gboolean embedding;
122 gboolean defer;
123 int keepalive;
124 gboolean setpgid;
125 } AgentConfig;
127 typedef struct
129 //Must be the first field to ensure pointer equivalence
130 DbgEngineStackFrame de;
131 int id;
132 guint32 il_offset;
134 * If method is gshared, this is the actual instance, otherwise this is equal to
135 * method.
137 MonoMethod *actual_method;
139 * This is the method which is visible to debugger clients. Same as method,
140 * except for native-to-managed wrappers.
142 MonoMethod *api_method;
143 MonoContext ctx;
144 MonoDebugMethodJitInfo *jit;
145 MonoInterpFrameHandle interp_frame;
146 gpointer frame_addr;
147 int flags;
148 host_mgreg_t *reg_locations [MONO_MAX_IREGS];
150 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
151 * the frame can become invalid.
153 gboolean has_ctx;
154 } StackFrame;
156 typedef struct _InvokeData InvokeData;
158 struct _InvokeData
160 int id;
161 int flags;
162 guint8 *p;
163 guint8 *endp;
164 /* This is the context which needs to be restored after the invoke */
165 MonoContext ctx;
166 gboolean has_ctx;
168 * If this is set, invoke this method with the arguments given by ARGS.
170 MonoMethod *method;
171 gpointer *args;
172 guint32 suspend_count;
173 int nmethods;
175 InvokeData *last_invoke;
178 struct _DebuggerTlsData {
179 MonoThreadUnwindState context;
181 /* This is computed on demand when it is requested using the wire protocol */
182 /* It is freed up when the thread is resumed */
183 int frame_count;
184 StackFrame **frames;
186 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
187 * re-compute it.
189 gboolean frames_up_to_date;
191 * Points to data about a pending invoke which needs to be executed after the thread
192 * resumes.
194 InvokeData *pending_invoke;
196 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
197 * native code.
199 gboolean suspended;
201 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
202 * within a finite amount of time.
204 gboolean suspending;
206 * Set to TRUE if this thread is suspended in suspend_current ().
208 gboolean really_suspended;
209 /* Used to pass the context to the breakpoint/single step handler */
210 MonoContext handler_ctx;
211 /* Whenever thread_stop () was called for this thread */
212 gboolean terminated;
214 /* Whenever to disable breakpoints (used during invokes) */
215 gboolean disable_breakpoints;
218 * Number of times this thread has been resumed using resume_thread ().
220 guint32 resume_count;
222 MonoInternalThread *thread;
223 intptr_t thread_id;
226 * Information about the frame which transitioned to native code for running
227 * threads.
229 StackFrameInfo async_last_frame;
232 * The context where the stack walk can be started for running threads.
234 MonoThreadUnwindState async_state;
237 * The context used for filter clauses
239 MonoThreadUnwindState filter_state;
241 gboolean abort_requested;
244 * The current mono_runtime_invoke_checked invocation.
246 InvokeData *invoke;
248 StackFrameInfo catch_frame;
249 gboolean has_catch_frame;
252 * The context which needs to be restored after handling a single step/breakpoint
253 * event. This is the same as the ctx at step/breakpoint site, but includes changes
254 * to caller saved registers done by set_var ().
256 MonoThreadUnwindState restore_state;
257 /* Frames computed from restore_state */
258 int restore_frame_count;
259 StackFrame **restore_frames;
261 /* The currently unloading appdomain */
262 MonoDomain *domain_unloading;
264 // The state that the debugger expects the thread to be in
265 MonoDebuggerThreadState thread_state;
266 MonoStopwatch step_time;
268 gboolean gc_finalizing;
271 typedef struct {
272 const char *name;
273 void (*connect) (const char *address);
274 void (*close1) (void);
275 void (*close2) (void);
276 gboolean (*send) (void *buf, int len);
277 int (*recv) (void *buf, int len);
278 } DebuggerTransport;
281 * Wire Protocol definitions
284 #define HEADER_LENGTH 11
286 #define MAJOR_VERSION 2
287 #define MINOR_VERSION 54
289 typedef enum {
290 CMD_SET_VM = 1,
291 CMD_SET_OBJECT_REF = 9,
292 CMD_SET_STRING_REF = 10,
293 CMD_SET_THREAD = 11,
294 CMD_SET_ARRAY_REF = 13,
295 CMD_SET_EVENT_REQUEST = 15,
296 CMD_SET_STACK_FRAME = 16,
297 CMD_SET_APPDOMAIN = 20,
298 CMD_SET_ASSEMBLY = 21,
299 CMD_SET_METHOD = 22,
300 CMD_SET_TYPE = 23,
301 CMD_SET_MODULE = 24,
302 CMD_SET_FIELD = 25,
303 CMD_SET_EVENT = 64,
304 CMD_SET_POINTER = 65
305 } CommandSet;
307 typedef enum {
308 SUSPEND_POLICY_NONE = 0,
309 SUSPEND_POLICY_EVENT_THREAD = 1,
310 SUSPEND_POLICY_ALL = 2
311 } SuspendPolicy;
313 typedef enum {
314 ERR_NONE = 0,
315 ERR_INVALID_OBJECT = 20,
316 ERR_INVALID_FIELDID = 25,
317 ERR_INVALID_FRAMEID = 30,
318 ERR_NOT_IMPLEMENTED = 100,
319 ERR_NOT_SUSPENDED = 101,
320 ERR_INVALID_ARGUMENT = 102,
321 ERR_UNLOADED = 103,
322 ERR_NO_INVOCATION = 104,
323 ERR_ABSENT_INFORMATION = 105,
324 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
325 ERR_INVOKE_ABORTED = 107,
326 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
327 } ErrorCode;
329 typedef enum {
330 TOKEN_TYPE_STRING = 0,
331 TOKEN_TYPE_TYPE = 1,
332 TOKEN_TYPE_FIELD = 2,
333 TOKEN_TYPE_METHOD = 3,
334 TOKEN_TYPE_UNKNOWN = 4
335 } DebuggerTokenType;
337 typedef enum {
338 VALUE_TYPE_ID_NULL = 0xf0,
339 VALUE_TYPE_ID_TYPE = 0xf1,
340 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2,
341 VALUE_TYPE_ID_FIXED_ARRAY = 0xf3
342 } ValueTypeId;
344 typedef enum {
345 FRAME_FLAG_DEBUGGER_INVOKE = 1,
346 FRAME_FLAG_NATIVE_TRANSITION = 2
347 } StackFrameFlags;
349 typedef enum {
350 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
351 INVOKE_FLAG_SINGLE_THREADED = 2,
352 INVOKE_FLAG_RETURN_OUT_THIS = 4,
353 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
354 INVOKE_FLAG_VIRTUAL = 16
355 } InvokeFlags;
357 typedef enum {
358 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
359 } BindingFlagsExtensions;
361 typedef enum {
362 CMD_VM_VERSION = 1,
363 CMD_VM_ALL_THREADS = 2,
364 CMD_VM_SUSPEND = 3,
365 CMD_VM_RESUME = 4,
366 CMD_VM_EXIT = 5,
367 CMD_VM_DISPOSE = 6,
368 CMD_VM_INVOKE_METHOD = 7,
369 CMD_VM_SET_PROTOCOL_VERSION = 8,
370 CMD_VM_ABORT_INVOKE = 9,
371 CMD_VM_SET_KEEPALIVE = 10,
372 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
373 CMD_VM_GET_TYPES = 12,
374 CMD_VM_INVOKE_METHODS = 13,
375 CMD_VM_START_BUFFERING = 14,
376 CMD_VM_STOP_BUFFERING = 15
377 } CmdVM;
379 typedef enum {
380 CMD_THREAD_GET_FRAME_INFO = 1,
381 CMD_THREAD_GET_NAME = 2,
382 CMD_THREAD_GET_STATE = 3,
383 CMD_THREAD_GET_INFO = 4,
384 CMD_THREAD_GET_ID = 5,
385 CMD_THREAD_GET_TID = 6,
386 CMD_THREAD_SET_IP = 7,
387 CMD_THREAD_ELAPSED_TIME = 8
388 } CmdThread;
390 typedef enum {
391 CMD_EVENT_REQUEST_SET = 1,
392 CMD_EVENT_REQUEST_CLEAR = 2,
393 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
394 } CmdEvent;
396 typedef enum {
397 CMD_COMPOSITE = 100
398 } CmdComposite;
400 typedef enum {
401 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
402 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
403 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
404 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
405 CMD_APPDOMAIN_CREATE_STRING = 5,
406 CMD_APPDOMAIN_GET_CORLIB = 6,
407 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
408 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
409 } CmdAppDomain;
411 typedef enum {
412 CMD_ASSEMBLY_GET_LOCATION = 1,
413 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
414 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
415 CMD_ASSEMBLY_GET_OBJECT = 4,
416 CMD_ASSEMBLY_GET_TYPE = 5,
417 CMD_ASSEMBLY_GET_NAME = 6,
418 CMD_ASSEMBLY_GET_DOMAIN = 7,
419 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
420 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
421 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
422 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
423 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
424 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13
425 } CmdAssembly;
427 typedef enum {
428 CMD_MODULE_GET_INFO = 1,
429 } CmdModule;
431 typedef enum {
432 CMD_FIELD_GET_INFO = 1,
433 } CmdField;
435 typedef enum {
436 CMD_METHOD_GET_NAME = 1,
437 CMD_METHOD_GET_DECLARING_TYPE = 2,
438 CMD_METHOD_GET_DEBUG_INFO = 3,
439 CMD_METHOD_GET_PARAM_INFO = 4,
440 CMD_METHOD_GET_LOCALS_INFO = 5,
441 CMD_METHOD_GET_INFO = 6,
442 CMD_METHOD_GET_BODY = 7,
443 CMD_METHOD_RESOLVE_TOKEN = 8,
444 CMD_METHOD_GET_CATTRS = 9,
445 CMD_METHOD_MAKE_GENERIC_METHOD = 10
446 } CmdMethod;
448 typedef enum {
449 CMD_TYPE_GET_INFO = 1,
450 CMD_TYPE_GET_METHODS = 2,
451 CMD_TYPE_GET_FIELDS = 3,
452 CMD_TYPE_GET_VALUES = 4,
453 CMD_TYPE_GET_OBJECT = 5,
454 CMD_TYPE_GET_SOURCE_FILES = 6,
455 CMD_TYPE_SET_VALUES = 7,
456 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
457 CMD_TYPE_GET_PROPERTIES = 9,
458 CMD_TYPE_GET_CATTRS = 10,
459 CMD_TYPE_GET_FIELD_CATTRS = 11,
460 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
461 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
462 CMD_TYPE_GET_VALUES_2 = 14,
463 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
464 CMD_TYPE_GET_INTERFACES = 16,
465 CMD_TYPE_GET_INTERFACE_MAP = 17,
466 CMD_TYPE_IS_INITIALIZED = 18,
467 CMD_TYPE_CREATE_INSTANCE = 19,
468 CMD_TYPE_GET_VALUE_SIZE = 20
469 } CmdType;
471 typedef enum {
472 CMD_STACK_FRAME_GET_VALUES = 1,
473 CMD_STACK_FRAME_GET_THIS = 2,
474 CMD_STACK_FRAME_SET_VALUES = 3,
475 CMD_STACK_FRAME_GET_DOMAIN = 4,
476 CMD_STACK_FRAME_SET_THIS = 5,
477 } CmdStackFrame;
479 typedef enum {
480 CMD_ARRAY_REF_GET_LENGTH = 1,
481 CMD_ARRAY_REF_GET_VALUES = 2,
482 CMD_ARRAY_REF_SET_VALUES = 3,
483 } CmdArray;
485 typedef enum {
486 CMD_STRING_REF_GET_VALUE = 1,
487 CMD_STRING_REF_GET_LENGTH = 2,
488 CMD_STRING_REF_GET_CHARS = 3
489 } CmdString;
491 typedef enum {
492 CMD_POINTER_GET_VALUE = 1
493 } CmdPointer;
495 typedef enum {
496 CMD_OBJECT_REF_GET_TYPE = 1,
497 CMD_OBJECT_REF_GET_VALUES = 2,
498 CMD_OBJECT_REF_IS_COLLECTED = 3,
499 CMD_OBJECT_REF_GET_ADDRESS = 4,
500 CMD_OBJECT_REF_GET_DOMAIN = 5,
501 CMD_OBJECT_REF_SET_VALUES = 6,
502 CMD_OBJECT_REF_GET_INFO = 7,
503 } CmdObject;
506 * Contains additional information for an event
508 typedef struct {
509 /* For EVENT_KIND_EXCEPTION */
510 MonoObject *exc;
511 MonoContext catch_ctx;
512 gboolean caught;
513 /* For EVENT_KIND_USER_LOG */
514 int level;
515 char *category, *message;
516 /* For EVENT_KIND_TYPE_LOAD */
517 MonoClass *klass;
518 /* For EVENT_KIND_CRASH */
519 char *dump;
520 MonoStackHash *hashes;
521 } EventInfo;
523 typedef struct {
524 guint8 *buf, *p, *end;
525 } Buffer;
527 typedef struct ReplyPacket {
528 int id;
529 int error;
530 Buffer *data;
531 } ReplyPacket;
533 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
535 #ifdef HOST_ANDROID
536 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
537 #else
538 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
539 #endif
541 #ifdef HOST_WIN32
542 #define get_last_sock_error() WSAGetLastError()
543 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
544 #define MONO_EINTR WSAEINTR
545 #else
546 #define get_last_sock_error() errno
547 #define MONO_EWOULDBLOCK EWOULDBLOCK
548 #define MONO_EINTR EINTR
549 #endif
551 #define CHECK_PROTOCOL_VERSION(major,minor) \
552 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
555 * Globals
558 static AgentConfig agent_config;
561 * Whenever the agent is fully initialized.
562 * When using the onuncaught or onthrow options, only some parts of the agent are
563 * initialized on startup, and the full initialization which includes connection
564 * establishment and the startup of the agent thread is only done in response to
565 * an event.
567 static gint32 inited;
569 #ifndef DISABLE_SOCKET_TRANSPORT
570 static int conn_fd;
571 static int listen_fd;
572 #endif
574 static int packet_id = 0;
576 static int objref_id = 0;
578 static int event_request_id = 0;
580 static int frame_id = 0;
582 static GPtrArray *event_requests;
584 static MonoNativeTlsKey debugger_tls_id;
586 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
588 /* Maps MonoInternalThread -> DebuggerTlsData */
589 /* Protected by the loader lock */
590 static MonoGHashTable *thread_to_tls;
592 /* Maps tid -> MonoInternalThread */
593 /* Protected by the loader lock */
594 static MonoGHashTable *tid_to_thread;
596 /* Maps tid -> MonoThread (not MonoInternalThread) */
597 /* Protected by the loader lock */
598 static MonoGHashTable *tid_to_thread_obj;
600 static MonoNativeThreadId debugger_thread_id;
602 static MonoThreadHandle *debugger_thread_handle;
604 static int log_level;
606 static gboolean embedding;
608 static FILE *log_file;
610 /* Assemblies whose assembly load event has no been sent yet */
611 /* Protected by the dbg lock */
612 static GPtrArray *pending_assembly_loads;
614 /* Whenever the debugger thread has exited */
615 static gboolean debugger_thread_exited;
617 /* Cond variable used to wait for debugger_thread_exited becoming true */
618 static MonoCoopCond debugger_thread_exited_cond;
620 /* Mutex for the cond var above */
621 static MonoCoopMutex debugger_thread_exited_mutex;
623 /* The protocol version of the client */
624 static int major_version, minor_version;
626 /* Whenever the variables above are set by the client */
627 static gboolean protocol_version_set;
629 /* The number of times the runtime is suspended */
630 static gint32 suspend_count;
632 /* Whenever to buffer reply messages and send them together */
633 static gboolean buffer_replies;
635 /* Buffered reply packets */
636 static ReplyPacket reply_packets [128];
637 static int nreply_packets;
639 #define dbg_lock mono_de_lock
640 #define dbg_unlock mono_de_unlock
642 static void transport_init (void);
643 static void transport_connect (const char *address);
644 static gboolean transport_handshake (void);
645 static void register_transport (DebuggerTransport *trans);
647 static gsize WINAPI debugger_thread (void *arg);
649 static void runtime_initialized (MonoProfiler *prof);
651 static void runtime_shutdown (MonoProfiler *prof);
653 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
655 static void thread_end (MonoProfiler *prof, uintptr_t tid);
657 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
659 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
661 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
663 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
665 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
667 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
669 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
671 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
673 static void gc_finalizing (MonoProfiler *prof);
675 static void gc_finalized (MonoProfiler *prof);
677 static void emit_assembly_load (gpointer assembly, gpointer user_data);
679 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
681 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
683 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
685 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
687 static void suspend_current (void);
689 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
691 static void clear_types_for_assembly (MonoAssembly *assembly);
693 static void process_profiler_event (EventKind event, gpointer arg);
695 /* Submodule init/cleanup */
696 static void event_requests_cleanup (void);
698 static void objrefs_init (void);
699 static void objrefs_cleanup (void);
701 static void ids_init (void);
702 static void ids_cleanup (void);
704 static void suspend_init (void);
706 static void start_debugger_thread (MonoError *error);
707 static void stop_debugger_thread (void);
709 static void finish_agent_init (gboolean on_startup);
711 static void process_profiler_event (EventKind event, gpointer arg);
713 static void invalidate_frames (DebuggerTlsData *tls);
715 /* Callbacks used by debugger-engine */
716 static MonoContext* tls_get_restore_state (void *the_tls);
717 static gboolean try_process_suspend (void *tls, MonoContext *ctx);
718 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
719 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
720 static void ss_discard_frame_context (void *the_tls);
721 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
722 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
723 static int ensure_runtime_is_suspended (void);
724 static int get_this_async_id (DbgEngineStackFrame *frame);
725 static gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame);
726 static MonoMethod* get_notify_debugger_of_wait_completion_method (void);
727 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
728 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
729 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
730 static void ss_args_destroy (SingleStepArgs *ss_args);
732 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
734 #ifndef DISABLE_SOCKET_TRANSPORT
735 static void
736 register_socket_transport (void);
737 #endif
739 static gboolean
740 is_debugger_thread (void)
742 MonoInternalThread *internal;
744 internal = mono_thread_internal_current ();
745 if (!internal)
746 return FALSE;
748 return internal->debugger_thread;
751 static int
752 parse_address (char *address, char **host, int *port)
754 char *pos = strchr (address, ':');
756 if (pos == NULL || pos == address)
757 return 1;
759 size_t len = pos - address;
760 *host = (char *)g_malloc (len + 1);
761 memcpy (*host, address, len);
762 (*host) [len] = '\0';
764 *port = atoi (pos + 1);
766 return 0;
769 static void
770 print_usage (void)
772 g_printerr ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
773 g_printerr ("Available options:\n");
774 g_printerr (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
775 g_printerr (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
776 g_printerr (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
777 g_printerr (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
778 g_printerr (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
779 g_printerr (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
780 g_printerr (" server=y/n\t\t\tWhether to listen for a client connection.\n");
781 g_printerr (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
782 g_printerr (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
783 g_printerr (" help\t\t\t\tPrint this help.\n");
786 static gboolean
787 parse_flag (const char *option, char *flag)
789 if (!strcmp (flag, "y"))
790 return TRUE;
791 else if (!strcmp (flag, "n"))
792 return FALSE;
793 else {
794 g_printerr ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
795 exit (1);
796 return FALSE;
800 static void
801 debugger_agent_parse_options (char *options)
803 char **args, **ptr;
804 char *host;
805 int port;
806 char *extra;
808 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
809 g_printerr ("--debugger-agent is not supported on this platform.\n");
810 exit (1);
811 #endif
813 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
814 if (extra) {
815 options = g_strdup_printf ("%s,%s", options, extra);
816 g_free (extra);
819 agent_config.enabled = TRUE;
820 agent_config.suspend = TRUE;
821 agent_config.server = FALSE;
822 agent_config.defer = FALSE;
823 agent_config.address = NULL;
825 //agent_config.log_level = 10;
827 args = g_strsplit (options, ",", -1);
828 for (ptr = args; ptr && *ptr; ptr ++) {
829 char *arg = *ptr;
831 if (strncmp (arg, "transport=", 10) == 0) {
832 agent_config.transport = g_strdup (arg + 10);
833 } else if (strncmp (arg, "address=", 8) == 0) {
834 agent_config.address = g_strdup (arg + 8);
835 } else if (strncmp (arg, "loglevel=", 9) == 0) {
836 agent_config.log_level = atoi (arg + 9);
837 } else if (strncmp (arg, "logfile=", 8) == 0) {
838 agent_config.log_file = g_strdup (arg + 8);
839 } else if (strncmp (arg, "suspend=", 8) == 0) {
840 agent_config.suspend = parse_flag ("suspend", arg + 8);
841 } else if (strncmp (arg, "server=", 7) == 0) {
842 agent_config.server = parse_flag ("server", arg + 7);
843 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
844 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
845 } else if (strncmp (arg, "onthrow=", 8) == 0) {
846 /* We support multiple onthrow= options */
847 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
848 } else if (strncmp (arg, "onthrow", 7) == 0) {
849 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
850 } else if (strncmp (arg, "help", 4) == 0) {
851 print_usage ();
852 exit (0);
853 } else if (strncmp (arg, "timeout=", 8) == 0) {
854 agent_config.timeout = atoi (arg + 8);
855 } else if (strncmp (arg, "launch=", 7) == 0) {
856 agent_config.launch = g_strdup (arg + 7);
857 } else if (strncmp (arg, "embedding=", 10) == 0) {
858 agent_config.embedding = atoi (arg + 10) == 1;
859 } else if (strncmp (arg, "keepalive=", 10) == 0) {
860 agent_config.keepalive = atoi (arg + 10);
861 } else if (strncmp (arg, "setpgid=", 8) == 0) {
862 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
863 } else {
864 print_usage ();
865 exit (1);
869 if (agent_config.server && !agent_config.suspend) {
870 /* Waiting for deferred attachment */
871 agent_config.defer = TRUE;
872 if (agent_config.address == NULL) {
873 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
877 //agent_config.log_level = 0;
879 if (agent_config.transport == NULL) {
880 g_printerr ("debugger-agent: The 'transport' option is mandatory.\n");
881 exit (1);
884 if (agent_config.address == NULL && !agent_config.server) {
885 g_printerr ("debugger-agent: The 'address' option is mandatory.\n");
886 exit (1);
889 // FIXME:
890 if (!strcmp (agent_config.transport, "dt_socket")) {
891 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
892 g_printerr ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
893 exit (1);
898 void
899 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
901 g_assertf (tls, "Cannot get state of null thread", NULL);
903 g_assert (tls->thread_state == expected);
905 tls->thread_state = set;
908 MonoDebuggerThreadState
909 mono_debugger_get_thread_state (DebuggerTlsData *tls)
911 g_assertf (tls, "Cannot get state of null thread", NULL);
913 return tls->thread_state;
916 gsize
917 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
919 if (!tls)
920 return 0;
922 return tls->thread_id;
925 // Only call this function with the loader lock held
926 MonoGHashTable *
927 mono_debugger_get_thread_states (void)
929 return thread_to_tls;
932 gboolean
933 mono_debugger_is_disconnected (void)
935 return disconnected;
938 static void
939 debugger_agent_init (void)
941 if (!agent_config.enabled)
942 return;
944 DebuggerEngineCallbacks cbs;
945 memset (&cbs, 0, sizeof (cbs));
946 cbs.tls_get_restore_state = tls_get_restore_state;
947 cbs.try_process_suspend = try_process_suspend;
948 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
949 cbs.begin_single_step_processing = begin_single_step_processing;
950 cbs.ss_discard_frame_context = ss_discard_frame_context;
951 cbs.ss_calculate_framecount = ss_calculate_framecount;
952 cbs.ensure_jit = ensure_jit;
953 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
954 cbs.get_this_async_id = get_this_async_id;
955 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
956 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
957 cbs.create_breakpoint_events = create_breakpoint_events;
958 cbs.process_breakpoint_events = process_breakpoint_events;
959 cbs.ss_create_init_args = ss_create_init_args;
960 cbs.ss_args_destroy = ss_args_destroy;
962 mono_de_init (&cbs);
964 transport_init ();
966 /* Need to know whenever a thread has acquired the loader mutex */
967 mono_loader_lock_track_ownership (TRUE);
969 event_requests = g_ptr_array_new ();
971 mono_coop_mutex_init (&debugger_thread_exited_mutex);
972 mono_coop_cond_init (&debugger_thread_exited_cond);
974 MonoProfilerHandle prof = mono_profiler_create (NULL);
975 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
976 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
977 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
978 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
979 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
980 mono_profiler_set_thread_started_callback (prof, thread_startup);
981 mono_profiler_set_thread_stopped_callback (prof, thread_end);
982 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
983 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
984 mono_profiler_set_jit_done_callback (prof, jit_done);
985 mono_profiler_set_jit_failed_callback (prof, jit_failed);
986 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
987 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
989 mono_native_tls_alloc (&debugger_tls_id, NULL);
991 /* Needed by the hash_table_new_type () call below */
992 mono_gc_base_init ();
994 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");
996 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
998 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");
1000 pending_assembly_loads = g_ptr_array_new ();
1002 log_level = agent_config.log_level;
1004 embedding = agent_config.embedding;
1005 disconnected = TRUE;
1007 if (agent_config.log_file) {
1008 log_file = fopen (agent_config.log_file, "w+");
1009 if (!log_file) {
1010 g_printerr ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1011 exit (1);
1013 } else {
1014 log_file = stdout;
1016 mono_de_set_log_level (log_level, log_file);
1018 ids_init ();
1019 objrefs_init ();
1020 suspend_init ();
1022 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1024 * This is needed because currently we don't handle liveness info.
1026 mini_get_debug_options ()->mdb_optimizations = TRUE;
1028 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1029 /* This is needed because we can't set local variables in registers yet */
1030 mono_disable_optimizations (MONO_OPT_LINEARS);
1031 #endif
1034 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1035 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1036 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1037 * workaround.
1039 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1041 #ifdef HAVE_SETPGID
1042 if (agent_config.setpgid)
1043 setpgid (0, 0);
1044 #endif
1046 if (!agent_config.onuncaught && !agent_config.onthrow)
1047 finish_agent_init (TRUE);
1051 * finish_agent_init:
1053 * Finish the initialization of the agent. This involves connecting the transport
1054 * and starting the agent thread. This is either done at startup, or
1055 * in response to some event like an unhandled exception.
1057 static void
1058 finish_agent_init (gboolean on_startup)
1060 int res;
1062 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1063 return;
1065 if (agent_config.launch) {
1066 char *argv [16];
1068 // FIXME: Generated address
1069 // FIXME: Races with transport_connect ()
1071 argv [0] = agent_config.launch;
1072 argv [1] = agent_config.transport;
1073 argv [2] = agent_config.address;
1074 argv [3] = NULL;
1076 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1077 if (!res) {
1078 g_printerr ("Failed to execute '%s'.\n", agent_config.launch);
1079 exit (1);
1083 transport_connect (agent_config.address);
1085 if (!on_startup) {
1086 /* Do some which is usually done after sending the VMStart () event */
1087 vm_start_event_sent = TRUE;
1088 ERROR_DECL (error);
1089 start_debugger_thread (error);
1090 mono_error_assert_ok (error);
1094 static void
1095 mono_debugger_agent_cleanup (void)
1097 if (!inited)
1098 return;
1100 stop_debugger_thread ();
1102 event_requests_cleanup ();
1103 objrefs_cleanup ();
1104 ids_cleanup ();
1106 mono_de_cleanup ();
1110 * SOCKET TRANSPORT
1113 #ifndef DISABLE_SOCKET_TRANSPORT
1116 * recv_length:
1118 * recv() + handle incomplete reads and EINTR
1120 static int
1121 socket_transport_recv (void *buf, int len)
1123 int res;
1124 int total = 0;
1125 int fd = conn_fd;
1126 int flags = 0;
1127 static gint64 last_keepalive;
1128 gint64 msecs;
1130 MONO_ENTER_GC_SAFE;
1132 do {
1133 again:
1134 res = recv (fd, (char *) buf + total, len - total, flags);
1135 if (res > 0)
1136 total += res;
1137 if (agent_config.keepalive) {
1138 gboolean need_keepalive = FALSE;
1139 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1140 need_keepalive = TRUE;
1141 } else if (res == -1) {
1142 /* This could happen if recv () is interrupted repeatedly */
1143 msecs = mono_msec_ticks ();
1144 if (msecs - last_keepalive >= agent_config.keepalive) {
1145 need_keepalive = TRUE;
1146 last_keepalive = msecs;
1149 if (need_keepalive) {
1150 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1151 goto again;
1154 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1156 MONO_EXIT_GC_SAFE;
1158 return total;
1161 static void
1162 set_keepalive (void)
1164 struct timeval tv;
1165 int result;
1167 if (!agent_config.keepalive || !conn_fd)
1168 return;
1170 tv.tv_sec = agent_config.keepalive / 1000;
1171 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1173 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1174 g_assert (result >= 0);
1177 static int
1178 socket_transport_accept (int socket_fd)
1180 MONO_ENTER_GC_SAFE;
1181 conn_fd = accept (socket_fd, NULL, NULL);
1182 MONO_EXIT_GC_SAFE;
1184 if (conn_fd == -1) {
1185 g_printerr ("debugger-agent: Unable to listen on %d\n", socket_fd);
1186 } else {
1187 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1190 return conn_fd;
1193 static gboolean
1194 socket_transport_send (void *data, int len)
1196 int res;
1198 MONO_ENTER_GC_SAFE;
1200 do {
1201 res = send (conn_fd, (const char*)data, len, 0);
1202 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1204 MONO_EXIT_GC_SAFE;
1206 if (res != len)
1207 return FALSE;
1208 else
1209 return TRUE;
1213 * socket_transport_connect:
1215 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1217 static void
1218 socket_transport_connect (const char *address)
1220 MonoAddressInfo *result;
1221 MonoAddressEntry *rp;
1222 int sfd = -1, s, res;
1223 char *host;
1224 int port;
1226 if (agent_config.address) {
1227 res = parse_address (agent_config.address, &host, &port);
1228 g_assert (res == 0);
1229 } else {
1230 host = NULL;
1231 port = 0;
1234 conn_fd = -1;
1235 listen_fd = -1;
1237 if (host) {
1238 int hints[] = {
1239 MONO_HINT_IPV4 | MONO_HINT_NUMERIC_HOST,
1240 MONO_HINT_IPV6 | MONO_HINT_NUMERIC_HOST,
1241 MONO_HINT_UNSPECIFIED
1244 mono_network_init ();
1246 for (int i = 0; i < sizeof(hints) / sizeof(int); i++) {
1247 /* Obtain address(es) matching host/port */
1248 s = mono_get_address_info (host, port, hints[i], &result);
1249 if (s == 0)
1250 break;
1252 if (s != 0) {
1253 g_printerr ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1254 exit (1);
1258 if (agent_config.server) {
1259 /* Wait for a connection */
1260 if (!host) {
1261 struct sockaddr_in addr;
1262 socklen_t addrlen;
1264 /* No address, generate one */
1265 sfd = socket (AF_INET, SOCK_STREAM, 0);
1266 if (sfd == -1) {
1267 g_printerr ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1268 exit (1);
1271 /* This will bind the socket to a random port */
1272 res = listen (sfd, 16);
1273 if (res == -1) {
1274 g_printerr ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1275 exit (1);
1277 listen_fd = sfd;
1279 addrlen = sizeof (addr);
1280 memset (&addr, 0, sizeof (addr));
1281 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1282 g_assert (res == 0);
1284 host = (char*)"127.0.0.1";
1285 port = ntohs (addr.sin_port);
1287 /* Emit the address to stdout */
1288 /* FIXME: Should print another interface, not localhost */
1289 printf ("%s:%d\n", host, port);
1290 } else {
1291 /* Listen on the provided address */
1292 for (rp = result->entries; rp != NULL; rp = rp->next) {
1293 MonoSocketAddress sockaddr;
1294 socklen_t sock_len;
1295 int n = 1;
1297 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1299 sfd = socket (rp->family, rp->socktype,
1300 rp->protocol);
1301 if (sfd == -1)
1302 continue;
1304 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1305 continue;
1307 res = bind (sfd, &sockaddr.addr, sock_len);
1308 if (res == -1)
1309 continue;
1311 res = listen (sfd, 16);
1312 if (res == -1)
1313 continue;
1314 listen_fd = sfd;
1315 break;
1318 mono_free_address_info (result);
1321 if (agent_config.defer)
1322 return;
1324 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1326 if (agent_config.timeout) {
1327 fd_set readfds;
1328 struct timeval tv;
1330 tv.tv_sec = 0;
1331 tv.tv_usec = agent_config.timeout * 1000;
1332 FD_ZERO (&readfds);
1333 FD_SET (sfd, &readfds);
1335 MONO_ENTER_GC_SAFE;
1336 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1337 MONO_EXIT_GC_SAFE;
1339 if (res == 0) {
1340 g_printerr ("debugger-agent: Timed out waiting to connect.\n");
1341 exit (1);
1345 conn_fd = socket_transport_accept (sfd);
1346 if (conn_fd == -1)
1347 exit (1);
1349 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1350 } else {
1351 /* Connect to the specified address */
1352 /* FIXME: Respect the timeout */
1353 for (rp = result->entries; rp != NULL; rp = rp->next) {
1354 MonoSocketAddress sockaddr;
1355 socklen_t sock_len;
1357 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1359 sfd = socket (rp->family, rp->socktype,
1360 rp->protocol);
1361 if (sfd == -1)
1362 continue;
1364 MONO_ENTER_GC_SAFE;
1365 res = connect (sfd, &sockaddr.addr, sock_len);
1366 MONO_EXIT_GC_SAFE;
1368 if (res != -1)
1369 break; /* Success */
1371 MONO_ENTER_GC_SAFE;
1372 #ifdef HOST_WIN32
1373 closesocket (sfd);
1374 #else
1375 close (sfd);
1376 #endif
1377 MONO_EXIT_GC_SAFE;
1380 if (rp == 0) {
1381 g_printerr ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1382 exit (1);
1385 conn_fd = sfd;
1387 mono_free_address_info (result);
1390 if (!transport_handshake ())
1391 exit (1);
1394 static void
1395 socket_transport_close1 (void)
1397 /* This will interrupt the agent thread */
1398 /* Close the read part only so it can still send back replies */
1399 /* Also shut down the connection listener so that we can exit normally */
1400 #ifdef HOST_WIN32
1401 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1402 shutdown (conn_fd, SD_BOTH);
1403 shutdown (listen_fd, SD_BOTH);
1404 closesocket (listen_fd);
1405 #else
1406 shutdown (conn_fd, SHUT_RD);
1407 shutdown (listen_fd, SHUT_RDWR);
1408 MONO_ENTER_GC_SAFE;
1409 close (listen_fd);
1410 MONO_EXIT_GC_SAFE;
1411 #endif
1414 static void
1415 socket_transport_close2 (void)
1417 #ifdef HOST_WIN32
1418 shutdown (conn_fd, SD_BOTH);
1419 #else
1420 shutdown (conn_fd, SHUT_RDWR);
1421 #endif
1424 static void
1425 register_socket_transport (void)
1427 DebuggerTransport trans;
1429 trans.name = "dt_socket";
1430 trans.connect = socket_transport_connect;
1431 trans.close1 = socket_transport_close1;
1432 trans.close2 = socket_transport_close2;
1433 trans.send = socket_transport_send;
1434 trans.recv = socket_transport_recv;
1436 register_transport (&trans);
1440 * socket_fd_transport_connect:
1443 static void
1444 socket_fd_transport_connect (const char *address)
1446 int res;
1448 res = sscanf (address, "%d", &conn_fd);
1449 if (res != 1) {
1450 g_printerr ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1451 exit (1);
1454 if (!transport_handshake ())
1455 exit (1);
1458 static void
1459 register_socket_fd_transport (void)
1461 DebuggerTransport trans;
1463 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1464 trans.name = "socket-fd";
1465 trans.connect = socket_fd_transport_connect;
1466 trans.close1 = socket_transport_close1;
1467 trans.close2 = socket_transport_close2;
1468 trans.send = socket_transport_send;
1469 trans.recv = socket_transport_recv;
1471 register_transport (&trans);
1474 #endif /* DISABLE_SOCKET_TRANSPORT */
1477 * TRANSPORT CODE
1480 #define MAX_TRANSPORTS 16
1482 static DebuggerTransport *transport;
1484 static DebuggerTransport transports [MAX_TRANSPORTS];
1485 static int ntransports;
1487 MONO_API void
1488 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1490 void
1491 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1493 register_transport (trans);
1496 static void
1497 register_transport (DebuggerTransport *trans)
1499 g_assert (ntransports < MAX_TRANSPORTS);
1501 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1502 ntransports ++;
1505 static void
1506 transport_init (void)
1508 int i;
1510 #ifndef DISABLE_SOCKET_TRANSPORT
1511 register_socket_transport ();
1512 register_socket_fd_transport ();
1513 #endif
1515 for (i = 0; i < ntransports; ++i) {
1516 if (!strcmp (agent_config.transport, transports [i].name))
1517 break;
1519 if (i == ntransports) {
1520 g_printerr ("debugger-agent: The supported values for the 'transport' option are: ");
1521 for (i = 0; i < ntransports; ++i)
1522 g_printerr ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1523 g_printerr ("\n");
1524 exit (1);
1526 transport = &transports [i];
1529 void
1530 transport_connect (const char *address)
1532 transport->connect (address);
1535 static void
1536 transport_close1 (void)
1538 transport->close1 ();
1541 static void
1542 transport_close2 (void)
1544 transport->close2 ();
1547 static int
1548 transport_send (void *buf, int len)
1550 return transport->send (buf, len);
1553 static int
1554 transport_recv (void *buf, int len)
1556 return transport->recv (buf, len);
1559 gboolean
1560 mono_debugger_agent_transport_handshake (void)
1562 return transport_handshake ();
1565 static gboolean
1566 transport_handshake (void)
1568 char handshake_msg [128];
1569 guint8 buf [128];
1570 int res;
1572 disconnected = TRUE;
1574 /* Write handshake message */
1575 sprintf (handshake_msg, "DWP-Handshake");
1577 do {
1578 res = transport_send (handshake_msg, strlen (handshake_msg));
1579 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1581 g_assert (res != -1);
1583 /* Read answer */
1584 res = transport_recv (buf, strlen (handshake_msg));
1585 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1586 g_printerr ("debugger-agent: DWP handshake failed.\n");
1587 return FALSE;
1591 * To support older clients, the client sends its protocol version after connecting
1592 * using a command. Until that is received, default to our protocol version.
1594 major_version = MAJOR_VERSION;
1595 minor_version = MINOR_VERSION;
1596 protocol_version_set = FALSE;
1598 #ifndef DISABLE_SOCKET_TRANSPORT
1599 // FIXME: Move this somewhere else
1601 * Set TCP_NODELAY on the socket so the client receives events/command
1602 * results immediately.
1604 if (conn_fd) {
1605 int flag = 1;
1606 int result = setsockopt (conn_fd,
1607 IPPROTO_TCP,
1608 TCP_NODELAY,
1609 (char *) &flag,
1610 sizeof(int));
1611 g_assert (result >= 0);
1614 set_keepalive ();
1615 #endif
1617 disconnected = FALSE;
1618 return TRUE;
1621 static void
1622 stop_debugger_thread (void)
1624 if (!inited)
1625 return;
1627 transport_close1 ();
1630 * Wait for the thread to exit.
1632 * If we continue with the shutdown without waiting for it, then the client might
1633 * not receive an answer to its last command like a resume.
1635 if (!is_debugger_thread ()) {
1636 do {
1637 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1638 if (!debugger_thread_exited)
1639 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1640 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1641 } while (!debugger_thread_exited);
1643 if (debugger_thread_handle)
1644 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1647 transport_close2 ();
1650 static void
1651 start_debugger_thread (MonoError *error)
1653 MonoInternalThread *thread;
1655 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1656 return_if_nok (error);
1658 /* Is it possible for the thread to be dead alreay ? */
1659 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1660 g_assert (debugger_thread_handle);
1665 * Functions to decode protocol data
1668 static int
1669 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1671 *endbuf = buf + 1;
1672 g_assert (*endbuf <= limit);
1673 return buf [0];
1676 static int
1677 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1679 *endbuf = buf + 4;
1680 g_assert (*endbuf <= limit);
1682 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1685 static gint64
1686 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1688 guint32 high = decode_int (buf, &buf, limit);
1689 guint32 low = decode_int (buf, &buf, limit);
1691 *endbuf = buf;
1693 return ((((guint64)high) << 32) | ((guint64)low));
1696 static int
1697 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1699 return decode_int (buf, endbuf, limit);
1702 static char*
1703 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1705 int len = decode_int (buf, &buf, limit);
1706 char *s;
1708 if (len < 0) {
1709 *endbuf = buf;
1710 return NULL;
1713 s = (char *)g_malloc (len + 1);
1714 g_assert (s);
1716 memcpy (s, buf, len);
1717 s [len] = '\0';
1718 buf += len;
1719 *endbuf = buf;
1721 return s;
1725 * Functions to encode protocol data
1728 static void
1729 buffer_init (Buffer *buf, int size)
1731 buf->buf = (guint8 *)g_malloc (size);
1732 buf->p = buf->buf;
1733 buf->end = buf->buf + size;
1736 static int
1737 buffer_len (Buffer *buf)
1739 return buf->p - buf->buf;
1742 static void
1743 buffer_make_room (Buffer *buf, int size)
1745 if (buf->end - buf->p < size) {
1746 int new_size = buf->end - buf->buf + size + 32;
1747 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1748 size = buf->p - buf->buf;
1749 buf->buf = p;
1750 buf->p = p + size;
1751 buf->end = buf->buf + new_size;
1755 static void
1756 buffer_add_byte (Buffer *buf, guint8 val)
1758 buffer_make_room (buf, 1);
1759 buf->p [0] = val;
1760 buf->p++;
1763 static void
1764 buffer_add_short (Buffer *buf, guint32 val)
1766 buffer_make_room (buf, 2);
1767 buf->p [0] = (val >> 8) & 0xff;
1768 buf->p [1] = (val >> 0) & 0xff;
1769 buf->p += 2;
1772 static void
1773 buffer_add_int (Buffer *buf, guint32 val)
1775 buffer_make_room (buf, 4);
1776 buf->p [0] = (val >> 24) & 0xff;
1777 buf->p [1] = (val >> 16) & 0xff;
1778 buf->p [2] = (val >> 8) & 0xff;
1779 buf->p [3] = (val >> 0) & 0xff;
1780 buf->p += 4;
1783 static void
1784 buffer_add_long (Buffer *buf, guint64 l)
1786 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1787 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1790 static void
1791 buffer_add_id (Buffer *buf, int id)
1793 buffer_add_int (buf, (guint64)id);
1796 static void
1797 buffer_add_data (Buffer *buf, guint8 *data, int len)
1799 buffer_make_room (buf, len);
1800 memcpy (buf->p, data, len);
1801 buf->p += len;
1804 static void
1805 buffer_add_string (Buffer *buf, const char *str)
1807 int len;
1809 if (str == NULL) {
1810 buffer_add_int (buf, 0);
1811 } else {
1812 len = strlen (str);
1813 buffer_add_int (buf, len);
1814 buffer_add_data (buf, (guint8*)str, len);
1818 static void
1819 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1821 buffer_add_int (buf, arr_len);
1822 buffer_add_data (buf, bytes, arr_len);
1825 static void
1826 buffer_add_buffer (Buffer *buf, Buffer *data)
1828 buffer_add_data (buf, data->buf, buffer_len (data));
1831 static void
1832 buffer_free (Buffer *buf)
1834 g_free (buf->buf);
1837 static gboolean
1838 send_packet (int command_set, int command, Buffer *data)
1840 Buffer buf;
1841 int len, id;
1842 gboolean res;
1844 id = mono_atomic_inc_i32 (&packet_id);
1846 len = data->p - data->buf + 11;
1847 buffer_init (&buf, len);
1848 buffer_add_int (&buf, len);
1849 buffer_add_int (&buf, id);
1850 buffer_add_byte (&buf, 0); /* flags */
1851 buffer_add_byte (&buf, command_set);
1852 buffer_add_byte (&buf, command);
1853 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1855 res = transport_send (buf.buf, len);
1857 buffer_free (&buf);
1859 return res;
1862 static gboolean
1863 send_reply_packets (int npackets, ReplyPacket *packets)
1865 Buffer buf;
1866 int i, len;
1867 gboolean res;
1869 len = 0;
1870 for (i = 0; i < npackets; ++i)
1871 len += buffer_len (packets [i].data) + 11;
1872 buffer_init (&buf, len);
1873 for (i = 0; i < npackets; ++i) {
1874 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1875 buffer_add_int (&buf, packets [i].id);
1876 buffer_add_byte (&buf, 0x80); /* flags */
1877 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1878 buffer_add_byte (&buf, packets [i].error);
1879 buffer_add_buffer (&buf, packets [i].data);
1882 res = transport_send (buf.buf, len);
1884 buffer_free (&buf);
1886 return res;
1889 static gboolean
1890 send_reply_packet (int id, int error, Buffer *data)
1892 ReplyPacket packet;
1894 memset (&packet, 0, sizeof (packet));
1895 packet.id = id;
1896 packet.error = error;
1897 packet.data = data;
1899 return send_reply_packets (1, &packet);
1902 static void
1903 send_buffered_reply_packets (void)
1905 int i;
1907 send_reply_packets (nreply_packets, reply_packets);
1908 for (i = 0; i < nreply_packets; ++i)
1909 buffer_free (reply_packets [i].data);
1910 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1911 nreply_packets = 0;
1914 static void
1915 buffer_reply_packet (int id, int error, Buffer *data)
1917 ReplyPacket *p;
1919 if (nreply_packets == 128)
1920 send_buffered_reply_packets ();
1922 p = &reply_packets [nreply_packets];
1923 p->id = id;
1924 p->error = error;
1925 p->data = g_new0 (Buffer, 1);
1926 buffer_init (p->data, buffer_len (data));
1927 buffer_add_buffer (p->data, data);
1928 nreply_packets ++;
1932 /* Maps objid -> ObjRef */
1933 /* Protected by the loader lock */
1934 static GHashTable *objrefs;
1935 /* Protected by the loader lock */
1936 static GHashTable *obj_to_objref;
1937 /* Protected by the dbg lock */
1938 static MonoGHashTable *suspended_objs;
1942 static void
1943 objrefs_init (void)
1945 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1946 obj_to_objref = g_hash_table_new (NULL, NULL);
1947 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");
1950 static void
1951 objrefs_cleanup (void)
1953 g_hash_table_destroy (objrefs);
1954 objrefs = NULL;
1958 * Return an ObjRef for OBJ.
1960 static ObjRef*
1961 get_objref (MonoObject *obj)
1963 ObjRef *ref;
1964 GSList *reflist = NULL, *l;
1965 int hash = 0;
1967 if (obj == NULL)
1968 return NULL;
1970 if (suspend_count) {
1972 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1974 dbg_lock ();
1975 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
1976 dbg_unlock ();
1979 mono_loader_lock ();
1981 /* FIXME: The tables can grow indefinitely */
1983 if (mono_gc_is_moving ()) {
1985 * Objects can move, so use a hash table mapping hash codes to lists of
1986 * ObjRef structures.
1988 hash = mono_object_hash_internal (obj);
1990 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1991 for (l = reflist; l; l = l->next) {
1992 ref = (ObjRef *)l->data;
1993 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1994 mono_loader_unlock ();
1995 return ref;
1998 } else {
1999 /* Use a hash table with masked pointers to internalize object references */
2000 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2001 /* ref might refer to a different object with the same addr which was GCd */
2002 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2003 mono_loader_unlock ();
2004 return ref;
2008 ref = g_new0 (ObjRef, 1);
2009 ref->id = mono_atomic_inc_i32 (&objref_id);
2010 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2012 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2014 if (mono_gc_is_moving ()) {
2015 reflist = g_slist_append (reflist, ref);
2016 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2017 } else {
2018 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2021 mono_loader_unlock ();
2023 return ref;
2026 static gboolean
2027 true_pred (gpointer key, gpointer value, gpointer user_data)
2029 return TRUE;
2032 static void
2033 clear_suspended_objs (void)
2035 dbg_lock ();
2036 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2037 dbg_unlock ();
2040 static int
2041 get_objid (MonoObject *obj)
2043 if (!obj)
2044 return 0;
2045 else
2046 return get_objref (obj)->id;
2050 * Set OBJ to the object identified by OBJID.
2051 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2052 * collected.
2054 static ErrorCode
2055 get_object_allow_null (int objid, MonoObject **obj)
2057 ObjRef *ref;
2059 if (objid == 0) {
2060 *obj = NULL;
2061 return ERR_NONE;
2064 if (!objrefs)
2065 return ERR_INVALID_OBJECT;
2067 mono_loader_lock ();
2069 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2071 if (ref) {
2072 *obj = mono_gchandle_get_target_internal (ref->handle);
2073 mono_loader_unlock ();
2074 if (!(*obj))
2075 return ERR_INVALID_OBJECT;
2076 return ERR_NONE;
2077 } else {
2078 mono_loader_unlock ();
2079 return ERR_INVALID_OBJECT;
2083 static ErrorCode
2084 get_object (int objid, MonoObject **obj)
2086 ErrorCode err = get_object_allow_null (objid, obj);
2088 if (err != ERR_NONE)
2089 return err;
2090 if (!(*obj))
2091 return ERR_INVALID_OBJECT;
2092 return ERR_NONE;
2095 static int
2096 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2098 return decode_id (buf, endbuf, limit);
2101 static void
2102 buffer_add_objid (Buffer *buf, MonoObject *o)
2104 buffer_add_id (buf, get_objid (o));
2108 * IDS
2111 typedef enum {
2112 ID_ASSEMBLY = 0,
2113 ID_MODULE = 1,
2114 ID_TYPE = 2,
2115 ID_METHOD = 3,
2116 ID_FIELD = 4,
2117 ID_DOMAIN = 5,
2118 ID_PROPERTY = 6,
2119 ID_NUM
2120 } IdType;
2123 * Represents a runtime structure accessible to the debugger client
2125 typedef struct {
2126 /* Unique id used in the wire protocol */
2127 int id;
2128 /* Domain of the runtime structure, NULL if the domain was unloaded */
2129 MonoDomain *domain;
2130 union {
2131 gpointer val;
2132 MonoClass *klass;
2133 MonoMethod *method;
2134 MonoImage *image;
2135 MonoAssembly *assembly;
2136 MonoClassField *field;
2137 MonoDomain *domain;
2138 MonoProperty *property;
2139 } data;
2140 } Id;
2142 typedef struct {
2143 /* Maps runtime structure -> Id */
2144 /* Protected by the dbg lock */
2145 GHashTable *val_to_id [ID_NUM];
2146 /* Classes whose class load event has been sent */
2147 /* Protected by the loader lock */
2148 GHashTable *loaded_classes;
2149 /* Maps MonoClass->GPtrArray of file names */
2150 GHashTable *source_files;
2151 /* Maps source file basename -> GSList of classes */
2152 GHashTable *source_file_to_class;
2153 /* Same with ignore-case */
2154 GHashTable *source_file_to_class_ignorecase;
2155 } AgentDomainInfo;
2157 /* Maps id -> Id */
2158 /* Protected by the dbg lock */
2159 static GPtrArray *ids [ID_NUM];
2161 static void
2162 ids_init (void)
2164 int i;
2166 for (i = 0; i < ID_NUM; ++i)
2167 ids [i] = g_ptr_array_new ();
2170 static void
2171 ids_cleanup (void)
2173 int i, j;
2175 for (i = 0; i < ID_NUM; ++i) {
2176 if (ids [i]) {
2177 for (j = 0; j < ids [i]->len; ++j)
2178 g_free (g_ptr_array_index (ids [i], j));
2179 g_ptr_array_free (ids [i], TRUE);
2181 ids [i] = NULL;
2185 static void
2186 debugger_agent_free_domain_info (MonoDomain *domain)
2188 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2189 int i, j;
2190 GHashTableIter iter;
2191 GPtrArray *file_names;
2192 char *basename;
2193 GSList *l;
2195 if (info) {
2196 for (i = 0; i < ID_NUM; ++i)
2197 g_hash_table_destroy (info->val_to_id [i]);
2198 g_hash_table_destroy (info->loaded_classes);
2200 g_hash_table_iter_init (&iter, info->source_files);
2201 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2202 for (i = 0; i < file_names->len; ++i)
2203 g_free (g_ptr_array_index (file_names, i));
2204 g_ptr_array_free (file_names, TRUE);
2207 g_hash_table_iter_init (&iter, info->source_file_to_class);
2208 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2209 g_free (basename);
2210 g_slist_free (l);
2213 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2214 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2215 g_free (basename);
2216 g_slist_free (l);
2219 g_free (info);
2222 domain_jit_info (domain)->agent_info = NULL;
2224 /* Clear ids referencing structures in the domain */
2225 dbg_lock ();
2226 for (i = 0; i < ID_NUM; ++i) {
2227 if (ids [i]) {
2228 for (j = 0; j < ids [i]->len; ++j) {
2229 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2230 if (id->domain == domain)
2231 id->domain = NULL;
2235 dbg_unlock ();
2237 mono_de_domain_remove (domain);
2240 static AgentDomainInfo*
2241 get_agent_domain_info (MonoDomain *domain)
2243 AgentDomainInfo *info = NULL;
2244 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2246 info = (AgentDomainInfo *)jit_info->agent_info;
2248 if (info) {
2249 mono_memory_read_barrier ();
2250 return info;
2253 info = g_new0 (AgentDomainInfo, 1);
2254 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2255 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2256 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2257 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2259 mono_memory_write_barrier ();
2261 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2263 if (other_info != NULL) {
2264 g_hash_table_destroy (info->loaded_classes);
2265 g_hash_table_destroy (info->source_files);
2266 g_hash_table_destroy (info->source_file_to_class);
2267 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2268 g_free (info);
2271 return (AgentDomainInfo *)jit_info->agent_info;
2274 static int
2275 get_id (MonoDomain *domain, IdType type, gpointer val)
2277 Id *id;
2278 AgentDomainInfo *info;
2280 if (val == NULL)
2281 return 0;
2283 info = get_agent_domain_info (domain);
2285 dbg_lock ();
2287 if (info->val_to_id [type] == NULL)
2288 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2290 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2291 if (id) {
2292 dbg_unlock ();
2293 return id->id;
2296 id = g_new0 (Id, 1);
2297 /* Reserve id 0 */
2298 id->id = ids [type]->len + 1;
2299 id->domain = domain;
2300 id->data.val = val;
2302 g_hash_table_insert (info->val_to_id [type], val, id);
2303 g_ptr_array_add (ids [type], id);
2305 dbg_unlock ();
2307 return id->id;
2310 static gpointer
2311 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2313 Id *res;
2315 int id = decode_id (buf, endbuf, limit);
2317 *err = ERR_NONE;
2318 if (domain)
2319 *domain = NULL;
2321 if (id == 0)
2322 return NULL;
2324 // FIXME: error handling
2325 dbg_lock ();
2326 g_assert (id > 0 && id <= ids [type]->len);
2328 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2329 dbg_unlock ();
2331 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2332 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2333 *err = ERR_UNLOADED;
2334 return NULL;
2337 if (domain)
2338 *domain = res->domain;
2340 return res->data.val;
2343 static int
2344 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2346 int id = get_id (domain, type, val);
2348 buffer_add_id (buf, id);
2349 return id;
2352 static MonoClass*
2353 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2355 MonoClass *klass;
2357 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2358 if (G_UNLIKELY (log_level >= 2) && klass) {
2359 char *s;
2361 s = mono_type_full_name (m_class_get_byval_arg (klass));
2362 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2363 g_free (s);
2365 return klass;
2368 static MonoAssembly*
2369 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2371 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2374 static MonoImage*
2375 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2377 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2380 static MonoMethod*
2381 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2383 MonoMethod *m;
2385 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2386 if (G_UNLIKELY (log_level >= 2) && m) {
2387 char *s;
2389 s = mono_method_full_name (m, TRUE);
2390 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2391 g_free (s);
2393 return m;
2396 static MonoClassField*
2397 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2399 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2402 static MonoDomain*
2403 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2405 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2408 static MonoProperty*
2409 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2411 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2414 static void
2415 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2417 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2418 if (G_UNLIKELY (log_level >= 2) && klass) {
2419 char *s;
2421 s = mono_type_full_name (m_class_get_byval_arg (klass));
2422 if (is_debugger_thread ())
2423 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2424 else
2425 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2426 g_free (s);
2430 static void
2431 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2433 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2434 if (G_UNLIKELY (log_level >= 2) && method) {
2435 char *s;
2437 s = mono_method_full_name (method, 1);
2438 if (is_debugger_thread ())
2439 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2440 else
2441 DEBUG_PRINTF (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2442 g_free (s);
2446 static void
2447 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2449 int id;
2451 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2452 if (G_UNLIKELY (log_level >= 2) && assembly)
2453 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2456 static void
2457 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2459 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2462 static void
2463 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2465 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2468 static void
2469 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2471 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2474 static void
2475 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2477 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2480 static void invoke_method (void);
2483 * SUSPEND/RESUME
2486 static MonoJitInfo*
2487 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2489 MonoJitInfo *ji;
2491 if (out_ip)
2492 *out_ip = ip;
2494 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2495 if (!ji) {
2496 /* Could be an interpreter method */
2498 MonoLMF *lmf = mono_get_lmf ();
2499 MonoInterpFrameHandle *frame;
2501 g_assert (((gsize)lmf->previous_lmf) & 2);
2502 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2504 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2505 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2506 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2507 if (domain)
2508 *domain = mono_domain_get ();
2509 if (out_ip)
2510 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2512 return ji;
2516 * save_thread_context:
2518 * Set CTX as the current threads context which is used for computing stack traces.
2519 * This function is signal-safe.
2521 static void
2522 save_thread_context (MonoContext *ctx)
2524 DebuggerTlsData *tls;
2526 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2527 g_assert (tls);
2529 if (ctx)
2530 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2531 else
2532 mono_thread_state_init_from_current (&tls->context);
2535 /* Number of threads suspended */
2537 * If this is equal to the size of thread_to_tls, the runtime is considered
2538 * suspended.
2540 static gint32 threads_suspend_count;
2542 static MonoCoopMutex suspend_mutex;
2544 /* Cond variable used to wait for suspend_count becoming 0 */
2545 static MonoCoopCond suspend_cond;
2547 /* Semaphore used to wait for a thread becoming suspended */
2548 static MonoCoopSem suspend_sem;
2550 static void
2551 suspend_init (void)
2553 mono_coop_mutex_init (&suspend_mutex);
2554 mono_coop_cond_init (&suspend_cond);
2555 mono_coop_sem_init (&suspend_sem, 0);
2558 typedef struct
2560 StackFrameInfo last_frame;
2561 gboolean last_frame_set;
2562 MonoContext ctx;
2563 gpointer lmf;
2564 MonoDomain *domain;
2565 } GetLastFrameUserData;
2567 static gboolean
2568 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2570 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2572 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2573 return FALSE;
2575 if (!data->last_frame_set) {
2576 /* Store the last frame */
2577 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2578 data->last_frame_set = TRUE;
2579 return FALSE;
2580 } else {
2581 /* Store the context/lmf for the frame above the last frame */
2582 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2583 data->lmf = info->lmf;
2584 data->domain = info->domain;
2585 return TRUE;
2589 static void
2590 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2592 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2594 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2595 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2596 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2597 to->valid = TRUE;
2601 * thread_interrupt:
2603 * Process interruption of a thread. This should be signal safe.
2605 * This always runs in the debugger thread.
2607 static void
2608 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2610 gpointer ip;
2611 MonoNativeThreadId tid;
2613 g_assert (info);
2615 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2616 tid = mono_thread_info_get_tid (info);
2618 // FIXME: Races when the thread leaves managed code before hitting a single step
2619 // event.
2621 if (ji && !ji->is_trampoline) {
2622 /* Running managed code, will be suspended by the single step code */
2623 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2624 } else {
2626 * Running native code, will be suspended when it returns to/enters
2627 * managed code. Treat it as already suspended.
2628 * This might interrupt the code in mono_de_process_single_step (), we use the
2629 * tls->suspending flag to avoid races when that happens.
2631 if (!tls->suspended && !tls->suspending) {
2632 GetLastFrameUserData data;
2634 // FIXME: printf is not signal safe, but this is only used during
2635 // debugger debugging
2636 if (ip)
2637 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2638 //save_thread_context (&ctx);
2640 if (!tls->thread)
2641 /* Already terminated */
2642 return;
2645 * We are in a difficult position: we want to be able to provide stack
2646 * traces for this thread, but we can't use the current ctx+lmf, since
2647 * the thread is still running, so it might return to managed code,
2648 * making these invalid.
2649 * So we start a stack walk and save the first frame, along with the
2650 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2651 * suspended when it returns to managed code, so the parent's ctx should
2652 * remain valid.
2654 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2656 data.last_frame_set = FALSE;
2657 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2658 if (data.last_frame_set) {
2659 gpointer jit_tls = tls->thread->thread_info->jit_data;
2661 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2663 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2665 * Store the current lmf instead of the parent one, since that
2666 * contains the interp exit data.
2668 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2671 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2672 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2673 } else {
2674 tls->async_state.valid = FALSE;
2677 mono_memory_barrier ();
2679 tls->suspended = TRUE;
2680 mono_coop_sem_post (&suspend_sem);
2686 * reset_native_thread_suspend_state:
2688 * Reset the suspended flag and state on native threads
2690 static void
2691 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2693 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2695 if (!tls->really_suspended && tls->suspended) {
2696 tls->suspended = FALSE;
2698 * The thread might still be running if it was executing native code, so the state won't be invalided by
2699 * suspend_current ().
2701 tls->context.valid = FALSE;
2702 tls->async_state.valid = FALSE;
2703 invalidate_frames (tls);
2707 typedef struct {
2708 DebuggerTlsData *tls;
2709 gboolean valid_info;
2710 } InterruptData;
2712 static SuspendThreadResult
2713 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2715 InterruptData *data = (InterruptData *)user_data;
2716 MonoJitInfo *ji;
2718 data->valid_info = TRUE;
2719 MonoDomain *domain = (MonoDomain *) mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN];
2720 if (!domain) {
2721 /* not attached */
2722 ji = NULL;
2723 } else {
2724 ji = mono_jit_info_table_find_internal ( domain, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx), TRUE, TRUE);
2727 /* This is signal safe */
2728 thread_interrupt (data->tls, info, ji);
2729 return MonoResumeThread;
2733 * notify_thread:
2735 * Notify a thread that it needs to suspend.
2737 static void
2738 notify_thread (gpointer key, gpointer value, gpointer user_data)
2740 MonoInternalThread *thread = (MonoInternalThread *)key;
2741 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2742 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2744 if (mono_thread_internal_is_current (thread) || tls->terminated)
2745 return;
2747 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2749 /* This is _not_ equivalent to mono_thread_internal_abort () */
2750 InterruptData interrupt_data = { 0 };
2751 interrupt_data.tls = tls;
2753 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2754 if (!interrupt_data.valid_info) {
2755 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2757 * Attached thread which died without detaching.
2759 tls->terminated = TRUE;
2763 static void
2764 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2766 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2767 MonoJitInfo *ji;
2768 MonoMethod *method;
2770 if (mono_loader_lock_is_owned_by_self ()) {
2772 * Shortcut for the check in suspend_current (). This speeds up processing
2773 * when executing long running code inside the loader lock, i.e. assembly load
2774 * hooks.
2776 return;
2779 if (is_debugger_thread ())
2780 return;
2782 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2783 if (suspend_count - tls->resume_count > 0)
2784 tls->suspending = TRUE;
2786 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2788 if (suspend_count - tls->resume_count == 0) {
2790 * We are executing a single threaded invoke but the single step for
2791 * suspending is still active.
2792 * FIXME: This slows down single threaded invokes.
2794 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2795 return;
2798 ji = get_top_method_ji (ip, NULL, NULL);
2799 g_assert (ji);
2800 /* Can't suspend in these methods */
2801 method = jinfo_get_method (ji);
2802 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2803 return;
2805 save_thread_context (ctx);
2807 suspend_current ();
2811 /* Conditionally call process_suspend depending oh the current state */
2812 static gboolean
2813 try_process_suspend (void *the_tls, MonoContext *ctx)
2815 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2817 if (suspend_count > 0) {
2818 /* Fastpath during invokes, see in process_suspend () */
2819 if (suspend_count - tls->resume_count == 0)
2820 return FALSE;
2821 if (tls->invoke)
2822 return FALSE;
2823 process_suspend (tls, ctx);
2824 return TRUE;
2826 return FALSE;
2830 * suspend_vm:
2832 * Increase the suspend count of the VM. While the suspend count is greater
2833 * than 0, runtime threads are suspended at certain points during execution.
2835 static void
2836 suspend_vm (void)
2838 gboolean tp_suspend = FALSE;
2839 mono_loader_lock ();
2841 mono_coop_mutex_lock (&suspend_mutex);
2843 suspend_count ++;
2845 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2847 if (suspend_count == 1) {
2848 // FIXME: Is it safe to call this inside the lock ?
2849 mono_de_start_single_stepping ();
2850 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2853 mono_coop_mutex_unlock (&suspend_mutex);
2855 if (suspend_count == 1)
2857 * Suspend creation of new threadpool threads, since they cannot run
2859 tp_suspend = TRUE;
2860 mono_loader_unlock ();
2862 #ifndef ENABLE_NETCORE
2863 if (tp_suspend)
2864 mono_threadpool_suspend ();
2865 #endif
2869 * resume_vm:
2871 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2872 * are resumed.
2874 static void
2875 resume_vm (void)
2877 g_assert (is_debugger_thread ());
2878 gboolean tp_resume = FALSE;
2880 mono_loader_lock ();
2882 mono_coop_mutex_lock (&suspend_mutex);
2884 g_assert (suspend_count > 0);
2885 suspend_count --;
2887 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2889 if (suspend_count == 0) {
2890 // FIXME: Is it safe to call this inside the lock ?
2891 mono_de_stop_single_stepping ();
2892 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2895 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2896 mono_coop_cond_broadcast (&suspend_cond);
2898 mono_coop_mutex_unlock (&suspend_mutex);
2899 //g_assert (err == 0);
2901 if (suspend_count == 0)
2902 tp_resume = TRUE;
2903 mono_loader_unlock ();
2905 #ifndef ENABLE_NETCORE
2906 if (tp_resume)
2907 mono_threadpool_resume ();
2908 #endif
2912 * resume_thread:
2914 * Resume just one thread.
2916 static void
2917 resume_thread (MonoInternalThread *thread)
2919 DebuggerTlsData *tls;
2921 g_assert (is_debugger_thread ());
2923 mono_loader_lock ();
2925 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2926 g_assert (tls);
2928 mono_coop_mutex_lock (&suspend_mutex);
2930 g_assert (suspend_count > 0);
2932 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2934 tls->resume_count += suspend_count;
2937 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2938 * but only the one whose resume_count field is > 0 will be resumed.
2940 mono_coop_cond_broadcast (&suspend_cond);
2942 mono_coop_mutex_unlock (&suspend_mutex);
2943 //g_assert (err == 0);
2945 mono_loader_unlock ();
2948 static void
2949 free_frames (StackFrame **frames, int nframes)
2951 int i;
2953 for (i = 0; i < nframes; ++i) {
2954 if (frames [i]->jit)
2955 mono_debug_free_method_jit_info (frames [i]->jit);
2956 g_free (frames [i]);
2958 g_free (frames);
2961 static void
2962 invalidate_frames (DebuggerTlsData *tls)
2964 mono_loader_lock ();
2966 if (!tls)
2967 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2968 g_assert (tls);
2970 free_frames (tls->frames, tls->frame_count);
2971 tls->frame_count = 0;
2972 tls->frames = NULL;
2974 free_frames (tls->restore_frames, tls->restore_frame_count);
2975 tls->restore_frame_count = 0;
2976 tls->restore_frames = NULL;
2978 mono_loader_unlock ();
2982 * suspend_current:
2984 * Suspend the current thread until the runtime is resumed. If the thread has a
2985 * pending invoke, then the invoke is executed before this function returns.
2987 static void
2988 suspend_current (void)
2990 DebuggerTlsData *tls;
2992 g_assert (!is_debugger_thread ());
2994 if (mono_loader_lock_is_owned_by_self ()) {
2996 * If we own the loader mutex, can't suspend until we release it, since the
2997 * whole runtime can deadlock otherwise.
2999 return;
3002 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3003 g_assert (tls);
3005 gboolean do_resume = FALSE;
3006 while (!do_resume) {
3007 mono_coop_mutex_lock (&suspend_mutex);
3009 tls->suspending = FALSE;
3010 tls->really_suspended = TRUE;
3012 if (!tls->suspended) {
3013 tls->suspended = TRUE;
3014 mono_coop_sem_post (&suspend_sem);
3017 mono_debugger_log_suspend (tls);
3018 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3020 while (suspend_count - tls->resume_count > 0) {
3021 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
3024 tls->suspended = FALSE;
3025 tls->really_suspended = FALSE;
3027 threads_suspend_count --;
3029 mono_coop_mutex_unlock (&suspend_mutex);
3031 mono_debugger_log_resume (tls);
3032 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3034 if (tls->pending_invoke) {
3035 /* Save the original context */
3036 tls->pending_invoke->has_ctx = TRUE;
3037 tls->pending_invoke->ctx = tls->context.ctx;
3039 invoke_method ();
3041 /* Have to suspend again */
3042 } else {
3043 do_resume = TRUE;
3047 /* The frame info becomes invalid after a resume */
3048 tls->context.valid = FALSE;
3049 tls->async_state.valid = FALSE;
3050 invalidate_frames (tls);
3051 mono_stopwatch_start (&tls->step_time);
3054 static void
3055 count_thread (gpointer key, gpointer value, gpointer user_data)
3057 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3059 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3060 *(int*)user_data = *(int*)user_data + 1;
3063 static int
3064 count_threads_to_wait_for (void)
3066 int count = 0;
3068 mono_loader_lock ();
3069 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3070 mono_loader_unlock ();
3072 return count;
3076 * wait_for_suspend:
3078 * Wait until the runtime is completely suspended.
3080 static void
3081 wait_for_suspend (void)
3083 int nthreads, nwait, err;
3084 gboolean waited = FALSE;
3086 // FIXME: Threads starting/stopping ?
3087 mono_loader_lock ();
3088 nthreads = mono_g_hash_table_size (thread_to_tls);
3089 mono_loader_unlock ();
3091 while (TRUE) {
3092 nwait = count_threads_to_wait_for ();
3093 if (nwait) {
3094 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3095 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3096 g_assert (err == 0);
3097 waited = TRUE;
3098 } else {
3099 break;
3103 if (waited)
3104 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3108 * is_suspended:
3110 * Return whenever the runtime is suspended.
3112 static gboolean
3113 is_suspended (void)
3115 return count_threads_to_wait_for () == 0;
3118 static void
3119 no_seq_points_found (MonoMethod *method, int offset)
3122 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3124 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3127 static int
3128 calc_il_offset (MonoDomain *domain, MonoMethod *method, int native_offset, gboolean is_top_frame)
3130 int ret = -1;
3131 if (is_top_frame) {
3132 SeqPoint sp;
3133 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3134 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
3135 ret = sp.il_offset;
3137 if (ret == -1)
3138 ret = mono_debug_il_offset_from_address (method, domain, native_offset);
3139 return ret;
3142 typedef struct {
3143 DebuggerTlsData *tls;
3144 GSList *frames;
3145 gboolean set_debugger_flag;
3146 } ComputeFramesUserData;
3148 static gboolean
3149 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3151 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3152 StackFrame *frame;
3153 MonoMethod *method, *actual_method, *api_method;
3154 int flags = 0;
3156 mono_loader_lock ();
3157 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3158 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3159 /* Mark the last frame as an invoke frame */
3160 if (ud->frames)
3161 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3162 else
3163 ud->set_debugger_flag = TRUE;
3165 mono_loader_unlock ();
3166 return FALSE;
3169 if (info->ji)
3170 method = jinfo_get_method (info->ji);
3171 else
3172 method = info->method;
3173 actual_method = info->actual_method;
3174 api_method = method;
3176 if (!method) {
3177 mono_loader_unlock ();
3178 return FALSE;
3181 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3182 mono_loader_unlock ();
3183 return FALSE;
3186 if (info->il_offset == -1) {
3187 info->il_offset = calc_il_offset (info->domain, method, info->native_offset, ud->frames == NULL);
3190 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);
3192 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3193 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3194 /* Older clients can't handle this flag */
3195 mono_loader_unlock ();
3196 return FALSE;
3198 api_method = mono_marshal_method_from_wrapper (method);
3199 if (!api_method) {
3200 mono_loader_unlock ();
3201 return FALSE;
3203 actual_method = api_method;
3204 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3207 if (ud->set_debugger_flag) {
3208 g_assert (g_slist_length (ud->frames) == 0);
3209 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3210 ud->set_debugger_flag = FALSE;
3213 frame = g_new0 (StackFrame, 1);
3214 frame->de.ji = info->ji;
3215 frame->de.domain = info->domain;
3216 frame->de.method = method;
3217 frame->de.native_offset = info->native_offset;
3219 frame->actual_method = actual_method;
3220 frame->api_method = api_method;
3221 frame->il_offset = info->il_offset;
3222 frame->flags = flags;
3223 frame->interp_frame = info->interp_frame;
3224 frame->frame_addr = info->frame_addr;
3225 if (info->reg_locations)
3226 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3227 if (ctx) {
3228 frame->ctx = *ctx;
3229 frame->has_ctx = TRUE;
3232 ud->frames = g_slist_append (ud->frames, frame);
3234 mono_loader_unlock ();
3235 return FALSE;
3238 static gint32 isFixedSizeArray (MonoClassField *f)
3240 ERROR_DECL (error);
3241 if (!CHECK_PROTOCOL_VERSION (2, 53) || f->type->type != MONO_TYPE_VALUETYPE) {
3242 return 1;
3244 MonoCustomAttrInfo *cinfo;
3245 MonoCustomAttrEntry *attr;
3246 int aindex;
3247 gint32 ret = 1;
3248 cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error);
3249 goto_if_nok (error, leave);
3250 attr = NULL;
3251 if (cinfo) {
3252 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
3253 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
3254 MonoClass *fixed_size_class = mono_class_try_get_fixed_buffer_class ();
3255 if (fixed_size_class != NULL && mono_class_has_parent (ctor_class, fixed_size_class)) {
3256 attr = &cinfo->attrs [aindex];
3257 gpointer *typed_args, *named_args;
3258 CattrNamedArg *arginfo;
3259 int num_named_args;
3261 mono_reflection_create_custom_attr_data_args_noalloc (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size,
3262 &typed_args, &named_args, &num_named_args, &arginfo, error);
3263 if (!is_ok (error)) {
3264 ret = 0;
3265 goto leave;
3267 ret = *(gint32*)typed_args [1];
3268 g_free (typed_args [1]);
3269 g_free (typed_args);
3270 g_free (named_args);
3271 g_free (arginfo);
3272 return ret;
3276 leave:
3277 mono_error_cleanup (error);
3278 return ret;
3281 static gboolean
3282 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3284 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3287 * 'tls->filter_ctx' is the location of the throw site.
3289 * mono_walk_stack() will never actually hit the throw site, but unwind
3290 * directly from the filter to the call site; we abort stack unwinding here
3291 * once this happens and resume from the throw site.
3293 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3294 return TRUE;
3296 return process_frame (info, ctx, user_data);
3300 * Return a malloc-ed list of StackFrame structures.
3302 static StackFrame**
3303 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3305 ComputeFramesUserData user_data;
3306 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3307 StackFrame **res;
3308 int i, nframes;
3309 GSList *l;
3311 user_data.tls = tls;
3312 user_data.frames = NULL;
3314 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3316 nframes = g_slist_length (user_data.frames);
3317 res = g_new0 (StackFrame*, nframes);
3318 l = user_data.frames;
3319 for (i = 0; i < nframes; ++i) {
3320 res [i] = (StackFrame *)l->data;
3321 l = l->next;
3323 *out_nframes = nframes;
3325 return res;
3328 static void
3329 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3331 ComputeFramesUserData user_data;
3332 GSList *tmp;
3333 int i, findex, new_frame_count;
3334 StackFrame **new_frames, *f;
3335 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3337 // FIXME: Locking on tls
3338 if (tls->frames && tls->frames_up_to_date && !force_update)
3339 return;
3341 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3343 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3344 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
3345 new_frames = compute_frame_info_from (thread, tls, &tls->restore_state, &new_frame_count);
3346 invalidate_frames (tls);
3348 tls->frames = new_frames;
3349 tls->frame_count = new_frame_count;
3350 tls->frames_up_to_date = TRUE;
3351 return;
3355 user_data.tls = tls;
3356 user_data.frames = NULL;
3357 if (tls->terminated) {
3358 tls->frame_count = 0;
3359 return;
3360 } if (!tls->really_suspended && tls->async_state.valid) {
3361 /* Have to use the state saved by the signal handler */
3362 process_frame (&tls->async_last_frame, NULL, &user_data);
3363 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3364 } else if (tls->filter_state.valid) {
3366 * We are inside an exception filter.
3368 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3370 if (tls->context.valid) {
3371 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3372 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3375 * After that, we resume unwinding from the location where the exception has been thrown.
3377 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3378 } else if (tls->context.valid) {
3379 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3380 } else {
3381 // FIXME:
3382 tls->frame_count = 0;
3383 return;
3386 new_frame_count = g_slist_length (user_data.frames);
3387 new_frames = g_new0 (StackFrame*, new_frame_count);
3388 findex = 0;
3389 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3390 f = (StackFrame *)tmp->data;
3393 * Reuse the id for already existing stack frames, so invokes don't invalidate
3394 * the still valid stack frames.
3396 for (i = 0; i < tls->frame_count; ++i) {
3397 if (tls->frames [i]->frame_addr == f->frame_addr) {
3398 f->id = tls->frames [i]->id;
3399 break;
3403 if (i >= tls->frame_count)
3404 f->id = mono_atomic_inc_i32 (&frame_id);
3406 new_frames [findex ++] = f;
3409 g_slist_free (user_data.frames);
3411 invalidate_frames (tls);
3413 tls->frames = new_frames;
3414 tls->frame_count = new_frame_count;
3415 tls->frames_up_to_date = TRUE;
3417 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3418 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
3419 gboolean has_interp_resume_state = FALSE;
3420 MonoInterpFrameHandle interp_resume_frame = NULL;
3421 gpointer interp_resume_ip = 0;
3422 mini_get_interp_callbacks ()->get_resume_state (jit_data, &has_interp_resume_state, &interp_resume_frame, &interp_resume_ip);
3423 if (has_interp_resume_state && tls->frame_count > 0) {
3424 StackFrame *top_frame = tls->frames [0];
3425 if (interp_resume_frame == top_frame->interp_frame) {
3426 int native_offset = (int) ((uintptr_t) interp_resume_ip - (uintptr_t) top_frame->de.ji->code_start);
3427 top_frame->il_offset = calc_il_offset (top_frame->de.domain, top_frame->de.method, native_offset, TRUE);
3434 * GHFunc to emit an appdomain creation event
3435 * @param key Don't care
3436 * @param value A loaded appdomain
3437 * @param user_data Don't care
3439 static void
3440 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3442 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3443 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3447 * GHFunc to emit a thread start event
3448 * @param key A thread id
3449 * @param value A thread object
3450 * @param user_data Don't care
3452 static void
3453 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3455 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3456 process_profiler_event (EVENT_KIND_THREAD_START, value);
3460 * GFunc to emit an assembly load event
3461 * @param value A loaded assembly
3462 * @param user_data Don't care
3464 static void
3465 emit_assembly_load (gpointer value, gpointer user_data)
3467 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3471 * GFunc to emit a type load event
3472 * @param value A loaded type
3473 * @param user_data Don't care
3475 static void
3476 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3478 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3482 static void gc_finalizing (MonoProfiler *prof)
3484 DebuggerTlsData *tls;
3486 if (is_debugger_thread ())
3487 return;
3489 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3490 g_assert (tls);
3491 tls->gc_finalizing = TRUE;
3494 static void gc_finalized (MonoProfiler *prof)
3496 DebuggerTlsData *tls;
3498 if (is_debugger_thread ())
3499 return;
3501 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3502 g_assert (tls);
3503 tls->gc_finalizing = FALSE;
3507 static char*
3508 strdup_tolower (char *s)
3510 char *s2, *p;
3512 s2 = g_strdup (s);
3513 for (p = s2; *p; ++p)
3514 *p = tolower (*p);
3515 return s2;
3519 * Same as g_path_get_basename () but handles windows paths as well,
3520 * which can occur in .mdb files created by pdb2mdb.
3522 static char*
3523 dbg_path_get_basename (const char *filename)
3525 char *r;
3527 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3528 return g_path_get_basename (filename);
3530 /* From gpath.c */
3532 /* No separator -> filename */
3533 r = (char*)strrchr (filename, '\\');
3534 if (r == NULL)
3535 return g_strdup (filename);
3537 /* Trailing slash, remove component */
3538 if (r [1] == 0){
3539 char *copy = g_strdup (filename);
3540 copy [r-filename] = 0;
3541 r = strrchr (copy, '\\');
3543 if (r == NULL){
3544 g_free (copy);
3545 return g_strdup ("/");
3547 r = g_strdup (&r[1]);
3548 g_free (copy);
3549 return r;
3552 return g_strdup (&r[1]);
3555 static void
3556 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3558 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3559 ERROR_DECL (error);
3560 MonoCustomAttrInfo *ainfo;
3562 if (ji->dbg_attrs_inited)
3563 return;
3565 if (!hidden_klass)
3566 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3568 if (!step_through_klass)
3569 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3571 if (!non_user_klass)
3572 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3574 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3575 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3576 if (ainfo) {
3577 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3578 ji->dbg_hidden = TRUE;
3579 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3580 ji->dbg_step_through = TRUE;
3581 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3582 ji->dbg_non_user_code = TRUE;
3583 mono_custom_attrs_free (ainfo);
3586 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3587 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3588 if (ainfo) {
3589 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3590 ji->dbg_step_through = TRUE;
3591 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3592 ji->dbg_non_user_code = TRUE;
3593 mono_custom_attrs_free (ainfo);
3596 mono_memory_barrier ();
3597 ji->dbg_attrs_inited = TRUE;
3601 * EVENT HANDLING
3605 * create_event_list:
3607 * Return a list of event request ids matching EVENT, starting from REQS, which
3608 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3609 * policy.
3610 * We return request ids, instead of requests, to simplify threading, since
3611 * requests could be deleted anytime when the loader lock is not held.
3612 * LOCKING: Assumes the loader lock is held.
3614 static GSList*
3615 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3617 int i, j;
3618 GSList *events = NULL;
3620 *suspend_policy = SUSPEND_POLICY_NONE;
3622 if (!reqs)
3623 reqs = event_requests;
3625 if (!reqs)
3626 return NULL;
3627 gboolean has_everything_else = FALSE;
3628 gboolean is_new_filtered_exception = FALSE;
3629 gboolean filteredException = TRUE;
3630 gint filtered_suspend_policy = 0;
3631 gint filtered_req_id = 0;
3632 gint everything_else_suspend_policy = 0;
3633 gint everything_else_req_id = 0;
3634 gboolean is_already_filtered = FALSE;
3635 for (i = 0; i < reqs->len; ++i) {
3636 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3637 if (req->event_kind == event) {
3638 gboolean filtered = FALSE;
3640 /* Apply filters */
3641 for (j = 0; j < req->nmodifiers; ++j) {
3642 Modifier *mod = &req->modifiers [j];
3644 if (mod->kind == MOD_KIND_COUNT) {
3645 filtered = TRUE;
3646 if (mod->data.count > 0) {
3647 if (mod->data.count > 0) {
3648 mod->data.count --;
3649 if (mod->data.count == 0)
3650 filtered = FALSE;
3653 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3654 if (mod->data.thread != mono_thread_internal_current ())
3655 filtered = TRUE;
3656 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && !mod->not_filtered_feature && ei) {
3657 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3658 filtered = TRUE;
3659 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3660 filtered = TRUE;
3661 if (ei->caught && !mod->caught)
3662 filtered = TRUE;
3663 if (!ei->caught && !mod->uncaught)
3664 filtered = TRUE;
3665 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && mod->not_filtered_feature && ei) {
3666 is_new_filtered_exception = TRUE;
3667 if ((mod->data.exc_class && mod->subclasses && mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass)) ||
3668 (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)) {
3669 is_already_filtered = TRUE;
3670 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3671 filteredException = FALSE;
3672 filtered_suspend_policy = req->suspend_policy;
3673 filtered_req_id = req->id;
3676 if (!mod->data.exc_class && mod->everything_else) {
3677 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3678 has_everything_else = TRUE;
3679 everything_else_req_id = req->id;
3680 everything_else_suspend_policy = req->suspend_policy;
3683 if (!mod->data.exc_class && !mod->everything_else) {
3684 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3685 filteredException = FALSE;
3686 filtered_suspend_policy = req->suspend_policy;
3687 filtered_req_id = req->id;
3690 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3691 int k;
3692 gboolean found = FALSE;
3693 MonoAssembly **assemblies = mod->data.assemblies;
3695 if (assemblies) {
3696 for (k = 0; assemblies [k]; ++k)
3697 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3698 found = TRUE;
3700 if (!found)
3701 filtered = TRUE;
3702 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3703 gpointer iter = NULL;
3704 MonoMethod *method;
3705 MonoDebugSourceInfo *sinfo;
3706 char *s;
3707 gboolean found = FALSE;
3708 int i;
3709 GPtrArray *source_file_list;
3711 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3712 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3714 if (minfo) {
3715 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
3716 for (i = 0; i < source_file_list->len; ++i) {
3717 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3719 * Do a case-insesitive match by converting the file name to
3720 * lowercase.
3722 s = strdup_tolower (sinfo->source_file);
3723 if (g_hash_table_lookup (mod->data.source_files, s))
3724 found = TRUE;
3725 else {
3726 char *s2 = dbg_path_get_basename (sinfo->source_file);
3727 char *s3 = strdup_tolower (s2);
3729 if (g_hash_table_lookup (mod->data.source_files, s3))
3730 found = TRUE;
3731 g_free (s2);
3732 g_free (s3);
3734 g_free (s);
3736 g_ptr_array_free (source_file_list, TRUE);
3739 if (!found)
3740 filtered = TRUE;
3741 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3742 char *s;
3744 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3745 if (!g_hash_table_lookup (mod->data.type_names, s))
3746 filtered = TRUE;
3747 g_free (s);
3748 } else if (mod->kind == MOD_KIND_STEP) {
3749 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3750 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3751 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3752 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3753 filtered = TRUE;
3754 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3755 init_jit_info_dbg_attrs (ji);
3756 if (ji->dbg_hidden)
3757 filtered = TRUE;
3759 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3760 init_jit_info_dbg_attrs (ji);
3761 if (ji->dbg_step_through)
3762 filtered = TRUE;
3764 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3765 init_jit_info_dbg_attrs (ji);
3766 if (ji->dbg_non_user_code)
3767 filtered = TRUE;
3772 if (!filtered && !is_new_filtered_exception) {
3773 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3774 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3779 if (has_everything_else && !is_already_filtered) {
3780 filteredException = FALSE;
3781 filtered_suspend_policy = everything_else_suspend_policy;
3782 filtered_req_id = everything_else_req_id;
3785 if (!filteredException) {
3786 *suspend_policy = MAX (*suspend_policy, filtered_suspend_policy);
3787 events = g_slist_append (events, GINT_TO_POINTER (filtered_req_id));
3790 /* Send a VM START/DEATH event by default */
3791 if (event == EVENT_KIND_VM_START)
3792 events = g_slist_append (events, GINT_TO_POINTER (0));
3793 if (event == EVENT_KIND_VM_DEATH)
3794 events = g_slist_append (events, GINT_TO_POINTER (0));
3796 return events;
3799 static G_GNUC_UNUSED const char*
3800 event_to_string (EventKind event)
3802 switch (event) {
3803 case EVENT_KIND_VM_START: return "VM_START";
3804 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3805 case EVENT_KIND_THREAD_START: return "THREAD_START";
3806 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3807 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3808 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3809 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3810 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3811 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3812 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3813 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3814 case EVENT_KIND_STEP: return "STEP";
3815 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3816 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3817 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3818 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3819 case EVENT_KIND_USER_LOG: return "USER_LOG";
3820 case EVENT_KIND_CRASH: return "CRASH";
3821 default:
3822 g_assert_not_reached ();
3823 return "";
3828 * process_event:
3830 * Send an event to the client, suspending the vm if needed.
3831 * LOCKING: Since this can suspend the calling thread, no locks should be held
3832 * by the caller.
3833 * The EVENTS list is freed by this function.
3835 static void
3836 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3838 Buffer buf;
3839 GSList *l;
3840 MonoDomain *domain = mono_domain_get ();
3841 MonoThread *thread = NULL;
3842 MonoObject *keepalive_obj = NULL;
3843 gboolean send_success = FALSE;
3844 static int ecount;
3845 int nevents;
3847 if (!inited) {
3848 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3849 return;
3852 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3853 // FIXME: We miss those events
3854 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3855 return;
3858 if (vm_death_event_sent) {
3859 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3860 return;
3863 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3864 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3865 return;
3868 if (disconnected) {
3869 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3870 return;
3873 if (event == EVENT_KIND_KEEPALIVE)
3874 suspend_policy = SUSPEND_POLICY_NONE;
3875 else {
3876 if (events == NULL)
3877 return;
3879 if (agent_config.defer) {
3880 if (is_debugger_thread ()) {
3881 /* Don't suspend on events from the debugger thread */
3882 suspend_policy = SUSPEND_POLICY_NONE;
3884 } else {
3885 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3886 // FIXME: Send these with a NULL thread, don't suspend the current thread
3887 return;
3891 nevents = g_slist_length (events);
3892 buffer_init (&buf, 128);
3893 buffer_add_byte (&buf, suspend_policy);
3894 buffer_add_int (&buf, nevents);
3896 for (l = events; l; l = l->next) {
3897 buffer_add_byte (&buf, event); // event kind
3898 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3900 ecount ++;
3902 if (event == EVENT_KIND_VM_DEATH) {
3903 thread = NULL;
3904 } else {
3905 if (!thread)
3906 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3908 if (event == EVENT_KIND_VM_START && arg != NULL)
3909 thread = (MonoThread *)arg;
3912 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3914 switch (event) {
3915 case EVENT_KIND_THREAD_START:
3916 case EVENT_KIND_THREAD_DEATH:
3917 break;
3918 case EVENT_KIND_APPDOMAIN_CREATE:
3919 case EVENT_KIND_APPDOMAIN_UNLOAD:
3920 buffer_add_domainid (&buf, (MonoDomain *)arg);
3921 break;
3922 case EVENT_KIND_METHOD_ENTRY:
3923 case EVENT_KIND_METHOD_EXIT:
3924 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3925 break;
3926 case EVENT_KIND_ASSEMBLY_LOAD:
3927 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3928 break;
3929 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3930 DebuggerTlsData *tls;
3932 /* The domain the assembly belonged to is not equal to the current domain */
3933 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3934 g_assert (tls);
3935 g_assert (tls->domain_unloading);
3937 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3938 break;
3940 case EVENT_KIND_TYPE_LOAD:
3941 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3942 break;
3943 case EVENT_KIND_BREAKPOINT:
3944 case EVENT_KIND_STEP: {
3945 DebuggerTlsData *tls;
3946 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3947 g_assert (tls);
3948 mono_stopwatch_stop (&tls->step_time);
3949 MonoMethod *method = (MonoMethod *)arg;
3951 buffer_add_methodid (&buf, domain, method);
3952 buffer_add_long (&buf, il_offset);
3953 break;
3955 case EVENT_KIND_VM_START:
3956 buffer_add_domainid (&buf, mono_get_root_domain ());
3957 break;
3958 case EVENT_KIND_VM_DEATH:
3959 if (CHECK_PROTOCOL_VERSION (2, 27))
3960 buffer_add_int (&buf, mono_environment_exitcode_get ());
3961 break;
3962 case EVENT_KIND_CRASH: {
3963 EventInfo *ei = (EventInfo *)arg;
3964 buffer_add_long (&buf, ei->hashes->offset_free_hash);
3965 buffer_add_string (&buf, ei->dump);
3966 break;
3968 case EVENT_KIND_EXCEPTION: {
3969 EventInfo *ei = (EventInfo *)arg;
3970 buffer_add_objid (&buf, ei->exc);
3972 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3973 * later after the suspension. (#12494).
3975 keepalive_obj = ei->exc;
3976 break;
3978 case EVENT_KIND_USER_BREAK: {
3979 DebuggerTlsData *tls;
3980 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3981 g_assert (tls);
3982 mono_stopwatch_stop (&tls->step_time);
3983 break;
3985 case EVENT_KIND_USER_LOG: {
3986 EventInfo *ei = (EventInfo *)arg;
3987 buffer_add_int (&buf, ei->level);
3988 buffer_add_string (&buf, ei->category ? ei->category : "");
3989 buffer_add_string (&buf, ei->message ? ei->message : "");
3990 break;
3992 case EVENT_KIND_KEEPALIVE:
3993 suspend_policy = SUSPEND_POLICY_NONE;
3994 break;
3995 default:
3996 g_assert_not_reached ();
4000 if (event == EVENT_KIND_VM_START) {
4001 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
4002 if (!agent_config.defer) {
4003 ERROR_DECL (error);
4004 start_debugger_thread (error);
4005 mono_error_assert_ok (error);
4009 if (event == EVENT_KIND_VM_DEATH) {
4010 vm_death_event_sent = TRUE;
4011 suspend_policy = SUSPEND_POLICY_NONE;
4014 if (mono_runtime_is_shutting_down ())
4015 suspend_policy = SUSPEND_POLICY_NONE;
4017 if (suspend_policy != SUSPEND_POLICY_NONE) {
4019 * Save the thread context and start suspending before sending the packet,
4020 * since we could be receiving the resume request before send_packet ()
4021 * returns.
4023 save_thread_context (ctx);
4024 suspend_vm ();
4026 if (keepalive_obj)
4027 /* This will keep this object alive */
4028 get_objref (keepalive_obj);
4031 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
4033 if (send_success) {
4034 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4035 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
4038 buffer_free (&buf);
4040 g_slist_free (events);
4041 events = NULL;
4043 if (!send_success) {
4044 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
4045 return;
4048 if (event == EVENT_KIND_VM_START) {
4049 vm_start_event_sent = TRUE;
4052 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);
4054 switch (suspend_policy) {
4055 case SUSPEND_POLICY_NONE:
4056 break;
4057 case SUSPEND_POLICY_ALL:
4058 suspend_current ();
4059 break;
4060 case SUSPEND_POLICY_EVENT_THREAD:
4061 NOT_IMPLEMENTED;
4062 break;
4063 default:
4064 g_assert_not_reached ();
4068 static void
4069 process_profiler_event (EventKind event, gpointer arg)
4071 int suspend_policy;
4072 GSList *events;
4073 EventInfo ei, *ei_arg = NULL;
4075 if (event == EVENT_KIND_TYPE_LOAD) {
4076 ei.klass = (MonoClass *)arg;
4077 ei_arg = &ei;
4080 mono_loader_lock ();
4081 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
4082 mono_loader_unlock ();
4084 process_event (event, arg, 0, NULL, events, suspend_policy);
4087 static void
4088 runtime_initialized (MonoProfiler *prof)
4090 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
4091 if (agent_config.defer) {
4092 ERROR_DECL (error);
4093 start_debugger_thread (error);
4094 mono_error_assert_ok (error);
4098 static void
4099 runtime_shutdown (MonoProfiler *prof)
4101 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
4103 mono_debugger_agent_cleanup ();
4106 static void
4107 thread_startup (MonoProfiler *prof, uintptr_t tid)
4109 MonoInternalThread *thread = mono_thread_internal_current ();
4110 MonoInternalThread *old_thread;
4111 DebuggerTlsData *tls;
4113 if (is_debugger_thread ())
4114 return;
4116 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
4118 mono_loader_lock ();
4119 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4120 mono_loader_unlock ();
4121 if (old_thread) {
4122 if (thread == old_thread) {
4124 * For some reason, thread_startup () might be called for the same thread
4125 * multiple times (attach ?).
4127 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4128 return;
4129 } else {
4131 * thread_end () might not be called for some threads, and the tid could
4132 * get reused.
4134 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4135 mono_loader_lock ();
4136 mono_g_hash_table_remove (thread_to_tls, old_thread);
4137 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
4138 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4139 mono_loader_unlock ();
4143 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4144 g_assert (!tls);
4145 // FIXME: Free this somewhere
4146 tls = g_new0 (DebuggerTlsData, 1);
4147 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
4148 tls->thread = thread;
4149 // Do so we have thread id even after termination
4150 tls->thread_id = (intptr_t) thread->tid;
4151 mono_native_tls_set_value (debugger_tls_id, tls);
4153 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4155 mono_loader_lock ();
4156 mono_g_hash_table_insert_internal (thread_to_tls, thread, tls);
4157 mono_g_hash_table_insert_internal (tid_to_thread, (gpointer)tid, thread);
4158 mono_g_hash_table_insert_internal (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
4159 mono_loader_unlock ();
4161 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4164 * suspend_vm () could have missed this thread, so wait for a resume.
4167 suspend_current ();
4170 static void
4171 thread_end (MonoProfiler *prof, uintptr_t tid)
4173 MonoInternalThread *thread;
4174 DebuggerTlsData *tls = NULL;
4176 mono_loader_lock ();
4177 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4178 if (thread) {
4179 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4180 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4181 if (tls) {
4182 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4183 tls->terminated = TRUE;
4184 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4185 MONO_GC_UNREGISTER_ROOT (tls->thread);
4186 tls->thread = NULL;
4189 mono_loader_unlock ();
4191 /* We might be called for threads started before we registered the start callback */
4192 if (thread) {
4193 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p (domain=%p).\n", (gpointer)tid, thread, tls, (gpointer)mono_domain_get ());
4195 if (mono_thread_internal_is_current (thread) &&
4196 (!mono_native_tls_get_value (debugger_tls_id) ||
4197 !mono_domain_get ())
4200 * This can happen on darwin and android since we
4201 * deregister threads using pthread dtors.
4202 * process_profiler_event () and the code it calls
4203 * cannot handle a null TLS value.
4205 return;
4208 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4212 static void
4213 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4215 mono_de_domain_add (domain);
4217 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4220 static void
4221 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4223 DebuggerTlsData *tls;
4225 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4226 if (is_debugger_thread ())
4227 return;
4230 * Remember the currently unloading appdomain as it is needed to generate
4231 * proper ids for unloading assemblies.
4233 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4234 g_assert (tls);
4235 tls->domain_unloading = domain;
4238 static void
4239 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4241 DebuggerTlsData *tls;
4243 if (is_debugger_thread ())
4244 return;
4246 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4247 g_assert (tls);
4248 tls->domain_unloading = NULL;
4250 mono_de_clear_breakpoints_for_domain (domain);
4252 mono_loader_lock ();
4253 /* Invalidate each thread's frame stack */
4254 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4255 mono_loader_unlock ();
4257 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4261 * invalidate_each_thread:
4263 * A GHFunc to invalidate frames.
4264 * value must be a DebuggerTlsData*
4266 static void
4267 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4269 invalidate_frames ((DebuggerTlsData *)value);
4272 static void
4273 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4275 /* Sent later in jit_end () */
4276 dbg_lock ();
4277 g_ptr_array_add (pending_assembly_loads, assembly);
4278 dbg_unlock ();
4281 static void
4282 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4284 if (is_debugger_thread ())
4285 return;
4287 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4289 clear_event_requests_for_assembly (assembly);
4290 clear_types_for_assembly (assembly);
4293 static void
4294 send_type_load (MonoClass *klass)
4296 gboolean type_load = FALSE;
4297 MonoDomain *domain = mono_domain_get ();
4298 AgentDomainInfo *info = NULL;
4300 info = get_agent_domain_info (domain);
4302 mono_loader_lock ();
4304 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4305 type_load = TRUE;
4306 g_hash_table_insert (info->loaded_classes, klass, klass);
4309 mono_loader_unlock ();
4311 if (type_load)
4312 emit_type_load (klass, klass, NULL);
4316 * Emit load events for all types currently loaded in the domain.
4317 * Takes the loader and domain locks.
4318 * user_data is unused.
4320 static void
4321 send_types_for_domain (MonoDomain *domain, void *user_data)
4323 MonoDomain* old_domain;
4324 AgentDomainInfo *info = NULL;
4326 info = get_agent_domain_info (domain);
4327 g_assert (info);
4329 old_domain = mono_domain_get ();
4331 mono_domain_set_fast (domain, TRUE);
4333 mono_loader_lock ();
4334 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4335 mono_loader_unlock ();
4337 mono_domain_set_fast (old_domain, TRUE);
4340 static void
4341 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4343 GSList *tmp;
4344 MonoDomain* old_domain;
4346 old_domain = mono_domain_get ();
4348 mono_domain_set_fast (domain, TRUE);
4350 mono_domain_assemblies_lock (domain);
4351 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4352 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4353 emit_assembly_load (ass, NULL);
4355 mono_domain_assemblies_unlock (domain);
4357 mono_domain_set_fast (old_domain, TRUE);
4360 static void
4361 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4363 jit_end (prof, method, jinfo);
4366 static void
4367 jit_failed (MonoProfiler *prof, MonoMethod *method)
4369 jit_end (prof, method, NULL);
4372 static void
4373 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4376 * We emit type load events when the first method of the type is JITted,
4377 * since the class load profiler callbacks might be called with the
4378 * loader lock held. They could also occur in the debugger thread.
4379 * Same for assembly load events.
4381 while (TRUE) {
4382 MonoAssembly *assembly = NULL;
4384 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4385 dbg_lock ();
4386 if (pending_assembly_loads->len > 0) {
4387 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4388 g_ptr_array_remove_index (pending_assembly_loads, 0);
4390 dbg_unlock ();
4392 if (assembly) {
4393 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4394 } else {
4395 break;
4399 send_type_load (method->klass);
4401 if (jinfo)
4402 mono_de_add_pending_breakpoints (method, jinfo);
4406 * SINGLE STEPPING
4409 static void
4410 event_requests_cleanup (void)
4412 mono_loader_lock ();
4413 int i = 0;
4414 while (i < event_requests->len) {
4415 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4417 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4418 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4419 g_ptr_array_remove_index_fast (event_requests, i);
4420 g_free (req);
4421 } else {
4422 i ++;
4425 mono_loader_unlock ();
4429 * ss_calculate_framecount:
4431 * Ensure DebuggerTlsData fields are filled out.
4433 static void
4434 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4436 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4438 if (force_use_ctx || !tls->context.valid)
4439 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4440 compute_frame_info (tls->thread, tls, FALSE);
4441 if (frames)
4442 *frames = (DbgEngineStackFrame**)tls->frames;
4443 if (nframes)
4444 *nframes = tls->frame_count;
4448 * ss_discard_frame_data:
4450 * Discard frame data and invalidate any context
4452 static void
4453 ss_discard_frame_context (void *the_tls)
4455 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4456 tls->context.valid = FALSE;
4457 tls->async_state.valid = FALSE;
4458 invalidate_frames (tls);
4461 static MonoContext*
4462 tls_get_restore_state (void *the_tls)
4464 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4466 return &tls->restore_state.ctx;
4469 static gboolean
4470 ensure_jit (DbgEngineStackFrame* the_frame)
4472 StackFrame *frame = (StackFrame*)the_frame;
4473 if (!frame->jit) {
4474 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4475 if (!frame->jit && frame->api_method->is_inflated)
4476 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4477 if (!frame->jit) {
4478 char *s;
4480 /* This could happen for aot images with no jit debug info */
4481 s = mono_method_full_name (frame->api_method, TRUE);
4482 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4483 g_free (s);
4484 return FALSE;
4487 return TRUE;
4490 static gboolean
4491 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4493 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4496 static gpointer
4497 get_this_addr (DbgEngineStackFrame *the_frame)
4499 StackFrame *frame = (StackFrame *)the_frame;
4500 if (frame->de.ji->is_interp)
4501 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4503 MonoDebugVarInfo *var = frame->jit->this_var;
4504 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4505 return NULL;
4507 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4508 addr += (gint32)var->offset;
4509 return addr;
4512 static MonoMethod*
4513 get_set_notification_method (MonoClass* async_builder_class)
4515 ERROR_DECL (error);
4516 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, 1, FALSE, error);
4517 mono_error_assert_ok (error);
4518 if (array->len == 0) {
4519 g_ptr_array_free (array, TRUE);
4520 return NULL;
4522 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4523 g_ptr_array_free (array, TRUE);
4524 return set_notification_method;
4527 static MonoMethod*
4528 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4530 ERROR_DECL (error);
4531 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, 1, FALSE, error);
4532 mono_error_assert_ok (error);
4533 g_assert (array->len == 1);
4534 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4535 g_ptr_array_free (array, TRUE);
4536 return method;
4539 static MonoClass *
4540 get_class_to_get_builder_field(DbgEngineStackFrame *frame)
4542 ERROR_DECL (error);
4543 gpointer this_addr = get_this_addr (frame);
4544 MonoClass *original_class = frame->method->klass;
4545 MonoClass *ret;
4546 if (!m_class_is_valuetype (original_class) && mono_class_is_open_constructed_type (m_class_get_byval_arg (original_class))) {
4547 MonoObject *this_obj = *(MonoObject**)this_addr;
4548 MonoGenericContext context;
4549 MonoType *inflated_type;
4551 g_assert (this_obj);
4552 context = mono_get_generic_context_from_stack_frame (frame->ji, this_obj->vtable);
4553 inflated_type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (original_class), &context, error);
4554 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4556 ret = mono_class_from_mono_type_internal (inflated_type);
4557 mono_metadata_free_type (inflated_type);
4558 return ret;
4560 return original_class;
4564 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4565 static gpointer
4566 get_async_method_builder (DbgEngineStackFrame *frame)
4568 MonoObject *this_obj;
4569 MonoClassField *builder_field;
4570 gpointer builder;
4571 gpointer this_addr;
4572 MonoClass* klass = frame->method->klass;
4574 klass = get_class_to_get_builder_field(frame);
4575 builder_field = mono_class_get_field_from_name_full (klass, "<>t__builder", NULL);
4576 g_assert (builder_field);
4578 this_addr = get_this_addr (frame);
4579 if (!this_addr)
4580 return NULL;
4582 if (m_class_is_valuetype (klass)) {
4583 builder = mono_vtype_get_field_addr (*(guint8**)this_addr, builder_field);
4584 } else {
4585 this_obj = *(MonoObject**)this_addr;
4586 builder = (char*)this_obj + builder_field->offset;
4589 return builder;
4592 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4593 //since thread probably changed...
4594 static int
4595 get_this_async_id (DbgEngineStackFrame *frame)
4597 MonoClassField *builder_field;
4598 gpointer builder;
4599 MonoMethod *method;
4600 MonoObject *ex;
4601 ERROR_DECL (error);
4602 MonoObject *obj;
4603 gboolean old_disable_breakpoints = FALSE;
4604 DebuggerTlsData *tls;
4607 * FRAME points to a method in a state machine class/struct.
4608 * Call the ObjectIdForDebugger method of the associated method builder type.
4610 builder = get_async_method_builder (frame);
4611 if (!builder)
4612 return 0;
4614 builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4615 g_assert (builder_field);
4617 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4618 if (tls) {
4619 old_disable_breakpoints = tls->disable_breakpoints;
4620 tls->disable_breakpoints = TRUE;
4623 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4624 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4625 mono_error_assert_ok (error);
4627 if (tls)
4628 tls->disable_breakpoints = old_disable_breakpoints;
4630 return get_objid (obj);
4633 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4634 // false if not(AsyncVoidBuilder)
4635 static gboolean
4636 set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame)
4638 MonoClassField *builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4639 g_assert (builder_field);
4640 gpointer builder = get_async_method_builder (frame);
4641 g_assert (builder);
4643 void* args [1];
4644 gboolean arg = TRUE;
4645 ERROR_DECL (error);
4646 args [0] = &arg;
4647 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type_internal (builder_field->type));
4648 if (method == NULL)
4649 return FALSE;
4650 mono_runtime_invoke_checked (method, builder, args, error);
4651 mono_error_assert_ok (error);
4652 return TRUE;
4655 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4657 static MonoMethod*
4658 get_notify_debugger_of_wait_completion_method (void)
4660 if (notify_debugger_of_wait_completion_method_cache != NULL)
4661 return notify_debugger_of_wait_completion_method_cache;
4662 ERROR_DECL (error);
4663 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4664 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error);
4665 mono_error_assert_ok (error);
4666 g_assert (array->len == 1);
4667 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4668 g_ptr_array_free (array, TRUE);
4669 return notify_debugger_of_wait_completion_method_cache;
4672 static gboolean
4673 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4675 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4678 * Skip the instruction causing the breakpoint signal.
4680 if (from_signal)
4681 mono_arch_skip_breakpoint (ctx, ji);
4683 if (tls->disable_breakpoints)
4684 return FALSE;
4685 return TRUE;
4688 typedef struct {
4689 GSList *bp_events, *ss_events, *enter_leave_events;
4690 EventKind kind;
4691 int suspend_policy;
4692 } BreakPointEvents;
4694 static void*
4695 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4697 int suspend_policy = 0;
4698 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4699 if (ss_reqs && ss_reqs->len > 0)
4700 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4701 else if (bp_reqs && bp_reqs->len > 0)
4702 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4703 else if (kind != EVENT_KIND_BREAKPOINT)
4704 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4706 evts->kind = kind;
4707 evts->suspend_policy = suspend_policy;
4708 return evts;
4711 static void
4712 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4714 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4716 * FIXME: The first event will suspend, so the second will only be sent after the
4717 * resume.
4719 if (evts->ss_events)
4720 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4721 if (evts->bp_events)
4722 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4723 if (evts->enter_leave_events)
4724 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4726 g_free (evts);
4729 /* Process a breakpoint/single step event after resuming from a signal handler */
4730 static void
4731 process_signal_event (void (*func) (void*, gboolean))
4733 DebuggerTlsData *tls;
4734 MonoThreadUnwindState orig_restore_state;
4735 MonoContext ctx;
4737 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4738 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4739 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4740 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4742 func (tls, TRUE);
4744 /* This is called when resuming from a signal handler, so it shouldn't return */
4745 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4746 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4747 mono_restore_context (&ctx);
4748 g_assert_not_reached ();
4751 static void
4752 process_breakpoint_from_signal (void)
4754 process_signal_event (mono_de_process_breakpoint);
4757 static void
4758 resume_from_signal_handler (void *sigctx, void *func)
4760 DebuggerTlsData *tls;
4761 MonoContext ctx;
4763 /* Save the original context in TLS */
4764 // FIXME: This might not work on an altstack ?
4765 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4766 if (!tls)
4767 g_printerr ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4768 g_assert (tls);
4770 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4771 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4772 // clob:c could be added to op_seq_point.
4774 mono_sigctx_to_monoctx (sigctx, &ctx);
4775 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4776 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4777 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4778 #else
4779 MONO_CONTEXT_SET_IP (&ctx, func);
4780 #endif
4781 mono_monoctx_to_sigctx (&ctx, sigctx);
4784 static void
4785 debugger_agent_breakpoint_hit (void *sigctx)
4788 * We are called from a signal handler, and running code there causes all kinds of
4789 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4790 * So set up the signal context to return to the real breakpoint handler function.
4792 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4795 typedef struct {
4796 gboolean found;
4797 MonoContext *ctx;
4798 } UserBreakCbData;
4800 static gboolean
4801 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4803 UserBreakCbData *data = (UserBreakCbData*)user_data;
4805 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4806 data->found = TRUE;
4807 return TRUE;
4809 if (frame->managed) {
4810 data->found = TRUE;
4811 *data->ctx = *ctx;
4813 return TRUE;
4815 return FALSE;
4819 * Called by System.Diagnostics.Debugger:Break ().
4821 static void
4822 debugger_agent_user_break (void)
4824 if (agent_config.enabled) {
4825 MonoContext ctx;
4826 int suspend_policy;
4827 GSList *events;
4828 UserBreakCbData data;
4830 memset (&data, 0, sizeof (data));
4831 data.ctx = &ctx;
4833 /* Obtain a context */
4834 MONO_CONTEXT_SET_IP (&ctx, NULL);
4835 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4836 g_assert (data.found);
4838 mono_loader_lock ();
4839 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4840 mono_loader_unlock ();
4842 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4843 } else if (mini_debug_options.native_debugger_break) {
4844 G_BREAKPOINT ();
4848 static void
4849 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4851 if (from_signal)
4852 mono_arch_skip_single_step (ctx);
4855 static void
4856 process_single_step (void)
4858 process_signal_event (mono_de_process_single_step);
4862 * debugger_agent_single_step_event:
4864 * Called from a signal handler to handle a single step event.
4866 static void
4867 debugger_agent_single_step_event (void *sigctx)
4869 /* Resume to process_single_step through the signal context */
4871 // FIXME: Since step out/over is implemented using step in, the step in case should
4872 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4873 // here
4875 if (is_debugger_thread ()) {
4877 * This could happen despite our best effors when the runtime calls
4878 * assembly/type resolve hooks.
4879 * FIXME: Breakpoints too.
4881 MonoContext ctx;
4883 mono_sigctx_to_monoctx (sigctx, &ctx);
4884 mono_arch_skip_single_step (&ctx);
4885 mono_monoctx_to_sigctx (&ctx, sigctx);
4886 return;
4889 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4892 static void
4893 debugger_agent_single_step_from_context (MonoContext *ctx)
4895 DebuggerTlsData *tls;
4896 MonoThreadUnwindState orig_restore_state;
4898 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4899 /* Fastpath during invokes, see in process_suspend () */
4900 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4901 return;
4903 if (is_debugger_thread ())
4904 return;
4906 g_assert (tls);
4908 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4909 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4910 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4911 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4913 mono_de_process_single_step (tls, FALSE);
4915 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4916 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4919 static void
4920 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4922 DebuggerTlsData *tls;
4923 MonoThreadUnwindState orig_restore_state;
4924 guint8 *orig_ip;
4926 if (is_debugger_thread ())
4927 return;
4929 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4930 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4932 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4933 g_assert (tls);
4934 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4935 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4936 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4938 mono_de_process_breakpoint (tls, FALSE);
4940 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4941 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4942 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4943 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4946 static void
4947 ss_args_destroy (SingleStepArgs *ss_args)
4949 if (ss_args->frames)
4950 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
4953 static int
4954 ensure_runtime_is_suspended (void)
4956 if (suspend_count == 0)
4957 return ERR_NOT_SUSPENDED;
4959 wait_for_suspend ();
4961 return ERR_NONE;
4964 static int
4965 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
4967 MonoSeqPointInfo *info = NULL;
4968 gboolean found_sp;
4969 MonoMethod *method = NULL;
4970 MonoDebugMethodInfo *minfo;
4971 gboolean step_to_catch = FALSE;
4972 gboolean set_ip = FALSE;
4973 StackFrame **frames = NULL;
4974 int nframes = 0;
4976 mono_loader_lock ();
4977 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4978 mono_loader_unlock ();
4979 g_assert (tls);
4980 if (!tls->context.valid) {
4981 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
4982 return ERR_INVALID_ARGUMENT;
4985 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
4987 * Need to start single stepping from restore_state and not from the current state
4989 set_ip = TRUE;
4990 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
4993 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4995 if (tls->has_catch_frame) {
4996 StackFrameInfo frame;
4999 * We are stopped at a throw site. Stepping should go to the catch site.
5001 frame = tls->catch_frame;
5002 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
5005 * Find the seq point corresponding to the landing site ip, which is the first seq
5006 * point after ip.
5008 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
5009 if (!found_sp)
5010 no_seq_points_found (frame.method, frame.native_offset);
5011 g_assert (found_sp);
5013 method = frame.method;
5015 step_to_catch = TRUE;
5016 /* This make sure the seq point is not skipped by process_single_step () */
5017 ss_req->last_sp = NULL;
5020 if (!step_to_catch) {
5021 StackFrame *frame = NULL;
5023 if (set_ip) {
5024 if (frames && nframes)
5025 frame = frames [0];
5026 } else {
5027 compute_frame_info (ss_req->thread, tls, FALSE);
5029 if (tls->frame_count)
5030 frame = tls->frames [0];
5033 if (ss_req->size == STEP_SIZE_LINE) {
5034 if (frame) {
5035 ss_req->last_method = frame->de.method;
5036 ss_req->last_line = -1;
5038 minfo = mono_debug_lookup_method (frame->de.method);
5039 if (minfo && frame->il_offset != -1) {
5040 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5042 if (loc) {
5043 ss_req->last_line = loc->row;
5044 g_free (loc);
5050 if (frame) {
5051 if (!method && frame->il_offset != -1) {
5052 /* FIXME: Sort the table and use a binary search */
5053 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
5054 if (!found_sp)
5055 no_seq_points_found (frame->de.method, frame->de.native_offset);
5056 g_assert (found_sp);
5057 method = frame->de.method;
5062 ss_req->start_method = method;
5064 args->method = method;
5065 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
5066 args->tls = tls;
5067 args->step_to_catch = step_to_catch;
5068 args->info = info;
5069 args->frames = (DbgEngineStackFrame**)frames;
5070 args->nframes = nframes;
5072 return ERR_NONE;
5075 static void
5076 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5078 GSList *l;
5079 gboolean found = TRUE;
5081 while (found) {
5082 found = FALSE;
5083 for (l = req->bps; l; l = l->next) {
5084 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5085 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
5086 req->bps = g_slist_delete_link (req->bps, l);
5087 found = TRUE;
5088 break;
5095 * This takes a lot of locks and stuff. Do this at the end, after
5096 * other things have dumped us, so that getting stuck here won't
5097 * prevent seeing other crash information
5099 static void
5100 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
5102 #ifndef DISABLE_CRASH_REPORTING
5103 int suspend_policy;
5104 GSList *events;
5105 EventInfo ei;
5107 if (!agent_config.enabled)
5108 return;
5110 // Don't send the event if the client doesn't expect it
5111 if (!CHECK_PROTOCOL_VERSION (2, 49))
5112 return;
5114 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5115 // actually enabled. Therefore we do the wait here.
5116 sleep (pause);
5118 // Don't heap allocate when we can avoid it
5119 EventRequest request;
5120 memset (&request, 0, sizeof (request));
5121 request.event_kind = EVENT_KIND_CRASH;
5123 gpointer pdata [1];
5124 pdata [0] = &request;
5125 GPtrArray array;
5126 memset (&array, 0, sizeof (array));
5127 array.pdata = pdata;
5128 array.len = 1;
5130 mono_loader_lock ();
5131 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5132 mono_loader_unlock ();
5134 ei.dump = json_dump;
5135 ei.hashes = hashes;
5137 g_assert (events != NULL);
5139 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5141 // Don't die before it is sent.
5142 sleep (4);
5143 #endif
5147 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5149 static void
5150 debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5152 ERROR_DECL (error);
5153 int suspend_policy;
5154 GSList *events;
5155 EventInfo ei;
5157 if (!agent_config.enabled)
5158 return;
5160 memset (&ei, 0, sizeof (ei));
5162 mono_loader_lock ();
5163 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5164 mono_loader_unlock ();
5166 ei.level = level;
5167 if (category) {
5168 ei.category = mono_string_to_utf8_checked_internal (category, error);
5169 mono_error_cleanup (error);
5170 error_init (error);
5172 if (message) {
5173 ei.message = mono_string_to_utf8_checked_internal (message, error);
5174 mono_error_cleanup (error);
5177 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5179 g_free (ei.category);
5180 g_free (ei.message);
5183 static gboolean
5184 debugger_agent_debug_log_is_enabled (void)
5186 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5187 return agent_config.enabled;
5190 static void
5191 debugger_agent_unhandled_exception (MonoException *exc)
5193 int suspend_policy;
5194 GSList *events;
5195 EventInfo ei;
5197 if (!inited)
5198 return;
5200 memset (&ei, 0, sizeof (ei));
5201 ei.exc = (MonoObject*)exc;
5203 mono_loader_lock ();
5204 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5205 mono_loader_unlock ();
5207 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5210 static void
5211 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5212 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5214 if (catch_ctx == NULL && catch_frame == NULL && mini_debug_options.suspend_on_unhandled && mono_object_class (exc) != mono_defaults.threadabortexception_class) {
5215 mono_runtime_printf_err ("Unhandled exception, suspending...");
5216 while (1)
5220 int i, j, suspend_policy;
5221 GSList *events;
5222 MonoJitInfo *ji, *catch_ji;
5223 EventInfo ei;
5224 DebuggerTlsData *tls = NULL;
5226 if (thread_to_tls != NULL) {
5227 MonoInternalThread *thread = mono_thread_internal_current ();
5229 mono_loader_lock ();
5230 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5231 mono_loader_unlock ();
5233 if (tls && tls->abort_requested)
5234 return;
5235 if (tls && tls->disable_breakpoints)
5236 return;
5239 memset (&ei, 0, sizeof (ei));
5241 /* Just-In-Time debugging */
5242 if (!catch_ctx) {
5243 if (agent_config.onuncaught && !inited) {
5244 finish_agent_init (FALSE);
5247 * Send an unsolicited EXCEPTION event with a dummy request id.
5249 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5250 ei.exc = (MonoObject*)exc;
5251 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5252 return;
5254 } else if (agent_config.onthrow && !inited) {
5255 GSList *l;
5256 gboolean found = FALSE;
5258 for (l = agent_config.onthrow; l; l = l->next) {
5259 char *ex_type = (char *)l->data;
5260 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5262 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5263 found = TRUE;
5265 g_free (f);
5268 if (found) {
5269 finish_agent_init (FALSE);
5272 * Send an unsolicited EXCEPTION event with a dummy request id.
5274 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5275 ei.exc = (MonoObject*)exc;
5276 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5277 return;
5281 if (!inited)
5282 return;
5284 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5285 if (catch_frame)
5286 catch_ji = catch_frame->ji;
5287 else
5288 catch_ji = NULL;
5290 ei.exc = (MonoObject*)exc;
5291 ei.caught = catch_ctx != NULL;
5293 mono_loader_lock ();
5295 /* Treat exceptions which are caught in non-user code as unhandled */
5296 for (i = 0; i < event_requests->len; ++i) {
5297 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5298 if (req->event_kind != EVENT_KIND_EXCEPTION)
5299 continue;
5301 for (j = 0; j < req->nmodifiers; ++j) {
5302 Modifier *mod = &req->modifiers [j];
5304 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5305 int k;
5306 gboolean found = FALSE;
5307 MonoAssembly **assemblies = mod->data.assemblies;
5309 if (assemblies) {
5310 for (k = 0; assemblies [k]; ++k)
5311 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5312 found = TRUE;
5314 if (!found)
5315 ei.caught = FALSE;
5320 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5321 mono_loader_unlock ();
5323 if (tls && ei.caught && catch_ctx) {
5324 if (catch_frame) {
5325 tls->has_catch_frame = TRUE;
5326 tls->catch_frame = *catch_frame;
5327 } else {
5328 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5332 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5334 if (tls)
5335 tls->has_catch_frame = FALSE;
5338 static void
5339 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5341 DebuggerTlsData *tls;
5343 if (!inited)
5344 return;
5346 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5347 if (!tls)
5348 return;
5351 * We're about to invoke an exception filter during the first pass of exception handling.
5353 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5354 * 'orig_ctx' is the context where the exception has been thrown.
5357 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5359 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5360 * the call site (line 37) and then continue to Main(), but it would never
5361 * include the throw site (line 32).
5363 * Since exception filters are invoked during the first pass of exception handling,
5364 * the stack frames of the throw site are still intact, so we should include them
5365 * in a stack trace.
5367 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5369 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5370 * but report the location of the 'throw' to the user.
5374 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5377 static void
5378 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5380 DebuggerTlsData *tls;
5382 if (!inited)
5383 return;
5385 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5386 if (!tls)
5387 return;
5389 tls->filter_state.valid = FALSE;
5392 static void
5393 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5394 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5396 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5397 buffer_add_byte (buf, t->type);
5398 buffer_add_int (buf, len_fixed_array );
5399 for (int i = 0; i < len_fixed_array; i++) {
5400 switch (t->type) {
5401 case MONO_TYPE_BOOLEAN:
5402 case MONO_TYPE_I1:
5403 case MONO_TYPE_U1:
5404 buffer_add_int (buf, ((gint8*)addr)[i]);
5405 break;
5406 case MONO_TYPE_CHAR:
5407 case MONO_TYPE_I2:
5408 case MONO_TYPE_U2:
5409 buffer_add_int (buf, ((gint16*)addr)[i]);
5410 break;
5411 case MONO_TYPE_I4:
5412 case MONO_TYPE_U4:
5413 case MONO_TYPE_R4:
5414 buffer_add_int (buf, ((gint32*)addr)[i]);
5415 break;
5416 case MONO_TYPE_I8:
5417 case MONO_TYPE_U8:
5418 case MONO_TYPE_R8:
5419 buffer_add_long (buf, ((gint64*)addr)[i]);
5420 break;
5421 case MONO_TYPE_PTR: {
5422 gssize val = *(gssize*)addr;
5424 buffer_add_byte (buf, t->type);
5425 buffer_add_long (buf, val);
5426 if (CHECK_PROTOCOL_VERSION(2, 46))
5427 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5428 break;
5434 * buffer_add_value_full:
5436 * Add the encoding of the value at ADDR described by T to the buffer.
5437 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5438 * vtypes.
5440 static void
5441 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5442 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5444 MonoObject *obj;
5445 gboolean boxed_vtype = FALSE;
5447 if (t->byref) {
5448 if (!(*(void**)addr)) {
5449 /* This can happen with compiler generated locals */
5450 //printf ("%s\n", mono_type_full_name (t));
5451 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5452 return;
5454 g_assert (*(void**)addr);
5455 addr = *(void**)addr;
5458 if (as_vtype) {
5459 switch (t->type) {
5460 case MONO_TYPE_BOOLEAN:
5461 case MONO_TYPE_I1:
5462 case MONO_TYPE_U1:
5463 case MONO_TYPE_CHAR:
5464 case MONO_TYPE_I2:
5465 case MONO_TYPE_U2:
5466 case MONO_TYPE_I4:
5467 case MONO_TYPE_U4:
5468 case MONO_TYPE_R4:
5469 case MONO_TYPE_I8:
5470 case MONO_TYPE_U8:
5471 case MONO_TYPE_R8:
5472 case MONO_TYPE_I:
5473 case MONO_TYPE_U:
5474 case MONO_TYPE_PTR:
5475 goto handle_vtype;
5476 break;
5477 default:
5478 break;
5482 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5484 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5485 return;
5487 switch (t->type) {
5488 case MONO_TYPE_VOID:
5489 buffer_add_byte (buf, t->type);
5490 break;
5491 case MONO_TYPE_BOOLEAN:
5492 case MONO_TYPE_I1:
5493 case MONO_TYPE_U1:
5494 buffer_add_byte (buf, t->type);
5495 buffer_add_int (buf, *(gint8*)addr);
5496 break;
5497 case MONO_TYPE_CHAR:
5498 case MONO_TYPE_I2:
5499 case MONO_TYPE_U2:
5500 buffer_add_byte (buf, t->type);
5501 buffer_add_int (buf, *(gint16*)addr);
5502 break;
5503 case MONO_TYPE_I4:
5504 case MONO_TYPE_U4:
5505 case MONO_TYPE_R4:
5506 buffer_add_byte (buf, t->type);
5507 buffer_add_int (buf, *(gint32*)addr);
5508 break;
5509 case MONO_TYPE_I8:
5510 case MONO_TYPE_U8:
5511 case MONO_TYPE_R8:
5512 buffer_add_byte (buf, t->type);
5513 buffer_add_long (buf, *(gint64*)addr);
5514 break;
5515 case MONO_TYPE_I:
5516 case MONO_TYPE_U:
5517 /* Treat it as a vtype */
5518 goto handle_vtype;
5519 case MONO_TYPE_PTR: {
5520 gssize val = *(gssize*)addr;
5522 buffer_add_byte (buf, t->type);
5523 buffer_add_long (buf, val);
5524 if (CHECK_PROTOCOL_VERSION(2, 46))
5525 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5526 break;
5528 handle_ref:
5529 case MONO_TYPE_STRING:
5530 case MONO_TYPE_SZARRAY:
5531 case MONO_TYPE_OBJECT:
5532 case MONO_TYPE_CLASS:
5533 case MONO_TYPE_ARRAY:
5534 obj = *(MonoObject**)addr;
5536 if (!obj) {
5537 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5538 } else {
5539 if (m_class_is_valuetype (obj->vtable->klass)) {
5540 t = m_class_get_byval_arg (obj->vtable->klass);
5541 addr = mono_object_unbox_internal (obj);
5542 boxed_vtype = TRUE;
5543 goto handle_vtype;
5544 } else if (m_class_get_rank (obj->vtable->klass)) {
5545 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5546 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5547 buffer_add_byte (buf, MONO_TYPE_CLASS);
5548 } else {
5549 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5551 buffer_add_objid (buf, obj);
5553 break;
5554 handle_vtype:
5555 case MONO_TYPE_VALUETYPE:
5556 case MONO_TYPE_TYPEDBYREF: {
5557 int nfields;
5558 gpointer iter;
5559 MonoClassField *f;
5560 MonoClass *klass = mono_class_from_mono_type_internal (t);
5561 int vtype_index;
5563 if (boxed_vtype) {
5565 * Handle boxed vtypes recursively referencing themselves using fields.
5567 if (!parent_vtypes)
5568 parent_vtypes = g_hash_table_new (NULL, NULL);
5569 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5570 if (vtype_index) {
5571 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5572 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5573 buffer_add_int (buf, vtype_index - 1);
5574 } else {
5575 /* The client can't handle PARENT_VTYPE */
5576 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5578 break;
5579 } else {
5580 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5584 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5585 buffer_add_byte (buf, m_class_is_enumtype (klass));
5586 buffer_add_typeid (buf, domain, klass);
5588 nfields = 0;
5589 iter = NULL;
5590 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5591 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5592 continue;
5593 if (mono_field_is_deleted (f))
5594 continue;
5595 nfields ++;
5597 buffer_add_int (buf, nfields);
5599 iter = NULL;
5600 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5601 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5602 continue;
5603 if (mono_field_is_deleted (f))
5604 continue;
5605 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));
5608 if (boxed_vtype) {
5609 g_hash_table_remove (parent_vtypes, addr);
5610 if (g_hash_table_size (parent_vtypes) == 0) {
5611 g_hash_table_destroy (parent_vtypes);
5612 parent_vtypes = NULL;
5615 break;
5617 case MONO_TYPE_GENERICINST:
5618 if (mono_type_generic_inst_is_valuetype (t)) {
5619 goto handle_vtype;
5620 } else {
5621 goto handle_ref;
5623 break;
5624 default:
5625 NOT_IMPLEMENTED;
5629 static void
5630 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5632 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5635 static gboolean
5636 obj_is_of_type (MonoObject *obj, MonoType *t)
5638 MonoClass *klass = obj->vtable->klass;
5639 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5640 if (mono_class_is_transparent_proxy (klass)) {
5641 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5642 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5643 return TRUE;
5646 return FALSE;
5648 return TRUE;
5651 static ErrorCode
5652 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5654 static ErrorCode
5655 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5657 guint8 *addr = (guint8*)void_addr;
5658 guint8 *buf = (guint8*)void_buf;
5659 gboolean is_enum;
5660 MonoClass *klass;
5661 MonoClassField *f;
5662 int nfields;
5663 gpointer iter = NULL;
5664 MonoDomain *d;
5665 ErrorCode err;
5667 is_enum = decode_byte (buf, &buf, limit);
5668 /* Enums are sent as a normal vtype */
5669 if (is_enum)
5670 return ERR_NOT_IMPLEMENTED;
5671 klass = decode_typeid (buf, &buf, limit, &d, &err);
5672 if (err != ERR_NONE)
5673 return err;
5675 if (t && klass != mono_class_from_mono_type_internal (t)) {
5676 char *name = mono_type_full_name (t);
5677 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5678 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5679 g_free (name);
5680 g_free (name2);
5681 return ERR_INVALID_ARGUMENT;
5684 nfields = decode_int (buf, &buf, limit);
5685 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5686 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5687 continue;
5688 if (mono_field_is_deleted (f))
5689 continue;
5690 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5691 if (err != ERR_NONE)
5692 return err;
5693 nfields --;
5695 g_assert (nfields == 0);
5697 *endbuf = buf;
5699 return ERR_NONE;
5701 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)
5703 ErrorCode err = ERR_NONE;
5704 int fixedSizeLen = 1;
5705 int newType = MONO_TYPE_END;
5706 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5707 newType = decode_byte (buf, &buf, limit);
5708 fixedSizeLen = decode_int (buf, &buf, limit);
5709 //t->type = newType;
5711 for (int i = 0 ; i < fixedSizeLen; i++) {
5712 switch (newType) {
5713 case MONO_TYPE_BOOLEAN:
5714 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5715 break;
5716 case MONO_TYPE_CHAR:
5717 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5718 break;
5719 case MONO_TYPE_I1:
5720 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5721 break;
5722 case MONO_TYPE_U1:
5723 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5724 break;
5725 case MONO_TYPE_I2:
5726 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5727 break;
5728 case MONO_TYPE_U2:
5729 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5730 break;
5731 case MONO_TYPE_I4:
5732 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5733 break;
5734 case MONO_TYPE_U4:
5735 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5736 break;
5737 case MONO_TYPE_I8:
5738 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5739 break;
5740 case MONO_TYPE_U8:
5741 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5742 break;
5743 case MONO_TYPE_R4:
5744 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5745 break;
5746 case MONO_TYPE_R8:
5747 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5748 break;
5751 *endbuf = buf;
5752 return err;
5754 static ErrorCode
5755 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5757 ErrorCode err;
5758 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5759 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5760 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5761 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5762 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5763 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5764 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5765 char *name = mono_type_full_name (t);
5766 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5767 g_free (name);
5768 return ERR_INVALID_ARGUMENT;
5770 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5771 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5772 return ERR_NONE;
5775 switch (t->type) {
5776 case MONO_TYPE_BOOLEAN:
5777 *(guint8*)addr = decode_int (buf, &buf, limit);
5778 break;
5779 case MONO_TYPE_CHAR:
5780 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5781 break;
5782 case MONO_TYPE_I1:
5783 *(gint8*)addr = decode_int (buf, &buf, limit);
5784 break;
5785 case MONO_TYPE_U1:
5786 *(guint8*)addr = decode_int (buf, &buf, limit);
5787 break;
5788 case MONO_TYPE_I2:
5789 *(gint16*)addr = decode_int (buf, &buf, limit);
5790 break;
5791 case MONO_TYPE_U2:
5792 *(guint16*)addr = decode_int (buf, &buf, limit);
5793 break;
5794 case MONO_TYPE_I4:
5795 *(gint32*)addr = decode_int (buf, &buf, limit);
5796 break;
5797 case MONO_TYPE_U4:
5798 *(guint32*)addr = decode_int (buf, &buf, limit);
5799 break;
5800 case MONO_TYPE_I8:
5801 *(gint64*)addr = decode_long (buf, &buf, limit);
5802 break;
5803 case MONO_TYPE_U8:
5804 *(guint64*)addr = decode_long (buf, &buf, limit);
5805 break;
5806 case MONO_TYPE_R4:
5807 *(guint32*)addr = decode_int (buf, &buf, limit);
5808 break;
5809 case MONO_TYPE_R8:
5810 *(guint64*)addr = decode_long (buf, &buf, limit);
5811 break;
5812 case MONO_TYPE_PTR:
5813 /* We send these as I8, so we get them back as such */
5814 g_assert (type == MONO_TYPE_I8);
5815 *(gssize*)addr = decode_long (buf, &buf, limit);
5816 break;
5817 case MONO_TYPE_GENERICINST:
5818 if (MONO_TYPE_ISSTRUCT (t)) {
5819 /* The client sends these as a valuetype */
5820 goto handle_vtype;
5821 } else {
5822 goto handle_ref;
5824 break;
5825 case MONO_TYPE_I:
5826 case MONO_TYPE_U:
5827 /* We send these as vtypes, so we get them back as such */
5828 g_assert (type == MONO_TYPE_VALUETYPE);
5829 /* Fall through */
5830 handle_vtype:
5831 case MONO_TYPE_VALUETYPE:
5832 if (type == MONO_TYPE_OBJECT) {
5833 /* Boxed vtype */
5834 int objid = decode_objid (buf, &buf, limit);
5835 ErrorCode err;
5836 MonoObject *obj;
5838 err = get_object (objid, (MonoObject**)&obj);
5839 if (err != ERR_NONE)
5840 return err;
5841 if (!obj)
5842 return ERR_INVALID_ARGUMENT;
5843 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5844 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5845 return ERR_INVALID_ARGUMENT;
5847 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5848 } else {
5849 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5850 if (err != ERR_NONE)
5851 return err;
5853 break;
5854 handle_ref:
5855 default:
5856 if (MONO_TYPE_IS_REFERENCE (t)) {
5857 if (type == MONO_TYPE_OBJECT) {
5858 int objid = decode_objid (buf, &buf, limit);
5859 ErrorCode err;
5860 MonoObject *obj;
5862 err = get_object (objid, (MonoObject**)&obj);
5863 if (err != ERR_NONE)
5864 return err;
5866 if (obj) {
5867 if (!obj_is_of_type (obj, t)) {
5868 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5869 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5870 return ERR_INVALID_ARGUMENT;
5874 if (obj && obj->vtable->domain != domain)
5875 return ERR_INVALID_ARGUMENT;
5877 mono_gc_wbarrier_generic_store_internal (addr, obj);
5878 } else if (type == VALUE_TYPE_ID_NULL) {
5879 *(MonoObject**)addr = NULL;
5880 } else if (type == MONO_TYPE_VALUETYPE) {
5881 ERROR_DECL (error);
5882 guint8 *buf2;
5883 gboolean is_enum;
5884 MonoClass *klass;
5885 MonoDomain *d;
5886 guint8 *vtype_buf;
5887 int vtype_buf_size;
5889 /* This can happen when round-tripping boxed vtypes */
5891 * Obtain vtype class.
5892 * Same as the beginning of the handle_vtype case above.
5894 buf2 = buf;
5895 is_enum = decode_byte (buf, &buf, limit);
5896 if (is_enum)
5897 return ERR_NOT_IMPLEMENTED;
5898 klass = decode_typeid (buf, &buf, limit, &d, &err);
5899 if (err != ERR_NONE)
5900 return err;
5902 /* Decode the vtype into a temporary buffer, then box it. */
5903 vtype_buf_size = mono_class_value_size (klass, NULL);
5904 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5905 g_assert (vtype_buf);
5907 buf = buf2;
5908 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5909 if (err != ERR_NONE) {
5910 g_free (vtype_buf);
5911 return err;
5913 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5914 mono_error_cleanup (error);
5915 g_free (vtype_buf);
5916 } else {
5917 char *name = mono_type_full_name (t);
5918 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5919 g_free (name);
5920 return ERR_INVALID_ARGUMENT;
5922 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5923 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5924 m_class_is_enumtype (t->data.generic_class->container_class)){
5925 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5926 if (err != ERR_NONE)
5927 return err;
5928 } else {
5929 NOT_IMPLEMENTED;
5931 break;
5935 *endbuf = buf;
5937 return ERR_NONE;
5940 static ErrorCode
5941 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5943 guint8 *addr = (guint8*)void_addr;
5944 guint8 *buf = (guint8*)void_buf;
5946 ERROR_DECL (error);
5947 ErrorCode err;
5948 int type = decode_byte (buf, &buf, limit);
5950 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5951 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5952 guint8 *nullable_buf;
5955 * First try decoding it as a Nullable`1
5957 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5958 if (err == ERR_NONE)
5959 return err;
5962 * Then try decoding as a primitive value or null.
5964 if (targ->type == type) {
5965 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
5966 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
5967 if (err != ERR_NONE) {
5968 g_free (nullable_buf);
5969 return err;
5971 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
5972 if (!is_ok (error)) {
5973 mono_error_cleanup (error);
5974 return ERR_INVALID_OBJECT;
5976 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
5977 g_free (nullable_buf);
5978 *endbuf = buf;
5979 return ERR_NONE;
5980 } else if (type == VALUE_TYPE_ID_NULL) {
5981 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
5982 *endbuf = buf;
5983 return ERR_NONE;
5987 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5990 static void
5991 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5993 guint32 flags;
5994 int reg;
5995 guint8 *addr, *gaddr;
5996 host_mgreg_t reg_val;
5998 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5999 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6001 switch (flags) {
6002 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6003 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6005 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
6006 break;
6007 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6008 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6009 addr += (gint32)var->offset;
6011 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6013 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6014 break;
6015 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6016 NOT_IMPLEMENTED;
6017 break;
6018 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6019 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6020 /* Same as regoffset, but with an indirection */
6021 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6022 addr += (gint32)var->offset;
6024 gaddr = (guint8 *)*(gpointer*)addr;
6025 g_assert (gaddr);
6026 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
6027 break;
6028 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6029 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6030 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6031 MonoGSharedVtMethodRuntimeInfo *info;
6032 guint8 *locals;
6033 int idx;
6035 idx = reg;
6037 g_assert (info_var);
6038 g_assert (locals_var);
6040 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6041 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6042 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6043 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6044 addr += (gint32)info_var->offset;
6045 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6046 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6047 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6048 } else {
6049 g_assert_not_reached ();
6051 g_assert (info);
6053 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6054 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6055 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6056 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6057 addr += (gint32)locals_var->offset;
6058 locals = (guint8 *)*(gpointer*)addr;
6059 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6060 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6061 } else {
6062 g_assert_not_reached ();
6064 g_assert (locals);
6066 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6068 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6069 break;
6072 default:
6073 g_assert_not_reached ();
6077 static void
6078 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
6080 guint32 flags;
6081 int reg, size;
6082 guint8 *addr, *gaddr;
6084 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6085 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6087 if (MONO_TYPE_IS_REFERENCE (t))
6088 size = sizeof (gpointer);
6089 else
6090 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6092 switch (flags) {
6093 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6094 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6095 host_mgreg_t v;
6096 gboolean is_signed = FALSE;
6098 if (t->byref) {
6099 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6101 if (addr) {
6102 // FIXME: Write barriers
6103 mono_gc_memmove_atomic (addr, val, size);
6105 break;
6108 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6109 is_signed = TRUE;
6111 switch (size) {
6112 case 1:
6113 v = is_signed ? *(gint8*)val : *(guint8*)val;
6114 break;
6115 case 2:
6116 v = is_signed ? *(gint16*)val : *(guint16*)val;
6117 break;
6118 case 4:
6119 v = is_signed ? *(gint32*)val : *(guint32*)val;
6120 break;
6121 case 8:
6122 v = is_signed ? *(gint64*)val : *(guint64*)val;
6123 break;
6124 default:
6125 g_assert_not_reached ();
6128 /* Set value on the stack or in the return ctx */
6129 if (reg_locations [reg]) {
6130 /* Saved on the stack */
6131 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6132 *(reg_locations [reg]) = v;
6133 } else {
6134 /* Not saved yet */
6135 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6136 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6139 // FIXME: Move these to mono-context.h/c.
6140 mono_arch_context_set_int_reg (ctx, reg, v);
6141 #else
6142 // FIXME: Can't set registers, so we disable linears
6143 NOT_IMPLEMENTED;
6144 #endif
6145 break;
6147 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6148 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6149 addr += (gint32)var->offset;
6151 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6153 if (t->byref) {
6154 addr = *(guint8**)addr;
6156 if (!addr)
6157 break;
6160 // FIXME: Write barriers
6161 mono_gc_memmove_atomic (addr, val, size);
6162 break;
6163 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6164 /* Same as regoffset, but with an indirection */
6165 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6166 addr += (gint32)var->offset;
6168 gaddr = (guint8 *)*(gpointer*)addr;
6169 g_assert (gaddr);
6170 // FIXME: Write barriers
6171 mono_gc_memmove_atomic (gaddr, val, size);
6172 break;
6173 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6174 NOT_IMPLEMENTED;
6175 break;
6176 default:
6177 g_assert_not_reached ();
6181 static void
6182 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6184 int size;
6186 if (t->byref) {
6187 addr = *(gpointer*)addr;
6188 g_assert (addr);
6191 if (MONO_TYPE_IS_REFERENCE (t))
6192 size = sizeof (gpointer);
6193 else
6194 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6196 memcpy (addr, val_buf, size);
6199 static void
6200 clear_event_request (int req_id, int etype)
6202 int i;
6204 mono_loader_lock ();
6205 for (i = 0; i < event_requests->len; ++i) {
6206 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6208 if (req->id == req_id && req->event_kind == etype) {
6209 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6210 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6211 if (req->event_kind == EVENT_KIND_STEP) {
6212 mono_de_cancel_ss ();
6214 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6215 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6216 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6217 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6218 g_ptr_array_remove_index_fast (event_requests, i);
6219 g_free (req);
6220 break;
6223 mono_loader_unlock ();
6226 static void
6227 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6229 int i;
6231 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6232 m->kind = MOD_KIND_NONE;
6233 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6234 int count = 0, match_count = 0, pos;
6235 MonoAssembly **newassemblies;
6237 for (i = 0; m->data.assemblies [i]; ++i) {
6238 count ++;
6239 if (m->data.assemblies [i] == assembly)
6240 match_count ++;
6243 if (match_count) {
6244 // +1 because we don't know length and we use last element to check for end
6245 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6247 pos = 0;
6248 for (i = 0; i < count; ++i)
6249 if (m->data.assemblies [i] != assembly)
6250 newassemblies [pos ++] = m->data.assemblies [i];
6251 g_assert (pos == count - match_count);
6252 g_free (m->data.assemblies);
6253 m->data.assemblies = newassemblies;
6258 static void
6259 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6261 int i;
6263 for (i = 0; i < req->nmodifiers; ++i) {
6264 Modifier *m = &req->modifiers [i];
6266 clear_assembly_from_modifier (req, m, assembly);
6271 * clear_event_requests_for_assembly:
6273 * Clear all events requests which reference ASSEMBLY.
6275 static void
6276 clear_event_requests_for_assembly (MonoAssembly *assembly)
6278 int i;
6279 gboolean found;
6281 mono_loader_lock ();
6282 found = TRUE;
6283 while (found) {
6284 found = FALSE;
6285 for (i = 0; i < event_requests->len; ++i) {
6286 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6288 clear_assembly_from_modifiers (req, assembly);
6290 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6291 clear_event_request (req->id, req->event_kind);
6292 found = TRUE;
6293 break;
6296 if (req->event_kind == EVENT_KIND_STEP)
6297 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6300 mono_loader_unlock ();
6304 * type_comes_from_assembly:
6306 * GHRFunc that returns TRUE if klass comes from assembly
6308 static gboolean
6309 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6311 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6315 * clear_types_for_assembly:
6317 * Clears types from loaded_classes for a given assembly
6319 static void
6320 clear_types_for_assembly (MonoAssembly *assembly)
6322 MonoDomain *domain = mono_domain_get ();
6323 AgentDomainInfo *info = NULL;
6325 if (!domain || !domain_jit_info (domain))
6326 /* Can happen during shutdown */
6327 return;
6329 info = get_agent_domain_info (domain);
6331 mono_loader_lock ();
6332 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6333 mono_loader_unlock ();
6336 static void
6337 dispose_vm (void)
6339 /* Clear all event requests */
6340 mono_loader_lock ();
6341 while (event_requests->len > 0) {
6342 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6344 clear_event_request (req->id, req->event_kind);
6346 mono_loader_unlock ();
6348 while (suspend_count > 0)
6349 resume_vm ();
6350 disconnected = TRUE;
6351 vm_start_event_sent = FALSE;
6354 static void
6355 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6357 MonoThread *thread = (MonoThread *)value;
6358 gboolean *ret = (gboolean *)user_data;
6359 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6360 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6361 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6362 *ret = TRUE;
6363 return;
6368 static void
6369 add_thread (gpointer key, gpointer value, gpointer user_data)
6371 MonoThread *thread = (MonoThread *)value;
6372 Buffer *buf = (Buffer *)user_data;
6373 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6374 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6375 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6376 return;
6378 buffer_add_objid (buf, (MonoObject*)thread);
6382 static ErrorCode
6383 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6385 ERROR_DECL (error);
6386 guint8 *end = invoke->endp;
6387 MonoMethod *m;
6388 int i, nargs;
6389 ErrorCode err;
6390 MonoMethodSignature *sig;
6391 guint8 **arg_buf;
6392 void **args;
6393 MonoObject *this_arg, *res, *exc = NULL;
6394 MonoDomain *domain;
6395 guint8 *this_buf;
6396 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6397 MonoLMFExt ext;
6398 #endif
6399 MonoStopwatch watch;
6401 if (invoke->method) {
6403 * Invoke this method directly, currently only Environment.Exit () is supported.
6405 this_arg = NULL;
6406 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>");
6408 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6409 mono_error_assert_ok (error);
6410 g_assert_not_reached ();
6413 m = decode_methodid (p, &p, end, &domain, &err);
6414 if (err != ERR_NONE)
6415 return err;
6416 sig = mono_method_signature_internal (m);
6418 if (m_class_is_valuetype (m->klass))
6419 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6420 else
6421 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6423 if (m->is_generic) {
6424 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));
6425 return ERR_INVALID_ARGUMENT;
6426 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6427 /* Should be null */
6428 int type = decode_byte (p, &p, end);
6429 if (type != VALUE_TYPE_ID_NULL) {
6430 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6431 return ERR_INVALID_ARGUMENT;
6433 memset (this_buf, 0, mono_class_instance_size (m->klass));
6434 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6435 /* Could be null */
6436 guint8 *tmp_p;
6438 int type = decode_byte (p, &tmp_p, end);
6439 if (type == VALUE_TYPE_ID_NULL) {
6440 memset (this_buf, 0, mono_class_instance_size (m->klass));
6441 p = tmp_p;
6442 } else {
6443 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6444 if (err != ERR_NONE)
6445 return err;
6447 } else {
6448 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6449 if (err != ERR_NONE)
6450 return err;
6453 if (!m_class_is_valuetype (m->klass))
6454 this_arg = *(MonoObject**)this_buf;
6455 else
6456 this_arg = NULL;
6458 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6459 if (!this_arg) {
6460 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6461 return ERR_INVALID_ARGUMENT;
6463 m = mono_object_get_virtual_method_internal (this_arg, m);
6464 /* Transform this to the format the rest of the code expects it to be */
6465 if (m_class_is_valuetype (m->klass)) {
6466 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6467 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6469 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6470 if (!this_arg) {
6471 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6472 return ERR_INVALID_ARGUMENT;
6474 m = mono_object_get_virtual_method_internal (this_arg, m);
6475 if (m_class_is_valuetype (m->klass)) {
6476 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6477 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6481 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>");
6483 if (this_arg && this_arg->vtable->domain != domain)
6484 NOT_IMPLEMENTED;
6486 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6487 if (!strcmp (m->name, ".ctor")) {
6488 if (mono_class_is_abstract (m->klass))
6489 return ERR_INVALID_ARGUMENT;
6490 else {
6491 ERROR_DECL (error);
6492 this_arg = mono_object_new_checked (domain, m->klass, error);
6493 mono_error_assert_ok (error);
6495 } else {
6496 return ERR_INVALID_ARGUMENT;
6500 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6501 return ERR_INVALID_ARGUMENT;
6503 nargs = decode_int (p, &p, end);
6504 if (nargs != sig->param_count)
6505 return ERR_INVALID_ARGUMENT;
6506 /* Use alloca to get gc tracking */
6507 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6508 memset (arg_buf, 0, nargs * sizeof (gpointer));
6509 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6510 for (i = 0; i < nargs; ++i) {
6511 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6512 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6513 if (err != ERR_NONE)
6514 break;
6515 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6516 NOT_IMPLEMENTED;
6518 if (sig->params [i]->byref) {
6519 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6520 *(gpointer*)arg_buf [i] = args [i];
6521 args [i] = arg_buf [i];
6523 } else {
6524 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6525 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6526 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6527 if (err != ERR_NONE)
6528 break;
6529 if (mono_class_is_nullable (arg_class)) {
6530 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6531 mono_error_assert_ok (error);
6532 } else {
6533 args [i] = arg_buf [i];
6538 if (i < nargs)
6539 return err;
6541 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6542 tls->disable_breakpoints = TRUE;
6543 else
6544 tls->disable_breakpoints = FALSE;
6547 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6549 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6550 if (invoke->has_ctx) {
6551 /* Setup our lmf */
6552 memset (&ext, 0, sizeof (ext));
6553 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6554 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6556 mono_push_lmf (&ext);
6558 #endif
6560 mono_stopwatch_start (&watch);
6561 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6562 if (!is_ok (error) && exc == NULL) {
6563 exc = (MonoObject*) mono_error_convert_to_exception (error);
6564 } else {
6565 mono_error_cleanup (error); /* FIXME report error */
6567 mono_stopwatch_stop (&watch);
6568 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));
6569 if (exc) {
6570 buffer_add_byte (buf, 0);
6571 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6572 } else {
6573 gboolean out_this = FALSE;
6574 gboolean out_args = FALSE;
6576 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6577 out_this = TRUE;
6578 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6579 out_args = TRUE;
6580 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6581 if (m->string_ctor) {
6582 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6583 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6584 if (!strcmp (m->name, ".ctor")) {
6585 if (!m_class_is_valuetype (m->klass))
6586 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6587 else
6588 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6589 } else {
6590 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6592 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6593 if (sig->ret->byref) {
6594 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6595 buffer_add_value (buf, ret_byval, &res, domain);
6596 } else {
6597 buffer_add_value (buf, sig->ret, &res, domain);
6599 } 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) {
6600 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6601 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6602 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6604 g_assert (nullable_buf);
6605 mono_nullable_init (nullable_buf, res, k);
6606 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6607 } else {
6608 g_assert (res);
6610 if (sig->ret->byref) {
6611 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6612 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6613 } else {
6614 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6617 } else {
6618 NOT_IMPLEMENTED;
6620 if (out_this)
6621 /* Return the new value of the receiver after the call */
6622 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6623 if (out_args) {
6624 buffer_add_int (buf, nargs);
6625 for (i = 0; i < nargs; ++i) {
6626 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6627 buffer_add_value (buf, sig->params [i], &args [i], domain);
6628 else if (sig->params [i]->byref)
6629 /* add_value () does an indirection */
6630 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6631 else
6632 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6637 tls->disable_breakpoints = FALSE;
6639 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6640 if (invoke->has_ctx)
6641 mono_pop_lmf ((MonoLMF*)&ext);
6642 #endif
6644 *endp = p;
6645 // FIXME: byref arguments
6646 // FIXME: varargs
6647 return ERR_NONE;
6651 * invoke_method:
6653 * Invoke the method given by tls->pending_invoke in the current thread.
6655 static void
6656 invoke_method (void)
6658 DebuggerTlsData *tls;
6659 InvokeData *invoke;
6660 int id;
6661 int i, mindex;
6662 ErrorCode err;
6663 Buffer buf;
6664 MonoContext restore_ctx;
6665 guint8 *p;
6667 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6668 g_assert (tls);
6671 * Store the `InvokeData *' in `tls->invoke' until we're done with
6672 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6675 mono_loader_lock ();
6677 invoke = tls->pending_invoke;
6678 g_assert (invoke);
6679 tls->pending_invoke = NULL;
6681 invoke->last_invoke = tls->invoke;
6682 tls->invoke = invoke;
6684 mono_loader_unlock ();
6686 tls->frames_up_to_date = FALSE;
6688 id = invoke->id;
6690 p = invoke->p;
6691 err = ERR_NONE;
6692 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6693 buffer_init (&buf, 128);
6695 if (err) {
6696 /* Fail the other invokes as well */
6697 } else {
6698 err = do_invoke_method (tls, &buf, invoke, p, &p);
6701 if (tls->abort_requested) {
6702 if (CHECK_PROTOCOL_VERSION (2, 42))
6703 err = ERR_INVOKE_ABORTED;
6706 /* Start suspending before sending the reply */
6707 if (mindex == invoke->nmethods - 1) {
6708 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6709 for (i = 0; i < invoke->suspend_count; ++i)
6710 suspend_vm ();
6714 send_reply_packet (id, err, &buf);
6716 buffer_free (&buf);
6719 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6721 if (invoke->has_ctx)
6722 save_thread_context (&restore_ctx);
6724 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6725 g_assert (tls->resume_count);
6726 tls->resume_count -= invoke->suspend_count;
6729 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6732 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6734 * It is possible that mono_thread_internal_abort () was called
6735 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6736 * because we reset the abort here.
6739 mono_loader_lock ();
6741 if (tls->abort_requested)
6742 mono_thread_internal_reset_abort (tls->thread);
6744 tls->invoke = tls->invoke->last_invoke;
6745 tls->abort_requested = FALSE;
6747 mono_loader_unlock ();
6749 g_free (invoke->p);
6750 g_free (invoke);
6753 static gboolean
6754 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6756 MonoThread *thread = (MonoThread *)value;
6757 DebuggerTlsData *tls;
6758 gboolean res;
6760 mono_loader_lock ();
6761 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6762 g_assert (tls);
6763 res = tls->really_suspended;
6764 mono_loader_unlock ();
6766 return res;
6769 static GPtrArray*
6770 get_source_files_for_type (MonoClass *klass)
6772 gpointer iter = NULL;
6773 MonoMethod *method;
6774 MonoDebugSourceInfo *sinfo;
6775 GPtrArray *files;
6776 int i, j;
6778 files = g_ptr_array_new ();
6780 while ((method = mono_class_get_methods (klass, &iter))) {
6781 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6782 GPtrArray *source_file_list;
6784 if (minfo) {
6785 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6786 for (j = 0; j < source_file_list->len; ++j) {
6787 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6788 for (i = 0; i < files->len; ++i)
6789 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6790 break;
6791 if (i == files->len)
6792 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6794 g_ptr_array_free (source_file_list, TRUE);
6798 return files;
6802 typedef struct {
6803 MonoTypeNameParse *info;
6804 gboolean ignore_case;
6805 GPtrArray *res_classes;
6806 GPtrArray *res_domains;
6807 } GetTypesArgs;
6809 static void
6810 get_types (gpointer key, gpointer value, gpointer user_data)
6812 MonoAssembly *ass;
6813 gboolean type_resolve;
6814 MonoType *t;
6815 GSList *tmp;
6816 MonoDomain *domain = (MonoDomain*)key;
6817 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
6818 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6820 mono_domain_assemblies_lock (domain);
6821 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6822 ass = (MonoAssembly *)tmp->data;
6824 if (ass->image) {
6825 ERROR_DECL (probe_type_error);
6826 /* FIXME really okay to call while holding locks? */
6827 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6828 mono_error_cleanup (probe_type_error);
6829 if (t) {
6830 g_ptr_array_add (ud->res_classes, mono_type_get_class_internal (t));
6831 g_ptr_array_add (ud->res_domains, domain);
6835 mono_domain_assemblies_unlock (domain);
6838 typedef struct {
6839 gboolean ignore_case;
6840 char *basename;
6841 GPtrArray *res_classes;
6842 GPtrArray *res_domains;
6843 } GetTypesForSourceFileArgs;
6845 static void
6846 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6848 GHashTableIter iter;
6849 GSList *class_list = NULL;
6850 MonoClass *klass = NULL;
6851 GPtrArray *files = NULL;
6853 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6854 MonoDomain *domain = (MonoDomain*)key;
6856 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6858 /* Update 'source_file_to_class' cache */
6859 g_hash_table_iter_init (&iter, info->loaded_classes);
6860 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6861 if (!g_hash_table_lookup (info->source_files, klass)) {
6862 files = get_source_files_for_type (klass);
6863 g_hash_table_insert (info->source_files, klass, files);
6865 for (int i = 0; i < files->len; ++i) {
6866 char *s = (char *)g_ptr_array_index (files, i);
6867 char *s2 = dbg_path_get_basename (s);
6868 char *s3;
6870 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6871 if (!class_list) {
6872 class_list = g_slist_prepend (class_list, klass);
6873 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6874 } else {
6875 class_list = g_slist_prepend (class_list, klass);
6876 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6879 /* The _ignorecase hash contains the lowercase path */
6880 s3 = strdup_tolower (s2);
6881 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6882 if (!class_list) {
6883 class_list = g_slist_prepend (class_list, klass);
6884 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6885 } else {
6886 class_list = g_slist_prepend (class_list, klass);
6887 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6890 g_free (s2);
6891 g_free (s3);
6896 if (ud->ignore_case) {
6897 char *s;
6899 s = strdup_tolower (ud->basename);
6900 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6901 g_free (s);
6902 } else {
6903 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6906 for (GSList *l = class_list; l; l = l->next) {
6907 klass = (MonoClass *)l->data;
6909 g_ptr_array_add (ud->res_classes, klass);
6910 g_ptr_array_add (ud->res_domains, domain);
6914 static ErrorCode
6915 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6917 switch (command) {
6918 case CMD_VM_VERSION: {
6919 char *build_info, *version;
6921 build_info = mono_get_runtime_build_info ();
6922 version = g_strdup_printf ("mono %s", build_info);
6924 buffer_add_string (buf, version); /* vm version */
6925 buffer_add_int (buf, MAJOR_VERSION);
6926 buffer_add_int (buf, MINOR_VERSION);
6927 g_free (build_info);
6928 g_free (version);
6929 break;
6931 case CMD_VM_SET_PROTOCOL_VERSION: {
6932 major_version = decode_int (p, &p, end);
6933 minor_version = decode_int (p, &p, end);
6934 protocol_version_set = TRUE;
6935 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6936 break;
6938 case CMD_VM_ALL_THREADS: {
6939 // FIXME: Domains
6940 gboolean remove_gc_finalizing = FALSE;
6941 mono_loader_lock ();
6942 int count = mono_g_hash_table_size (tid_to_thread_obj);
6943 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
6944 if (remove_gc_finalizing)
6945 count--;
6946 buffer_add_int (buf, count);
6947 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6949 mono_loader_unlock ();
6950 break;
6952 case CMD_VM_SUSPEND:
6953 suspend_vm ();
6954 wait_for_suspend ();
6955 break;
6956 case CMD_VM_RESUME:
6957 if (suspend_count == 0)
6958 return ERR_NOT_SUSPENDED;
6959 resume_vm ();
6960 clear_suspended_objs ();
6961 break;
6962 case CMD_VM_DISPOSE:
6963 dispose_vm ();
6964 break;
6965 case CMD_VM_EXIT: {
6966 MonoInternalThread *thread;
6967 DebuggerTlsData *tls;
6968 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6969 MonoClass *env_class;
6970 #endif
6971 MonoMethod *exit_method = NULL;
6972 gpointer *args;
6973 int exit_code;
6975 exit_code = decode_int (p, &p, end);
6977 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6979 /* Have to send a reply before exiting */
6980 send_reply_packet (id, 0, buf);
6982 /* Clear all event requests */
6983 mono_loader_lock ();
6984 while (event_requests->len > 0) {
6985 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6987 clear_event_request (req->id, req->event_kind);
6989 mono_loader_unlock ();
6992 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6993 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6994 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6995 * better than doing the shutdown ourselves, since it avoids various races.
6998 suspend_vm ();
6999 wait_for_suspend ();
7001 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7002 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7003 if (env_class) {
7004 ERROR_DECL (error);
7005 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
7006 mono_error_assert_ok (error);
7008 #endif
7010 mono_loader_lock ();
7011 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7012 mono_loader_unlock ();
7014 if (thread && exit_method) {
7015 mono_loader_lock ();
7016 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7017 mono_loader_unlock ();
7019 args = g_new0 (gpointer, 1);
7020 args [0] = g_malloc (sizeof (int));
7021 *(int*)(args [0]) = exit_code;
7023 tls->pending_invoke = g_new0 (InvokeData, 1);
7024 tls->pending_invoke->method = exit_method;
7025 tls->pending_invoke->args = args;
7026 tls->pending_invoke->nmethods = 1;
7028 while (suspend_count > 0)
7029 resume_vm ();
7030 } else {
7032 * No thread found, do it ourselves.
7033 * FIXME: This can race with normal shutdown etc.
7035 while (suspend_count > 0)
7036 resume_vm ();
7038 if (!mono_runtime_try_shutdown ())
7039 break;
7041 mono_environment_exitcode_set (exit_code);
7043 /* Suspend all managed threads since the runtime is going away */
7044 #ifndef ENABLE_NETCORE
7045 DEBUG_PRINTF (1, "Suspending all threads...\n");
7046 mono_thread_suspend_all_other_threads ();
7047 #endif
7048 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7049 mono_runtime_quit_internal ();
7050 transport_close2 ();
7051 DEBUG_PRINTF (1, "Exiting...\n");
7053 exit (exit_code);
7055 break;
7057 case CMD_VM_INVOKE_METHOD:
7058 case CMD_VM_INVOKE_METHODS: {
7059 int objid = decode_objid (p, &p, end);
7060 MonoThread *thread;
7061 DebuggerTlsData *tls;
7062 int i, count, flags, nmethods;
7063 ErrorCode err;
7065 err = get_object (objid, (MonoObject**)&thread);
7066 if (err != ERR_NONE)
7067 return err;
7069 flags = decode_int (p, &p, end);
7071 if (command == CMD_VM_INVOKE_METHODS)
7072 nmethods = decode_int (p, &p, end);
7073 else
7074 nmethods = 1;
7076 // Wait for suspending if it already started
7077 if (suspend_count)
7078 wait_for_suspend ();
7079 if (!is_suspended ())
7080 return ERR_NOT_SUSPENDED;
7082 mono_loader_lock ();
7083 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7084 mono_loader_unlock ();
7085 g_assert (tls);
7087 if (!tls->really_suspended)
7088 /* The thread is still running native code, can't do invokes */
7089 return ERR_NOT_SUSPENDED;
7092 * Store the invoke data into tls, the thread will execute it after it is
7093 * resumed.
7095 if (tls->pending_invoke)
7096 return ERR_NOT_SUSPENDED;
7097 tls->pending_invoke = g_new0 (InvokeData, 1);
7098 tls->pending_invoke->id = id;
7099 tls->pending_invoke->flags = flags;
7100 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7101 memcpy (tls->pending_invoke->p, p, end - p);
7102 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7103 tls->pending_invoke->suspend_count = suspend_count;
7104 tls->pending_invoke->nmethods = nmethods;
7106 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7107 resume_thread (THREAD_TO_INTERNAL (thread));
7109 else {
7110 count = suspend_count;
7111 for (i = 0; i < count; ++i)
7112 resume_vm ();
7114 break;
7116 case CMD_VM_ABORT_INVOKE: {
7117 int objid = decode_objid (p, &p, end);
7118 MonoThread *thread;
7119 DebuggerTlsData *tls;
7120 int invoke_id;
7121 ErrorCode err;
7123 err = get_object (objid, (MonoObject**)&thread);
7124 if (err != ERR_NONE)
7125 return err;
7127 invoke_id = decode_int (p, &p, end);
7129 mono_loader_lock ();
7130 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7131 g_assert (tls);
7133 if (tls->abort_requested) {
7134 DEBUG_PRINTF (1, "Abort already requested.\n");
7135 mono_loader_unlock ();
7136 break;
7140 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7141 * actually the correct invocation.
7143 * Careful, we do not stop the thread that's doing the invocation, so we can't
7144 * inspect its stack. However, invoke_method() also acquires the loader lock
7145 * when it's done, so we're safe here.
7149 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7150 mono_loader_unlock ();
7151 return ERR_NO_INVOCATION;
7154 tls->abort_requested = TRUE;
7156 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7157 mono_loader_unlock ();
7158 break;
7161 case CMD_VM_SET_KEEPALIVE: {
7162 int timeout = decode_int (p, &p, end);
7163 agent_config.keepalive = timeout;
7164 // FIXME:
7165 #ifndef DISABLE_SOCKET_TRANSPORT
7166 set_keepalive ();
7167 #else
7168 NOT_IMPLEMENTED;
7169 #endif
7170 break;
7172 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7173 int i;
7174 char *fname, *basename;
7175 gboolean ignore_case;
7176 GPtrArray *res_classes, *res_domains;
7178 fname = decode_string (p, &p, end);
7179 ignore_case = decode_byte (p, &p, end);
7181 basename = dbg_path_get_basename (fname);
7183 res_classes = g_ptr_array_new ();
7184 res_domains = g_ptr_array_new ();
7186 mono_loader_lock ();
7187 GetTypesForSourceFileArgs args;
7188 memset (&args, 0, sizeof (args));
7189 args.ignore_case = ignore_case;
7190 args.basename = basename;
7191 args.res_classes = res_classes;
7192 args.res_domains = res_domains;
7193 mono_de_foreach_domain (get_types_for_source_file, &args);
7194 mono_loader_unlock ();
7196 g_free (fname);
7197 g_free (basename);
7199 buffer_add_int (buf, res_classes->len);
7200 for (i = 0; i < res_classes->len; ++i)
7201 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7202 g_ptr_array_free (res_classes, TRUE);
7203 g_ptr_array_free (res_domains, TRUE);
7204 break;
7206 case CMD_VM_GET_TYPES: {
7207 ERROR_DECL (error);
7208 int i;
7209 char *name;
7210 gboolean ignore_case;
7211 GPtrArray *res_classes, *res_domains;
7212 MonoTypeNameParse info;
7214 name = decode_string (p, &p, end);
7215 ignore_case = decode_byte (p, &p, end);
7217 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7218 mono_error_cleanup (error);
7219 g_free (name);
7220 mono_reflection_free_type_info (&info);
7221 return ERR_INVALID_ARGUMENT;
7224 res_classes = g_ptr_array_new ();
7225 res_domains = g_ptr_array_new ();
7227 mono_loader_lock ();
7229 GetTypesArgs args;
7230 memset (&args, 0, sizeof (args));
7231 args.info = &info;
7232 args.ignore_case = ignore_case;
7233 args.res_classes = res_classes;
7234 args.res_domains = res_domains;
7236 mono_de_foreach_domain (get_types, &args);
7238 mono_loader_unlock ();
7240 g_free (name);
7241 mono_reflection_free_type_info (&info);
7243 buffer_add_int (buf, res_classes->len);
7244 for (i = 0; i < res_classes->len; ++i)
7245 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7246 g_ptr_array_free (res_classes, TRUE);
7247 g_ptr_array_free (res_domains, TRUE);
7248 break;
7250 case CMD_VM_START_BUFFERING:
7251 case CMD_VM_STOP_BUFFERING:
7252 /* Handled in the main loop */
7253 break;
7254 default:
7255 return ERR_NOT_IMPLEMENTED;
7258 return ERR_NONE;
7261 static ErrorCode
7262 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7264 ErrorCode err;
7265 ERROR_DECL (error);
7267 switch (command) {
7268 case CMD_EVENT_REQUEST_SET: {
7269 EventRequest *req;
7270 int i, event_kind, suspend_policy, nmodifiers;
7271 ModifierKind mod;
7272 MonoMethod *method;
7273 long location = 0;
7274 MonoThread *step_thread;
7275 int step_thread_id = 0;
7276 StepDepth depth = STEP_DEPTH_INTO;
7277 StepSize size = STEP_SIZE_MIN;
7278 StepFilter filter = STEP_FILTER_NONE;
7279 MonoDomain *domain;
7280 Modifier *modifier;
7282 event_kind = decode_byte (p, &p, end);
7283 suspend_policy = decode_byte (p, &p, end);
7284 nmodifiers = decode_byte (p, &p, end);
7286 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7287 req->id = mono_atomic_inc_i32 (&event_request_id);
7288 req->event_kind = event_kind;
7289 req->suspend_policy = suspend_policy;
7290 req->nmodifiers = nmodifiers;
7292 method = NULL;
7293 for (i = 0; i < nmodifiers; ++i) {
7294 mod = (ModifierKind)decode_byte (p, &p, end);
7296 req->modifiers [i].kind = mod;
7297 if (mod == MOD_KIND_COUNT) {
7298 req->modifiers [i].data.count = decode_int (p, &p, end);
7299 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7300 method = decode_methodid (p, &p, end, &domain, &err);
7301 if (err != ERR_NONE)
7302 return err;
7303 location = decode_long (p, &p, end);
7304 } else if (mod == MOD_KIND_STEP) {
7305 step_thread_id = decode_id (p, &p, end);
7306 size = (StepSize)decode_int (p, &p, end);
7307 depth = (StepDepth)decode_int (p, &p, end);
7308 if (CHECK_PROTOCOL_VERSION (2, 16))
7309 filter = (StepFilter)decode_int (p, &p, end);
7310 req->modifiers [i].data.filter = filter;
7311 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7312 /* Treat STEP_THOUGH the same as HIDDEN */
7313 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7314 } else if (mod == MOD_KIND_THREAD_ONLY) {
7315 int id = decode_id (p, &p, end);
7317 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7318 if (err != ERR_NONE) {
7319 g_free (req);
7320 return err;
7322 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7323 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7325 if (err != ERR_NONE)
7326 return err;
7327 req->modifiers [i].caught = decode_byte (p, &p, end);
7328 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7329 if (CHECK_PROTOCOL_VERSION (2, 25))
7330 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7331 else
7332 req->modifiers [i].subclasses = TRUE;
7333 if (exc_class) {
7334 req->modifiers [i].data.exc_class = exc_class;
7336 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7337 g_free (req);
7338 return ERR_INVALID_ARGUMENT;
7341 if (CHECK_PROTOCOL_VERSION (2, 54)) {
7342 req->modifiers [i].not_filtered_feature = decode_byte (p, &p, end);
7343 req->modifiers [i].everything_else = decode_byte (p, &p, end);
7344 DEBUG_PRINTF (1, "[dbg] \tEXCEPTION_ONLY 2 filter (%s%s%s%s).\n", exc_class ? m_class_get_name (exc_class) : (req->modifiers [i].everything_else ? "everything else" : "all"), req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : "");
7345 } else {
7346 req->modifiers [i].not_filtered_feature = FALSE;
7347 req->modifiers [i].everything_else = FALSE;
7348 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" : "");
7351 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7352 int n = decode_int (p, &p, end);
7353 int j;
7355 // +1 because we don't know length and we use last element to check for end
7356 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7357 for (j = 0; j < n; ++j) {
7358 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7359 if (err != ERR_NONE) {
7360 g_free (req->modifiers [i].data.assemblies);
7361 return err;
7364 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7365 int n = decode_int (p, &p, end);
7366 int j;
7368 modifier = &req->modifiers [i];
7369 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7370 for (j = 0; j < n; ++j) {
7371 char *s = decode_string (p, &p, end);
7372 char *s2;
7374 if (s) {
7375 s2 = strdup_tolower (s);
7376 g_hash_table_insert (modifier->data.source_files, s2, s2);
7377 g_free (s);
7380 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7381 int n = decode_int (p, &p, end);
7382 int j;
7384 modifier = &req->modifiers [i];
7385 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7386 for (j = 0; j < n; ++j) {
7387 char *s = decode_string (p, &p, end);
7389 if (s)
7390 g_hash_table_insert (modifier->data.type_names, s, s);
7392 } else {
7393 g_free (req);
7394 return ERR_NOT_IMPLEMENTED;
7398 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7399 g_assert (method);
7401 req->info = mono_de_set_breakpoint (method, location, req, error);
7402 if (!is_ok (error)) {
7403 g_free (req);
7404 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7405 mono_error_cleanup (error);
7406 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7408 } else if (req->event_kind == EVENT_KIND_STEP) {
7409 g_assert (step_thread_id);
7411 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7412 if (err != ERR_NONE) {
7413 g_free (req);
7414 return err;
7417 mono_loader_lock ();
7418 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7419 mono_loader_unlock ();
7420 g_assert (tls);
7422 if (tls->terminated) {
7423 /* if the thread is already terminated ignore the single step */
7424 buffer_add_int (buf, req->id);
7425 return ERR_NONE;
7428 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7429 if (err != ERR_NONE) {
7430 g_free (req);
7431 return err;
7433 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7434 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7435 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7436 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7437 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7438 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7439 } else {
7440 if (req->nmodifiers) {
7441 g_free (req);
7442 return ERR_NOT_IMPLEMENTED;
7446 mono_loader_lock ();
7447 g_ptr_array_add (event_requests, req);
7449 if (agent_config.defer) {
7450 /* Transmit cached data to the client on receipt of the event request */
7451 switch (req->event_kind) {
7452 case EVENT_KIND_APPDOMAIN_CREATE:
7453 /* Emit load events for currently loaded domains */
7454 mono_de_foreach_domain (emit_appdomain_load, NULL);
7455 break;
7456 case EVENT_KIND_ASSEMBLY_LOAD:
7457 /* Emit load events for currently loaded assemblies */
7458 mono_domain_foreach (send_assemblies_for_domain, NULL);
7459 break;
7460 case EVENT_KIND_THREAD_START:
7461 /* Emit start events for currently started threads */
7462 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7463 break;
7464 case EVENT_KIND_TYPE_LOAD:
7465 /* Emit type load events for currently loaded types */
7466 mono_domain_foreach (send_types_for_domain, NULL);
7467 break;
7468 default:
7469 break;
7472 mono_loader_unlock ();
7474 buffer_add_int (buf, req->id);
7475 break;
7477 case CMD_EVENT_REQUEST_CLEAR: {
7478 int etype = decode_byte (p, &p, end);
7479 int req_id = decode_int (p, &p, end);
7481 // FIXME: Make a faster mapping from req_id to request
7482 mono_loader_lock ();
7483 clear_event_request (req_id, etype);
7484 mono_loader_unlock ();
7485 break;
7487 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7488 int i;
7490 mono_loader_lock ();
7491 i = 0;
7492 while (i < event_requests->len) {
7493 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7495 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7496 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7498 g_ptr_array_remove_index_fast (event_requests, i);
7499 g_free (req);
7500 } else {
7501 i ++;
7504 mono_loader_unlock ();
7505 break;
7507 default:
7508 return ERR_NOT_IMPLEMENTED;
7511 return ERR_NONE;
7514 static ErrorCode
7515 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7517 ErrorCode err;
7518 MonoDomain *domain;
7520 switch (command) {
7521 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7522 buffer_add_domainid (buf, mono_get_root_domain ());
7523 break;
7525 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7526 domain = decode_domainid (p, &p, end, NULL, &err);
7527 if (err != ERR_NONE)
7528 return err;
7529 buffer_add_string (buf, domain->friendly_name);
7530 break;
7532 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7533 GSList *tmp;
7534 MonoAssembly *ass;
7535 int count;
7537 domain = decode_domainid (p, &p, end, NULL, &err);
7538 if (err != ERR_NONE)
7539 return err;
7540 mono_domain_assemblies_lock (domain);
7541 count = 0;
7542 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7543 count ++;
7545 buffer_add_int (buf, count);
7546 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7547 ass = (MonoAssembly *)tmp->data;
7548 buffer_add_assemblyid (buf, domain, ass);
7550 mono_domain_assemblies_unlock (domain);
7551 break;
7553 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7554 domain = decode_domainid (p, &p, end, NULL, &err);
7555 if (err != ERR_NONE)
7556 return err;
7558 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7559 break;
7561 case CMD_APPDOMAIN_GET_CORLIB: {
7562 domain = decode_domainid (p, &p, end, NULL, &err);
7563 if (err != ERR_NONE)
7564 return err;
7566 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7567 break;
7569 case CMD_APPDOMAIN_CREATE_STRING: {
7570 char *s;
7571 MonoString *o;
7572 ERROR_DECL (error);
7574 domain = decode_domainid (p, &p, end, NULL, &err);
7575 if (err != ERR_NONE)
7576 return err;
7577 s = decode_string (p, &p, end);
7579 o = mono_string_new_checked (domain, s, error);
7580 if (!is_ok (error)) {
7581 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7582 mono_error_cleanup (error);
7583 return ERR_INVALID_OBJECT;
7585 buffer_add_objid (buf, (MonoObject*)o);
7586 break;
7588 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7589 ERROR_DECL (error);
7590 MonoArray *arr;
7591 gpointer elem;
7592 domain = decode_domainid (p, &p, end, NULL, &err);
7593 uintptr_t size = 0;
7594 int len = decode_int (p, &p, end);
7595 size = len;
7596 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7597 elem = mono_array_addr_internal (arr, guint8, 0);
7598 memcpy (elem, p, len);
7599 p += len;
7600 buffer_add_objid (buf, (MonoObject*) arr);
7601 break;
7603 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7604 ERROR_DECL (error);
7605 MonoClass *klass;
7606 MonoDomain *domain2;
7607 MonoObject *o;
7609 domain = decode_domainid (p, &p, end, NULL, &err);
7610 if (err != ERR_NONE)
7611 return err;
7612 klass = decode_typeid (p, &p, end, &domain2, &err);
7613 if (err != ERR_NONE)
7614 return err;
7616 // FIXME:
7617 g_assert (domain == domain2);
7619 o = mono_object_new_checked (domain, klass, error);
7620 mono_error_assert_ok (error);
7622 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7623 if (err != ERR_NONE)
7624 return err;
7626 buffer_add_objid (buf, o);
7627 break;
7629 default:
7630 return ERR_NOT_IMPLEMENTED;
7633 return ERR_NONE;
7636 static ErrorCode
7637 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7639 HANDLE_FUNCTION_ENTER();
7640 ErrorCode err = ERR_NONE;
7641 error_init (error);
7642 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7643 if (MONO_HANDLE_IS_NULL (o)) {
7644 err = ERR_INVALID_OBJECT;
7645 goto leave;
7647 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7648 leave:
7649 HANDLE_FUNCTION_RETURN_VAL (err);
7653 static ErrorCode
7654 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7656 ErrorCode err;
7657 MonoAssembly *ass;
7658 MonoDomain *domain;
7660 ass = decode_assemblyid (p, &p, end, &domain, &err);
7661 if (err != ERR_NONE)
7662 return err;
7664 switch (command) {
7665 case CMD_ASSEMBLY_GET_LOCATION: {
7666 buffer_add_string (buf, mono_image_get_filename (ass->image));
7667 break;
7669 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7670 guint32 token;
7671 MonoMethod *m;
7673 if (ass->image->dynamic) {
7674 buffer_add_id (buf, 0);
7675 } else {
7676 token = mono_image_get_entry_point (ass->image);
7677 if (token == 0) {
7678 buffer_add_id (buf, 0);
7679 } else {
7680 ERROR_DECL (error);
7681 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7682 if (!m)
7683 mono_error_cleanup (error); /* FIXME don't swallow the error */
7684 buffer_add_methodid (buf, domain, m);
7687 break;
7689 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7690 buffer_add_moduleid (buf, domain, ass->image);
7691 break;
7693 case CMD_ASSEMBLY_GET_OBJECT: {
7694 ERROR_DECL (error);
7695 err = get_assembly_object_command (domain, ass, buf, error);
7696 mono_error_cleanup (error);
7697 return err;
7699 case CMD_ASSEMBLY_GET_DOMAIN: {
7700 buffer_add_domainid (buf, domain);
7701 break;
7703 case CMD_ASSEMBLY_GET_TYPE: {
7704 ERROR_DECL (error);
7705 char *s = decode_string (p, &p, end);
7706 gboolean ignorecase = decode_byte (p, &p, end);
7707 MonoTypeNameParse info;
7708 MonoType *t;
7709 gboolean type_resolve, res;
7710 MonoDomain *d = mono_domain_get ();
7711 MonoAssemblyLoadContext *alc = mono_domain_default_alc (d);
7713 /* This is needed to be able to find referenced assemblies */
7714 res = mono_domain_set_fast (domain, FALSE);
7715 g_assert (res);
7717 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7718 mono_error_cleanup (error);
7719 t = NULL;
7720 } else {
7721 if (info.assembly.name)
7722 NOT_IMPLEMENTED;
7723 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7724 if (!is_ok (error)) {
7725 mono_error_cleanup (error); /* FIXME don't swallow the error */
7726 mono_reflection_free_type_info (&info);
7727 g_free (s);
7728 return ERR_INVALID_ARGUMENT;
7731 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7732 mono_reflection_free_type_info (&info);
7733 g_free (s);
7735 mono_domain_set_fast (d, TRUE);
7737 break;
7739 case CMD_ASSEMBLY_GET_NAME: {
7740 gchar *name;
7741 MonoAssembly *mass = ass;
7743 name = g_strdup_printf (
7744 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7745 mass->aname.name,
7746 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7747 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7748 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7749 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7751 buffer_add_string (buf, name);
7752 g_free (name);
7753 break;
7755 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7756 MonoImage* image = ass->image;
7757 if (ass->dynamic) {
7758 return ERR_NOT_IMPLEMENTED;
7760 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7761 break;
7763 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7764 buffer_add_byte (buf, ass->dynamic);
7765 break;
7767 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7768 MonoImage* image = ass->image;
7769 MonoDebugHandle* handle = mono_debug_get_handle (image);
7770 if (!handle) {
7771 return ERR_INVALID_ARGUMENT;
7773 MonoPPDBFile* ppdb = handle->ppdb;
7774 if (ppdb) {
7775 image = mono_ppdb_get_image (ppdb);
7776 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7777 } else {
7778 buffer_add_byte_array (buf, NULL, 0);
7780 break;
7782 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7783 if (ass->dynamic) {
7784 return ERR_NOT_IMPLEMENTED;
7786 guint32 token = decode_int (p, &p, end);
7787 ERROR_DECL (error);
7788 error_init (error);
7789 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7790 if (!is_ok (error)) {
7791 mono_error_cleanup (error);
7792 return ERR_INVALID_ARGUMENT;
7794 buffer_add_typeid (buf, domain, mono_class);
7795 mono_error_cleanup (error);
7796 break;
7798 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7799 if (ass->dynamic) {
7800 return ERR_NOT_IMPLEMENTED;
7802 guint32 token = decode_int (p, &p, end);
7803 ERROR_DECL (error);
7804 error_init (error);
7805 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7806 if (!is_ok (error)) {
7807 mono_error_cleanup (error);
7808 return ERR_INVALID_ARGUMENT;
7810 buffer_add_methodid (buf, domain, mono_method);
7811 mono_error_cleanup (error);
7812 break;
7814 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7815 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7816 break;
7818 default:
7819 return ERR_NOT_IMPLEMENTED;
7822 return ERR_NONE;
7825 static ErrorCode
7826 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7828 ErrorCode err;
7829 MonoDomain *domain;
7831 switch (command) {
7832 case CMD_MODULE_GET_INFO: {
7833 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7834 char *basename, *sourcelink = NULL;
7836 if (CHECK_PROTOCOL_VERSION (2, 48))
7837 sourcelink = mono_debug_image_get_sourcelink (image);
7839 basename = g_path_get_basename (image->name);
7840 buffer_add_string (buf, basename); // name
7841 buffer_add_string (buf, image->module_name); // scopename
7842 buffer_add_string (buf, image->name); // fqname
7843 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7844 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7845 if (CHECK_PROTOCOL_VERSION (2, 48))
7846 buffer_add_string (buf, sourcelink);
7847 g_free (basename);
7848 g_free (sourcelink);
7849 break;
7851 default:
7852 return ERR_NOT_IMPLEMENTED;
7855 return ERR_NONE;
7858 static ErrorCode
7859 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7861 ErrorCode err;
7862 MonoDomain *domain;
7864 switch (command) {
7865 case CMD_FIELD_GET_INFO: {
7866 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7868 buffer_add_string (buf, f->name);
7869 buffer_add_typeid (buf, domain, f->parent);
7870 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7871 buffer_add_int (buf, f->type->attrs);
7872 break;
7874 default:
7875 return ERR_NOT_IMPLEMENTED;
7878 return ERR_NONE;
7881 static void
7882 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7884 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7885 /* Special case these so the client doesn't have to handle Type objects */
7887 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7888 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
7889 } else if (MONO_TYPE_IS_REFERENCE (t))
7890 buffer_add_value (buf, t, &val, domain);
7891 else
7892 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
7895 static ErrorCode
7896 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7898 int i, j;
7899 int nattrs = 0;
7901 if (!cinfo) {
7902 buffer_add_int (buf, 0);
7903 return ERR_NONE;
7906 SETUP_ICALL_FUNCTION;
7908 for (i = 0; i < cinfo->num_attrs; ++i) {
7909 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7910 nattrs ++;
7912 buffer_add_int (buf, nattrs);
7914 for (i = 0; i < cinfo->num_attrs; ++i) {
7915 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7916 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7917 MonoArray *typed_args, *named_args;
7918 MonoArrayHandleOut typed_args_h, named_args_h;
7919 MonoObjectHandle val_h;
7920 MonoType *t;
7921 CattrNamedArg *arginfo = NULL;
7922 ERROR_DECL (error);
7924 SETUP_ICALL_FRAME;
7925 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
7926 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
7927 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
7929 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
7930 if (!is_ok (error)) {
7931 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
7932 mono_error_cleanup (error);
7933 CLEAR_ICALL_FRAME;
7934 return ERR_LOADER_ERROR;
7936 typed_args = MONO_HANDLE_RAW (typed_args_h);
7937 named_args = MONO_HANDLE_RAW (named_args_h);
7939 buffer_add_methodid (buf, domain, attr->ctor);
7941 /* Ctor args */
7942 if (typed_args) {
7943 buffer_add_int (buf, mono_array_length_internal (typed_args));
7944 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
7945 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
7946 MONO_HANDLE_ASSIGN_RAW (val_h, val);
7948 t = mono_method_signature_internal (attr->ctor)->params [j];
7950 buffer_add_cattr_arg (buf, t, domain, val);
7952 } else {
7953 buffer_add_int (buf, 0);
7956 /* Named args */
7957 if (named_args) {
7958 buffer_add_int (buf, mono_array_length_internal (named_args));
7960 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
7961 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
7962 MONO_HANDLE_ASSIGN_RAW (val_h, val);
7964 if (arginfo [j].prop) {
7965 buffer_add_byte (buf, 0x54);
7966 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7967 } else if (arginfo [j].field) {
7968 buffer_add_byte (buf, 0x53);
7969 buffer_add_fieldid (buf, domain, arginfo [j].field);
7970 } else {
7971 g_assert_not_reached ();
7974 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7976 } else {
7977 buffer_add_int (buf, 0);
7979 g_free (arginfo);
7981 CLEAR_ICALL_FRAME;
7985 return ERR_NONE;
7988 /* FIXME: Code duplication with icall.c */
7989 static void
7990 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7992 int i;
7993 MonoClass *ic;
7995 mono_class_setup_interfaces (klass, error);
7996 if (!is_ok (error))
7997 return;
7999 int klass_interface_count = m_class_get_interface_count (klass);
8000 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
8001 for (i = 0; i < klass_interface_count; i++) {
8002 ic = klass_interfaces [i];
8003 g_hash_table_insert (ifaces, ic, ic);
8005 collect_interfaces (ic, ifaces, error);
8006 if (!is_ok (error))
8007 return;
8011 static ErrorCode
8012 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8014 HANDLE_FUNCTION_ENTER ();
8016 ERROR_DECL (error);
8017 MonoClass *nested;
8018 MonoType *type;
8019 gpointer iter;
8020 guint8 b;
8021 int nnested;
8022 ErrorCode err;
8023 char *name;
8024 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
8026 switch (command) {
8027 case CMD_TYPE_GET_INFO: {
8028 buffer_add_string (buf, m_class_get_name_space (klass));
8029 buffer_add_string (buf, m_class_get_name (klass));
8030 // FIXME: byref
8031 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8032 buffer_add_string (buf, name);
8033 g_free (name);
8034 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
8035 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
8036 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
8037 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
8038 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
8039 else
8040 buffer_add_id (buf, 0);
8041 buffer_add_int (buf, m_class_get_type_token (klass));
8042 buffer_add_byte (buf, m_class_get_rank (klass));
8043 buffer_add_int (buf, mono_class_get_flags (klass));
8044 b = 0;
8045 type = m_class_get_byval_arg (klass);
8046 // FIXME: Can't decide whenever a class represents a byref type
8047 if (FALSE)
8048 b |= (1 << 0);
8049 if (type->type == MONO_TYPE_PTR)
8050 b |= (1 << 1);
8051 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8052 b |= (1 << 2);
8053 if (type->type == MONO_TYPE_VALUETYPE)
8054 b |= (1 << 3);
8055 if (m_class_is_enumtype (klass))
8056 b |= (1 << 4);
8057 if (mono_class_is_gtd (klass))
8058 b |= (1 << 5);
8059 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8060 b |= (1 << 6);
8061 buffer_add_byte (buf, b);
8062 nnested = 0;
8063 iter = NULL;
8064 while ((nested = mono_class_get_nested_types (klass, &iter)))
8065 nnested ++;
8066 buffer_add_int (buf, nnested);
8067 iter = NULL;
8068 while ((nested = mono_class_get_nested_types (klass, &iter)))
8069 buffer_add_typeid (buf, domain, nested);
8070 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8071 if (mono_class_is_gtd (klass))
8072 buffer_add_typeid (buf, domain, klass);
8073 else if (mono_class_is_ginst (klass))
8074 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8075 else
8076 buffer_add_id (buf, 0);
8078 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8079 int count, i;
8081 if (mono_class_is_ginst (klass)) {
8082 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8084 count = inst->type_argc;
8085 buffer_add_int (buf, count);
8086 for (i = 0; i < count; i++)
8087 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8088 } else if (mono_class_is_gtd (klass)) {
8089 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8090 MonoClass *pklass;
8092 count = container->type_argc;
8093 buffer_add_int (buf, count);
8094 for (i = 0; i < count; i++) {
8095 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8096 buffer_add_typeid (buf, domain, pklass);
8098 } else {
8099 buffer_add_int (buf, 0);
8102 break;
8104 case CMD_TYPE_GET_METHODS: {
8105 int nmethods;
8106 int i = 0;
8107 gpointer iter = NULL;
8108 MonoMethod *m;
8110 mono_class_setup_methods (klass);
8112 nmethods = mono_class_num_methods (klass);
8114 buffer_add_int (buf, nmethods);
8116 while ((m = mono_class_get_methods (klass, &iter))) {
8117 buffer_add_methodid (buf, domain, m);
8118 i ++;
8120 g_assert (i == nmethods);
8121 break;
8123 case CMD_TYPE_GET_FIELDS: {
8124 int nfields;
8125 int i = 0;
8126 gpointer iter = NULL;
8127 MonoClassField *f;
8129 nfields = mono_class_num_fields (klass);
8131 buffer_add_int (buf, nfields);
8133 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8134 buffer_add_fieldid (buf, domain, f);
8135 buffer_add_string (buf, f->name);
8136 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8137 buffer_add_int (buf, f->type->attrs);
8138 i ++;
8140 g_assert (i == nfields);
8141 break;
8143 case CMD_TYPE_GET_PROPERTIES: {
8144 int nprops;
8145 int i = 0;
8146 gpointer iter = NULL;
8147 MonoProperty *p;
8149 nprops = mono_class_num_properties (klass);
8151 buffer_add_int (buf, nprops);
8153 while ((p = mono_class_get_properties (klass, &iter))) {
8154 buffer_add_propertyid (buf, domain, p);
8155 buffer_add_string (buf, p->name);
8156 buffer_add_methodid (buf, domain, p->get);
8157 buffer_add_methodid (buf, domain, p->set);
8158 buffer_add_int (buf, p->attrs);
8159 i ++;
8161 g_assert (i == nprops);
8162 break;
8164 case CMD_TYPE_GET_CATTRS: {
8165 MonoClass *attr_klass;
8166 MonoCustomAttrInfo *cinfo;
8168 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8169 /* attr_klass can be NULL */
8170 if (err != ERR_NONE)
8171 goto exit;
8173 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8174 if (!is_ok (error)) {
8175 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8176 goto loader_error;
8179 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8180 if (err != ERR_NONE)
8181 goto exit;
8182 break;
8184 case CMD_TYPE_GET_FIELD_CATTRS: {
8185 MonoClass *attr_klass;
8186 MonoCustomAttrInfo *cinfo;
8187 MonoClassField *field;
8189 field = decode_fieldid (p, &p, end, NULL, &err);
8190 if (err != ERR_NONE)
8191 goto exit;
8192 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8193 if (err != ERR_NONE)
8194 goto exit;
8196 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8197 if (!is_ok (error)) {
8198 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8199 goto loader_error;
8202 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8203 if (err != ERR_NONE)
8204 goto exit;
8205 break;
8207 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8208 MonoClass *attr_klass;
8209 MonoCustomAttrInfo *cinfo;
8210 MonoProperty *prop;
8212 prop = decode_propertyid (p, &p, end, NULL, &err);
8213 if (err != ERR_NONE)
8214 goto exit;
8215 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8216 if (err != ERR_NONE)
8217 goto exit;
8219 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8220 if (!is_ok (error)) {
8221 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8222 goto loader_error;
8225 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8226 if (err != ERR_NONE)
8227 goto exit;
8228 break;
8230 case CMD_TYPE_GET_VALUES:
8231 case CMD_TYPE_GET_VALUES_2: {
8232 guint8 *val;
8233 MonoClassField *f;
8234 MonoVTable *vtable;
8235 MonoClass *k;
8236 int len, i;
8237 gboolean found;
8238 MonoThread *thread_obj;
8239 MonoInternalThread *thread = NULL;
8240 guint32 special_static_type;
8242 if (command == CMD_TYPE_GET_VALUES_2) {
8243 int objid = decode_objid (p, &p, end);
8245 err = get_object (objid, (MonoObject**)&thread_obj);
8246 if (err != ERR_NONE)
8247 goto exit;
8249 thread = THREAD_TO_INTERNAL (thread_obj);
8252 len = decode_int (p, &p, end);
8253 for (i = 0; i < len; ++i) {
8254 f = decode_fieldid (p, &p, end, NULL, &err);
8255 if (err != ERR_NONE)
8256 goto exit;
8258 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8259 goto invalid_fieldid;
8261 special_static_type = mono_class_field_get_special_static_type (f);
8262 if (special_static_type != SPECIAL_STATIC_NONE) {
8263 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8264 goto invalid_fieldid;
8267 /* Check that the field belongs to the object */
8268 found = FALSE;
8269 for (k = klass; k; k = m_class_get_parent (k)) {
8270 if (k == f->parent) {
8271 found = TRUE;
8272 break;
8275 if (!found)
8276 goto invalid_fieldid;
8278 vtable = mono_class_vtable_checked (domain, f->parent, error);
8279 goto_if_nok (error, invalid_fieldid);
8281 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8282 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, string_handle, error);
8283 goto_if_nok (error, invalid_fieldid);
8285 buffer_add_value (buf, f->type, val, domain);
8286 g_free (val);
8288 break;
8290 case CMD_TYPE_SET_VALUES: {
8291 guint8 *val;
8292 MonoClassField *f;
8293 MonoVTable *vtable;
8294 MonoClass *k;
8295 int len, i;
8296 gboolean found;
8298 len = decode_int (p, &p, end);
8299 for (i = 0; i < len; ++i) {
8300 f = decode_fieldid (p, &p, end, NULL, &err);
8301 if (err != ERR_NONE)
8302 goto exit;
8304 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8305 goto invalid_fieldid;
8307 if (mono_class_field_is_special_static (f))
8308 goto invalid_fieldid;
8310 /* Check that the field belongs to the object */
8311 found = FALSE;
8312 for (k = klass; k; k = m_class_get_parent (k)) {
8313 if (k == f->parent) {
8314 found = TRUE;
8315 break;
8318 if (!found)
8319 goto invalid_fieldid;
8321 // FIXME: Check for literal/const
8323 vtable = mono_class_vtable_checked (domain, f->parent, error);
8324 goto_if_nok (error, invalid_fieldid);
8326 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8327 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8328 if (err != ERR_NONE) {
8329 g_free (val);
8330 goto exit;
8332 if (MONO_TYPE_IS_REFERENCE (f->type))
8333 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8334 else
8335 mono_field_static_set_value_internal (vtable, f, val);
8336 g_free (val);
8338 break;
8340 case CMD_TYPE_GET_OBJECT: {
8341 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8342 if (!is_ok (error)) {
8343 mono_error_cleanup (error);
8344 goto invalid_object;
8346 buffer_add_objid (buf, o);
8347 break;
8349 case CMD_TYPE_GET_SOURCE_FILES:
8350 case CMD_TYPE_GET_SOURCE_FILES_2: {
8351 char *source_file, *base;
8352 GPtrArray *files;
8353 int i;
8355 files = get_source_files_for_type (klass);
8357 buffer_add_int (buf, files->len);
8358 for (i = 0; i < files->len; ++i) {
8359 source_file = (char *)g_ptr_array_index (files, i);
8360 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8361 buffer_add_string (buf, source_file);
8362 } else {
8363 base = dbg_path_get_basename (source_file);
8364 buffer_add_string (buf, base);
8365 g_free (base);
8367 g_free (source_file);
8369 g_ptr_array_free (files, TRUE);
8370 break;
8372 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8373 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8375 if (err != ERR_NONE)
8376 goto exit;
8377 if (mono_class_is_assignable_from_internal (klass, oklass))
8378 buffer_add_byte (buf, 1);
8379 else
8380 buffer_add_byte (buf, 0);
8381 break;
8383 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8384 char *name = decode_string (p, &p, end);
8385 int i, flags = decode_int (p, &p, end);
8386 int mlisttype;
8387 if (CHECK_PROTOCOL_VERSION (2, 48))
8388 mlisttype = decode_int (p, &p, end);
8389 else
8390 mlisttype = 0; // MLISTTYPE_All
8391 ERROR_DECL (error);
8392 GPtrArray *array;
8394 error_init (error);
8395 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8396 if (!is_ok (error)) {
8397 mono_error_cleanup (error);
8398 goto loader_error;
8400 buffer_add_int (buf, array->len);
8401 for (i = 0; i < array->len; ++i) {
8402 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8403 buffer_add_methodid (buf, domain, method);
8406 g_ptr_array_free (array, TRUE);
8407 g_free (name);
8408 break;
8410 case CMD_TYPE_GET_INTERFACES: {
8411 MonoClass *parent;
8412 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8413 MonoClass *tclass, *iface;
8414 GHashTableIter iter;
8416 tclass = klass;
8418 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8419 mono_class_setup_interfaces (parent, error);
8420 goto_if_nok (error, loader_error);
8422 collect_interfaces (parent, iface_hash, error);
8423 goto_if_nok (error, loader_error);
8426 buffer_add_int (buf, g_hash_table_size (iface_hash));
8428 g_hash_table_iter_init (&iter, iface_hash);
8429 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8430 buffer_add_typeid (buf, domain, iface);
8431 g_hash_table_destroy (iface_hash);
8432 break;
8434 case CMD_TYPE_GET_INTERFACE_MAP: {
8435 int tindex, ioffset;
8436 gboolean variance_used;
8437 MonoClass *iclass;
8438 int len, nmethods, i;
8439 gpointer iter;
8440 MonoMethod *method;
8442 len = decode_int (p, &p, end);
8443 mono_class_setup_vtable (klass);
8445 for (tindex = 0; tindex < len; ++tindex) {
8446 iclass = decode_typeid (p, &p, end, NULL, &err);
8447 if (err != ERR_NONE)
8448 goto exit;
8450 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8451 if (ioffset == -1)
8452 goto invalid_argument;
8454 nmethods = mono_class_num_methods (iclass);
8455 buffer_add_int (buf, nmethods);
8457 iter = NULL;
8458 while ((method = mono_class_get_methods (iclass, &iter))) {
8459 buffer_add_methodid (buf, domain, method);
8461 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8462 for (i = 0; i < nmethods; ++i)
8463 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8465 break;
8467 case CMD_TYPE_IS_INITIALIZED: {
8468 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8469 goto_if_nok (error, loader_error);
8471 if (vtable)
8472 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8473 else
8474 buffer_add_int (buf, 0);
8475 break;
8477 case CMD_TYPE_CREATE_INSTANCE: {
8478 ERROR_DECL (error);
8479 MonoObject *obj;
8481 obj = mono_object_new_checked (domain, klass, error);
8482 mono_error_assert_ok (error);
8483 buffer_add_objid (buf, obj);
8484 break;
8486 case CMD_TYPE_GET_VALUE_SIZE: {
8487 int32_t value_size;
8489 value_size = mono_class_value_size (klass, NULL);
8490 buffer_add_int (buf, value_size);
8491 break;
8493 default:
8494 err = ERR_NOT_IMPLEMENTED;
8495 goto exit;
8498 err = ERR_NONE;
8499 goto exit;
8500 invalid_argument:
8501 err = ERR_INVALID_ARGUMENT;
8502 goto exit;
8503 invalid_fieldid:
8504 err = ERR_INVALID_FIELDID;
8505 goto exit;
8506 invalid_object:
8507 err = ERR_INVALID_OBJECT;
8508 goto exit;
8509 loader_error:
8510 err = ERR_LOADER_ERROR;
8511 goto exit;
8512 exit:
8513 HANDLE_FUNCTION_RETURN_VAL (err);
8516 static ErrorCode
8517 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8519 MonoClass *klass;
8520 MonoDomain *old_domain;
8521 MonoDomain *domain;
8522 ErrorCode err;
8524 klass = decode_typeid (p, &p, end, &domain, &err);
8525 if (err != ERR_NONE)
8526 return err;
8528 old_domain = mono_domain_get ();
8530 mono_domain_set_fast (domain, TRUE);
8532 err = type_commands_internal (command, klass, domain, p, end, buf);
8534 mono_domain_set_fast (old_domain, TRUE);
8536 return err;
8539 static ErrorCode
8540 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8542 MonoMethodHeader *header;
8543 ErrorCode err;
8545 switch (command) {
8546 case CMD_METHOD_GET_NAME: {
8547 buffer_add_string (buf, method->name);
8548 break;
8550 case CMD_METHOD_GET_DECLARING_TYPE: {
8551 buffer_add_typeid (buf, domain, method->klass);
8552 break;
8554 case CMD_METHOD_GET_DEBUG_INFO: {
8555 ERROR_DECL (error);
8556 MonoDebugMethodInfo *minfo;
8557 char *source_file;
8558 int i, j, n_il_offsets;
8559 int *source_files;
8560 GPtrArray *source_file_list;
8561 MonoSymSeqPoint *sym_seq_points;
8563 header = mono_method_get_header_checked (method, error);
8564 if (!header) {
8565 mono_error_cleanup (error); /* FIXME don't swallow the error */
8566 buffer_add_int (buf, 0);
8567 buffer_add_string (buf, "");
8568 buffer_add_int (buf, 0);
8569 break;
8572 minfo = mono_debug_lookup_method (method);
8573 if (!minfo) {
8574 buffer_add_int (buf, header->code_size);
8575 buffer_add_string (buf, "");
8576 buffer_add_int (buf, 0);
8577 mono_metadata_free_mh (header);
8578 break;
8581 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8582 buffer_add_int (buf, header->code_size);
8583 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8584 buffer_add_int (buf, source_file_list->len);
8585 for (i = 0; i < source_file_list->len; ++i) {
8586 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8587 buffer_add_string (buf, sinfo->source_file);
8588 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8589 for (j = 0; j < 16; ++j)
8590 buffer_add_byte (buf, sinfo->hash [j]);
8593 } else {
8594 buffer_add_string (buf, source_file);
8596 buffer_add_int (buf, n_il_offsets);
8597 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8598 for (i = 0; i < n_il_offsets; ++i) {
8599 MonoSymSeqPoint *sp = &sym_seq_points [i];
8600 const char *srcfile = "";
8602 if (source_files [i] != -1) {
8603 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8604 srcfile = sinfo->source_file;
8606 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);
8607 buffer_add_int (buf, sp->il_offset);
8608 buffer_add_int (buf, sp->line);
8609 if (CHECK_PROTOCOL_VERSION (2, 13))
8610 buffer_add_int (buf, source_files [i]);
8611 if (CHECK_PROTOCOL_VERSION (2, 19))
8612 buffer_add_int (buf, sp->column);
8613 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8614 buffer_add_int (buf, sp->end_line);
8615 buffer_add_int (buf, sp->end_column);
8618 g_free (source_file);
8619 g_free (source_files);
8620 g_free (sym_seq_points);
8621 g_ptr_array_free (source_file_list, TRUE);
8622 mono_metadata_free_mh (header);
8623 break;
8625 case CMD_METHOD_GET_PARAM_INFO: {
8626 MonoMethodSignature *sig = mono_method_signature_internal (method);
8627 guint32 i;
8628 char **names;
8630 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8632 /* FIXME: Use a smaller encoding */
8633 buffer_add_int (buf, sig->call_convention);
8634 buffer_add_int (buf, sig->param_count);
8635 buffer_add_int (buf, sig->generic_param_count);
8636 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8637 for (i = 0; i < sig->param_count; ++i) {
8638 /* FIXME: vararg */
8639 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8642 /* Emit parameter names */
8643 names = g_new (char *, sig->param_count);
8644 mono_method_get_param_names (method, (const char **) names);
8645 for (i = 0; i < sig->param_count; ++i)
8646 buffer_add_string (buf, names [i]);
8647 g_free (names);
8649 break;
8651 case CMD_METHOD_GET_LOCALS_INFO: {
8652 ERROR_DECL (error);
8653 int i, num_locals;
8654 MonoDebugLocalsInfo *locals;
8655 int *locals_map = NULL;
8657 header = mono_method_get_header_checked (method, error);
8658 if (!header) {
8659 mono_error_cleanup (error); /* FIXME don't swallow the error */
8660 return ERR_INVALID_ARGUMENT;
8663 locals = mono_debug_lookup_locals (method);
8664 if (!locals) {
8665 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8666 /* Scopes */
8667 buffer_add_int (buf, 1);
8668 buffer_add_int (buf, 0);
8669 buffer_add_int (buf, header->code_size);
8671 buffer_add_int (buf, header->num_locals);
8672 /* Types */
8673 for (i = 0; i < header->num_locals; ++i) {
8674 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8676 /* Names */
8677 for (i = 0; i < header->num_locals; ++i) {
8678 char lname [128];
8679 sprintf (lname, "V_%d", i);
8680 buffer_add_string (buf, lname);
8682 /* Scopes */
8683 for (i = 0; i < header->num_locals; ++i) {
8684 buffer_add_int (buf, 0);
8685 buffer_add_int (buf, header->code_size);
8687 } else {
8688 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8689 /* Scopes */
8690 buffer_add_int (buf, locals->num_blocks);
8691 int last_start = 0;
8692 for (i = 0; i < locals->num_blocks; ++i) {
8693 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8694 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8695 last_start = locals->code_blocks [i].start_offset;
8699 num_locals = locals->num_locals;
8700 buffer_add_int (buf, num_locals);
8702 /* Types */
8703 for (i = 0; i < num_locals; ++i) {
8704 g_assert (locals->locals [i].index < header->num_locals);
8705 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8707 /* Names */
8708 for (i = 0; i < num_locals; ++i)
8709 buffer_add_string (buf, locals->locals [i].name);
8710 /* Scopes */
8711 for (i = 0; i < num_locals; ++i) {
8712 if (locals->locals [i].block) {
8713 buffer_add_int (buf, locals->locals [i].block->start_offset);
8714 buffer_add_int (buf, locals->locals [i].block->end_offset);
8715 } else {
8716 buffer_add_int (buf, 0);
8717 buffer_add_int (buf, header->code_size);
8721 mono_metadata_free_mh (header);
8723 if (locals)
8724 mono_debug_free_locals (locals);
8725 g_free (locals_map);
8727 break;
8729 case CMD_METHOD_GET_INFO:
8730 buffer_add_int (buf, method->flags);
8731 buffer_add_int (buf, method->iflags);
8732 buffer_add_int (buf, method->token);
8733 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8734 guint8 attrs = 0;
8735 if (method->is_generic)
8736 attrs |= (1 << 0);
8737 if (mono_method_signature_internal (method)->generic_param_count)
8738 attrs |= (1 << 1);
8739 buffer_add_byte (buf, attrs);
8740 if (method->is_generic || method->is_inflated) {
8741 MonoMethod *result;
8743 if (method->is_generic) {
8744 result = method;
8745 } else {
8746 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8748 result = imethod->declaring;
8749 if (imethod->context.class_inst) {
8750 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8751 /*Generic methods gets the context of the GTD.*/
8752 if (mono_class_get_context (klass)) {
8753 ERROR_DECL (error);
8754 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8755 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8760 buffer_add_methodid (buf, domain, result);
8761 } else {
8762 buffer_add_id (buf, 0);
8764 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8765 if (mono_method_signature_internal (method)->generic_param_count) {
8766 int count, i;
8768 if (method->is_inflated) {
8769 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8770 if (inst) {
8771 count = inst->type_argc;
8772 buffer_add_int (buf, count);
8774 for (i = 0; i < count; i++)
8775 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8776 } else {
8777 buffer_add_int (buf, 0);
8779 } else if (method->is_generic) {
8780 MonoGenericContainer *container = mono_method_get_generic_container (method);
8782 count = mono_method_signature_internal (method)->generic_param_count;
8783 buffer_add_int (buf, count);
8784 for (i = 0; i < count; i++) {
8785 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8786 MonoClass *pklass = mono_class_create_generic_parameter (param);
8787 buffer_add_typeid (buf, domain, pklass);
8789 } else {
8790 buffer_add_int (buf, 0);
8792 } else {
8793 buffer_add_int (buf, 0);
8797 break;
8798 case CMD_METHOD_GET_BODY: {
8799 ERROR_DECL (error);
8800 int i;
8802 header = mono_method_get_header_checked (method, error);
8803 if (!header) {
8804 mono_error_cleanup (error); /* FIXME don't swallow the error */
8805 buffer_add_int (buf, 0);
8807 if (CHECK_PROTOCOL_VERSION (2, 18))
8808 buffer_add_int (buf, 0);
8809 } else {
8810 buffer_add_int (buf, header->code_size);
8811 for (i = 0; i < header->code_size; ++i)
8812 buffer_add_byte (buf, header->code [i]);
8814 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8815 buffer_add_int (buf, header->num_clauses);
8816 for (i = 0; i < header->num_clauses; ++i) {
8817 MonoExceptionClause *clause = &header->clauses [i];
8819 buffer_add_int (buf, clause->flags);
8820 buffer_add_int (buf, clause->try_offset);
8821 buffer_add_int (buf, clause->try_len);
8822 buffer_add_int (buf, clause->handler_offset);
8823 buffer_add_int (buf, clause->handler_len);
8824 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8825 buffer_add_typeid (buf, domain, clause->data.catch_class);
8826 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8827 buffer_add_int (buf, clause->data.filter_offset);
8831 mono_metadata_free_mh (header);
8834 break;
8836 case CMD_METHOD_RESOLVE_TOKEN: {
8837 guint32 token = decode_int (p, &p, end);
8839 // FIXME: Generics
8840 switch (mono_metadata_token_code (token)) {
8841 case MONO_TOKEN_STRING: {
8842 ERROR_DECL (error);
8843 MonoString *s;
8844 char *s2;
8846 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8847 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8849 s2 = mono_string_to_utf8_checked_internal (s, error);
8850 mono_error_assert_ok (error);
8852 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8853 buffer_add_string (buf, s2);
8854 g_free (s2);
8855 break;
8857 default: {
8858 ERROR_DECL (error);
8859 gpointer val;
8860 MonoClass *handle_class;
8862 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8863 val = mono_method_get_wrapper_data (method, token);
8864 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8866 if (handle_class == NULL) {
8867 // Can't figure out the token type
8868 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8869 break;
8871 } else {
8872 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8873 if (!val)
8874 g_error ("Could not load token due to %s", mono_error_get_message (error));
8877 if (handle_class == mono_defaults.typehandle_class) {
8878 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8879 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8880 buffer_add_typeid (buf, domain, (MonoClass *) val);
8881 else
8882 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8883 } else if (handle_class == mono_defaults.fieldhandle_class) {
8884 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8885 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8886 } else if (handle_class == mono_defaults.methodhandle_class) {
8887 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8888 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8889 } else if (handle_class == mono_defaults.string_class) {
8890 char *s;
8892 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8893 mono_error_assert_ok (error);
8894 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8895 buffer_add_string (buf, s);
8896 g_free (s);
8897 } else {
8898 g_assert_not_reached ();
8900 break;
8903 break;
8905 case CMD_METHOD_GET_CATTRS: {
8906 ERROR_DECL (error);
8907 MonoClass *attr_klass;
8908 MonoCustomAttrInfo *cinfo;
8910 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8911 /* attr_klass can be NULL */
8912 if (err != ERR_NONE)
8913 return err;
8915 cinfo = mono_custom_attrs_from_method_checked (method, error);
8916 if (!is_ok (error)) {
8917 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8918 return ERR_LOADER_ERROR;
8921 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
8922 if (err != ERR_NONE)
8923 return err;
8924 break;
8926 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8927 ERROR_DECL (error);
8928 MonoType **type_argv;
8929 int i, type_argc;
8930 MonoDomain *d;
8931 MonoClass *klass;
8932 MonoGenericInst *ginst;
8933 MonoGenericContext tmp_context;
8934 MonoMethod *inflated;
8936 type_argc = decode_int (p, &p, end);
8937 type_argv = g_new0 (MonoType*, type_argc);
8938 for (i = 0; i < type_argc; ++i) {
8939 klass = decode_typeid (p, &p, end, &d, &err);
8940 if (err != ERR_NONE) {
8941 g_free (type_argv);
8942 return err;
8944 if (domain != d) {
8945 g_free (type_argv);
8946 return ERR_INVALID_ARGUMENT;
8948 type_argv [i] = m_class_get_byval_arg (klass);
8950 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8951 g_free (type_argv);
8952 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8953 tmp_context.method_inst = ginst;
8955 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
8956 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8957 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8958 return ERR_INVALID_ARGUMENT;
8959 buffer_add_methodid (buf, domain, inflated);
8960 break;
8962 default:
8963 return ERR_NOT_IMPLEMENTED;
8966 return ERR_NONE;
8969 static ErrorCode
8970 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8972 ErrorCode err;
8973 MonoDomain *old_domain;
8974 MonoDomain *domain;
8975 MonoMethod *method;
8977 method = decode_methodid (p, &p, end, &domain, &err);
8978 if (err != ERR_NONE)
8979 return err;
8981 old_domain = mono_domain_get ();
8983 mono_domain_set_fast (domain, TRUE);
8985 err = method_commands_internal (command, method, domain, p, end, buf);
8987 mono_domain_set_fast (old_domain, TRUE);
8989 return err;
8992 static ErrorCode
8993 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8995 int objid = decode_objid (p, &p, end);
8996 ErrorCode err;
8997 MonoThread *thread_obj;
8998 MonoInternalThread *thread;
9000 err = get_object (objid, (MonoObject**)&thread_obj);
9001 if (err != ERR_NONE)
9002 return err;
9004 thread = THREAD_TO_INTERNAL (thread_obj);
9006 switch (command) {
9007 case CMD_THREAD_GET_NAME: {
9008 char *s = mono_thread_get_name_utf8 (thread_obj);
9010 if (!s) {
9011 buffer_add_int (buf, 0);
9012 } else {
9013 const size_t len = strlen (s);
9014 buffer_add_int (buf, len);
9015 buffer_add_data (buf, (guint8*)s, len);
9016 g_free (s);
9018 break;
9020 case CMD_THREAD_GET_FRAME_INFO: {
9021 DebuggerTlsData *tls;
9022 int i, start_frame, length;
9024 // Wait for suspending if it already started
9025 // FIXME: Races with suspend_count
9026 while (!is_suspended ()) {
9027 if (suspend_count)
9028 wait_for_suspend ();
9031 if (suspend_count)
9032 wait_for_suspend ();
9033 if (!is_suspended ())
9034 return ERR_NOT_SUSPENDED;
9037 start_frame = decode_int (p, &p, end);
9038 length = decode_int (p, &p, end);
9040 if (start_frame != 0 || length != -1)
9041 return ERR_NOT_IMPLEMENTED;
9043 mono_loader_lock ();
9044 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9045 mono_loader_unlock ();
9046 g_assert (tls);
9048 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
9050 buffer_add_int (buf, tls->frame_count);
9051 for (i = 0; i < tls->frame_count; ++i) {
9052 buffer_add_int (buf, tls->frames [i]->id);
9053 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
9054 buffer_add_int (buf, tls->frames [i]->il_offset);
9056 * Instead of passing the frame type directly to the client, we associate
9057 * it with the previous frame using a set of flags. This avoids lots of
9058 * conditional code in the client, since a frame whose type isn't
9059 * FRAME_TYPE_MANAGED has no method, location, etc.
9061 buffer_add_byte (buf, tls->frames [i]->flags);
9064 break;
9066 case CMD_THREAD_GET_STATE:
9067 buffer_add_int (buf, thread->state);
9068 break;
9069 case CMD_THREAD_GET_INFO:
9070 buffer_add_byte (buf, thread->threadpool_thread);
9071 break;
9072 case CMD_THREAD_GET_ID:
9073 buffer_add_long (buf, (guint64)(gsize)thread);
9074 break;
9075 case CMD_THREAD_GET_TID:
9076 buffer_add_long (buf, (guint64)thread->tid);
9077 break;
9078 case CMD_THREAD_SET_IP: {
9079 DebuggerTlsData *tls;
9080 MonoMethod *method;
9081 MonoDomain *domain;
9082 MonoSeqPointInfo *seq_points;
9083 SeqPoint sp;
9084 gboolean found_sp;
9085 gint64 il_offset;
9087 method = decode_methodid (p, &p, end, &domain, &err);
9088 if (err != ERR_NONE)
9089 return err;
9090 il_offset = decode_long (p, &p, end);
9092 while (!is_suspended ()) {
9093 if (suspend_count)
9094 wait_for_suspend ();
9097 mono_loader_lock ();
9098 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9099 mono_loader_unlock ();
9100 g_assert (tls);
9102 compute_frame_info (thread, tls, FALSE);
9103 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9104 return ERR_INVALID_ARGUMENT;
9106 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9108 g_assert (seq_points);
9110 if (!found_sp)
9111 return ERR_INVALID_ARGUMENT;
9113 // FIXME: Check that the ip change is safe
9115 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);
9117 if (tls->frames [0]->de.ji->is_interp) {
9118 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
9119 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);
9120 } else {
9121 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9123 break;
9125 case CMD_THREAD_ELAPSED_TIME: {
9126 DebuggerTlsData *tls;
9127 mono_loader_lock ();
9128 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9129 mono_loader_unlock ();
9130 g_assert (tls);
9131 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9132 break;
9134 default:
9135 return ERR_NOT_IMPLEMENTED;
9138 return ERR_NONE;
9141 static ErrorCode
9142 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9144 int objid;
9145 ErrorCode err;
9146 MonoThread *thread_obj;
9147 MonoInternalThread *thread;
9148 int pos, i, len, frame_idx;
9149 DebuggerTlsData *tls;
9150 StackFrame *frame;
9151 MonoDebugMethodJitInfo *jit;
9152 MonoMethodSignature *sig;
9153 gssize id;
9154 MonoMethodHeader *header;
9156 objid = decode_objid (p, &p, end);
9157 err = get_object (objid, (MonoObject**)&thread_obj);
9158 if (err != ERR_NONE)
9159 return err;
9161 thread = THREAD_TO_INTERNAL (thread_obj);
9163 id = decode_id (p, &p, end);
9165 mono_loader_lock ();
9166 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9167 mono_loader_unlock ();
9168 g_assert (tls);
9170 for (i = 0; i < tls->frame_count; ++i) {
9171 if (tls->frames [i]->id == id)
9172 break;
9174 if (i == tls->frame_count)
9175 return ERR_INVALID_FRAMEID;
9177 /* The thread is still running native code, can't get frame variables info */
9178 if (!tls->really_suspended && !tls->async_state.valid)
9179 return ERR_NOT_SUSPENDED;
9180 frame_idx = i;
9181 frame = tls->frames [frame_idx];
9183 /* This is supported for frames without has_ctx etc. set */
9184 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9185 if (CHECK_PROTOCOL_VERSION (2, 38))
9186 buffer_add_domainid (buf, frame->de.domain);
9187 return ERR_NONE;
9190 if (!frame->has_ctx)
9191 return ERR_ABSENT_INFORMATION;
9193 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9194 return ERR_ABSENT_INFORMATION;
9196 jit = frame->jit;
9198 sig = mono_method_signature_internal (frame->actual_method);
9200 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9202 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9204 return ERR_ABSENT_INFORMATION;
9206 switch (command) {
9207 case CMD_STACK_FRAME_GET_VALUES: {
9208 ERROR_DECL (error);
9209 len = decode_int (p, &p, end);
9210 header = mono_method_get_header_checked (frame->actual_method, error);
9211 mono_error_assert_ok (error); /* FIXME report error */
9213 for (i = 0; i < len; ++i) {
9214 pos = decode_int (p, &p, end);
9216 if (pos < 0) {
9217 pos = - pos - 1;
9219 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9221 if (frame->de.ji->is_interp) {
9222 guint8 *addr;
9224 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9226 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9227 } else {
9228 g_assert (pos >= 0 && pos < jit->num_params);
9230 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9232 } else {
9233 MonoDebugLocalsInfo *locals;
9235 locals = mono_debug_lookup_locals (frame->de.method);
9236 if (locals) {
9237 g_assert (pos < locals->num_locals);
9238 pos = locals->locals [pos].index;
9239 mono_debug_free_locals (locals);
9242 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9244 if (frame->de.ji->is_interp) {
9245 guint8 *addr;
9247 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9249 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9250 } else {
9251 g_assert (pos >= 0 && pos < jit->num_locals);
9253 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9257 mono_metadata_free_mh (header);
9258 break;
9260 case CMD_STACK_FRAME_GET_THIS: {
9261 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9262 return ERR_ABSENT_INFORMATION;
9263 if (m_class_is_valuetype (frame->api_method->klass)) {
9264 if (!sig->hasthis) {
9265 MonoObject *p = NULL;
9266 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
9267 } else {
9268 if (frame->de.ji->is_interp) {
9269 guint8 *addr;
9271 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9273 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9274 } else {
9275 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9278 } else {
9279 if (!sig->hasthis) {
9280 MonoObject *p = NULL;
9281 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9282 } else {
9283 if (frame->de.ji->is_interp) {
9284 guint8 *addr;
9286 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9288 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9289 } else {
9290 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9294 break;
9296 case CMD_STACK_FRAME_SET_VALUES: {
9297 ERROR_DECL (error);
9298 guint8 *val_buf;
9299 MonoType *t;
9300 MonoDebugVarInfo *var = NULL;
9301 gboolean is_arg = FALSE;
9303 len = decode_int (p, &p, end);
9304 header = mono_method_get_header_checked (frame->actual_method, error);
9305 mono_error_assert_ok (error); /* FIXME report error */
9307 for (i = 0; i < len; ++i) {
9308 pos = decode_int (p, &p, end);
9310 if (pos < 0) {
9311 pos = - pos - 1;
9313 g_assert (pos >= 0 && pos < jit->num_params);
9315 t = sig->params [pos];
9316 var = &jit->params [pos];
9317 is_arg = TRUE;
9318 } else {
9319 MonoDebugLocalsInfo *locals;
9321 locals = mono_debug_lookup_locals (frame->de.method);
9322 if (locals) {
9323 g_assert (pos < locals->num_locals);
9324 pos = locals->locals [pos].index;
9325 mono_debug_free_locals (locals);
9327 g_assert (pos >= 0 && pos < jit->num_locals);
9329 t = header->locals [pos];
9330 var = &jit->locals [pos];
9333 if (MONO_TYPE_IS_REFERENCE (t))
9334 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9335 else
9336 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9337 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9338 if (err != ERR_NONE)
9339 return err;
9341 if (frame->de.ji->is_interp) {
9342 guint8 *addr;
9344 if (is_arg)
9345 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9346 else
9347 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9348 set_interp_var (t, addr, val_buf);
9349 } else {
9350 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9353 mono_metadata_free_mh (header);
9354 break;
9356 case CMD_STACK_FRAME_GET_DOMAIN: {
9357 if (CHECK_PROTOCOL_VERSION (2, 38))
9358 buffer_add_domainid (buf, frame->de.domain);
9359 break;
9361 case CMD_STACK_FRAME_SET_THIS: {
9362 guint8 *val_buf;
9363 MonoType *t;
9364 MonoDebugVarInfo *var;
9366 t = m_class_get_byval_arg (frame->actual_method->klass);
9367 /* Checked by the sender */
9368 g_assert (MONO_TYPE_ISSTRUCT (t));
9370 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9371 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9372 if (err != ERR_NONE)
9373 return err;
9375 if (frame->de.ji->is_interp) {
9376 guint8 *addr;
9378 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9379 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9380 } else {
9381 var = jit->this_var;
9382 g_assert (var);
9384 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);
9386 break;
9388 default:
9389 return ERR_NOT_IMPLEMENTED;
9392 return ERR_NONE;
9395 static ErrorCode
9396 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9398 MonoArray *arr;
9399 int objid, index, len, i, esize;
9400 ErrorCode err;
9401 gpointer elem;
9403 objid = decode_objid (p, &p, end);
9404 err = get_object (objid, (MonoObject**)&arr);
9405 if (err != ERR_NONE)
9406 return err;
9408 switch (command) {
9409 case CMD_ARRAY_REF_GET_LENGTH:
9410 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9411 if (!arr->bounds) {
9412 buffer_add_int (buf, arr->max_length);
9413 buffer_add_int (buf, 0);
9414 } else {
9415 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9416 buffer_add_int (buf, arr->bounds [i].length);
9417 buffer_add_int (buf, arr->bounds [i].lower_bound);
9420 break;
9421 case CMD_ARRAY_REF_GET_VALUES:
9422 index = decode_int (p, &p, end);
9423 len = decode_int (p, &p, end);
9425 g_assert (index >= 0 && len >= 0);
9426 // Reordered to avoid integer overflow
9427 g_assert (!(index > arr->max_length - len));
9429 esize = mono_array_element_size (arr->obj.vtable->klass);
9430 for (i = index; i < index + len; ++i) {
9431 elem = (gpointer*)((char*)arr->vector + (i * esize));
9432 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9434 break;
9435 case CMD_ARRAY_REF_SET_VALUES:
9436 index = decode_int (p, &p, end);
9437 len = decode_int (p, &p, end);
9439 g_assert (index >= 0 && len >= 0);
9440 // Reordered to avoid integer overflow
9441 g_assert (!(index > arr->max_length - len));
9443 esize = mono_array_element_size (arr->obj.vtable->klass);
9444 for (i = index; i < index + len; ++i) {
9445 elem = (gpointer*)((char*)arr->vector + (i * esize));
9447 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);
9449 break;
9450 default:
9451 return ERR_NOT_IMPLEMENTED;
9454 return ERR_NONE;
9457 static ErrorCode
9458 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9460 int objid;
9461 ErrorCode err;
9462 MonoString *str;
9463 char *s;
9464 int i, index, length;
9465 gunichar2 *c;
9466 gboolean use_utf16 = FALSE;
9468 objid = decode_objid (p, &p, end);
9469 err = get_object (objid, (MonoObject**)&str);
9470 if (err != ERR_NONE)
9471 return err;
9473 switch (command) {
9474 case CMD_STRING_REF_GET_VALUE:
9475 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9476 for (i = 0; i < mono_string_length_internal (str); ++i)
9477 if (mono_string_chars_internal (str)[i] == 0)
9478 use_utf16 = TRUE;
9479 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9481 if (use_utf16) {
9482 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9483 buffer_add_data (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9484 } else {
9485 ERROR_DECL (error);
9486 s = mono_string_to_utf8_checked_internal (str, error);
9487 if (!is_ok (error)) {
9488 if (s)
9489 g_free (s);
9491 return ERR_INVALID_ARGUMENT;
9493 buffer_add_string (buf, s);
9494 g_free (s);
9496 break;
9497 case CMD_STRING_REF_GET_LENGTH:
9498 buffer_add_long (buf, mono_string_length_internal (str));
9499 break;
9500 case CMD_STRING_REF_GET_CHARS:
9501 index = decode_long (p, &p, end);
9502 length = decode_long (p, &p, end);
9503 if (index > mono_string_length_internal (str) - length)
9504 return ERR_INVALID_ARGUMENT;
9505 c = mono_string_chars_internal (str) + index;
9506 for (i = 0; i < length; ++i)
9507 buffer_add_short (buf, c [i]);
9508 break;
9509 default:
9510 return ERR_NOT_IMPLEMENTED;
9513 return ERR_NONE;
9516 static ErrorCode
9517 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9519 ErrorCode err;
9520 gint64 addr;
9521 MonoClass* klass;
9522 MonoDomain* domain = NULL;
9524 switch (command) {
9525 case CMD_POINTER_GET_VALUE:
9526 addr = decode_long (p, &p, end);
9527 klass = decode_typeid (p, &p, end, &domain, &err);
9528 if (err != ERR_NONE)
9529 return err;
9531 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9532 return ERR_INVALID_ARGUMENT;
9534 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (klass)), (gpointer)addr, domain);
9536 break;
9537 default:
9538 return ERR_NOT_IMPLEMENTED;
9541 return ERR_NONE;
9544 static ErrorCode
9545 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9547 HANDLE_FUNCTION_ENTER ();
9549 ERROR_DECL (error);
9550 int objid;
9551 ErrorCode err;
9552 MonoObject *obj;
9553 int len, i;
9554 MonoClassField *f;
9555 MonoClass *k;
9556 gboolean found;
9557 gboolean remote_obj = FALSE;
9558 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
9560 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9561 objid = decode_objid (p, &p, end);
9562 err = get_object (objid, &obj);
9563 if (err != ERR_NONE)
9564 buffer_add_int (buf, 1);
9565 else
9566 buffer_add_int (buf, 0);
9567 err = ERR_NONE;
9568 goto exit;
9571 objid = decode_objid (p, &p, end);
9572 err = get_object (objid, &obj);
9573 if (err != ERR_NONE)
9574 goto exit;
9576 MonoClass *obj_type;
9578 obj_type = obj->vtable->klass;
9579 if (mono_class_is_transparent_proxy (obj_type)) {
9580 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9581 remote_obj = TRUE;
9584 g_assert (obj_type);
9586 switch (command) {
9587 case CMD_OBJECT_REF_GET_TYPE:
9588 /* This handles transparent proxies too */
9589 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9590 break;
9591 case CMD_OBJECT_REF_GET_VALUES:
9592 len = decode_int (p, &p, end);
9594 for (i = 0; i < len; ++i) {
9595 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9596 if (err != ERR_NONE)
9597 goto exit;
9599 /* Check that the field belongs to the object */
9600 found = FALSE;
9601 for (k = obj_type; k; k = m_class_get_parent (k)) {
9602 if (k == f->parent) {
9603 found = TRUE;
9604 break;
9607 if (!found)
9608 goto invalid_fieldid;
9610 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9611 guint8 *val;
9612 MonoVTable *vtable;
9614 if (mono_class_field_is_special_static (f))
9615 goto invalid_fieldid;
9617 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9618 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9619 if (!is_ok (error)) {
9620 mono_error_cleanup (error);
9621 goto invalid_object;
9623 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9624 mono_field_static_get_value_checked (vtable, f, val, string_handle, error);
9625 if (!is_ok (error)) {
9626 mono_error_cleanup (error); /* FIXME report the error */
9627 goto invalid_object;
9629 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9630 g_free (val);
9631 } else {
9632 void *field_value = NULL;
9633 #ifndef DISABLE_REMOTING
9634 void *field_storage = NULL;
9635 #endif
9636 if (remote_obj) {
9637 #ifndef DISABLE_REMOTING
9638 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9639 if (!is_ok (error)) {
9640 mono_error_cleanup (error); /* FIXME report the error */
9641 goto invalid_object;
9643 #else
9644 g_assert_not_reached ();
9645 #endif
9646 } else
9647 field_value = (guint8*)obj + f->offset;
9649 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9652 break;
9653 case CMD_OBJECT_REF_SET_VALUES:
9654 len = decode_int (p, &p, end);
9656 for (i = 0; i < len; ++i) {
9657 f = decode_fieldid (p, &p, end, NULL, &err);
9658 if (err != ERR_NONE)
9659 goto exit;
9661 /* Check that the field belongs to the object */
9662 found = FALSE;
9663 for (k = obj_type; k; k = m_class_get_parent (k)) {
9664 if (k == f->parent) {
9665 found = TRUE;
9666 break;
9669 if (!found)
9670 goto invalid_fieldid;
9672 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9673 guint8 *val;
9674 MonoVTable *vtable;
9676 if (mono_class_field_is_special_static (f))
9677 goto invalid_fieldid;
9679 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9680 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9681 if (!is_ok (error)) {
9682 mono_error_cleanup (error);
9683 goto invalid_fieldid;
9686 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9687 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9688 if (err != ERR_NONE) {
9689 g_free (val);
9690 goto exit;
9692 mono_field_static_set_value_internal (vtable, f, val);
9693 g_free (val);
9694 } else {
9695 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9696 if (err != ERR_NONE)
9697 goto exit;
9700 break;
9701 case CMD_OBJECT_REF_GET_ADDRESS:
9702 buffer_add_long (buf, (gssize)obj);
9703 break;
9704 case CMD_OBJECT_REF_GET_DOMAIN:
9705 buffer_add_domainid (buf, obj->vtable->domain);
9706 break;
9707 case CMD_OBJECT_REF_GET_INFO:
9708 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9709 buffer_add_domainid (buf, obj->vtable->domain);
9710 break;
9711 default:
9712 err = ERR_NOT_IMPLEMENTED;
9713 goto exit;
9716 err = ERR_NONE;
9717 goto exit;
9718 invalid_fieldid:
9719 err = ERR_INVALID_FIELDID;
9720 goto exit;
9721 invalid_object:
9722 err = ERR_INVALID_OBJECT;
9723 goto exit;
9724 exit:
9725 HANDLE_FUNCTION_RETURN_VAL (err);
9728 static const char*
9729 command_set_to_string (CommandSet command_set)
9731 switch (command_set) {
9732 case CMD_SET_VM:
9733 return "VM";
9734 case CMD_SET_OBJECT_REF:
9735 return "OBJECT_REF";
9736 case CMD_SET_STRING_REF:
9737 return "STRING_REF";
9738 case CMD_SET_THREAD:
9739 return "THREAD";
9740 case CMD_SET_ARRAY_REF:
9741 return "ARRAY_REF";
9742 case CMD_SET_EVENT_REQUEST:
9743 return "EVENT_REQUEST";
9744 case CMD_SET_STACK_FRAME:
9745 return "STACK_FRAME";
9746 case CMD_SET_APPDOMAIN:
9747 return "APPDOMAIN";
9748 case CMD_SET_ASSEMBLY:
9749 return "ASSEMBLY";
9750 case CMD_SET_METHOD:
9751 return "METHOD";
9752 case CMD_SET_TYPE:
9753 return "TYPE";
9754 case CMD_SET_MODULE:
9755 return "MODULE";
9756 case CMD_SET_FIELD:
9757 return "FIELD";
9758 case CMD_SET_EVENT:
9759 return "EVENT";
9760 case CMD_SET_POINTER:
9761 return "POINTER";
9762 default:
9763 return "";
9767 static const char* vm_cmds_str [] = {
9768 "VERSION",
9769 "ALL_THREADS",
9770 "SUSPEND",
9771 "RESUME",
9772 "EXIT",
9773 "DISPOSE",
9774 "INVOKE_METHOD",
9775 "SET_PROTOCOL_VERSION",
9776 "ABORT_INVOKE",
9777 "SET_KEEPALIVE"
9778 "GET_TYPES_FOR_SOURCE_FILE",
9779 "GET_TYPES",
9780 "INVOKE_METHODS"
9783 static const char* thread_cmds_str[] = {
9784 "GET_FRAME_INFO",
9785 "GET_NAME",
9786 "GET_STATE",
9787 "GET_INFO",
9788 "GET_ID",
9789 "GET_TID",
9790 "SET_IP"
9793 static const char* event_cmds_str[] = {
9794 "REQUEST_SET",
9795 "REQUEST_CLEAR",
9796 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9799 static const char* appdomain_cmds_str[] = {
9800 "GET_ROOT_DOMAIN",
9801 "GET_FRIENDLY_NAME",
9802 "GET_ASSEMBLIES",
9803 "GET_ENTRY_ASSEMBLY",
9804 "CREATE_STRING",
9805 "GET_CORLIB",
9806 "CREATE_BOXED_VALUE",
9807 "CREATE_BYTE_ARRAY",
9810 static const char* assembly_cmds_str[] = {
9811 "GET_LOCATION",
9812 "GET_ENTRY_POINT",
9813 "GET_MANIFEST_MODULE",
9814 "GET_OBJECT",
9815 "GET_TYPE",
9816 "GET_NAME",
9817 "GET_DOMAIN",
9818 "HAS_DEBUG_INFO"
9821 static const char* module_cmds_str[] = {
9822 "GET_INFO",
9825 static const char* field_cmds_str[] = {
9826 "GET_INFO",
9829 static const char* method_cmds_str[] = {
9830 "GET_NAME",
9831 "GET_DECLARING_TYPE",
9832 "GET_DEBUG_INFO",
9833 "GET_PARAM_INFO",
9834 "GET_LOCALS_INFO",
9835 "GET_INFO",
9836 "GET_BODY",
9837 "RESOLVE_TOKEN",
9838 "GET_CATTRS ",
9839 "MAKE_GENERIC_METHOD"
9842 static const char* type_cmds_str[] = {
9843 "GET_INFO",
9844 "GET_METHODS",
9845 "GET_FIELDS",
9846 "GET_VALUES",
9847 "GET_OBJECT",
9848 "GET_SOURCE_FILES",
9849 "SET_VALUES",
9850 "IS_ASSIGNABLE_FROM",
9851 "GET_PROPERTIES ",
9852 "GET_CATTRS",
9853 "GET_FIELD_CATTRS",
9854 "GET_PROPERTY_CATTRS",
9855 "GET_SOURCE_FILES_2",
9856 "GET_VALUES_2",
9857 "GET_METHODS_BY_NAME_FLAGS",
9858 "GET_INTERFACES",
9859 "GET_INTERFACE_MAP",
9860 "IS_INITIALIZED",
9861 "CREATE_INSTANCE",
9862 "GET_VALUE_SIZE"
9865 static const char* stack_frame_cmds_str[] = {
9866 "GET_VALUES",
9867 "GET_THIS",
9868 "SET_VALUES",
9869 "GET_DOMAIN",
9870 "SET_THIS"
9873 static const char* array_cmds_str[] = {
9874 "GET_LENGTH",
9875 "GET_VALUES",
9876 "SET_VALUES",
9879 static const char* string_cmds_str[] = {
9880 "GET_VALUE",
9881 "GET_LENGTH",
9882 "GET_CHARS"
9885 static const char* pointer_cmds_str[] = {
9886 "GET_VALUE"
9889 static const char* object_cmds_str[] = {
9890 "GET_TYPE",
9891 "GET_VALUES",
9892 "IS_COLLECTED",
9893 "GET_ADDRESS",
9894 "GET_DOMAIN",
9895 "SET_VALUES",
9896 "GET_INFO",
9899 static const char*
9900 cmd_to_string (CommandSet set, int command)
9902 const char **cmds;
9903 int cmds_len = 0;
9905 switch (set) {
9906 case CMD_SET_VM:
9907 cmds = vm_cmds_str;
9908 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9909 break;
9910 case CMD_SET_OBJECT_REF:
9911 cmds = object_cmds_str;
9912 cmds_len = G_N_ELEMENTS (object_cmds_str);
9913 break;
9914 case CMD_SET_STRING_REF:
9915 cmds = string_cmds_str;
9916 cmds_len = G_N_ELEMENTS (string_cmds_str);
9917 break;
9918 case CMD_SET_THREAD:
9919 cmds = thread_cmds_str;
9920 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9921 break;
9922 case CMD_SET_ARRAY_REF:
9923 cmds = array_cmds_str;
9924 cmds_len = G_N_ELEMENTS (array_cmds_str);
9925 break;
9926 case CMD_SET_EVENT_REQUEST:
9927 cmds = event_cmds_str;
9928 cmds_len = G_N_ELEMENTS (event_cmds_str);
9929 break;
9930 case CMD_SET_STACK_FRAME:
9931 cmds = stack_frame_cmds_str;
9932 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9933 break;
9934 case CMD_SET_APPDOMAIN:
9935 cmds = appdomain_cmds_str;
9936 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9937 break;
9938 case CMD_SET_ASSEMBLY:
9939 cmds = assembly_cmds_str;
9940 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9941 break;
9942 case CMD_SET_METHOD:
9943 cmds = method_cmds_str;
9944 cmds_len = G_N_ELEMENTS (method_cmds_str);
9945 break;
9946 case CMD_SET_TYPE:
9947 cmds = type_cmds_str;
9948 cmds_len = G_N_ELEMENTS (type_cmds_str);
9949 break;
9950 case CMD_SET_MODULE:
9951 cmds = module_cmds_str;
9952 cmds_len = G_N_ELEMENTS (module_cmds_str);
9953 break;
9954 case CMD_SET_FIELD:
9955 cmds = field_cmds_str;
9956 cmds_len = G_N_ELEMENTS (field_cmds_str);
9957 break;
9958 case CMD_SET_EVENT:
9959 cmds = event_cmds_str;
9960 cmds_len = G_N_ELEMENTS (event_cmds_str);
9961 break;
9962 case CMD_SET_POINTER:
9963 cmds = pointer_cmds_str;
9964 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
9965 break;
9966 default:
9967 return NULL;
9969 if (command > 0 && command <= cmds_len)
9970 return cmds [command - 1];
9971 else
9972 return NULL;
9975 static gboolean
9976 wait_for_attach (void)
9978 #ifndef DISABLE_SOCKET_TRANSPORT
9979 if (listen_fd == -1) {
9980 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9981 return FALSE;
9984 /* Block and wait for client connection */
9985 conn_fd = socket_transport_accept (listen_fd);
9987 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9988 if (conn_fd == -1) {
9989 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9990 return FALSE;
9992 #else
9993 g_assert_not_reached ();
9994 #endif
9996 /* Handshake */
9997 disconnected = !transport_handshake ();
9998 if (disconnected) {
9999 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10000 return FALSE;
10003 return TRUE;
10007 * debugger_thread:
10009 * This thread handles communication with the debugger client using a JDWP
10010 * like protocol.
10012 static gsize WINAPI
10013 debugger_thread (void *arg)
10015 int res, len, id, flags, command = 0;
10016 CommandSet command_set = (CommandSet)0;
10017 guint8 header [HEADER_LENGTH];
10018 guint8 *data, *p, *end;
10019 Buffer buf;
10020 ErrorCode err;
10021 gboolean no_reply;
10022 gboolean attach_failed = FALSE;
10024 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10026 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
10028 debugger_thread_id = mono_native_thread_id_get ();
10030 MonoInternalThread *internal = mono_thread_internal_current ();
10031 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
10033 internal->state |= ThreadState_Background;
10034 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10036 if (agent_config.defer) {
10037 if (!wait_for_attach ()) {
10038 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10039 attach_failed = TRUE; // Don't abort process when we can't listen
10040 } else {
10041 mono_set_is_debugger_attached (TRUE);
10042 /* Send start event to client */
10043 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10045 } else {
10046 mono_set_is_debugger_attached (TRUE);
10049 while (!attach_failed) {
10050 res = transport_recv (header, HEADER_LENGTH);
10052 /* This will break if the socket is closed during shutdown too */
10053 if (res != HEADER_LENGTH) {
10054 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10055 command_set = (CommandSet)0;
10056 command = 0;
10057 dispose_vm ();
10058 break;
10059 } else {
10060 p = header;
10061 end = header + HEADER_LENGTH;
10063 len = decode_int (p, &p, end);
10064 id = decode_int (p, &p, end);
10065 flags = decode_byte (p, &p, end);
10066 command_set = (CommandSet)decode_byte (p, &p, end);
10067 command = decode_byte (p, &p, end);
10070 g_assert (flags == 0);
10071 const char *cmd_str;
10072 char cmd_num [256];
10074 cmd_str = cmd_to_string (command_set, command);
10075 if (!cmd_str) {
10076 sprintf (cmd_num, "%d", command);
10077 cmd_str = cmd_num;
10080 if (log_level) {
10081 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);
10084 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10085 if (len - HEADER_LENGTH > 0)
10087 res = transport_recv (data, len - HEADER_LENGTH);
10088 if (res != len - HEADER_LENGTH) {
10089 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10090 break;
10094 p = data;
10095 end = data + (len - HEADER_LENGTH);
10097 buffer_init (&buf, 128);
10099 err = ERR_NONE;
10100 no_reply = FALSE;
10102 /* Process the request */
10103 switch (command_set) {
10104 case CMD_SET_VM:
10105 err = vm_commands (command, id, p, end, &buf);
10106 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10107 /* Sent after the invoke is complete */
10108 no_reply = TRUE;
10109 break;
10110 case CMD_SET_EVENT_REQUEST:
10111 err = event_commands (command, p, end, &buf);
10112 break;
10113 case CMD_SET_APPDOMAIN:
10114 err = domain_commands (command, p, end, &buf);
10115 break;
10116 case CMD_SET_ASSEMBLY:
10117 err = assembly_commands (command, p, end, &buf);
10118 break;
10119 case CMD_SET_MODULE:
10120 err = module_commands (command, p, end, &buf);
10121 break;
10122 case CMD_SET_FIELD:
10123 err = field_commands (command, p, end, &buf);
10124 break;
10125 case CMD_SET_TYPE:
10126 err = type_commands (command, p, end, &buf);
10127 break;
10128 case CMD_SET_METHOD:
10129 err = method_commands (command, p, end, &buf);
10130 break;
10131 case CMD_SET_THREAD:
10132 err = thread_commands (command, p, end, &buf);
10133 break;
10134 case CMD_SET_STACK_FRAME:
10135 err = frame_commands (command, p, end, &buf);
10136 break;
10137 case CMD_SET_ARRAY_REF:
10138 err = array_commands (command, p, end, &buf);
10139 break;
10140 case CMD_SET_STRING_REF:
10141 err = string_commands (command, p, end, &buf);
10142 break;
10143 case CMD_SET_POINTER:
10144 err = pointer_commands (command, p, end, &buf);
10145 break;
10146 case CMD_SET_OBJECT_REF:
10147 err = object_commands (command, p, end, &buf);
10148 break;
10149 default:
10150 err = ERR_NOT_IMPLEMENTED;
10153 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10154 buffer_replies = TRUE;
10157 if (!no_reply) {
10158 if (buffer_replies) {
10159 buffer_reply_packet (id, err, &buf);
10160 } else {
10161 send_reply_packet (id, err, &buf);
10162 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10166 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10168 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10169 send_buffered_reply_packets ();
10170 buffer_replies = FALSE;
10173 g_free (data);
10174 buffer_free (&buf);
10176 if (log_each_step) {
10177 char *debugger_log = mono_debugger_state_str ();
10178 if (debugger_log) {
10179 fprintf (stderr, "Debugger state: %s\n", debugger_log);
10180 g_free (debugger_log);
10184 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10185 break;
10188 mono_set_is_debugger_attached (FALSE);
10190 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10191 debugger_thread_exited = TRUE;
10192 mono_coop_cond_signal (&debugger_thread_exited_cond);
10193 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10195 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10197 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10198 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10199 ERROR_DECL (error);
10200 start_debugger_thread (error);
10201 mono_error_cleanup (error);
10204 return 0;
10207 void
10208 mono_debugger_agent_init (void)
10210 MonoDebuggerCallbacks cbs;
10212 memset (&cbs, 0, sizeof (cbs));
10213 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10214 cbs.parse_options = debugger_agent_parse_options;
10215 cbs.init = debugger_agent_init;
10216 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10217 cbs.single_step_event = debugger_agent_single_step_event;
10218 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10219 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10220 cbs.free_domain_info = debugger_agent_free_domain_info;
10221 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10222 cbs.handle_exception = debugger_agent_handle_exception;
10223 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10224 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10225 cbs.user_break = debugger_agent_user_break;
10226 cbs.debug_log = debugger_agent_debug_log;
10227 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10228 cbs.send_crash = mono_debugger_agent_send_crash;
10230 mini_install_dbg_callbacks (&cbs);
10233 void
10234 mono_debugger_agent_parse_options (char *options)
10236 sdb_options = options;
10239 #endif /* DISABLE_SDB */