[interp] Fix interp logging (#17636)
[mono-project.git] / mono / mini / debugger-agent.c
blobd681e2536feab7b89d8c8f0dc5d31dd7a9114597
1 /**
2 * \file
3 * Soft Debugger back-end module
5 * Author:
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright 2011 Xamarin Inc.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 #include <config.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #ifdef HAVE_SYS_TYPES_H
18 #include <sys/types.h>
19 #endif
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.h>
22 #endif
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
25 #endif
26 #ifdef HAVE_NETINET_TCP_H
27 #include <netinet/tcp.h>
28 #endif
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #include <errno.h>
36 #include <glib.h>
38 #ifdef HAVE_PTHREAD_H
39 #include <pthread.h>
40 #endif
42 #ifdef HOST_WIN32
43 #ifdef _MSC_VER
44 #include <winsock2.h>
45 #include <process.h>
46 #endif
47 #include <ws2tcpip.h>
48 #endif
50 #ifdef HOST_ANDROID
51 #include <linux/in.h>
52 #include <linux/tcp.h>
53 #include <sys/endian.h>
54 #endif
56 #include <mono/metadata/mono-debug.h>
57 #include <mono/metadata/debug-internals.h>
58 #include <mono/metadata/domain-internals.h>
59 #include <mono/metadata/gc-internals.h>
60 #include <mono/metadata/environment.h>
61 #include <mono/metadata/mono-hash-internals.h>
62 #include <mono/metadata/threads-types.h>
63 #include <mono/metadata/threadpool.h>
64 #include <mono/metadata/assembly.h>
65 #include <mono/metadata/assembly-internals.h>
66 #include <mono/metadata/runtime.h>
67 #include <mono/metadata/verify-internals.h>
68 #include <mono/metadata/reflection-internals.h>
69 #include <mono/metadata/w32socket.h>
70 #include <mono/utils/mono-coop-mutex.h>
71 #include <mono/utils/mono-coop-semaphore.h>
72 #include <mono/utils/mono-error-internals.h>
73 #include <mono/utils/mono-stack-unwinding.h>
74 #include <mono/utils/mono-time.h>
75 #include <mono/utils/mono-threads.h>
76 #include <mono/utils/networking.h>
77 #include <mono/utils/mono-proclib.h>
78 #include <mono/utils/w32api.h>
79 #include "debugger-state-machine.h"
80 #include "debugger-agent.h"
81 #include "mini.h"
82 #include "seq-points.h"
83 #include "aot-runtime.h"
84 #include "mini-runtime.h"
85 #include "interp/interp.h"
86 #include "debugger-engine.h"
87 #include "mono/metadata/debug-mono-ppdb.h"
88 #include "mono/metadata/custom-attrs-internals.h"
91 * On iOS we can't use System.Environment.Exit () as it will do the wrong
92 * shutdown sequence.
94 #if !defined (TARGET_IOS)
95 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
96 #endif
98 #if DISABLE_SOCKETS
99 #define DISABLE_SOCKET_TRANSPORT
100 #endif
102 #ifndef DISABLE_SDB
104 #include <mono/utils/mono-os-mutex.h>
106 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
108 typedef struct {
109 gboolean enabled;
110 char *transport;
111 char *address;
112 int log_level;
113 char *log_file;
114 gboolean suspend;
115 gboolean server;
116 gboolean onuncaught;
117 GSList *onthrow;
118 int timeout;
119 char *launch;
120 gboolean embedding;
121 gboolean defer;
122 int keepalive;
123 gboolean setpgid;
124 } AgentConfig;
126 typedef struct
128 //Must be the first field to ensure pointer equivalence
129 DbgEngineStackFrame de;
130 int id;
131 guint32 il_offset;
133 * If method is gshared, this is the actual instance, otherwise this is equal to
134 * method.
136 MonoMethod *actual_method;
138 * This is the method which is visible to debugger clients. Same as method,
139 * except for native-to-managed wrappers.
141 MonoMethod *api_method;
142 MonoContext ctx;
143 MonoDebugMethodJitInfo *jit;
144 MonoInterpFrameHandle interp_frame;
145 gpointer frame_addr;
146 int flags;
147 host_mgreg_t *reg_locations [MONO_MAX_IREGS];
149 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
150 * the frame can become invalid.
152 gboolean has_ctx;
153 } StackFrame;
155 typedef struct _InvokeData InvokeData;
157 struct _InvokeData
159 int id;
160 int flags;
161 guint8 *p;
162 guint8 *endp;
163 /* This is the context which needs to be restored after the invoke */
164 MonoContext ctx;
165 gboolean has_ctx;
167 * If this is set, invoke this method with the arguments given by ARGS.
169 MonoMethod *method;
170 gpointer *args;
171 guint32 suspend_count;
172 int nmethods;
174 InvokeData *last_invoke;
177 struct _DebuggerTlsData {
178 MonoThreadUnwindState context;
180 /* This is computed on demand when it is requested using the wire protocol */
181 /* It is freed up when the thread is resumed */
182 int frame_count;
183 StackFrame **frames;
185 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
186 * re-compute it.
188 gboolean frames_up_to_date;
190 * Points to data about a pending invoke which needs to be executed after the thread
191 * resumes.
193 InvokeData *pending_invoke;
195 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
196 * native code.
198 gboolean suspended;
200 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
201 * within a finite amount of time.
203 gboolean suspending;
205 * Set to TRUE if this thread is suspended in suspend_current ().
207 gboolean really_suspended;
208 /* Used to pass the context to the breakpoint/single step handler */
209 MonoContext handler_ctx;
210 /* Whenever thread_stop () was called for this thread */
211 gboolean terminated;
213 /* Whenever to disable breakpoints (used during invokes) */
214 gboolean disable_breakpoints;
217 * Number of times this thread has been resumed using resume_thread ().
219 guint32 resume_count;
221 MonoInternalThread *thread;
222 intptr_t thread_id;
225 * Information about the frame which transitioned to native code for running
226 * threads.
228 StackFrameInfo async_last_frame;
231 * The context where the stack walk can be started for running threads.
233 MonoThreadUnwindState async_state;
236 * The context used for filter clauses
238 MonoThreadUnwindState filter_state;
240 gboolean abort_requested;
243 * The current mono_runtime_invoke_checked invocation.
245 InvokeData *invoke;
247 StackFrameInfo catch_frame;
248 gboolean has_catch_frame;
251 * The context which needs to be restored after handling a single step/breakpoint
252 * event. This is the same as the ctx at step/breakpoint site, but includes changes
253 * to caller saved registers done by set_var ().
255 MonoThreadUnwindState restore_state;
256 /* Frames computed from restore_state */
257 int restore_frame_count;
258 StackFrame **restore_frames;
260 /* The currently unloading appdomain */
261 MonoDomain *domain_unloading;
263 // The state that the debugger expects the thread to be in
264 MonoDebuggerThreadState thread_state;
265 MonoStopwatch step_time;
267 gboolean gc_finalizing;
270 typedef struct {
271 const char *name;
272 void (*connect) (const char *address);
273 void (*close1) (void);
274 void (*close2) (void);
275 gboolean (*send) (void *buf, int len);
276 int (*recv) (void *buf, int len);
277 } DebuggerTransport;
280 * Wire Protocol definitions
283 #define HEADER_LENGTH 11
285 #define MAJOR_VERSION 2
286 #define MINOR_VERSION 54
288 typedef enum {
289 CMD_SET_VM = 1,
290 CMD_SET_OBJECT_REF = 9,
291 CMD_SET_STRING_REF = 10,
292 CMD_SET_THREAD = 11,
293 CMD_SET_ARRAY_REF = 13,
294 CMD_SET_EVENT_REQUEST = 15,
295 CMD_SET_STACK_FRAME = 16,
296 CMD_SET_APPDOMAIN = 20,
297 CMD_SET_ASSEMBLY = 21,
298 CMD_SET_METHOD = 22,
299 CMD_SET_TYPE = 23,
300 CMD_SET_MODULE = 24,
301 CMD_SET_FIELD = 25,
302 CMD_SET_EVENT = 64,
303 CMD_SET_POINTER = 65
304 } CommandSet;
306 typedef enum {
307 SUSPEND_POLICY_NONE = 0,
308 SUSPEND_POLICY_EVENT_THREAD = 1,
309 SUSPEND_POLICY_ALL = 2
310 } SuspendPolicy;
312 typedef enum {
313 ERR_NONE = 0,
314 ERR_INVALID_OBJECT = 20,
315 ERR_INVALID_FIELDID = 25,
316 ERR_INVALID_FRAMEID = 30,
317 ERR_NOT_IMPLEMENTED = 100,
318 ERR_NOT_SUSPENDED = 101,
319 ERR_INVALID_ARGUMENT = 102,
320 ERR_UNLOADED = 103,
321 ERR_NO_INVOCATION = 104,
322 ERR_ABSENT_INFORMATION = 105,
323 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
324 ERR_INVOKE_ABORTED = 107,
325 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
326 } ErrorCode;
328 typedef enum {
329 TOKEN_TYPE_STRING = 0,
330 TOKEN_TYPE_TYPE = 1,
331 TOKEN_TYPE_FIELD = 2,
332 TOKEN_TYPE_METHOD = 3,
333 TOKEN_TYPE_UNKNOWN = 4
334 } DebuggerTokenType;
336 typedef enum {
337 VALUE_TYPE_ID_NULL = 0xf0,
338 VALUE_TYPE_ID_TYPE = 0xf1,
339 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2,
340 VALUE_TYPE_ID_FIXED_ARRAY = 0xf3
341 } ValueTypeId;
343 typedef enum {
344 FRAME_FLAG_DEBUGGER_INVOKE = 1,
345 FRAME_FLAG_NATIVE_TRANSITION = 2
346 } StackFrameFlags;
348 typedef enum {
349 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
350 INVOKE_FLAG_SINGLE_THREADED = 2,
351 INVOKE_FLAG_RETURN_OUT_THIS = 4,
352 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
353 INVOKE_FLAG_VIRTUAL = 16
354 } InvokeFlags;
356 typedef enum {
357 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
358 } BindingFlagsExtensions;
360 typedef enum {
361 CMD_VM_VERSION = 1,
362 CMD_VM_ALL_THREADS = 2,
363 CMD_VM_SUSPEND = 3,
364 CMD_VM_RESUME = 4,
365 CMD_VM_EXIT = 5,
366 CMD_VM_DISPOSE = 6,
367 CMD_VM_INVOKE_METHOD = 7,
368 CMD_VM_SET_PROTOCOL_VERSION = 8,
369 CMD_VM_ABORT_INVOKE = 9,
370 CMD_VM_SET_KEEPALIVE = 10,
371 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
372 CMD_VM_GET_TYPES = 12,
373 CMD_VM_INVOKE_METHODS = 13,
374 CMD_VM_START_BUFFERING = 14,
375 CMD_VM_STOP_BUFFERING = 15
376 } CmdVM;
378 typedef enum {
379 CMD_THREAD_GET_FRAME_INFO = 1,
380 CMD_THREAD_GET_NAME = 2,
381 CMD_THREAD_GET_STATE = 3,
382 CMD_THREAD_GET_INFO = 4,
383 CMD_THREAD_GET_ID = 5,
384 CMD_THREAD_GET_TID = 6,
385 CMD_THREAD_SET_IP = 7,
386 CMD_THREAD_ELAPSED_TIME = 8
387 } CmdThread;
389 typedef enum {
390 CMD_EVENT_REQUEST_SET = 1,
391 CMD_EVENT_REQUEST_CLEAR = 2,
392 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
393 } CmdEvent;
395 typedef enum {
396 CMD_COMPOSITE = 100
397 } CmdComposite;
399 typedef enum {
400 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
401 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
402 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
403 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
404 CMD_APPDOMAIN_CREATE_STRING = 5,
405 CMD_APPDOMAIN_GET_CORLIB = 6,
406 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
407 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
408 } CmdAppDomain;
410 typedef enum {
411 CMD_ASSEMBLY_GET_LOCATION = 1,
412 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
413 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
414 CMD_ASSEMBLY_GET_OBJECT = 4,
415 CMD_ASSEMBLY_GET_TYPE = 5,
416 CMD_ASSEMBLY_GET_NAME = 6,
417 CMD_ASSEMBLY_GET_DOMAIN = 7,
418 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
419 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
420 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
421 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
422 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
423 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13
424 } CmdAssembly;
426 typedef enum {
427 CMD_MODULE_GET_INFO = 1,
428 } CmdModule;
430 typedef enum {
431 CMD_FIELD_GET_INFO = 1,
432 } CmdField;
434 typedef enum {
435 CMD_METHOD_GET_NAME = 1,
436 CMD_METHOD_GET_DECLARING_TYPE = 2,
437 CMD_METHOD_GET_DEBUG_INFO = 3,
438 CMD_METHOD_GET_PARAM_INFO = 4,
439 CMD_METHOD_GET_LOCALS_INFO = 5,
440 CMD_METHOD_GET_INFO = 6,
441 CMD_METHOD_GET_BODY = 7,
442 CMD_METHOD_RESOLVE_TOKEN = 8,
443 CMD_METHOD_GET_CATTRS = 9,
444 CMD_METHOD_MAKE_GENERIC_METHOD = 10
445 } CmdMethod;
447 typedef enum {
448 CMD_TYPE_GET_INFO = 1,
449 CMD_TYPE_GET_METHODS = 2,
450 CMD_TYPE_GET_FIELDS = 3,
451 CMD_TYPE_GET_VALUES = 4,
452 CMD_TYPE_GET_OBJECT = 5,
453 CMD_TYPE_GET_SOURCE_FILES = 6,
454 CMD_TYPE_SET_VALUES = 7,
455 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
456 CMD_TYPE_GET_PROPERTIES = 9,
457 CMD_TYPE_GET_CATTRS = 10,
458 CMD_TYPE_GET_FIELD_CATTRS = 11,
459 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
460 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
461 CMD_TYPE_GET_VALUES_2 = 14,
462 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
463 CMD_TYPE_GET_INTERFACES = 16,
464 CMD_TYPE_GET_INTERFACE_MAP = 17,
465 CMD_TYPE_IS_INITIALIZED = 18,
466 CMD_TYPE_CREATE_INSTANCE = 19,
467 CMD_TYPE_GET_VALUE_SIZE = 20
468 } CmdType;
470 typedef enum {
471 CMD_STACK_FRAME_GET_VALUES = 1,
472 CMD_STACK_FRAME_GET_THIS = 2,
473 CMD_STACK_FRAME_SET_VALUES = 3,
474 CMD_STACK_FRAME_GET_DOMAIN = 4,
475 CMD_STACK_FRAME_SET_THIS = 5,
476 } CmdStackFrame;
478 typedef enum {
479 CMD_ARRAY_REF_GET_LENGTH = 1,
480 CMD_ARRAY_REF_GET_VALUES = 2,
481 CMD_ARRAY_REF_SET_VALUES = 3,
482 } CmdArray;
484 typedef enum {
485 CMD_STRING_REF_GET_VALUE = 1,
486 CMD_STRING_REF_GET_LENGTH = 2,
487 CMD_STRING_REF_GET_CHARS = 3
488 } CmdString;
490 typedef enum {
491 CMD_POINTER_GET_VALUE = 1
492 } CmdPointer;
494 typedef enum {
495 CMD_OBJECT_REF_GET_TYPE = 1,
496 CMD_OBJECT_REF_GET_VALUES = 2,
497 CMD_OBJECT_REF_IS_COLLECTED = 3,
498 CMD_OBJECT_REF_GET_ADDRESS = 4,
499 CMD_OBJECT_REF_GET_DOMAIN = 5,
500 CMD_OBJECT_REF_SET_VALUES = 6,
501 CMD_OBJECT_REF_GET_INFO = 7,
502 } CmdObject;
505 * Contains additional information for an event
507 typedef struct {
508 /* For EVENT_KIND_EXCEPTION */
509 MonoObject *exc;
510 MonoContext catch_ctx;
511 gboolean caught;
512 /* For EVENT_KIND_USER_LOG */
513 int level;
514 char *category, *message;
515 /* For EVENT_KIND_TYPE_LOAD */
516 MonoClass *klass;
517 /* For EVENT_KIND_CRASH */
518 char *dump;
519 MonoStackHash *hashes;
520 } EventInfo;
522 typedef struct {
523 guint8 *buf, *p, *end;
524 } Buffer;
526 typedef struct ReplyPacket {
527 int id;
528 int error;
529 Buffer *data;
530 } ReplyPacket;
532 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
534 #ifdef HOST_ANDROID
535 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
536 #else
537 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
538 #endif
540 #ifdef HOST_WIN32
541 #define get_last_sock_error() WSAGetLastError()
542 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
543 #define MONO_EINTR WSAEINTR
544 #else
545 #define get_last_sock_error() errno
546 #define MONO_EWOULDBLOCK EWOULDBLOCK
547 #define MONO_EINTR EINTR
548 #endif
550 #define CHECK_PROTOCOL_VERSION(major,minor) \
551 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
554 * Globals
557 static AgentConfig agent_config;
560 * Whenever the agent is fully initialized.
561 * When using the onuncaught or onthrow options, only some parts of the agent are
562 * initialized on startup, and the full initialization which includes connection
563 * establishment and the startup of the agent thread is only done in response to
564 * an event.
566 static gint32 inited;
568 #ifndef DISABLE_SOCKET_TRANSPORT
569 static int conn_fd;
570 static int listen_fd;
571 #endif
573 static int packet_id = 0;
575 static int objref_id = 0;
577 static int event_request_id = 0;
579 static int frame_id = 0;
581 static GPtrArray *event_requests;
583 static MonoNativeTlsKey debugger_tls_id;
585 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
587 /* Maps MonoInternalThread -> DebuggerTlsData */
588 /* Protected by the loader lock */
589 static MonoGHashTable *thread_to_tls;
591 /* Maps tid -> MonoInternalThread */
592 /* Protected by the loader lock */
593 static MonoGHashTable *tid_to_thread;
595 /* Maps tid -> MonoThread (not MonoInternalThread) */
596 /* Protected by the loader lock */
597 static MonoGHashTable *tid_to_thread_obj;
599 static MonoNativeThreadId debugger_thread_id;
601 static MonoThreadHandle *debugger_thread_handle;
603 static int log_level;
605 static gboolean embedding;
607 static FILE *log_file;
609 /* Assemblies whose assembly load event has no been sent yet */
610 /* Protected by the dbg lock */
611 static GPtrArray *pending_assembly_loads;
613 /* Whenever the debugger thread has exited */
614 static gboolean debugger_thread_exited;
616 /* Cond variable used to wait for debugger_thread_exited becoming true */
617 static MonoCoopCond debugger_thread_exited_cond;
619 /* Mutex for the cond var above */
620 static MonoCoopMutex debugger_thread_exited_mutex;
622 /* The protocol version of the client */
623 static int major_version, minor_version;
625 /* Whenever the variables above are set by the client */
626 static gboolean protocol_version_set;
628 /* The number of times the runtime is suspended */
629 static gint32 suspend_count;
631 /* Whenever to buffer reply messages and send them together */
632 static gboolean buffer_replies;
634 /* Buffered reply packets */
635 static ReplyPacket reply_packets [128];
636 static int nreply_packets;
638 #define dbg_lock mono_de_lock
639 #define dbg_unlock mono_de_unlock
641 static void transport_init (void);
642 static void transport_connect (const char *address);
643 static gboolean transport_handshake (void);
644 static void register_transport (DebuggerTransport *trans);
646 static gsize WINAPI debugger_thread (void *arg);
648 static void runtime_initialized (MonoProfiler *prof);
650 static void runtime_shutdown (MonoProfiler *prof);
652 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
654 static void thread_end (MonoProfiler *prof, uintptr_t tid);
656 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
658 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
660 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
662 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
664 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
666 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
668 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
670 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
672 static void gc_finalizing (MonoProfiler *prof);
674 static void gc_finalized (MonoProfiler *prof);
676 static void emit_assembly_load (gpointer assembly, gpointer user_data);
678 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
680 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
682 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
684 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
686 static void suspend_current (void);
688 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
690 static void clear_types_for_assembly (MonoAssembly *assembly);
692 static void process_profiler_event (EventKind event, gpointer arg);
694 /* Submodule init/cleanup */
695 static void event_requests_cleanup (void);
697 static void objrefs_init (void);
698 static void objrefs_cleanup (void);
700 static void ids_init (void);
701 static void ids_cleanup (void);
703 static void suspend_init (void);
705 static void start_debugger_thread (MonoError *error);
706 static void stop_debugger_thread (void);
708 static void finish_agent_init (gboolean on_startup);
710 static void process_profiler_event (EventKind event, gpointer arg);
712 static void invalidate_frames (DebuggerTlsData *tls);
714 /* Callbacks used by debugger-engine */
715 static MonoContext* tls_get_restore_state (void *the_tls);
716 static gboolean try_process_suspend (void *tls, MonoContext *ctx);
717 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
718 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
719 static void ss_discard_frame_context (void *the_tls);
720 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
721 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
722 static int ensure_runtime_is_suspended (void);
723 static int get_this_async_id (DbgEngineStackFrame *frame);
724 static gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame);
725 static MonoMethod* get_notify_debugger_of_wait_completion_method (void);
726 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
727 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
728 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
729 static void ss_args_destroy (SingleStepArgs *ss_args);
731 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
733 #ifndef DISABLE_SOCKET_TRANSPORT
734 static void
735 register_socket_transport (void);
736 #endif
738 static gboolean
739 is_debugger_thread (void)
741 MonoInternalThread *internal;
743 internal = mono_thread_internal_current ();
744 if (!internal)
745 return FALSE;
747 return internal->debugger_thread;
750 static int
751 parse_address (char *address, char **host, int *port)
753 char *pos = strchr (address, ':');
755 if (pos == NULL || pos == address)
756 return 1;
758 size_t len = pos - address;
759 *host = (char *)g_malloc (len + 1);
760 memcpy (*host, address, len);
761 (*host) [len] = '\0';
763 *port = atoi (pos + 1);
765 return 0;
768 static void
769 print_usage (void)
771 g_printerr ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
772 g_printerr ("Available options:\n");
773 g_printerr (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
774 g_printerr (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
775 g_printerr (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
776 g_printerr (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
777 g_printerr (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
778 g_printerr (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
779 g_printerr (" server=y/n\t\t\tWhether to listen for a client connection.\n");
780 g_printerr (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
781 g_printerr (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
782 g_printerr (" help\t\t\t\tPrint this help.\n");
785 static gboolean
786 parse_flag (const char *option, char *flag)
788 if (!strcmp (flag, "y"))
789 return TRUE;
790 else if (!strcmp (flag, "n"))
791 return FALSE;
792 else {
793 g_printerr ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
794 exit (1);
795 return FALSE;
799 static void
800 debugger_agent_parse_options (char *options)
802 char **args, **ptr;
803 char *host;
804 int port;
805 char *extra;
807 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
808 g_printerr ("--debugger-agent is not supported on this platform.\n");
809 exit (1);
810 #endif
812 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
813 if (extra) {
814 options = g_strdup_printf ("%s,%s", options, extra);
815 g_free (extra);
818 agent_config.enabled = TRUE;
819 agent_config.suspend = TRUE;
820 agent_config.server = FALSE;
821 agent_config.defer = FALSE;
822 agent_config.address = NULL;
824 //agent_config.log_level = 10;
826 args = g_strsplit (options, ",", -1);
827 for (ptr = args; ptr && *ptr; ptr ++) {
828 char *arg = *ptr;
830 if (strncmp (arg, "transport=", 10) == 0) {
831 agent_config.transport = g_strdup (arg + 10);
832 } else if (strncmp (arg, "address=", 8) == 0) {
833 agent_config.address = g_strdup (arg + 8);
834 } else if (strncmp (arg, "loglevel=", 9) == 0) {
835 agent_config.log_level = atoi (arg + 9);
836 } else if (strncmp (arg, "logfile=", 8) == 0) {
837 agent_config.log_file = g_strdup (arg + 8);
838 } else if (strncmp (arg, "suspend=", 8) == 0) {
839 agent_config.suspend = parse_flag ("suspend", arg + 8);
840 } else if (strncmp (arg, "server=", 7) == 0) {
841 agent_config.server = parse_flag ("server", arg + 7);
842 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
843 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
844 } else if (strncmp (arg, "onthrow=", 8) == 0) {
845 /* We support multiple onthrow= options */
846 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
847 } else if (strncmp (arg, "onthrow", 7) == 0) {
848 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
849 } else if (strncmp (arg, "help", 4) == 0) {
850 print_usage ();
851 exit (0);
852 } else if (strncmp (arg, "timeout=", 8) == 0) {
853 agent_config.timeout = atoi (arg + 8);
854 } else if (strncmp (arg, "launch=", 7) == 0) {
855 agent_config.launch = g_strdup (arg + 7);
856 } else if (strncmp (arg, "embedding=", 10) == 0) {
857 agent_config.embedding = atoi (arg + 10) == 1;
858 } else if (strncmp (arg, "keepalive=", 10) == 0) {
859 agent_config.keepalive = atoi (arg + 10);
860 } else if (strncmp (arg, "setpgid=", 8) == 0) {
861 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
862 } else {
863 print_usage ();
864 exit (1);
868 if (agent_config.server && !agent_config.suspend) {
869 /* Waiting for deferred attachment */
870 agent_config.defer = TRUE;
871 if (agent_config.address == NULL) {
872 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
876 //agent_config.log_level = 0;
878 if (agent_config.transport == NULL) {
879 g_printerr ("debugger-agent: The 'transport' option is mandatory.\n");
880 exit (1);
883 if (agent_config.address == NULL && !agent_config.server) {
884 g_printerr ("debugger-agent: The 'address' option is mandatory.\n");
885 exit (1);
888 // FIXME:
889 if (!strcmp (agent_config.transport, "dt_socket")) {
890 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
891 g_printerr ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
892 exit (1);
897 void
898 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
900 g_assertf (tls, "Cannot get state of null thread", NULL);
902 g_assert (tls->thread_state == expected);
904 tls->thread_state = set;
906 return;
909 MonoDebuggerThreadState
910 mono_debugger_get_thread_state (DebuggerTlsData *tls)
912 g_assertf (tls, "Cannot get state of null thread", NULL);
914 return tls->thread_state;
917 gsize
918 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
920 if (!tls)
921 return 0;
923 return tls->thread_id;
926 // Only call this function with the loader lock held
927 MonoGHashTable *
928 mono_debugger_get_thread_states (void)
930 return thread_to_tls;
933 gboolean
934 mono_debugger_is_disconnected (void)
936 return disconnected;
939 static void
940 debugger_agent_init (void)
942 if (!agent_config.enabled)
943 return;
945 DebuggerEngineCallbacks cbs;
946 memset (&cbs, 0, sizeof (cbs));
947 cbs.tls_get_restore_state = tls_get_restore_state;
948 cbs.try_process_suspend = try_process_suspend;
949 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
950 cbs.begin_single_step_processing = begin_single_step_processing;
951 cbs.ss_discard_frame_context = ss_discard_frame_context;
952 cbs.ss_calculate_framecount = ss_calculate_framecount;
953 cbs.ensure_jit = ensure_jit;
954 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
955 cbs.get_this_async_id = get_this_async_id;
956 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
957 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
958 cbs.create_breakpoint_events = create_breakpoint_events;
959 cbs.process_breakpoint_events = process_breakpoint_events;
960 cbs.ss_create_init_args = ss_create_init_args;
961 cbs.ss_args_destroy = ss_args_destroy;
963 mono_de_init (&cbs);
965 transport_init ();
967 /* Need to know whenever a thread has acquired the loader mutex */
968 mono_loader_lock_track_ownership (TRUE);
970 event_requests = g_ptr_array_new ();
972 mono_coop_mutex_init (&debugger_thread_exited_mutex);
973 mono_coop_cond_init (&debugger_thread_exited_cond);
975 MonoProfilerHandle prof = mono_profiler_create (NULL);
976 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
977 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
978 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
979 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
980 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
981 mono_profiler_set_thread_started_callback (prof, thread_startup);
982 mono_profiler_set_thread_stopped_callback (prof, thread_end);
983 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
984 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
985 mono_profiler_set_jit_done_callback (prof, jit_done);
986 mono_profiler_set_jit_failed_callback (prof, jit_failed);
987 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
988 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
990 mono_native_tls_alloc (&debugger_tls_id, NULL);
992 /* Needed by the hash_table_new_type () call below */
993 mono_gc_base_init ();
995 thread_to_tls = mono_g_hash_table_new_type_internal ((GHashFunc)mono_object_hash_internal, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger TLS Table");
997 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
999 tid_to_thread_obj = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Object Table");
1001 pending_assembly_loads = g_ptr_array_new ();
1003 log_level = agent_config.log_level;
1005 embedding = agent_config.embedding;
1006 disconnected = TRUE;
1008 if (agent_config.log_file) {
1009 log_file = fopen (agent_config.log_file, "w+");
1010 if (!log_file) {
1011 g_printerr ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1012 exit (1);
1014 } else {
1015 log_file = stdout;
1017 mono_de_set_log_level (log_level, log_file);
1019 ids_init ();
1020 objrefs_init ();
1021 suspend_init ();
1023 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1025 * This is needed because currently we don't handle liveness info.
1027 mini_get_debug_options ()->mdb_optimizations = TRUE;
1029 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1030 /* This is needed because we can't set local variables in registers yet */
1031 mono_disable_optimizations (MONO_OPT_LINEARS);
1032 #endif
1035 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1036 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1037 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1038 * workaround.
1040 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1042 #ifdef HAVE_SETPGID
1043 if (agent_config.setpgid)
1044 setpgid (0, 0);
1045 #endif
1047 if (!agent_config.onuncaught && !agent_config.onthrow)
1048 finish_agent_init (TRUE);
1052 * finish_agent_init:
1054 * Finish the initialization of the agent. This involves connecting the transport
1055 * and starting the agent thread. This is either done at startup, or
1056 * in response to some event like an unhandled exception.
1058 static void
1059 finish_agent_init (gboolean on_startup)
1061 int res;
1063 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1064 return;
1066 if (agent_config.launch) {
1067 char *argv [16];
1069 // FIXME: Generated address
1070 // FIXME: Races with transport_connect ()
1072 argv [0] = agent_config.launch;
1073 argv [1] = agent_config.transport;
1074 argv [2] = agent_config.address;
1075 argv [3] = NULL;
1077 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1078 if (!res) {
1079 g_printerr ("Failed to execute '%s'.\n", agent_config.launch);
1080 exit (1);
1084 transport_connect (agent_config.address);
1086 if (!on_startup) {
1087 /* Do some which is usually done after sending the VMStart () event */
1088 vm_start_event_sent = TRUE;
1089 ERROR_DECL (error);
1090 start_debugger_thread (error);
1091 mono_error_assert_ok (error);
1095 static void
1096 mono_debugger_agent_cleanup (void)
1098 if (!inited)
1099 return;
1101 stop_debugger_thread ();
1103 event_requests_cleanup ();
1104 objrefs_cleanup ();
1105 ids_cleanup ();
1107 mono_de_cleanup ();
1111 * SOCKET TRANSPORT
1114 #ifndef DISABLE_SOCKET_TRANSPORT
1117 * recv_length:
1119 * recv() + handle incomplete reads and EINTR
1121 static int
1122 socket_transport_recv (void *buf, int len)
1124 int res;
1125 int total = 0;
1126 int fd = conn_fd;
1127 int flags = 0;
1128 static gint64 last_keepalive;
1129 gint64 msecs;
1131 MONO_ENTER_GC_SAFE;
1133 do {
1134 again:
1135 res = recv (fd, (char *) buf + total, len - total, flags);
1136 if (res > 0)
1137 total += res;
1138 if (agent_config.keepalive) {
1139 gboolean need_keepalive = FALSE;
1140 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1141 need_keepalive = TRUE;
1142 } else if (res == -1) {
1143 /* This could happen if recv () is interrupted repeatedly */
1144 msecs = mono_msec_ticks ();
1145 if (msecs - last_keepalive >= agent_config.keepalive) {
1146 need_keepalive = TRUE;
1147 last_keepalive = msecs;
1150 if (need_keepalive) {
1151 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1152 goto again;
1155 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1157 MONO_EXIT_GC_SAFE;
1159 return total;
1162 static void
1163 set_keepalive (void)
1165 struct timeval tv;
1166 int result;
1168 if (!agent_config.keepalive || !conn_fd)
1169 return;
1171 tv.tv_sec = agent_config.keepalive / 1000;
1172 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1174 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1175 g_assert (result >= 0);
1178 static int
1179 socket_transport_accept (int socket_fd)
1181 MONO_ENTER_GC_SAFE;
1182 conn_fd = accept (socket_fd, NULL, NULL);
1183 MONO_EXIT_GC_SAFE;
1185 if (conn_fd == -1) {
1186 g_printerr ("debugger-agent: Unable to listen on %d\n", socket_fd);
1187 } else {
1188 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1191 return conn_fd;
1194 static gboolean
1195 socket_transport_send (void *data, int len)
1197 int res;
1199 MONO_ENTER_GC_SAFE;
1201 do {
1202 res = send (conn_fd, (const char*)data, len, 0);
1203 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1205 MONO_EXIT_GC_SAFE;
1207 if (res != len)
1208 return FALSE;
1209 else
1210 return TRUE;
1214 * socket_transport_connect:
1216 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1218 static void
1219 socket_transport_connect (const char *address)
1221 MonoAddressInfo *result;
1222 MonoAddressEntry *rp;
1223 int sfd = -1, s, res;
1224 char *host;
1225 int port;
1227 if (agent_config.address) {
1228 res = parse_address (agent_config.address, &host, &port);
1229 g_assert (res == 0);
1230 } else {
1231 host = NULL;
1232 port = 0;
1235 conn_fd = -1;
1236 listen_fd = -1;
1238 if (host) {
1240 mono_network_init ();
1242 /* Obtain address(es) matching host/port */
1243 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1244 if (s != 0) {
1245 g_printerr ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1246 exit (1);
1250 if (agent_config.server) {
1251 /* Wait for a connection */
1252 if (!host) {
1253 struct sockaddr_in addr;
1254 socklen_t addrlen;
1256 /* No address, generate one */
1257 sfd = socket (AF_INET, SOCK_STREAM, 0);
1258 if (sfd == -1) {
1259 g_printerr ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1260 exit (1);
1263 /* This will bind the socket to a random port */
1264 res = listen (sfd, 16);
1265 if (res == -1) {
1266 g_printerr ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1267 exit (1);
1269 listen_fd = sfd;
1271 addrlen = sizeof (addr);
1272 memset (&addr, 0, sizeof (addr));
1273 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1274 g_assert (res == 0);
1276 host = (char*)"127.0.0.1";
1277 port = ntohs (addr.sin_port);
1279 /* Emit the address to stdout */
1280 /* FIXME: Should print another interface, not localhost */
1281 printf ("%s:%d\n", host, port);
1282 } else {
1283 /* Listen on the provided address */
1284 for (rp = result->entries; rp != NULL; rp = rp->next) {
1285 MonoSocketAddress sockaddr;
1286 socklen_t sock_len;
1287 int n = 1;
1289 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1291 sfd = socket (rp->family, rp->socktype,
1292 rp->protocol);
1293 if (sfd == -1)
1294 continue;
1296 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1297 continue;
1299 res = bind (sfd, &sockaddr.addr, sock_len);
1300 if (res == -1)
1301 continue;
1303 res = listen (sfd, 16);
1304 if (res == -1)
1305 continue;
1306 listen_fd = sfd;
1307 break;
1310 mono_free_address_info (result);
1313 if (agent_config.defer)
1314 return;
1316 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1318 if (agent_config.timeout) {
1319 fd_set readfds;
1320 struct timeval tv;
1322 tv.tv_sec = 0;
1323 tv.tv_usec = agent_config.timeout * 1000;
1324 FD_ZERO (&readfds);
1325 FD_SET (sfd, &readfds);
1327 MONO_ENTER_GC_SAFE;
1328 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1329 MONO_EXIT_GC_SAFE;
1331 if (res == 0) {
1332 g_printerr ("debugger-agent: Timed out waiting to connect.\n");
1333 exit (1);
1337 conn_fd = socket_transport_accept (sfd);
1338 if (conn_fd == -1)
1339 exit (1);
1341 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1342 } else {
1343 /* Connect to the specified address */
1344 /* FIXME: Respect the timeout */
1345 for (rp = result->entries; rp != NULL; rp = rp->next) {
1346 MonoSocketAddress sockaddr;
1347 socklen_t sock_len;
1349 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1351 sfd = socket (rp->family, rp->socktype,
1352 rp->protocol);
1353 if (sfd == -1)
1354 continue;
1356 MONO_ENTER_GC_SAFE;
1357 res = connect (sfd, &sockaddr.addr, sock_len);
1358 MONO_EXIT_GC_SAFE;
1360 if (res != -1)
1361 break; /* Success */
1363 MONO_ENTER_GC_SAFE;
1364 #ifdef HOST_WIN32
1365 closesocket (sfd);
1366 #else
1367 close (sfd);
1368 #endif
1369 MONO_EXIT_GC_SAFE;
1372 if (rp == 0) {
1373 g_printerr ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1374 exit (1);
1377 conn_fd = sfd;
1379 mono_free_address_info (result);
1382 if (!transport_handshake ())
1383 exit (1);
1386 static void
1387 socket_transport_close1 (void)
1389 /* This will interrupt the agent thread */
1390 /* Close the read part only so it can still send back replies */
1391 /* Also shut down the connection listener so that we can exit normally */
1392 #ifdef HOST_WIN32
1393 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1394 shutdown (conn_fd, SD_BOTH);
1395 shutdown (listen_fd, SD_BOTH);
1396 closesocket (listen_fd);
1397 #else
1398 shutdown (conn_fd, SHUT_RD);
1399 shutdown (listen_fd, SHUT_RDWR);
1400 MONO_ENTER_GC_SAFE;
1401 close (listen_fd);
1402 MONO_EXIT_GC_SAFE;
1403 #endif
1406 static void
1407 socket_transport_close2 (void)
1409 #ifdef HOST_WIN32
1410 shutdown (conn_fd, SD_BOTH);
1411 #else
1412 shutdown (conn_fd, SHUT_RDWR);
1413 #endif
1416 static void
1417 register_socket_transport (void)
1419 DebuggerTransport trans;
1421 trans.name = "dt_socket";
1422 trans.connect = socket_transport_connect;
1423 trans.close1 = socket_transport_close1;
1424 trans.close2 = socket_transport_close2;
1425 trans.send = socket_transport_send;
1426 trans.recv = socket_transport_recv;
1428 register_transport (&trans);
1432 * socket_fd_transport_connect:
1435 static void
1436 socket_fd_transport_connect (const char *address)
1438 int res;
1440 res = sscanf (address, "%d", &conn_fd);
1441 if (res != 1) {
1442 g_printerr ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1443 exit (1);
1446 if (!transport_handshake ())
1447 exit (1);
1450 static void
1451 register_socket_fd_transport (void)
1453 DebuggerTransport trans;
1455 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1456 trans.name = "socket-fd";
1457 trans.connect = socket_fd_transport_connect;
1458 trans.close1 = socket_transport_close1;
1459 trans.close2 = socket_transport_close2;
1460 trans.send = socket_transport_send;
1461 trans.recv = socket_transport_recv;
1463 register_transport (&trans);
1466 #endif /* DISABLE_SOCKET_TRANSPORT */
1469 * TRANSPORT CODE
1472 #define MAX_TRANSPORTS 16
1474 static DebuggerTransport *transport;
1476 static DebuggerTransport transports [MAX_TRANSPORTS];
1477 static int ntransports;
1479 MONO_API void
1480 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1482 void
1483 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1485 register_transport (trans);
1488 static void
1489 register_transport (DebuggerTransport *trans)
1491 g_assert (ntransports < MAX_TRANSPORTS);
1493 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1494 ntransports ++;
1497 static void
1498 transport_init (void)
1500 int i;
1502 #ifndef DISABLE_SOCKET_TRANSPORT
1503 register_socket_transport ();
1504 register_socket_fd_transport ();
1505 #endif
1507 for (i = 0; i < ntransports; ++i) {
1508 if (!strcmp (agent_config.transport, transports [i].name))
1509 break;
1511 if (i == ntransports) {
1512 g_printerr ("debugger-agent: The supported values for the 'transport' option are: ");
1513 for (i = 0; i < ntransports; ++i)
1514 g_printerr ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1515 g_printerr ("\n");
1516 exit (1);
1518 transport = &transports [i];
1521 void
1522 transport_connect (const char *address)
1524 transport->connect (address);
1527 static void
1528 transport_close1 (void)
1530 transport->close1 ();
1533 static void
1534 transport_close2 (void)
1536 transport->close2 ();
1539 static int
1540 transport_send (void *buf, int len)
1542 return transport->send (buf, len);
1545 static int
1546 transport_recv (void *buf, int len)
1548 return transport->recv (buf, len);
1551 gboolean
1552 mono_debugger_agent_transport_handshake (void)
1554 return transport_handshake ();
1557 static gboolean
1558 transport_handshake (void)
1560 char handshake_msg [128];
1561 guint8 buf [128];
1562 int res;
1564 disconnected = TRUE;
1566 /* Write handshake message */
1567 sprintf (handshake_msg, "DWP-Handshake");
1569 do {
1570 res = transport_send (handshake_msg, strlen (handshake_msg));
1571 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1573 g_assert (res != -1);
1575 /* Read answer */
1576 res = transport_recv (buf, strlen (handshake_msg));
1577 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1578 g_printerr ("debugger-agent: DWP handshake failed.\n");
1579 return FALSE;
1583 * To support older clients, the client sends its protocol version after connecting
1584 * using a command. Until that is received, default to our protocol version.
1586 major_version = MAJOR_VERSION;
1587 minor_version = MINOR_VERSION;
1588 protocol_version_set = FALSE;
1590 #ifndef DISABLE_SOCKET_TRANSPORT
1591 // FIXME: Move this somewhere else
1593 * Set TCP_NODELAY on the socket so the client receives events/command
1594 * results immediately.
1596 if (conn_fd) {
1597 int flag = 1;
1598 int result = setsockopt (conn_fd,
1599 IPPROTO_TCP,
1600 TCP_NODELAY,
1601 (char *) &flag,
1602 sizeof(int));
1603 g_assert (result >= 0);
1606 set_keepalive ();
1607 #endif
1609 disconnected = FALSE;
1610 return TRUE;
1613 static void
1614 stop_debugger_thread (void)
1616 if (!inited)
1617 return;
1619 transport_close1 ();
1622 * Wait for the thread to exit.
1624 * If we continue with the shutdown without waiting for it, then the client might
1625 * not receive an answer to its last command like a resume.
1627 if (!is_debugger_thread ()) {
1628 do {
1629 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1630 if (!debugger_thread_exited)
1631 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1632 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1633 } while (!debugger_thread_exited);
1635 if (debugger_thread_handle)
1636 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1639 transport_close2 ();
1642 static void
1643 start_debugger_thread (MonoError *error)
1645 MonoInternalThread *thread;
1647 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1648 return_if_nok (error);
1650 /* Is it possible for the thread to be dead alreay ? */
1651 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1652 g_assert (debugger_thread_handle);
1657 * Functions to decode protocol data
1660 static int
1661 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1663 *endbuf = buf + 1;
1664 g_assert (*endbuf <= limit);
1665 return buf [0];
1668 static int
1669 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1671 *endbuf = buf + 4;
1672 g_assert (*endbuf <= limit);
1674 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1677 static gint64
1678 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1680 guint32 high = decode_int (buf, &buf, limit);
1681 guint32 low = decode_int (buf, &buf, limit);
1683 *endbuf = buf;
1685 return ((((guint64)high) << 32) | ((guint64)low));
1688 static int
1689 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1691 return decode_int (buf, endbuf, limit);
1694 static char*
1695 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1697 int len = decode_int (buf, &buf, limit);
1698 char *s;
1700 if (len < 0) {
1701 *endbuf = buf;
1702 return NULL;
1705 s = (char *)g_malloc (len + 1);
1706 g_assert (s);
1708 memcpy (s, buf, len);
1709 s [len] = '\0';
1710 buf += len;
1711 *endbuf = buf;
1713 return s;
1717 * Functions to encode protocol data
1720 static void
1721 buffer_init (Buffer *buf, int size)
1723 buf->buf = (guint8 *)g_malloc (size);
1724 buf->p = buf->buf;
1725 buf->end = buf->buf + size;
1728 static int
1729 buffer_len (Buffer *buf)
1731 return buf->p - buf->buf;
1734 static void
1735 buffer_make_room (Buffer *buf, int size)
1737 if (buf->end - buf->p < size) {
1738 int new_size = buf->end - buf->buf + size + 32;
1739 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1740 size = buf->p - buf->buf;
1741 buf->buf = p;
1742 buf->p = p + size;
1743 buf->end = buf->buf + new_size;
1747 static void
1748 buffer_add_byte (Buffer *buf, guint8 val)
1750 buffer_make_room (buf, 1);
1751 buf->p [0] = val;
1752 buf->p++;
1755 static void
1756 buffer_add_short (Buffer *buf, guint32 val)
1758 buffer_make_room (buf, 2);
1759 buf->p [0] = (val >> 8) & 0xff;
1760 buf->p [1] = (val >> 0) & 0xff;
1761 buf->p += 2;
1764 static void
1765 buffer_add_int (Buffer *buf, guint32 val)
1767 buffer_make_room (buf, 4);
1768 buf->p [0] = (val >> 24) & 0xff;
1769 buf->p [1] = (val >> 16) & 0xff;
1770 buf->p [2] = (val >> 8) & 0xff;
1771 buf->p [3] = (val >> 0) & 0xff;
1772 buf->p += 4;
1775 static void
1776 buffer_add_long (Buffer *buf, guint64 l)
1778 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1779 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1782 static void
1783 buffer_add_id (Buffer *buf, int id)
1785 buffer_add_int (buf, (guint64)id);
1788 static void
1789 buffer_add_data (Buffer *buf, guint8 *data, int len)
1791 buffer_make_room (buf, len);
1792 memcpy (buf->p, data, len);
1793 buf->p += len;
1796 static void
1797 buffer_add_string (Buffer *buf, const char *str)
1799 int len;
1801 if (str == NULL) {
1802 buffer_add_int (buf, 0);
1803 } else {
1804 len = strlen (str);
1805 buffer_add_int (buf, len);
1806 buffer_add_data (buf, (guint8*)str, len);
1810 static void
1811 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1813 buffer_add_int (buf, arr_len);
1814 buffer_add_data (buf, bytes, arr_len);
1817 static void
1818 buffer_add_buffer (Buffer *buf, Buffer *data)
1820 buffer_add_data (buf, data->buf, buffer_len (data));
1823 static void
1824 buffer_free (Buffer *buf)
1826 g_free (buf->buf);
1829 static gboolean
1830 send_packet (int command_set, int command, Buffer *data)
1832 Buffer buf;
1833 int len, id;
1834 gboolean res;
1836 id = mono_atomic_inc_i32 (&packet_id);
1838 len = data->p - data->buf + 11;
1839 buffer_init (&buf, len);
1840 buffer_add_int (&buf, len);
1841 buffer_add_int (&buf, id);
1842 buffer_add_byte (&buf, 0); /* flags */
1843 buffer_add_byte (&buf, command_set);
1844 buffer_add_byte (&buf, command);
1845 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1847 res = transport_send (buf.buf, len);
1849 buffer_free (&buf);
1851 return res;
1854 static gboolean
1855 send_reply_packets (int npackets, ReplyPacket *packets)
1857 Buffer buf;
1858 int i, len;
1859 gboolean res;
1861 len = 0;
1862 for (i = 0; i < npackets; ++i)
1863 len += buffer_len (packets [i].data) + 11;
1864 buffer_init (&buf, len);
1865 for (i = 0; i < npackets; ++i) {
1866 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1867 buffer_add_int (&buf, packets [i].id);
1868 buffer_add_byte (&buf, 0x80); /* flags */
1869 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1870 buffer_add_byte (&buf, packets [i].error);
1871 buffer_add_buffer (&buf, packets [i].data);
1874 res = transport_send (buf.buf, len);
1876 buffer_free (&buf);
1878 return res;
1881 static gboolean
1882 send_reply_packet (int id, int error, Buffer *data)
1884 ReplyPacket packet;
1886 memset (&packet, 0, sizeof (ReplyPacket));
1887 packet.id = id;
1888 packet.error = error;
1889 packet.data = data;
1891 return send_reply_packets (1, &packet);
1894 static void
1895 send_buffered_reply_packets (void)
1897 int i;
1899 send_reply_packets (nreply_packets, reply_packets);
1900 for (i = 0; i < nreply_packets; ++i)
1901 buffer_free (reply_packets [i].data);
1902 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1903 nreply_packets = 0;
1906 static void
1907 buffer_reply_packet (int id, int error, Buffer *data)
1909 ReplyPacket *p;
1911 if (nreply_packets == 128)
1912 send_buffered_reply_packets ();
1914 p = &reply_packets [nreply_packets];
1915 p->id = id;
1916 p->error = error;
1917 p->data = g_new0 (Buffer, 1);
1918 buffer_init (p->data, buffer_len (data));
1919 buffer_add_buffer (p->data, data);
1920 nreply_packets ++;
1924 /* Maps objid -> ObjRef */
1925 /* Protected by the loader lock */
1926 static GHashTable *objrefs;
1927 /* Protected by the loader lock */
1928 static GHashTable *obj_to_objref;
1929 /* Protected by the dbg lock */
1930 static MonoGHashTable *suspended_objs;
1934 static void
1935 objrefs_init (void)
1937 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1938 obj_to_objref = g_hash_table_new (NULL, NULL);
1939 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");
1942 static void
1943 objrefs_cleanup (void)
1945 g_hash_table_destroy (objrefs);
1946 objrefs = NULL;
1950 * Return an ObjRef for OBJ.
1952 static ObjRef*
1953 get_objref (MonoObject *obj)
1955 ObjRef *ref;
1956 GSList *reflist = NULL, *l;
1957 int hash = 0;
1959 if (obj == NULL)
1960 return NULL;
1962 if (suspend_count) {
1964 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1966 dbg_lock ();
1967 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
1968 dbg_unlock ();
1971 mono_loader_lock ();
1973 /* FIXME: The tables can grow indefinitely */
1975 if (mono_gc_is_moving ()) {
1977 * Objects can move, so use a hash table mapping hash codes to lists of
1978 * ObjRef structures.
1980 hash = mono_object_hash_internal (obj);
1982 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1983 for (l = reflist; l; l = l->next) {
1984 ref = (ObjRef *)l->data;
1985 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1986 mono_loader_unlock ();
1987 return ref;
1990 } else {
1991 /* Use a hash table with masked pointers to internalize object references */
1992 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1993 /* ref might refer to a different object with the same addr which was GCd */
1994 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1995 mono_loader_unlock ();
1996 return ref;
2000 ref = g_new0 (ObjRef, 1);
2001 ref->id = mono_atomic_inc_i32 (&objref_id);
2002 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2004 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2006 if (mono_gc_is_moving ()) {
2007 reflist = g_slist_append (reflist, ref);
2008 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2009 } else {
2010 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2013 mono_loader_unlock ();
2015 return ref;
2018 static gboolean
2019 true_pred (gpointer key, gpointer value, gpointer user_data)
2021 return TRUE;
2024 static void
2025 clear_suspended_objs (void)
2027 dbg_lock ();
2028 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2029 dbg_unlock ();
2032 static int
2033 get_objid (MonoObject *obj)
2035 if (!obj)
2036 return 0;
2037 else
2038 return get_objref (obj)->id;
2042 * Set OBJ to the object identified by OBJID.
2043 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2044 * collected.
2046 static ErrorCode
2047 get_object_allow_null (int objid, MonoObject **obj)
2049 ObjRef *ref;
2051 if (objid == 0) {
2052 *obj = NULL;
2053 return ERR_NONE;
2056 if (!objrefs)
2057 return ERR_INVALID_OBJECT;
2059 mono_loader_lock ();
2061 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2063 if (ref) {
2064 *obj = mono_gchandle_get_target_internal (ref->handle);
2065 mono_loader_unlock ();
2066 if (!(*obj))
2067 return ERR_INVALID_OBJECT;
2068 return ERR_NONE;
2069 } else {
2070 mono_loader_unlock ();
2071 return ERR_INVALID_OBJECT;
2075 static ErrorCode
2076 get_object (int objid, MonoObject **obj)
2078 ErrorCode err = get_object_allow_null (objid, obj);
2080 if (err != ERR_NONE)
2081 return err;
2082 if (!(*obj))
2083 return ERR_INVALID_OBJECT;
2084 return ERR_NONE;
2087 static int
2088 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2090 return decode_id (buf, endbuf, limit);
2093 static void
2094 buffer_add_objid (Buffer *buf, MonoObject *o)
2096 buffer_add_id (buf, get_objid (o));
2100 * IDS
2103 typedef enum {
2104 ID_ASSEMBLY = 0,
2105 ID_MODULE = 1,
2106 ID_TYPE = 2,
2107 ID_METHOD = 3,
2108 ID_FIELD = 4,
2109 ID_DOMAIN = 5,
2110 ID_PROPERTY = 6,
2111 ID_NUM
2112 } IdType;
2115 * Represents a runtime structure accessible to the debugger client
2117 typedef struct {
2118 /* Unique id used in the wire protocol */
2119 int id;
2120 /* Domain of the runtime structure, NULL if the domain was unloaded */
2121 MonoDomain *domain;
2122 union {
2123 gpointer val;
2124 MonoClass *klass;
2125 MonoMethod *method;
2126 MonoImage *image;
2127 MonoAssembly *assembly;
2128 MonoClassField *field;
2129 MonoDomain *domain;
2130 MonoProperty *property;
2131 } data;
2132 } Id;
2134 typedef struct {
2135 /* Maps runtime structure -> Id */
2136 /* Protected by the dbg lock */
2137 GHashTable *val_to_id [ID_NUM];
2138 /* Classes whose class load event has been sent */
2139 /* Protected by the loader lock */
2140 GHashTable *loaded_classes;
2141 /* Maps MonoClass->GPtrArray of file names */
2142 GHashTable *source_files;
2143 /* Maps source file basename -> GSList of classes */
2144 GHashTable *source_file_to_class;
2145 /* Same with ignore-case */
2146 GHashTable *source_file_to_class_ignorecase;
2147 } AgentDomainInfo;
2149 /* Maps id -> Id */
2150 /* Protected by the dbg lock */
2151 static GPtrArray *ids [ID_NUM];
2153 static void
2154 ids_init (void)
2156 int i;
2158 for (i = 0; i < ID_NUM; ++i)
2159 ids [i] = g_ptr_array_new ();
2162 static void
2163 ids_cleanup (void)
2165 int i, j;
2167 for (i = 0; i < ID_NUM; ++i) {
2168 if (ids [i]) {
2169 for (j = 0; j < ids [i]->len; ++j)
2170 g_free (g_ptr_array_index (ids [i], j));
2171 g_ptr_array_free (ids [i], TRUE);
2173 ids [i] = NULL;
2177 static void
2178 debugger_agent_free_domain_info (MonoDomain *domain)
2180 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2181 int i, j;
2182 GHashTableIter iter;
2183 GPtrArray *file_names;
2184 char *basename;
2185 GSList *l;
2187 if (info) {
2188 for (i = 0; i < ID_NUM; ++i)
2189 g_hash_table_destroy (info->val_to_id [i]);
2190 g_hash_table_destroy (info->loaded_classes);
2192 g_hash_table_iter_init (&iter, info->source_files);
2193 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2194 for (i = 0; i < file_names->len; ++i)
2195 g_free (g_ptr_array_index (file_names, i));
2196 g_ptr_array_free (file_names, TRUE);
2199 g_hash_table_iter_init (&iter, info->source_file_to_class);
2200 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2201 g_free (basename);
2202 g_slist_free (l);
2205 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2206 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2207 g_free (basename);
2208 g_slist_free (l);
2211 g_free (info);
2214 domain_jit_info (domain)->agent_info = NULL;
2216 /* Clear ids referencing structures in the domain */
2217 dbg_lock ();
2218 for (i = 0; i < ID_NUM; ++i) {
2219 if (ids [i]) {
2220 for (j = 0; j < ids [i]->len; ++j) {
2221 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2222 if (id->domain == domain)
2223 id->domain = NULL;
2227 dbg_unlock ();
2229 mono_de_domain_remove (domain);
2232 static AgentDomainInfo*
2233 get_agent_domain_info (MonoDomain *domain)
2235 AgentDomainInfo *info = NULL;
2236 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2238 info = (AgentDomainInfo *)jit_info->agent_info;
2240 if (info) {
2241 mono_memory_read_barrier ();
2242 return info;
2245 info = g_new0 (AgentDomainInfo, 1);
2246 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2247 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2248 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2249 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2251 mono_memory_write_barrier ();
2253 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2255 if (other_info != NULL) {
2256 g_hash_table_destroy (info->loaded_classes);
2257 g_hash_table_destroy (info->source_files);
2258 g_hash_table_destroy (info->source_file_to_class);
2259 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2260 g_free (info);
2263 return (AgentDomainInfo *)jit_info->agent_info;
2266 static int
2267 get_id (MonoDomain *domain, IdType type, gpointer val)
2269 Id *id;
2270 AgentDomainInfo *info;
2272 if (val == NULL)
2273 return 0;
2275 info = get_agent_domain_info (domain);
2277 dbg_lock ();
2279 if (info->val_to_id [type] == NULL)
2280 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2282 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2283 if (id) {
2284 dbg_unlock ();
2285 return id->id;
2288 id = g_new0 (Id, 1);
2289 /* Reserve id 0 */
2290 id->id = ids [type]->len + 1;
2291 id->domain = domain;
2292 id->data.val = val;
2294 g_hash_table_insert (info->val_to_id [type], val, id);
2295 g_ptr_array_add (ids [type], id);
2297 dbg_unlock ();
2299 return id->id;
2302 static gpointer
2303 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2305 Id *res;
2307 int id = decode_id (buf, endbuf, limit);
2309 *err = ERR_NONE;
2310 if (domain)
2311 *domain = NULL;
2313 if (id == 0)
2314 return NULL;
2316 // FIXME: error handling
2317 dbg_lock ();
2318 g_assert (id > 0 && id <= ids [type]->len);
2320 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2321 dbg_unlock ();
2323 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2324 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2325 *err = ERR_UNLOADED;
2326 return NULL;
2329 if (domain)
2330 *domain = res->domain;
2332 return res->data.val;
2335 static int
2336 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2338 int id = get_id (domain, type, val);
2340 buffer_add_id (buf, id);
2341 return id;
2344 static MonoClass*
2345 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2347 MonoClass *klass;
2349 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2350 if (G_UNLIKELY (log_level >= 2) && klass) {
2351 char *s;
2353 s = mono_type_full_name (m_class_get_byval_arg (klass));
2354 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2355 g_free (s);
2357 return klass;
2360 static MonoAssembly*
2361 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2363 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2366 static MonoImage*
2367 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2369 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2372 static MonoMethod*
2373 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2375 MonoMethod *m;
2377 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2378 if (G_UNLIKELY (log_level >= 2) && m) {
2379 char *s;
2381 s = mono_method_full_name (m, TRUE);
2382 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2383 g_free (s);
2385 return m;
2388 static MonoClassField*
2389 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2391 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2394 static MonoDomain*
2395 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2397 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2400 static MonoProperty*
2401 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2403 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2406 static void
2407 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2409 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2410 if (G_UNLIKELY (log_level >= 2) && klass) {
2411 char *s;
2413 s = mono_type_full_name (m_class_get_byval_arg (klass));
2414 if (is_debugger_thread ())
2415 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2416 else
2417 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2418 g_free (s);
2422 static void
2423 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2425 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2426 if (G_UNLIKELY (log_level >= 2) && method) {
2427 char *s;
2429 s = mono_method_full_name (method, 1);
2430 if (is_debugger_thread ())
2431 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2432 else
2433 DEBUG_PRINTF (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2434 g_free (s);
2438 static void
2439 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2441 int id;
2443 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2444 if (G_UNLIKELY (log_level >= 2) && assembly)
2445 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2448 static void
2449 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2451 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2454 static void
2455 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2457 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2460 static void
2461 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2463 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2466 static void
2467 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2469 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2472 static void invoke_method (void);
2475 * SUSPEND/RESUME
2478 static MonoJitInfo*
2479 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2481 MonoJitInfo *ji;
2483 if (out_ip)
2484 *out_ip = ip;
2486 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2487 if (!ji) {
2488 /* Could be an interpreter method */
2490 MonoLMF *lmf = mono_get_lmf ();
2491 MonoInterpFrameHandle *frame;
2493 g_assert (((gsize)lmf->previous_lmf) & 2);
2494 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2496 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2497 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2498 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2499 if (domain)
2500 *domain = mono_domain_get ();
2501 if (out_ip)
2502 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2504 return ji;
2508 * save_thread_context:
2510 * Set CTX as the current threads context which is used for computing stack traces.
2511 * This function is signal-safe.
2513 static void
2514 save_thread_context (MonoContext *ctx)
2516 DebuggerTlsData *tls;
2518 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2519 g_assert (tls);
2521 if (ctx)
2522 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2523 else
2524 mono_thread_state_init_from_current (&tls->context);
2527 /* Number of threads suspended */
2529 * If this is equal to the size of thread_to_tls, the runtime is considered
2530 * suspended.
2532 static gint32 threads_suspend_count;
2534 static MonoCoopMutex suspend_mutex;
2536 /* Cond variable used to wait for suspend_count becoming 0 */
2537 static MonoCoopCond suspend_cond;
2539 /* Semaphore used to wait for a thread becoming suspended */
2540 static MonoCoopSem suspend_sem;
2542 static void
2543 suspend_init (void)
2545 mono_coop_mutex_init (&suspend_mutex);
2546 mono_coop_cond_init (&suspend_cond);
2547 mono_coop_sem_init (&suspend_sem, 0);
2550 typedef struct
2552 StackFrameInfo last_frame;
2553 gboolean last_frame_set;
2554 MonoContext ctx;
2555 gpointer lmf;
2556 MonoDomain *domain;
2557 } GetLastFrameUserData;
2559 static gboolean
2560 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2562 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2564 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2565 return FALSE;
2567 if (!data->last_frame_set) {
2568 /* Store the last frame */
2569 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2570 data->last_frame_set = TRUE;
2571 return FALSE;
2572 } else {
2573 /* Store the context/lmf for the frame above the last frame */
2574 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2575 data->lmf = info->lmf;
2576 data->domain = info->domain;
2577 return TRUE;
2581 static void
2582 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2584 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2586 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2587 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2588 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2589 to->valid = TRUE;
2593 * thread_interrupt:
2595 * Process interruption of a thread. This should be signal safe.
2597 * This always runs in the debugger thread.
2599 static void
2600 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2602 gpointer ip;
2603 MonoNativeThreadId tid;
2605 g_assert (info);
2607 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2608 tid = mono_thread_info_get_tid (info);
2610 // FIXME: Races when the thread leaves managed code before hitting a single step
2611 // event.
2613 if (ji && !ji->is_trampoline) {
2614 /* Running managed code, will be suspended by the single step code */
2615 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2616 } else {
2618 * Running native code, will be suspended when it returns to/enters
2619 * managed code. Treat it as already suspended.
2620 * This might interrupt the code in mono_de_process_single_step (), we use the
2621 * tls->suspending flag to avoid races when that happens.
2623 if (!tls->suspended && !tls->suspending) {
2624 GetLastFrameUserData data;
2626 // FIXME: printf is not signal safe, but this is only used during
2627 // debugger debugging
2628 if (ip)
2629 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2630 //save_thread_context (&ctx);
2632 if (!tls->thread)
2633 /* Already terminated */
2634 return;
2637 * We are in a difficult position: we want to be able to provide stack
2638 * traces for this thread, but we can't use the current ctx+lmf, since
2639 * the thread is still running, so it might return to managed code,
2640 * making these invalid.
2641 * So we start a stack walk and save the first frame, along with the
2642 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2643 * suspended when it returns to managed code, so the parent's ctx should
2644 * remain valid.
2646 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2648 data.last_frame_set = FALSE;
2649 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2650 if (data.last_frame_set) {
2651 gpointer jit_tls = tls->thread->thread_info->jit_data;
2653 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2655 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2657 * Store the current lmf instead of the parent one, since that
2658 * contains the interp exit data.
2660 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2663 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2664 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2665 } else {
2666 tls->async_state.valid = FALSE;
2669 mono_memory_barrier ();
2671 tls->suspended = TRUE;
2672 mono_coop_sem_post (&suspend_sem);
2678 * reset_native_thread_suspend_state:
2680 * Reset the suspended flag and state on native threads
2682 static void
2683 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2685 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2687 if (!tls->really_suspended && tls->suspended) {
2688 tls->suspended = FALSE;
2690 * The thread might still be running if it was executing native code, so the state won't be invalided by
2691 * suspend_current ().
2693 tls->context.valid = FALSE;
2694 tls->async_state.valid = FALSE;
2695 invalidate_frames (tls);
2699 typedef struct {
2700 DebuggerTlsData *tls;
2701 gboolean valid_info;
2702 } InterruptData;
2704 static SuspendThreadResult
2705 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2707 InterruptData *data = (InterruptData *)user_data;
2708 MonoJitInfo *ji;
2710 data->valid_info = TRUE;
2711 ji = mono_jit_info_table_find_internal (
2712 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2713 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2714 TRUE,
2715 TRUE);
2717 /* This is signal safe */
2718 thread_interrupt (data->tls, info, ji);
2719 return MonoResumeThread;
2723 * notify_thread:
2725 * Notify a thread that it needs to suspend.
2727 static void
2728 notify_thread (gpointer key, gpointer value, gpointer user_data)
2730 MonoInternalThread *thread = (MonoInternalThread *)key;
2731 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2732 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2734 if (mono_thread_internal_is_current (thread) || tls->terminated)
2735 return;
2737 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2739 /* This is _not_ equivalent to mono_thread_internal_abort () */
2740 InterruptData interrupt_data = { 0 };
2741 interrupt_data.tls = tls;
2743 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2744 if (!interrupt_data.valid_info) {
2745 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2747 * Attached thread which died without detaching.
2749 tls->terminated = TRUE;
2753 static void
2754 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2756 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2757 MonoJitInfo *ji;
2758 MonoMethod *method;
2760 if (mono_loader_lock_is_owned_by_self ()) {
2762 * Shortcut for the check in suspend_current (). This speeds up processing
2763 * when executing long running code inside the loader lock, i.e. assembly load
2764 * hooks.
2766 return;
2769 if (is_debugger_thread ())
2770 return;
2772 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2773 if (suspend_count - tls->resume_count > 0)
2774 tls->suspending = TRUE;
2776 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2778 if (suspend_count - tls->resume_count == 0) {
2780 * We are executing a single threaded invoke but the single step for
2781 * suspending is still active.
2782 * FIXME: This slows down single threaded invokes.
2784 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2785 return;
2788 ji = get_top_method_ji (ip, NULL, NULL);
2789 g_assert (ji);
2790 /* Can't suspend in these methods */
2791 method = jinfo_get_method (ji);
2792 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2793 return;
2795 save_thread_context (ctx);
2797 suspend_current ();
2801 /* Conditionally call process_suspend depending oh the current state */
2802 static gboolean
2803 try_process_suspend (void *the_tls, MonoContext *ctx)
2805 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2807 if (suspend_count > 0) {
2808 /* Fastpath during invokes, see in process_suspend () */
2809 if (suspend_count - tls->resume_count == 0)
2810 return FALSE;
2811 if (tls->invoke)
2812 return FALSE;
2813 process_suspend (tls, ctx);
2814 return TRUE;
2816 return FALSE;
2820 * suspend_vm:
2822 * Increase the suspend count of the VM. While the suspend count is greater
2823 * than 0, runtime threads are suspended at certain points during execution.
2825 static void
2826 suspend_vm (void)
2828 gboolean tp_suspend = FALSE;
2829 mono_loader_lock ();
2831 mono_coop_mutex_lock (&suspend_mutex);
2833 suspend_count ++;
2835 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2837 if (suspend_count == 1) {
2838 // FIXME: Is it safe to call this inside the lock ?
2839 mono_de_start_single_stepping ();
2840 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2843 mono_coop_mutex_unlock (&suspend_mutex);
2845 if (suspend_count == 1)
2847 * Suspend creation of new threadpool threads, since they cannot run
2849 tp_suspend = TRUE;
2850 mono_loader_unlock ();
2852 #ifndef ENABLE_NETCORE
2853 if (tp_suspend)
2854 mono_threadpool_suspend ();
2855 #endif
2859 * resume_vm:
2861 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2862 * are resumed.
2864 static void
2865 resume_vm (void)
2867 g_assert (is_debugger_thread ());
2868 gboolean tp_resume = FALSE;
2870 mono_loader_lock ();
2872 mono_coop_mutex_lock (&suspend_mutex);
2874 g_assert (suspend_count > 0);
2875 suspend_count --;
2877 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2879 if (suspend_count == 0) {
2880 // FIXME: Is it safe to call this inside the lock ?
2881 mono_de_stop_single_stepping ();
2882 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2885 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2886 mono_coop_cond_broadcast (&suspend_cond);
2888 mono_coop_mutex_unlock (&suspend_mutex);
2889 //g_assert (err == 0);
2891 if (suspend_count == 0)
2892 tp_resume = TRUE;
2893 mono_loader_unlock ();
2895 #ifndef ENABLE_NETCORE
2896 if (tp_resume)
2897 mono_threadpool_resume ();
2898 #endif
2902 * resume_thread:
2904 * Resume just one thread.
2906 static void
2907 resume_thread (MonoInternalThread *thread)
2909 DebuggerTlsData *tls;
2911 g_assert (is_debugger_thread ());
2913 mono_loader_lock ();
2915 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2916 g_assert (tls);
2918 mono_coop_mutex_lock (&suspend_mutex);
2920 g_assert (suspend_count > 0);
2922 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2924 tls->resume_count += suspend_count;
2927 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2928 * but only the one whose resume_count field is > 0 will be resumed.
2930 mono_coop_cond_broadcast (&suspend_cond);
2932 mono_coop_mutex_unlock (&suspend_mutex);
2933 //g_assert (err == 0);
2935 mono_loader_unlock ();
2938 static void
2939 free_frames (StackFrame **frames, int nframes)
2941 int i;
2943 for (i = 0; i < nframes; ++i) {
2944 if (frames [i]->jit)
2945 mono_debug_free_method_jit_info (frames [i]->jit);
2946 g_free (frames [i]);
2948 g_free (frames);
2951 static void
2952 invalidate_frames (DebuggerTlsData *tls)
2954 mono_loader_lock ();
2956 if (!tls)
2957 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2958 g_assert (tls);
2960 free_frames (tls->frames, tls->frame_count);
2961 tls->frame_count = 0;
2962 tls->frames = NULL;
2964 free_frames (tls->restore_frames, tls->restore_frame_count);
2965 tls->restore_frame_count = 0;
2966 tls->restore_frames = NULL;
2968 mono_loader_unlock ();
2972 * suspend_current:
2974 * Suspend the current thread until the runtime is resumed. If the thread has a
2975 * pending invoke, then the invoke is executed before this function returns.
2977 static void
2978 suspend_current (void)
2980 DebuggerTlsData *tls;
2982 g_assert (!is_debugger_thread ());
2984 if (mono_loader_lock_is_owned_by_self ()) {
2986 * If we own the loader mutex, can't suspend until we release it, since the
2987 * whole runtime can deadlock otherwise.
2989 return;
2992 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2993 g_assert (tls);
2995 gboolean do_resume = FALSE;
2996 while (!do_resume) {
2997 mono_coop_mutex_lock (&suspend_mutex);
2999 tls->suspending = FALSE;
3000 tls->really_suspended = TRUE;
3002 if (!tls->suspended) {
3003 tls->suspended = TRUE;
3004 mono_coop_sem_post (&suspend_sem);
3007 mono_debugger_log_suspend (tls);
3008 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3010 while (suspend_count - tls->resume_count > 0) {
3011 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
3014 tls->suspended = FALSE;
3015 tls->really_suspended = FALSE;
3017 threads_suspend_count --;
3019 mono_coop_mutex_unlock (&suspend_mutex);
3021 mono_debugger_log_resume (tls);
3022 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3024 if (tls->pending_invoke) {
3025 /* Save the original context */
3026 tls->pending_invoke->has_ctx = TRUE;
3027 tls->pending_invoke->ctx = tls->context.ctx;
3029 invoke_method ();
3031 /* Have to suspend again */
3032 } else {
3033 do_resume = TRUE;
3037 /* The frame info becomes invalid after a resume */
3038 tls->context.valid = FALSE;
3039 tls->async_state.valid = FALSE;
3040 invalidate_frames (tls);
3041 mono_stopwatch_start (&tls->step_time);
3044 static void
3045 count_thread (gpointer key, gpointer value, gpointer user_data)
3047 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3049 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3050 *(int*)user_data = *(int*)user_data + 1;
3053 static int
3054 count_threads_to_wait_for (void)
3056 int count = 0;
3058 mono_loader_lock ();
3059 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3060 mono_loader_unlock ();
3062 return count;
3066 * wait_for_suspend:
3068 * Wait until the runtime is completely suspended.
3070 static void
3071 wait_for_suspend (void)
3073 int nthreads, nwait, err;
3074 gboolean waited = FALSE;
3076 // FIXME: Threads starting/stopping ?
3077 mono_loader_lock ();
3078 nthreads = mono_g_hash_table_size (thread_to_tls);
3079 mono_loader_unlock ();
3081 while (TRUE) {
3082 nwait = count_threads_to_wait_for ();
3083 if (nwait) {
3084 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3085 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3086 g_assert (err == 0);
3087 waited = TRUE;
3088 } else {
3089 break;
3093 if (waited)
3094 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3098 * is_suspended:
3100 * Return whenever the runtime is suspended.
3102 static gboolean
3103 is_suspended (void)
3105 return count_threads_to_wait_for () == 0;
3108 static void
3109 no_seq_points_found (MonoMethod *method, int offset)
3112 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3114 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3117 static int
3118 calc_il_offset (MonoDomain *domain, MonoMethod *method, int native_offset, gboolean is_top_frame)
3120 int ret = -1;
3121 if (is_top_frame) {
3122 SeqPoint sp;
3123 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3124 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
3125 ret = sp.il_offset;
3127 if (ret == -1)
3128 ret = mono_debug_il_offset_from_address (method, domain, native_offset);
3129 return ret;
3132 typedef struct {
3133 DebuggerTlsData *tls;
3134 GSList *frames;
3135 gboolean set_debugger_flag;
3136 } ComputeFramesUserData;
3138 static gboolean
3139 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3141 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3142 StackFrame *frame;
3143 MonoMethod *method, *actual_method, *api_method;
3144 int flags = 0;
3146 mono_loader_lock ();
3147 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3148 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3149 /* Mark the last frame as an invoke frame */
3150 if (ud->frames)
3151 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3152 else
3153 ud->set_debugger_flag = TRUE;
3155 mono_loader_unlock ();
3156 return FALSE;
3159 if (info->ji)
3160 method = jinfo_get_method (info->ji);
3161 else
3162 method = info->method;
3163 actual_method = info->actual_method;
3164 api_method = method;
3166 if (!method) {
3167 mono_loader_unlock ();
3168 return FALSE;
3171 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3172 mono_loader_unlock ();
3173 return FALSE;
3176 if (info->il_offset == -1) {
3177 info->il_offset = calc_il_offset (info->domain, method, info->native_offset, ud->frames == NULL);
3180 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);
3182 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3183 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3184 /* Older clients can't handle this flag */
3185 mono_loader_unlock ();
3186 return FALSE;
3188 api_method = mono_marshal_method_from_wrapper (method);
3189 if (!api_method) {
3190 mono_loader_unlock ();
3191 return FALSE;
3193 actual_method = api_method;
3194 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3197 if (ud->set_debugger_flag) {
3198 g_assert (g_slist_length (ud->frames) == 0);
3199 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3200 ud->set_debugger_flag = FALSE;
3203 frame = g_new0 (StackFrame, 1);
3204 frame->de.ji = info->ji;
3205 frame->de.domain = info->domain;
3206 frame->de.method = method;
3207 frame->de.native_offset = info->native_offset;
3209 frame->actual_method = actual_method;
3210 frame->api_method = api_method;
3211 frame->il_offset = info->il_offset;
3212 frame->flags = flags;
3213 frame->interp_frame = info->interp_frame;
3214 frame->frame_addr = info->frame_addr;
3215 if (info->reg_locations)
3216 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3217 if (ctx) {
3218 frame->ctx = *ctx;
3219 frame->has_ctx = TRUE;
3222 ud->frames = g_slist_append (ud->frames, frame);
3224 mono_loader_unlock ();
3225 return FALSE;
3228 static gint32 isFixedSizeArray (MonoClassField *f)
3230 ERROR_DECL (error);
3231 if (!CHECK_PROTOCOL_VERSION (2, 53) || f->type->type != MONO_TYPE_VALUETYPE) {
3232 return 1;
3234 MonoCustomAttrInfo *cinfo;
3235 MonoCustomAttrEntry *attr;
3236 int aindex;
3237 gint32 ret = 1;
3238 cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error);
3239 goto_if_nok (error, leave);
3240 attr = NULL;
3241 if (cinfo) {
3242 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
3243 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
3244 MonoClass *fixed_size_class = mono_class_try_get_fixed_buffer_class ();
3245 if (fixed_size_class != NULL && mono_class_has_parent (ctor_class, fixed_size_class)) {
3246 attr = &cinfo->attrs [aindex];
3247 gpointer *typed_args, *named_args;
3248 CattrNamedArg *arginfo;
3249 int num_named_args;
3251 mono_reflection_create_custom_attr_data_args_noalloc (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size,
3252 &typed_args, &named_args, &num_named_args, &arginfo, error);
3253 if (!is_ok (error)) {
3254 ret = 0;
3255 goto leave;
3257 ret = *(gint32*)typed_args [1];
3258 g_free (typed_args [1]);
3259 g_free (typed_args);
3260 g_free (named_args);
3261 g_free (arginfo);
3262 return ret;
3266 leave:
3267 mono_error_cleanup (error);
3268 return ret;
3271 static gboolean
3272 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3274 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3277 * 'tls->filter_ctx' is the location of the throw site.
3279 * mono_walk_stack() will never actually hit the throw site, but unwind
3280 * directly from the filter to the call site; we abort stack unwinding here
3281 * once this happens and resume from the throw site.
3283 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3284 return TRUE;
3286 return process_frame (info, ctx, user_data);
3290 * Return a malloc-ed list of StackFrame structures.
3292 static StackFrame**
3293 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3295 ComputeFramesUserData user_data;
3296 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3297 StackFrame **res;
3298 int i, nframes;
3299 GSList *l;
3301 user_data.tls = tls;
3302 user_data.frames = NULL;
3304 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3306 nframes = g_slist_length (user_data.frames);
3307 res = g_new0 (StackFrame*, nframes);
3308 l = user_data.frames;
3309 for (i = 0; i < nframes; ++i) {
3310 res [i] = (StackFrame *)l->data;
3311 l = l->next;
3313 *out_nframes = nframes;
3315 return res;
3318 static void
3319 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3321 ComputeFramesUserData user_data;
3322 GSList *tmp;
3323 int i, findex, new_frame_count;
3324 StackFrame **new_frames, *f;
3325 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3327 // FIXME: Locking on tls
3328 if (tls->frames && tls->frames_up_to_date && !force_update)
3329 return;
3331 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3333 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3334 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
3335 new_frames = compute_frame_info_from (thread, tls, &tls->restore_state, &new_frame_count);
3336 invalidate_frames (tls);
3338 tls->frames = new_frames;
3339 tls->frame_count = new_frame_count;
3340 tls->frames_up_to_date = TRUE;
3341 return;
3345 user_data.tls = tls;
3346 user_data.frames = NULL;
3347 if (tls->terminated) {
3348 tls->frame_count = 0;
3349 return;
3350 } if (!tls->really_suspended && tls->async_state.valid) {
3351 /* Have to use the state saved by the signal handler */
3352 process_frame (&tls->async_last_frame, NULL, &user_data);
3353 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3354 } else if (tls->filter_state.valid) {
3356 * We are inside an exception filter.
3358 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3360 if (tls->context.valid) {
3361 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3362 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3365 * After that, we resume unwinding from the location where the exception has been thrown.
3367 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3368 } else if (tls->context.valid) {
3369 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3370 } else {
3371 // FIXME:
3372 tls->frame_count = 0;
3373 return;
3376 new_frame_count = g_slist_length (user_data.frames);
3377 new_frames = g_new0 (StackFrame*, new_frame_count);
3378 findex = 0;
3379 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3380 f = (StackFrame *)tmp->data;
3383 * Reuse the id for already existing stack frames, so invokes don't invalidate
3384 * the still valid stack frames.
3386 for (i = 0; i < tls->frame_count; ++i) {
3387 if (tls->frames [i]->frame_addr == f->frame_addr) {
3388 f->id = tls->frames [i]->id;
3389 break;
3393 if (i >= tls->frame_count)
3394 f->id = mono_atomic_inc_i32 (&frame_id);
3396 new_frames [findex ++] = f;
3399 g_slist_free (user_data.frames);
3401 invalidate_frames (tls);
3403 tls->frames = new_frames;
3404 tls->frame_count = new_frame_count;
3405 tls->frames_up_to_date = TRUE;
3407 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3408 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
3409 gboolean has_interp_resume_state = FALSE;
3410 MonoInterpFrameHandle interp_resume_frame = NULL;
3411 gpointer interp_resume_ip = 0;
3412 mini_get_interp_callbacks ()->get_resume_state (jit_data, &has_interp_resume_state, &interp_resume_frame, &interp_resume_ip);
3413 if (has_interp_resume_state && tls->frame_count > 0) {
3414 StackFrame *top_frame = tls->frames [0];
3415 if (interp_resume_frame == top_frame->interp_frame) {
3416 int native_offset = (int) ((uintptr_t) interp_resume_ip - (uintptr_t) top_frame->de.ji->code_start);
3417 top_frame->il_offset = calc_il_offset (top_frame->de.domain, top_frame->de.method, native_offset, TRUE);
3424 * GHFunc to emit an appdomain creation event
3425 * @param key Don't care
3426 * @param value A loaded appdomain
3427 * @param user_data Don't care
3429 static void
3430 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3432 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3433 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3437 * GHFunc to emit a thread start event
3438 * @param key A thread id
3439 * @param value A thread object
3440 * @param user_data Don't care
3442 static void
3443 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3445 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3446 process_profiler_event (EVENT_KIND_THREAD_START, value);
3450 * GFunc to emit an assembly load event
3451 * @param value A loaded assembly
3452 * @param user_data Don't care
3454 static void
3455 emit_assembly_load (gpointer value, gpointer user_data)
3457 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3461 * GFunc to emit a type load event
3462 * @param value A loaded type
3463 * @param user_data Don't care
3465 static void
3466 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3468 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3472 static void gc_finalizing (MonoProfiler *prof)
3474 DebuggerTlsData *tls;
3476 if (is_debugger_thread ())
3477 return;
3479 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3480 g_assert (tls);
3481 tls->gc_finalizing = TRUE;
3484 static void gc_finalized (MonoProfiler *prof)
3486 DebuggerTlsData *tls;
3488 if (is_debugger_thread ())
3489 return;
3491 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3492 g_assert (tls);
3493 tls->gc_finalizing = FALSE;
3497 static char*
3498 strdup_tolower (char *s)
3500 char *s2, *p;
3502 s2 = g_strdup (s);
3503 for (p = s2; *p; ++p)
3504 *p = tolower (*p);
3505 return s2;
3509 * Same as g_path_get_basename () but handles windows paths as well,
3510 * which can occur in .mdb files created by pdb2mdb.
3512 static char*
3513 dbg_path_get_basename (const char *filename)
3515 char *r;
3517 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3518 return g_path_get_basename (filename);
3520 /* From gpath.c */
3522 /* No separator -> filename */
3523 r = (char*)strrchr (filename, '\\');
3524 if (r == NULL)
3525 return g_strdup (filename);
3527 /* Trailing slash, remove component */
3528 if (r [1] == 0){
3529 char *copy = g_strdup (filename);
3530 copy [r-filename] = 0;
3531 r = strrchr (copy, '\\');
3533 if (r == NULL){
3534 g_free (copy);
3535 return g_strdup ("/");
3537 r = g_strdup (&r[1]);
3538 g_free (copy);
3539 return r;
3542 return g_strdup (&r[1]);
3545 static void
3546 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3548 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3549 ERROR_DECL (error);
3550 MonoCustomAttrInfo *ainfo;
3552 if (ji->dbg_attrs_inited)
3553 return;
3555 if (!hidden_klass)
3556 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3558 if (!step_through_klass)
3559 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3561 if (!non_user_klass)
3562 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3564 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3565 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3566 if (ainfo) {
3567 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3568 ji->dbg_hidden = TRUE;
3569 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3570 ji->dbg_step_through = TRUE;
3571 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3572 ji->dbg_non_user_code = TRUE;
3573 mono_custom_attrs_free (ainfo);
3576 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3577 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3578 if (ainfo) {
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 mono_memory_barrier ();
3587 ji->dbg_attrs_inited = TRUE;
3591 * EVENT HANDLING
3595 * create_event_list:
3597 * Return a list of event request ids matching EVENT, starting from REQS, which
3598 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3599 * policy.
3600 * We return request ids, instead of requests, to simplify threading, since
3601 * requests could be deleted anytime when the loader lock is not held.
3602 * LOCKING: Assumes the loader lock is held.
3604 static GSList*
3605 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3607 int i, j;
3608 GSList *events = NULL;
3610 *suspend_policy = SUSPEND_POLICY_NONE;
3612 if (!reqs)
3613 reqs = event_requests;
3615 if (!reqs)
3616 return NULL;
3617 gboolean has_everything_else = FALSE;
3618 gboolean is_new_filtered_exception = FALSE;
3619 gboolean filteredException = TRUE;
3620 gint filtered_suspend_policy = 0;
3621 gint filtered_req_id = 0;
3622 gint everything_else_suspend_policy = 0;
3623 gint everything_else_req_id = 0;
3624 gboolean is_already_filtered = FALSE;
3625 for (i = 0; i < reqs->len; ++i) {
3626 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3627 if (req->event_kind == event) {
3628 gboolean filtered = FALSE;
3630 /* Apply filters */
3631 for (j = 0; j < req->nmodifiers; ++j) {
3632 Modifier *mod = &req->modifiers [j];
3634 if (mod->kind == MOD_KIND_COUNT) {
3635 filtered = TRUE;
3636 if (mod->data.count > 0) {
3637 if (mod->data.count > 0) {
3638 mod->data.count --;
3639 if (mod->data.count == 0)
3640 filtered = FALSE;
3643 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3644 if (mod->data.thread != mono_thread_internal_current ())
3645 filtered = TRUE;
3646 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && !mod->not_filtered_feature && ei) {
3647 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3648 filtered = TRUE;
3649 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3650 filtered = TRUE;
3651 if (ei->caught && !mod->caught)
3652 filtered = TRUE;
3653 if (!ei->caught && !mod->uncaught)
3654 filtered = TRUE;
3655 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && mod->not_filtered_feature && ei) {
3656 is_new_filtered_exception = TRUE;
3657 if ((mod->data.exc_class && mod->subclasses && mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass)) ||
3658 (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)) {
3659 is_already_filtered = TRUE;
3660 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3661 filteredException = FALSE;
3662 filtered_suspend_policy = req->suspend_policy;
3663 filtered_req_id = req->id;
3666 if (!mod->data.exc_class && mod->everything_else) {
3667 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3668 has_everything_else = TRUE;
3669 everything_else_req_id = req->id;
3670 everything_else_suspend_policy = req->suspend_policy;
3673 if (!mod->data.exc_class && !mod->everything_else) {
3674 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3675 filteredException = FALSE;
3676 filtered_suspend_policy = req->suspend_policy;
3677 filtered_req_id = req->id;
3680 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3681 int k;
3682 gboolean found = FALSE;
3683 MonoAssembly **assemblies = mod->data.assemblies;
3685 if (assemblies) {
3686 for (k = 0; assemblies [k]; ++k)
3687 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3688 found = TRUE;
3690 if (!found)
3691 filtered = TRUE;
3692 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3693 gpointer iter = NULL;
3694 MonoMethod *method;
3695 MonoDebugSourceInfo *sinfo;
3696 char *s;
3697 gboolean found = FALSE;
3698 int i;
3699 GPtrArray *source_file_list;
3701 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3702 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3704 if (minfo) {
3705 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
3706 for (i = 0; i < source_file_list->len; ++i) {
3707 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3709 * Do a case-insesitive match by converting the file name to
3710 * lowercase.
3712 s = strdup_tolower (sinfo->source_file);
3713 if (g_hash_table_lookup (mod->data.source_files, s))
3714 found = TRUE;
3715 else {
3716 char *s2 = dbg_path_get_basename (sinfo->source_file);
3717 char *s3 = strdup_tolower (s2);
3719 if (g_hash_table_lookup (mod->data.source_files, s3))
3720 found = TRUE;
3721 g_free (s2);
3722 g_free (s3);
3724 g_free (s);
3726 g_ptr_array_free (source_file_list, TRUE);
3729 if (!found)
3730 filtered = TRUE;
3731 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3732 char *s;
3734 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3735 if (!g_hash_table_lookup (mod->data.type_names, s))
3736 filtered = TRUE;
3737 g_free (s);
3738 } else if (mod->kind == MOD_KIND_STEP) {
3739 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3740 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3741 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3742 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3743 filtered = TRUE;
3744 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3745 init_jit_info_dbg_attrs (ji);
3746 if (ji->dbg_hidden)
3747 filtered = TRUE;
3749 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3750 init_jit_info_dbg_attrs (ji);
3751 if (ji->dbg_step_through)
3752 filtered = TRUE;
3754 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3755 init_jit_info_dbg_attrs (ji);
3756 if (ji->dbg_non_user_code)
3757 filtered = TRUE;
3762 if (!filtered && !is_new_filtered_exception) {
3763 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3764 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3769 if (has_everything_else && !is_already_filtered) {
3770 filteredException = FALSE;
3771 filtered_suspend_policy = everything_else_suspend_policy;
3772 filtered_req_id = everything_else_req_id;
3775 if (!filteredException) {
3776 *suspend_policy = MAX (*suspend_policy, filtered_suspend_policy);
3777 events = g_slist_append (events, GINT_TO_POINTER (filtered_req_id));
3780 /* Send a VM START/DEATH event by default */
3781 if (event == EVENT_KIND_VM_START)
3782 events = g_slist_append (events, GINT_TO_POINTER (0));
3783 if (event == EVENT_KIND_VM_DEATH)
3784 events = g_slist_append (events, GINT_TO_POINTER (0));
3786 return events;
3789 static G_GNUC_UNUSED const char*
3790 event_to_string (EventKind event)
3792 switch (event) {
3793 case EVENT_KIND_VM_START: return "VM_START";
3794 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3795 case EVENT_KIND_THREAD_START: return "THREAD_START";
3796 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3797 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3798 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3799 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3800 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3801 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3802 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3803 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3804 case EVENT_KIND_STEP: return "STEP";
3805 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3806 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3807 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3808 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3809 case EVENT_KIND_USER_LOG: return "USER_LOG";
3810 case EVENT_KIND_CRASH: return "CRASH";
3811 default:
3812 g_assert_not_reached ();
3813 return "";
3818 * process_event:
3820 * Send an event to the client, suspending the vm if needed.
3821 * LOCKING: Since this can suspend the calling thread, no locks should be held
3822 * by the caller.
3823 * The EVENTS list is freed by this function.
3825 static void
3826 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3828 Buffer buf;
3829 GSList *l;
3830 MonoDomain *domain = mono_domain_get ();
3831 MonoThread *thread = NULL;
3832 MonoObject *keepalive_obj = NULL;
3833 gboolean send_success = FALSE;
3834 static int ecount;
3835 int nevents;
3837 if (!inited) {
3838 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3839 return;
3842 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3843 // FIXME: We miss those events
3844 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3845 return;
3848 if (vm_death_event_sent) {
3849 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3850 return;
3853 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3854 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3855 return;
3858 if (disconnected) {
3859 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3860 return;
3863 if (event == EVENT_KIND_KEEPALIVE)
3864 suspend_policy = SUSPEND_POLICY_NONE;
3865 else {
3866 if (events == NULL)
3867 return;
3869 if (agent_config.defer) {
3870 if (is_debugger_thread ()) {
3871 /* Don't suspend on events from the debugger thread */
3872 suspend_policy = SUSPEND_POLICY_NONE;
3874 } else {
3875 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3876 // FIXME: Send these with a NULL thread, don't suspend the current thread
3877 return;
3881 nevents = g_slist_length (events);
3882 buffer_init (&buf, 128);
3883 buffer_add_byte (&buf, suspend_policy);
3884 buffer_add_int (&buf, nevents);
3886 for (l = events; l; l = l->next) {
3887 buffer_add_byte (&buf, event); // event kind
3888 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3890 ecount ++;
3892 if (event == EVENT_KIND_VM_DEATH) {
3893 thread = NULL;
3894 } else {
3895 if (!thread)
3896 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3898 if (event == EVENT_KIND_VM_START && arg != NULL)
3899 thread = (MonoThread *)arg;
3902 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3904 switch (event) {
3905 case EVENT_KIND_THREAD_START:
3906 case EVENT_KIND_THREAD_DEATH:
3907 break;
3908 case EVENT_KIND_APPDOMAIN_CREATE:
3909 case EVENT_KIND_APPDOMAIN_UNLOAD:
3910 buffer_add_domainid (&buf, (MonoDomain *)arg);
3911 break;
3912 case EVENT_KIND_METHOD_ENTRY:
3913 case EVENT_KIND_METHOD_EXIT:
3914 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3915 break;
3916 case EVENT_KIND_ASSEMBLY_LOAD:
3917 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3918 break;
3919 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3920 DebuggerTlsData *tls;
3922 /* The domain the assembly belonged to is not equal to the current domain */
3923 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3924 g_assert (tls);
3925 g_assert (tls->domain_unloading);
3927 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3928 break;
3930 case EVENT_KIND_TYPE_LOAD:
3931 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3932 break;
3933 case EVENT_KIND_BREAKPOINT:
3934 case EVENT_KIND_STEP: {
3935 DebuggerTlsData *tls;
3936 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3937 g_assert (tls);
3938 mono_stopwatch_stop (&tls->step_time);
3939 MonoMethod *method = (MonoMethod *)arg;
3941 buffer_add_methodid (&buf, domain, method);
3942 buffer_add_long (&buf, il_offset);
3943 break;
3945 case EVENT_KIND_VM_START:
3946 buffer_add_domainid (&buf, mono_get_root_domain ());
3947 break;
3948 case EVENT_KIND_VM_DEATH:
3949 if (CHECK_PROTOCOL_VERSION (2, 27))
3950 buffer_add_int (&buf, mono_environment_exitcode_get ());
3951 break;
3952 case EVENT_KIND_CRASH: {
3953 EventInfo *ei = (EventInfo *)arg;
3954 buffer_add_long (&buf, ei->hashes->offset_free_hash);
3955 buffer_add_string (&buf, ei->dump);
3956 break;
3958 case EVENT_KIND_EXCEPTION: {
3959 EventInfo *ei = (EventInfo *)arg;
3960 buffer_add_objid (&buf, ei->exc);
3962 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3963 * later after the suspension. (#12494).
3965 keepalive_obj = ei->exc;
3966 break;
3968 case EVENT_KIND_USER_BREAK: {
3969 DebuggerTlsData *tls;
3970 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3971 g_assert (tls);
3972 mono_stopwatch_stop (&tls->step_time);
3973 break;
3975 case EVENT_KIND_USER_LOG: {
3976 EventInfo *ei = (EventInfo *)arg;
3977 buffer_add_int (&buf, ei->level);
3978 buffer_add_string (&buf, ei->category ? ei->category : "");
3979 buffer_add_string (&buf, ei->message ? ei->message : "");
3980 break;
3982 case EVENT_KIND_KEEPALIVE:
3983 suspend_policy = SUSPEND_POLICY_NONE;
3984 break;
3985 default:
3986 g_assert_not_reached ();
3990 if (event == EVENT_KIND_VM_START) {
3991 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3992 if (!agent_config.defer) {
3993 ERROR_DECL (error);
3994 start_debugger_thread (error);
3995 mono_error_assert_ok (error);
3999 if (event == EVENT_KIND_VM_DEATH) {
4000 vm_death_event_sent = TRUE;
4001 suspend_policy = SUSPEND_POLICY_NONE;
4004 if (mono_runtime_is_shutting_down ())
4005 suspend_policy = SUSPEND_POLICY_NONE;
4007 if (suspend_policy != SUSPEND_POLICY_NONE) {
4009 * Save the thread context and start suspending before sending the packet,
4010 * since we could be receiving the resume request before send_packet ()
4011 * returns.
4013 save_thread_context (ctx);
4014 suspend_vm ();
4016 if (keepalive_obj)
4017 /* This will keep this object alive */
4018 get_objref (keepalive_obj);
4021 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
4023 if (send_success) {
4024 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4025 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
4028 buffer_free (&buf);
4030 g_slist_free (events);
4031 events = NULL;
4033 if (!send_success) {
4034 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
4035 return;
4038 if (event == EVENT_KIND_VM_START) {
4039 vm_start_event_sent = TRUE;
4042 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);
4044 switch (suspend_policy) {
4045 case SUSPEND_POLICY_NONE:
4046 break;
4047 case SUSPEND_POLICY_ALL:
4048 suspend_current ();
4049 break;
4050 case SUSPEND_POLICY_EVENT_THREAD:
4051 NOT_IMPLEMENTED;
4052 break;
4053 default:
4054 g_assert_not_reached ();
4058 static void
4059 process_profiler_event (EventKind event, gpointer arg)
4061 int suspend_policy;
4062 GSList *events;
4063 EventInfo ei, *ei_arg = NULL;
4065 if (event == EVENT_KIND_TYPE_LOAD) {
4066 ei.klass = (MonoClass *)arg;
4067 ei_arg = &ei;
4070 mono_loader_lock ();
4071 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
4072 mono_loader_unlock ();
4074 process_event (event, arg, 0, NULL, events, suspend_policy);
4077 static void
4078 runtime_initialized (MonoProfiler *prof)
4080 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
4081 if (agent_config.defer) {
4082 ERROR_DECL (error);
4083 start_debugger_thread (error);
4084 mono_error_assert_ok (error);
4088 static void
4089 runtime_shutdown (MonoProfiler *prof)
4091 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
4093 mono_debugger_agent_cleanup ();
4096 static void
4097 thread_startup (MonoProfiler *prof, uintptr_t tid)
4099 MonoInternalThread *thread = mono_thread_internal_current ();
4100 MonoInternalThread *old_thread;
4101 DebuggerTlsData *tls;
4103 if (is_debugger_thread ())
4104 return;
4106 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
4108 mono_loader_lock ();
4109 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4110 mono_loader_unlock ();
4111 if (old_thread) {
4112 if (thread == old_thread) {
4114 * For some reason, thread_startup () might be called for the same thread
4115 * multiple times (attach ?).
4117 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4118 return;
4119 } else {
4121 * thread_end () might not be called for some threads, and the tid could
4122 * get reused.
4124 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4125 mono_loader_lock ();
4126 mono_g_hash_table_remove (thread_to_tls, old_thread);
4127 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
4128 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4129 mono_loader_unlock ();
4133 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4134 g_assert (!tls);
4135 // FIXME: Free this somewhere
4136 tls = g_new0 (DebuggerTlsData, 1);
4137 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
4138 tls->thread = thread;
4139 // Do so we have thread id even after termination
4140 tls->thread_id = (intptr_t) thread->tid;
4141 mono_native_tls_set_value (debugger_tls_id, tls);
4143 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4145 mono_loader_lock ();
4146 mono_g_hash_table_insert_internal (thread_to_tls, thread, tls);
4147 mono_g_hash_table_insert_internal (tid_to_thread, (gpointer)tid, thread);
4148 mono_g_hash_table_insert_internal (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
4149 mono_loader_unlock ();
4151 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4154 * suspend_vm () could have missed this thread, so wait for a resume.
4157 suspend_current ();
4160 static void
4161 thread_end (MonoProfiler *prof, uintptr_t tid)
4163 MonoInternalThread *thread;
4164 DebuggerTlsData *tls = NULL;
4166 mono_loader_lock ();
4167 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4168 if (thread) {
4169 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4170 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4171 if (tls) {
4172 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4173 tls->terminated = TRUE;
4174 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4175 MONO_GC_UNREGISTER_ROOT (tls->thread);
4176 tls->thread = NULL;
4179 mono_loader_unlock ();
4181 /* We might be called for threads started before we registered the start callback */
4182 if (thread) {
4183 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p (domain=%p).\n", (gpointer)tid, thread, tls, (gpointer)mono_domain_get ());
4185 if (mono_thread_internal_is_current (thread) &&
4186 (!mono_native_tls_get_value (debugger_tls_id) ||
4187 !mono_domain_get ())
4190 * This can happen on darwin and android since we
4191 * deregister threads using pthread dtors.
4192 * process_profiler_event () and the code it calls
4193 * cannot handle a null TLS value.
4195 return;
4198 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4202 static void
4203 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4205 mono_de_domain_add (domain);
4207 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4210 static void
4211 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4213 DebuggerTlsData *tls;
4215 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4216 if (is_debugger_thread ())
4217 return;
4220 * Remember the currently unloading appdomain as it is needed to generate
4221 * proper ids for unloading assemblies.
4223 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4224 g_assert (tls);
4225 tls->domain_unloading = domain;
4228 static void
4229 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4231 DebuggerTlsData *tls;
4233 if (is_debugger_thread ())
4234 return;
4236 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4237 g_assert (tls);
4238 tls->domain_unloading = NULL;
4240 mono_de_clear_breakpoints_for_domain (domain);
4242 mono_loader_lock ();
4243 /* Invalidate each thread's frame stack */
4244 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4245 mono_loader_unlock ();
4247 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4251 * invalidate_each_thread:
4253 * A GHFunc to invalidate frames.
4254 * value must be a DebuggerTlsData*
4256 static void
4257 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4259 invalidate_frames ((DebuggerTlsData *)value);
4262 static void
4263 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4265 /* Sent later in jit_end () */
4266 dbg_lock ();
4267 g_ptr_array_add (pending_assembly_loads, assembly);
4268 dbg_unlock ();
4271 static void
4272 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4274 if (is_debugger_thread ())
4275 return;
4277 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4279 clear_event_requests_for_assembly (assembly);
4280 clear_types_for_assembly (assembly);
4283 static void
4284 send_type_load (MonoClass *klass)
4286 gboolean type_load = FALSE;
4287 MonoDomain *domain = mono_domain_get ();
4288 AgentDomainInfo *info = NULL;
4290 info = get_agent_domain_info (domain);
4292 mono_loader_lock ();
4294 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4295 type_load = TRUE;
4296 g_hash_table_insert (info->loaded_classes, klass, klass);
4299 mono_loader_unlock ();
4301 if (type_load)
4302 emit_type_load (klass, klass, NULL);
4306 * Emit load events for all types currently loaded in the domain.
4307 * Takes the loader and domain locks.
4308 * user_data is unused.
4310 static void
4311 send_types_for_domain (MonoDomain *domain, void *user_data)
4313 MonoDomain* old_domain;
4314 AgentDomainInfo *info = NULL;
4316 info = get_agent_domain_info (domain);
4317 g_assert (info);
4319 old_domain = mono_domain_get ();
4321 mono_domain_set_fast (domain, TRUE);
4323 mono_loader_lock ();
4324 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4325 mono_loader_unlock ();
4327 mono_domain_set_fast (old_domain, TRUE);
4330 static void
4331 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4333 GSList *tmp;
4334 MonoDomain* old_domain;
4336 old_domain = mono_domain_get ();
4338 mono_domain_set_fast (domain, TRUE);
4340 mono_domain_assemblies_lock (domain);
4341 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4342 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4343 emit_assembly_load (ass, NULL);
4345 mono_domain_assemblies_unlock (domain);
4347 mono_domain_set_fast (old_domain, TRUE);
4350 static void
4351 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4353 jit_end (prof, method, jinfo);
4356 static void
4357 jit_failed (MonoProfiler *prof, MonoMethod *method)
4359 jit_end (prof, method, NULL);
4362 static void
4363 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4366 * We emit type load events when the first method of the type is JITted,
4367 * since the class load profiler callbacks might be called with the
4368 * loader lock held. They could also occur in the debugger thread.
4369 * Same for assembly load events.
4371 while (TRUE) {
4372 MonoAssembly *assembly = NULL;
4374 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4375 dbg_lock ();
4376 if (pending_assembly_loads->len > 0) {
4377 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4378 g_ptr_array_remove_index (pending_assembly_loads, 0);
4380 dbg_unlock ();
4382 if (assembly) {
4383 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4384 } else {
4385 break;
4389 send_type_load (method->klass);
4391 if (jinfo)
4392 mono_de_add_pending_breakpoints (method, jinfo);
4396 * SINGLE STEPPING
4399 static void
4400 event_requests_cleanup (void)
4402 mono_loader_lock ();
4403 int i = 0;
4404 while (i < event_requests->len) {
4405 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4407 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4408 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4409 g_ptr_array_remove_index_fast (event_requests, i);
4410 g_free (req);
4411 } else {
4412 i ++;
4415 mono_loader_unlock ();
4419 * ss_calculate_framecount:
4421 * Ensure DebuggerTlsData fields are filled out.
4423 static void
4424 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4426 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4428 if (force_use_ctx || !tls->context.valid)
4429 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4430 compute_frame_info (tls->thread, tls, FALSE);
4431 if (frames)
4432 *frames = (DbgEngineStackFrame**)tls->frames;
4433 if (nframes)
4434 *nframes = tls->frame_count;
4438 * ss_discard_frame_data:
4440 * Discard frame data and invalidate any context
4442 static void
4443 ss_discard_frame_context (void *the_tls)
4445 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4446 tls->context.valid = FALSE;
4447 tls->async_state.valid = FALSE;
4448 invalidate_frames (tls);
4451 static MonoContext*
4452 tls_get_restore_state (void *the_tls)
4454 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4456 return &tls->restore_state.ctx;
4459 static gboolean
4460 ensure_jit (DbgEngineStackFrame* the_frame)
4462 StackFrame *frame = (StackFrame*)the_frame;
4463 if (!frame->jit) {
4464 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4465 if (!frame->jit && frame->api_method->is_inflated)
4466 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4467 if (!frame->jit) {
4468 char *s;
4470 /* This could happen for aot images with no jit debug info */
4471 s = mono_method_full_name (frame->api_method, TRUE);
4472 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4473 g_free (s);
4474 return FALSE;
4477 return TRUE;
4480 static gboolean
4481 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4483 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4486 static gpointer
4487 get_this_addr (DbgEngineStackFrame *the_frame)
4489 StackFrame *frame = (StackFrame *)the_frame;
4490 if (frame->de.ji->is_interp)
4491 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4493 MonoDebugVarInfo *var = frame->jit->this_var;
4494 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4495 return NULL;
4497 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4498 addr += (gint32)var->offset;
4499 return addr;
4502 static MonoMethod*
4503 get_set_notification_method (MonoClass* async_builder_class)
4505 ERROR_DECL (error);
4506 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, 1, FALSE, error);
4507 mono_error_assert_ok (error);
4508 if (array->len == 0) {
4509 g_ptr_array_free (array, TRUE);
4510 return NULL;
4512 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4513 g_ptr_array_free (array, TRUE);
4514 return set_notification_method;
4517 static MonoMethod*
4518 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4520 ERROR_DECL (error);
4521 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, 1, FALSE, error);
4522 mono_error_assert_ok (error);
4523 g_assert (array->len == 1);
4524 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4525 g_ptr_array_free (array, TRUE);
4526 return method;
4529 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4530 static gpointer
4531 get_async_method_builder (DbgEngineStackFrame *frame)
4533 MonoObject *this_obj;
4534 MonoClassField *builder_field;
4535 gpointer builder;
4536 gpointer this_addr;
4538 builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4539 g_assert (builder_field);
4541 this_addr = get_this_addr (frame);
4542 if (!this_addr)
4543 return NULL;
4545 if (m_class_is_valuetype (frame->method->klass)) {
4546 builder = mono_vtype_get_field_addr (*(guint8**)this_addr, builder_field);
4547 } else {
4548 this_obj = *(MonoObject**)this_addr;
4549 builder = (char*)this_obj + builder_field->offset;
4552 return builder;
4555 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4556 //since thread probably changed...
4557 static int
4558 get_this_async_id (DbgEngineStackFrame *frame)
4560 MonoClassField *builder_field;
4561 gpointer builder;
4562 MonoMethod *method;
4563 MonoObject *ex;
4564 ERROR_DECL (error);
4565 MonoObject *obj;
4566 gboolean old_disable_breakpoints = FALSE;
4567 DebuggerTlsData *tls;
4570 * FRAME points to a method in a state machine class/struct.
4571 * Call the ObjectIdForDebugger method of the associated method builder type.
4573 builder = get_async_method_builder (frame);
4574 if (!builder)
4575 return 0;
4577 builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4578 g_assert (builder_field);
4580 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4581 if (tls) {
4582 old_disable_breakpoints = tls->disable_breakpoints;
4583 tls->disable_breakpoints = TRUE;
4586 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4587 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4588 mono_error_assert_ok (error);
4590 if (tls)
4591 tls->disable_breakpoints = old_disable_breakpoints;
4593 return get_objid (obj);
4596 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4597 // false if not(AsyncVoidBuilder)
4598 static gboolean
4599 set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame)
4601 MonoClassField *builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4602 g_assert (builder_field);
4603 gpointer builder = get_async_method_builder (frame);
4604 g_assert (builder);
4606 void* args [1];
4607 gboolean arg = TRUE;
4608 ERROR_DECL (error);
4609 args [0] = &arg;
4610 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type_internal (builder_field->type));
4611 if (method == NULL)
4612 return FALSE;
4613 mono_runtime_invoke_checked (method, builder, args, error);
4614 mono_error_assert_ok (error);
4615 return TRUE;
4618 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4620 static MonoMethod*
4621 get_notify_debugger_of_wait_completion_method (void)
4623 if (notify_debugger_of_wait_completion_method_cache != NULL)
4624 return notify_debugger_of_wait_completion_method_cache;
4625 ERROR_DECL (error);
4626 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4627 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error);
4628 mono_error_assert_ok (error);
4629 g_assert (array->len == 1);
4630 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4631 g_ptr_array_free (array, TRUE);
4632 return notify_debugger_of_wait_completion_method_cache;
4635 static gboolean
4636 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4638 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4641 * Skip the instruction causing the breakpoint signal.
4643 if (from_signal)
4644 mono_arch_skip_breakpoint (ctx, ji);
4646 if (tls->disable_breakpoints)
4647 return FALSE;
4648 return TRUE;
4651 typedef struct {
4652 GSList *bp_events, *ss_events, *enter_leave_events;
4653 EventKind kind;
4654 int suspend_policy;
4655 } BreakPointEvents;
4657 static void*
4658 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4660 int suspend_policy = 0;
4661 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4662 if (ss_reqs && ss_reqs->len > 0)
4663 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4664 else if (bp_reqs && bp_reqs->len > 0)
4665 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4666 else if (kind != EVENT_KIND_BREAKPOINT)
4667 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4669 evts->kind = kind;
4670 evts->suspend_policy = suspend_policy;
4671 return evts;
4674 static void
4675 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4677 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4679 * FIXME: The first event will suspend, so the second will only be sent after the
4680 * resume.
4682 if (evts->ss_events)
4683 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4684 if (evts->bp_events)
4685 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4686 if (evts->enter_leave_events)
4687 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4689 g_free (evts);
4692 /* Process a breakpoint/single step event after resuming from a signal handler */
4693 static void
4694 process_signal_event (void (*func) (void*, gboolean))
4696 DebuggerTlsData *tls;
4697 MonoThreadUnwindState orig_restore_state;
4698 MonoContext ctx;
4700 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4701 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4702 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4703 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4705 func (tls, TRUE);
4707 /* This is called when resuming from a signal handler, so it shouldn't return */
4708 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4709 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4710 mono_restore_context (&ctx);
4711 g_assert_not_reached ();
4714 static void
4715 process_breakpoint_from_signal (void)
4717 process_signal_event (mono_de_process_breakpoint);
4720 static void
4721 resume_from_signal_handler (void *sigctx, void *func)
4723 DebuggerTlsData *tls;
4724 MonoContext ctx;
4726 /* Save the original context in TLS */
4727 // FIXME: This might not work on an altstack ?
4728 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4729 if (!tls)
4730 g_printerr ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4731 g_assert (tls);
4733 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4734 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4735 // clob:c could be added to op_seq_point.
4737 mono_sigctx_to_monoctx (sigctx, &ctx);
4738 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4739 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4740 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4741 #else
4742 MONO_CONTEXT_SET_IP (&ctx, func);
4743 #endif
4744 mono_monoctx_to_sigctx (&ctx, sigctx);
4747 static void
4748 debugger_agent_breakpoint_hit (void *sigctx)
4751 * We are called from a signal handler, and running code there causes all kinds of
4752 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4753 * So set up the signal context to return to the real breakpoint handler function.
4755 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4758 typedef struct {
4759 gboolean found;
4760 MonoContext *ctx;
4761 } UserBreakCbData;
4763 static gboolean
4764 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4766 UserBreakCbData *data = (UserBreakCbData*)user_data;
4768 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4769 data->found = TRUE;
4770 return TRUE;
4772 if (frame->managed) {
4773 data->found = TRUE;
4774 *data->ctx = *ctx;
4776 return TRUE;
4778 return FALSE;
4782 * Called by System.Diagnostics.Debugger:Break ().
4784 static void
4785 debugger_agent_user_break (void)
4787 if (agent_config.enabled) {
4788 MonoContext ctx;
4789 int suspend_policy;
4790 GSList *events;
4791 UserBreakCbData data;
4793 memset (&data, 0, sizeof (UserBreakCbData));
4794 data.ctx = &ctx;
4796 /* Obtain a context */
4797 MONO_CONTEXT_SET_IP (&ctx, NULL);
4798 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4799 g_assert (data.found);
4801 mono_loader_lock ();
4802 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4803 mono_loader_unlock ();
4805 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4806 } else if (mini_debug_options.native_debugger_break) {
4807 G_BREAKPOINT ();
4811 static void
4812 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4814 if (from_signal)
4815 mono_arch_skip_single_step (ctx);
4818 static void
4819 process_single_step (void)
4821 process_signal_event (mono_de_process_single_step);
4825 * debugger_agent_single_step_event:
4827 * Called from a signal handler to handle a single step event.
4829 static void
4830 debugger_agent_single_step_event (void *sigctx)
4832 /* Resume to process_single_step through the signal context */
4834 // FIXME: Since step out/over is implemented using step in, the step in case should
4835 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4836 // here
4838 if (is_debugger_thread ()) {
4840 * This could happen despite our best effors when the runtime calls
4841 * assembly/type resolve hooks.
4842 * FIXME: Breakpoints too.
4844 MonoContext ctx;
4846 mono_sigctx_to_monoctx (sigctx, &ctx);
4847 mono_arch_skip_single_step (&ctx);
4848 mono_monoctx_to_sigctx (&ctx, sigctx);
4849 return;
4852 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4855 static void
4856 debugger_agent_single_step_from_context (MonoContext *ctx)
4858 DebuggerTlsData *tls;
4859 MonoThreadUnwindState orig_restore_state;
4861 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4862 /* Fastpath during invokes, see in process_suspend () */
4863 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4864 return;
4866 if (is_debugger_thread ())
4867 return;
4869 g_assert (tls);
4871 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4872 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4873 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4874 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4876 mono_de_process_single_step (tls, FALSE);
4878 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4879 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4882 static void
4883 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4885 DebuggerTlsData *tls;
4886 MonoThreadUnwindState orig_restore_state;
4887 guint8 *orig_ip;
4889 if (is_debugger_thread ())
4890 return;
4892 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4893 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4895 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4896 g_assert (tls);
4897 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4898 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4899 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4901 mono_de_process_breakpoint (tls, FALSE);
4903 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4904 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4905 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4906 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4909 static void
4910 ss_args_destroy (SingleStepArgs *ss_args)
4912 if (ss_args->frames)
4913 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
4916 static int
4917 ensure_runtime_is_suspended (void)
4919 if (suspend_count == 0)
4920 return ERR_NOT_SUSPENDED;
4922 wait_for_suspend ();
4924 return ERR_NONE;
4927 static int
4928 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
4930 MonoSeqPointInfo *info = NULL;
4931 gboolean found_sp;
4932 MonoMethod *method = NULL;
4933 MonoDebugMethodInfo *minfo;
4934 gboolean step_to_catch = FALSE;
4935 gboolean set_ip = FALSE;
4936 StackFrame **frames = NULL;
4937 int nframes = 0;
4939 mono_loader_lock ();
4940 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4941 mono_loader_unlock ();
4942 g_assert (tls);
4943 if (!tls->context.valid) {
4944 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
4945 return ERR_INVALID_ARGUMENT;
4948 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
4950 * Need to start single stepping from restore_state and not from the current state
4952 set_ip = TRUE;
4953 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
4956 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4958 if (tls->has_catch_frame) {
4959 StackFrameInfo frame;
4962 * We are stopped at a throw site. Stepping should go to the catch site.
4964 frame = tls->catch_frame;
4965 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
4968 * Find the seq point corresponding to the landing site ip, which is the first seq
4969 * point after ip.
4971 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
4972 if (!found_sp)
4973 no_seq_points_found (frame.method, frame.native_offset);
4974 g_assert (found_sp);
4976 method = frame.method;
4978 step_to_catch = TRUE;
4979 /* This make sure the seq point is not skipped by process_single_step () */
4980 ss_req->last_sp = NULL;
4983 if (!step_to_catch) {
4984 StackFrame *frame = NULL;
4986 if (set_ip) {
4987 if (frames && nframes)
4988 frame = frames [0];
4989 } else {
4990 compute_frame_info (ss_req->thread, tls, FALSE);
4992 if (tls->frame_count)
4993 frame = tls->frames [0];
4996 if (ss_req->size == STEP_SIZE_LINE) {
4997 if (frame) {
4998 ss_req->last_method = frame->de.method;
4999 ss_req->last_line = -1;
5001 minfo = mono_debug_lookup_method (frame->de.method);
5002 if (minfo && frame->il_offset != -1) {
5003 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5005 if (loc) {
5006 ss_req->last_line = loc->row;
5007 g_free (loc);
5013 if (frame) {
5014 if (!method && frame->il_offset != -1) {
5015 /* FIXME: Sort the table and use a binary search */
5016 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
5017 if (!found_sp)
5018 no_seq_points_found (frame->de.method, frame->de.native_offset);
5019 g_assert (found_sp);
5020 method = frame->de.method;
5025 ss_req->start_method = method;
5027 args->method = method;
5028 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
5029 args->tls = tls;
5030 args->step_to_catch = step_to_catch;
5031 args->info = info;
5032 args->frames = (DbgEngineStackFrame**)frames;
5033 args->nframes = nframes;
5035 return ERR_NONE;
5038 static void
5039 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5041 GSList *l;
5042 gboolean found = TRUE;
5044 while (found) {
5045 found = FALSE;
5046 for (l = req->bps; l; l = l->next) {
5047 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5048 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
5049 req->bps = g_slist_delete_link (req->bps, l);
5050 found = TRUE;
5051 break;
5058 * This takes a lot of locks and stuff. Do this at the end, after
5059 * other things have dumped us, so that getting stuck here won't
5060 * prevent seeing other crash information
5062 static void
5063 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
5065 #ifndef DISABLE_CRASH_REPORTING
5066 int suspend_policy;
5067 GSList *events;
5068 EventInfo ei;
5070 if (!agent_config.enabled)
5071 return;
5073 // Don't send the event if the client doesn't expect it
5074 if (!CHECK_PROTOCOL_VERSION (2, 49))
5075 return;
5077 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5078 // actually enabled. Therefore we do the wait here.
5079 sleep (pause);
5081 // Don't heap allocate when we can avoid it
5082 EventRequest request;
5083 memset (&request, 0, sizeof (request));
5084 request.event_kind = EVENT_KIND_CRASH;
5086 gpointer pdata [1];
5087 pdata [0] = &request;
5088 GPtrArray array;
5089 memset (&array, 0, sizeof (array));
5090 array.pdata = pdata;
5091 array.len = 1;
5093 mono_loader_lock ();
5094 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5095 mono_loader_unlock ();
5097 ei.dump = json_dump;
5098 ei.hashes = hashes;
5100 g_assert (events != NULL);
5102 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5104 // Don't die before it is sent.
5105 sleep (4);
5106 #endif
5110 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5112 static void
5113 debugger_agent_debug_log (int level, MonoStringHandle category, MonoStringHandle message)
5115 ERROR_DECL (error);
5116 int suspend_policy;
5117 GSList *events;
5118 EventInfo ei;
5120 if (!agent_config.enabled)
5121 return;
5123 mono_loader_lock ();
5124 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5125 mono_loader_unlock ();
5127 ei.level = level;
5128 ei.category = NULL;
5129 if (!MONO_HANDLE_IS_NULL (category)) {
5130 ei.category = mono_string_handle_to_utf8 (category, error);
5131 mono_error_cleanup (error);
5133 ei.message = NULL;
5134 if (!MONO_HANDLE_IS_NULL (message)) {
5135 ei.message = mono_string_handle_to_utf8 (message, error);
5136 mono_error_cleanup (error);
5139 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5141 g_free (ei.category);
5142 g_free (ei.message);
5145 static gboolean
5146 debugger_agent_debug_log_is_enabled (void)
5148 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5149 return agent_config.enabled;
5152 static void
5153 debugger_agent_unhandled_exception (MonoException *exc)
5155 int suspend_policy;
5156 GSList *events;
5157 EventInfo ei;
5159 if (!inited)
5160 return;
5162 memset (&ei, 0, sizeof (EventInfo));
5163 ei.exc = (MonoObject*)exc;
5165 mono_loader_lock ();
5166 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5167 mono_loader_unlock ();
5169 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5172 static void
5173 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5174 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5176 int i, j, suspend_policy;
5177 GSList *events;
5178 MonoJitInfo *ji, *catch_ji;
5179 EventInfo ei;
5180 DebuggerTlsData *tls = NULL;
5182 if (thread_to_tls != NULL) {
5183 MonoInternalThread *thread = mono_thread_internal_current ();
5185 mono_loader_lock ();
5186 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5187 mono_loader_unlock ();
5189 if (tls && tls->abort_requested)
5190 return;
5191 if (tls && tls->disable_breakpoints)
5192 return;
5195 memset (&ei, 0, sizeof (EventInfo));
5197 /* Just-In-Time debugging */
5198 if (!catch_ctx) {
5199 if (agent_config.onuncaught && !inited) {
5200 finish_agent_init (FALSE);
5203 * Send an unsolicited EXCEPTION event with a dummy request id.
5205 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5206 ei.exc = (MonoObject*)exc;
5207 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5208 return;
5210 } else if (agent_config.onthrow && !inited) {
5211 GSList *l;
5212 gboolean found = FALSE;
5214 for (l = agent_config.onthrow; l; l = l->next) {
5215 char *ex_type = (char *)l->data;
5216 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5218 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5219 found = TRUE;
5221 g_free (f);
5224 if (found) {
5225 finish_agent_init (FALSE);
5228 * Send an unsolicited EXCEPTION event with a dummy request id.
5230 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5231 ei.exc = (MonoObject*)exc;
5232 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5233 return;
5237 if (!inited)
5238 return;
5240 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5241 if (catch_frame)
5242 catch_ji = catch_frame->ji;
5243 else
5244 catch_ji = NULL;
5246 ei.exc = (MonoObject*)exc;
5247 ei.caught = catch_ctx != NULL;
5249 mono_loader_lock ();
5251 /* Treat exceptions which are caught in non-user code as unhandled */
5252 for (i = 0; i < event_requests->len; ++i) {
5253 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5254 if (req->event_kind != EVENT_KIND_EXCEPTION)
5255 continue;
5257 for (j = 0; j < req->nmodifiers; ++j) {
5258 Modifier *mod = &req->modifiers [j];
5260 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5261 int k;
5262 gboolean found = FALSE;
5263 MonoAssembly **assemblies = mod->data.assemblies;
5265 if (assemblies) {
5266 for (k = 0; assemblies [k]; ++k)
5267 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5268 found = TRUE;
5270 if (!found)
5271 ei.caught = FALSE;
5276 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5277 mono_loader_unlock ();
5279 if (tls && ei.caught && catch_ctx) {
5280 if (catch_frame) {
5281 tls->has_catch_frame = TRUE;
5282 tls->catch_frame = *catch_frame;
5283 } else {
5284 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5288 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5290 if (tls)
5291 tls->has_catch_frame = FALSE;
5294 static void
5295 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5297 DebuggerTlsData *tls;
5299 if (!inited)
5300 return;
5302 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5303 if (!tls)
5304 return;
5307 * We're about to invoke an exception filter during the first pass of exception handling.
5309 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5310 * 'orig_ctx' is the context where the exception has been thrown.
5313 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5315 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5316 * the call site (line 37) and then continue to Main(), but it would never
5317 * include the throw site (line 32).
5319 * Since exception filters are invoked during the first pass of exception handling,
5320 * the stack frames of the throw site are still intact, so we should include them
5321 * in a stack trace.
5323 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5325 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5326 * but report the location of the 'throw' to the user.
5330 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5333 static void
5334 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5336 DebuggerTlsData *tls;
5338 if (!inited)
5339 return;
5341 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5342 if (!tls)
5343 return;
5345 tls->filter_state.valid = FALSE;
5348 static void
5349 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5350 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5352 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5353 buffer_add_byte (buf, t->type);
5354 buffer_add_int (buf, len_fixed_array );
5355 for (int i = 0; i < len_fixed_array; i++) {
5356 switch (t->type) {
5357 case MONO_TYPE_BOOLEAN:
5358 case MONO_TYPE_I1:
5359 case MONO_TYPE_U1:
5360 buffer_add_int (buf, ((gint8*)addr)[i]);
5361 break;
5362 case MONO_TYPE_CHAR:
5363 case MONO_TYPE_I2:
5364 case MONO_TYPE_U2:
5365 buffer_add_int (buf, ((gint16*)addr)[i]);
5366 break;
5367 case MONO_TYPE_I4:
5368 case MONO_TYPE_U4:
5369 case MONO_TYPE_R4:
5370 buffer_add_int (buf, ((gint32*)addr)[i]);
5371 break;
5372 case MONO_TYPE_I8:
5373 case MONO_TYPE_U8:
5374 case MONO_TYPE_R8:
5375 buffer_add_long (buf, ((gint64*)addr)[i]);
5376 break;
5377 case MONO_TYPE_PTR: {
5378 gssize val = *(gssize*)addr;
5380 buffer_add_byte (buf, t->type);
5381 buffer_add_long (buf, val);
5382 if (CHECK_PROTOCOL_VERSION(2, 46))
5383 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5384 break;
5390 * buffer_add_value_full:
5392 * Add the encoding of the value at ADDR described by T to the buffer.
5393 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5394 * vtypes.
5396 static void
5397 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5398 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5400 MonoObject *obj;
5401 gboolean boxed_vtype = FALSE;
5403 if (t->byref) {
5404 if (!(*(void**)addr)) {
5405 /* This can happen with compiler generated locals */
5406 //printf ("%s\n", mono_type_full_name (t));
5407 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5408 return;
5410 g_assert (*(void**)addr);
5411 addr = *(void**)addr;
5414 if (as_vtype) {
5415 switch (t->type) {
5416 case MONO_TYPE_BOOLEAN:
5417 case MONO_TYPE_I1:
5418 case MONO_TYPE_U1:
5419 case MONO_TYPE_CHAR:
5420 case MONO_TYPE_I2:
5421 case MONO_TYPE_U2:
5422 case MONO_TYPE_I4:
5423 case MONO_TYPE_U4:
5424 case MONO_TYPE_R4:
5425 case MONO_TYPE_I8:
5426 case MONO_TYPE_U8:
5427 case MONO_TYPE_R8:
5428 case MONO_TYPE_I:
5429 case MONO_TYPE_U:
5430 case MONO_TYPE_PTR:
5431 goto handle_vtype;
5432 break;
5433 default:
5434 break;
5438 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5440 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5441 return;
5443 switch (t->type) {
5444 case MONO_TYPE_VOID:
5445 buffer_add_byte (buf, t->type);
5446 break;
5447 case MONO_TYPE_BOOLEAN:
5448 case MONO_TYPE_I1:
5449 case MONO_TYPE_U1:
5450 buffer_add_byte (buf, t->type);
5451 buffer_add_int (buf, *(gint8*)addr);
5452 break;
5453 case MONO_TYPE_CHAR:
5454 case MONO_TYPE_I2:
5455 case MONO_TYPE_U2:
5456 buffer_add_byte (buf, t->type);
5457 buffer_add_int (buf, *(gint16*)addr);
5458 break;
5459 case MONO_TYPE_I4:
5460 case MONO_TYPE_U4:
5461 case MONO_TYPE_R4:
5462 buffer_add_byte (buf, t->type);
5463 buffer_add_int (buf, *(gint32*)addr);
5464 break;
5465 case MONO_TYPE_I8:
5466 case MONO_TYPE_U8:
5467 case MONO_TYPE_R8:
5468 buffer_add_byte (buf, t->type);
5469 buffer_add_long (buf, *(gint64*)addr);
5470 break;
5471 case MONO_TYPE_I:
5472 case MONO_TYPE_U:
5473 /* Treat it as a vtype */
5474 goto handle_vtype;
5475 case MONO_TYPE_PTR: {
5476 gssize val = *(gssize*)addr;
5478 buffer_add_byte (buf, t->type);
5479 buffer_add_long (buf, val);
5480 if (CHECK_PROTOCOL_VERSION(2, 46))
5481 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5482 break;
5484 handle_ref:
5485 case MONO_TYPE_STRING:
5486 case MONO_TYPE_SZARRAY:
5487 case MONO_TYPE_OBJECT:
5488 case MONO_TYPE_CLASS:
5489 case MONO_TYPE_ARRAY:
5490 obj = *(MonoObject**)addr;
5492 if (!obj) {
5493 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5494 } else {
5495 if (m_class_is_valuetype (obj->vtable->klass)) {
5496 t = m_class_get_byval_arg (obj->vtable->klass);
5497 addr = mono_object_unbox_internal (obj);
5498 boxed_vtype = TRUE;
5499 goto handle_vtype;
5500 } else if (m_class_get_rank (obj->vtable->klass)) {
5501 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5502 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5503 buffer_add_byte (buf, MONO_TYPE_CLASS);
5504 } else {
5505 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5507 buffer_add_objid (buf, obj);
5509 break;
5510 handle_vtype:
5511 case MONO_TYPE_VALUETYPE:
5512 case MONO_TYPE_TYPEDBYREF: {
5513 int nfields;
5514 gpointer iter;
5515 MonoClassField *f;
5516 MonoClass *klass = mono_class_from_mono_type_internal (t);
5517 int vtype_index;
5519 if (boxed_vtype) {
5521 * Handle boxed vtypes recursively referencing themselves using fields.
5523 if (!parent_vtypes)
5524 parent_vtypes = g_hash_table_new (NULL, NULL);
5525 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5526 if (vtype_index) {
5527 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5528 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5529 buffer_add_int (buf, vtype_index - 1);
5530 } else {
5531 /* The client can't handle PARENT_VTYPE */
5532 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5534 break;
5535 } else {
5536 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5540 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5541 buffer_add_byte (buf, m_class_is_enumtype (klass));
5542 buffer_add_typeid (buf, domain, klass);
5544 nfields = 0;
5545 iter = NULL;
5546 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5547 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5548 continue;
5549 if (mono_field_is_deleted (f))
5550 continue;
5551 nfields ++;
5553 buffer_add_int (buf, nfields);
5555 iter = NULL;
5556 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5557 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5558 continue;
5559 if (mono_field_is_deleted (f))
5560 continue;
5561 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));
5564 if (boxed_vtype) {
5565 g_hash_table_remove (parent_vtypes, addr);
5566 if (g_hash_table_size (parent_vtypes) == 0) {
5567 g_hash_table_destroy (parent_vtypes);
5568 parent_vtypes = NULL;
5571 break;
5573 case MONO_TYPE_GENERICINST:
5574 if (mono_type_generic_inst_is_valuetype (t)) {
5575 goto handle_vtype;
5576 } else {
5577 goto handle_ref;
5579 break;
5580 default:
5581 NOT_IMPLEMENTED;
5585 static void
5586 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5588 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5591 static gboolean
5592 obj_is_of_type (MonoObject *obj, MonoType *t)
5594 MonoClass *klass = obj->vtable->klass;
5595 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5596 if (mono_class_is_transparent_proxy (klass)) {
5597 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5598 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5599 return TRUE;
5602 return FALSE;
5604 return TRUE;
5607 static ErrorCode
5608 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5610 static ErrorCode
5611 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5613 guint8 *addr = (guint8*)void_addr;
5614 guint8 *buf = (guint8*)void_buf;
5615 gboolean is_enum;
5616 MonoClass *klass;
5617 MonoClassField *f;
5618 int nfields;
5619 gpointer iter = NULL;
5620 MonoDomain *d;
5621 ErrorCode err;
5623 is_enum = decode_byte (buf, &buf, limit);
5624 /* Enums are sent as a normal vtype */
5625 if (is_enum)
5626 return ERR_NOT_IMPLEMENTED;
5627 klass = decode_typeid (buf, &buf, limit, &d, &err);
5628 if (err != ERR_NONE)
5629 return err;
5631 if (t && klass != mono_class_from_mono_type_internal (t)) {
5632 char *name = mono_type_full_name (t);
5633 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5634 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5635 g_free (name);
5636 g_free (name2);
5637 return ERR_INVALID_ARGUMENT;
5640 nfields = decode_int (buf, &buf, limit);
5641 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5642 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5643 continue;
5644 if (mono_field_is_deleted (f))
5645 continue;
5646 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5647 if (err != ERR_NONE)
5648 return err;
5649 nfields --;
5651 g_assert (nfields == 0);
5653 *endbuf = buf;
5655 return ERR_NONE;
5657 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)
5659 ErrorCode err = ERR_NONE;
5660 int fixedSizeLen = 1;
5661 int newType = MONO_TYPE_END;
5662 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5663 newType = decode_byte (buf, &buf, limit);
5664 fixedSizeLen = decode_int (buf, &buf, limit);
5665 //t->type = newType;
5667 for (int i = 0 ; i < fixedSizeLen; i++) {
5668 switch (newType) {
5669 case MONO_TYPE_BOOLEAN:
5670 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5671 break;
5672 case MONO_TYPE_CHAR:
5673 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5674 break;
5675 case MONO_TYPE_I1:
5676 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5677 break;
5678 case MONO_TYPE_U1:
5679 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5680 break;
5681 case MONO_TYPE_I2:
5682 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5683 break;
5684 case MONO_TYPE_U2:
5685 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5686 break;
5687 case MONO_TYPE_I4:
5688 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5689 break;
5690 case MONO_TYPE_U4:
5691 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5692 break;
5693 case MONO_TYPE_I8:
5694 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5695 break;
5696 case MONO_TYPE_U8:
5697 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5698 break;
5699 case MONO_TYPE_R4:
5700 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5701 break;
5702 case MONO_TYPE_R8:
5703 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5704 break;
5707 *endbuf = buf;
5708 return err;
5710 static ErrorCode
5711 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5713 ErrorCode err;
5714 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5715 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5716 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5717 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5718 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5719 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5720 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5721 char *name = mono_type_full_name (t);
5722 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5723 g_free (name);
5724 return ERR_INVALID_ARGUMENT;
5726 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5727 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5728 return ERR_NONE;
5731 switch (t->type) {
5732 case MONO_TYPE_BOOLEAN:
5733 *(guint8*)addr = decode_int (buf, &buf, limit);
5734 break;
5735 case MONO_TYPE_CHAR:
5736 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5737 break;
5738 case MONO_TYPE_I1:
5739 *(gint8*)addr = decode_int (buf, &buf, limit);
5740 break;
5741 case MONO_TYPE_U1:
5742 *(guint8*)addr = decode_int (buf, &buf, limit);
5743 break;
5744 case MONO_TYPE_I2:
5745 *(gint16*)addr = decode_int (buf, &buf, limit);
5746 break;
5747 case MONO_TYPE_U2:
5748 *(guint16*)addr = decode_int (buf, &buf, limit);
5749 break;
5750 case MONO_TYPE_I4:
5751 *(gint32*)addr = decode_int (buf, &buf, limit);
5752 break;
5753 case MONO_TYPE_U4:
5754 *(guint32*)addr = decode_int (buf, &buf, limit);
5755 break;
5756 case MONO_TYPE_I8:
5757 *(gint64*)addr = decode_long (buf, &buf, limit);
5758 break;
5759 case MONO_TYPE_U8:
5760 *(guint64*)addr = decode_long (buf, &buf, limit);
5761 break;
5762 case MONO_TYPE_R4:
5763 *(guint32*)addr = decode_int (buf, &buf, limit);
5764 break;
5765 case MONO_TYPE_R8:
5766 *(guint64*)addr = decode_long (buf, &buf, limit);
5767 break;
5768 case MONO_TYPE_PTR:
5769 /* We send these as I8, so we get them back as such */
5770 g_assert (type == MONO_TYPE_I8);
5771 *(gssize*)addr = decode_long (buf, &buf, limit);
5772 break;
5773 case MONO_TYPE_GENERICINST:
5774 if (MONO_TYPE_ISSTRUCT (t)) {
5775 /* The client sends these as a valuetype */
5776 goto handle_vtype;
5777 } else {
5778 goto handle_ref;
5780 break;
5781 case MONO_TYPE_I:
5782 case MONO_TYPE_U:
5783 /* We send these as vtypes, so we get them back as such */
5784 g_assert (type == MONO_TYPE_VALUETYPE);
5785 /* Fall through */
5786 handle_vtype:
5787 case MONO_TYPE_VALUETYPE:
5788 if (type == MONO_TYPE_OBJECT) {
5789 /* Boxed vtype */
5790 int objid = decode_objid (buf, &buf, limit);
5791 ErrorCode err;
5792 MonoObject *obj;
5794 err = get_object (objid, (MonoObject**)&obj);
5795 if (err != ERR_NONE)
5796 return err;
5797 if (!obj)
5798 return ERR_INVALID_ARGUMENT;
5799 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5800 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5801 return ERR_INVALID_ARGUMENT;
5803 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5804 } else {
5805 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5806 if (err != ERR_NONE)
5807 return err;
5809 break;
5810 handle_ref:
5811 default:
5812 if (MONO_TYPE_IS_REFERENCE (t)) {
5813 if (type == MONO_TYPE_OBJECT) {
5814 int objid = decode_objid (buf, &buf, limit);
5815 ErrorCode err;
5816 MonoObject *obj;
5818 err = get_object (objid, (MonoObject**)&obj);
5819 if (err != ERR_NONE)
5820 return err;
5822 if (obj) {
5823 if (!obj_is_of_type (obj, t)) {
5824 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5825 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5826 return ERR_INVALID_ARGUMENT;
5830 if (obj && obj->vtable->domain != domain)
5831 return ERR_INVALID_ARGUMENT;
5833 mono_gc_wbarrier_generic_store_internal (addr, obj);
5834 } else if (type == VALUE_TYPE_ID_NULL) {
5835 *(MonoObject**)addr = NULL;
5836 } else if (type == MONO_TYPE_VALUETYPE) {
5837 ERROR_DECL (error);
5838 guint8 *buf2;
5839 gboolean is_enum;
5840 MonoClass *klass;
5841 MonoDomain *d;
5842 guint8 *vtype_buf;
5843 int vtype_buf_size;
5845 /* This can happen when round-tripping boxed vtypes */
5847 * Obtain vtype class.
5848 * Same as the beginning of the handle_vtype case above.
5850 buf2 = buf;
5851 is_enum = decode_byte (buf, &buf, limit);
5852 if (is_enum)
5853 return ERR_NOT_IMPLEMENTED;
5854 klass = decode_typeid (buf, &buf, limit, &d, &err);
5855 if (err != ERR_NONE)
5856 return err;
5858 /* Decode the vtype into a temporary buffer, then box it. */
5859 vtype_buf_size = mono_class_value_size (klass, NULL);
5860 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5861 g_assert (vtype_buf);
5863 buf = buf2;
5864 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5865 if (err != ERR_NONE) {
5866 g_free (vtype_buf);
5867 return err;
5869 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5870 mono_error_cleanup (error);
5871 g_free (vtype_buf);
5872 } else {
5873 char *name = mono_type_full_name (t);
5874 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5875 g_free (name);
5876 return ERR_INVALID_ARGUMENT;
5878 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5879 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5880 m_class_is_enumtype (t->data.generic_class->container_class)){
5881 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5882 if (err != ERR_NONE)
5883 return err;
5884 } else {
5885 NOT_IMPLEMENTED;
5887 break;
5891 *endbuf = buf;
5893 return ERR_NONE;
5896 static ErrorCode
5897 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5899 guint8 *addr = (guint8*)void_addr;
5900 guint8 *buf = (guint8*)void_buf;
5902 ERROR_DECL (error);
5903 ErrorCode err;
5904 int type = decode_byte (buf, &buf, limit);
5906 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5907 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5908 guint8 *nullable_buf;
5911 * First try decoding it as a Nullable`1
5913 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5914 if (err == ERR_NONE)
5915 return err;
5918 * Then try decoding as a primitive value or null.
5920 if (targ->type == type) {
5921 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
5922 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
5923 if (err != ERR_NONE) {
5924 g_free (nullable_buf);
5925 return err;
5927 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
5928 if (!is_ok (error)) {
5929 mono_error_cleanup (error);
5930 return ERR_INVALID_OBJECT;
5932 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
5933 g_free (nullable_buf);
5934 *endbuf = buf;
5935 return ERR_NONE;
5936 } else if (type == VALUE_TYPE_ID_NULL) {
5937 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
5938 *endbuf = buf;
5939 return ERR_NONE;
5943 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5946 static void
5947 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5949 guint32 flags;
5950 int reg;
5951 guint8 *addr, *gaddr;
5952 host_mgreg_t reg_val;
5954 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5955 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5957 switch (flags) {
5958 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5959 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5961 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
5962 break;
5963 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5964 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5965 addr += (gint32)var->offset;
5967 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5969 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
5970 break;
5971 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5972 NOT_IMPLEMENTED;
5973 break;
5974 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5975 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5976 /* Same as regoffset, but with an indirection */
5977 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5978 addr += (gint32)var->offset;
5980 gaddr = (guint8 *)*(gpointer*)addr;
5981 g_assert (gaddr);
5982 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
5983 break;
5984 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5985 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5986 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5987 MonoGSharedVtMethodRuntimeInfo *info;
5988 guint8 *locals;
5989 int idx;
5991 idx = reg;
5993 g_assert (info_var);
5994 g_assert (locals_var);
5996 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5997 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5998 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5999 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6000 addr += (gint32)info_var->offset;
6001 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6002 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6003 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6004 } else {
6005 g_assert_not_reached ();
6007 g_assert (info);
6009 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6010 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6011 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6012 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6013 addr += (gint32)locals_var->offset;
6014 locals = (guint8 *)*(gpointer*)addr;
6015 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6016 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6017 } else {
6018 g_assert_not_reached ();
6020 g_assert (locals);
6022 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6024 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6025 break;
6028 default:
6029 g_assert_not_reached ();
6033 static void
6034 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
6036 guint32 flags;
6037 int reg, size;
6038 guint8 *addr, *gaddr;
6040 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6041 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6043 if (MONO_TYPE_IS_REFERENCE (t))
6044 size = sizeof (gpointer);
6045 else
6046 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6048 switch (flags) {
6049 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6050 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6051 host_mgreg_t v;
6052 gboolean is_signed = FALSE;
6054 if (t->byref) {
6055 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6057 if (addr) {
6058 // FIXME: Write barriers
6059 mono_gc_memmove_atomic (addr, val, size);
6061 break;
6064 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6065 is_signed = TRUE;
6067 switch (size) {
6068 case 1:
6069 v = is_signed ? *(gint8*)val : *(guint8*)val;
6070 break;
6071 case 2:
6072 v = is_signed ? *(gint16*)val : *(guint16*)val;
6073 break;
6074 case 4:
6075 v = is_signed ? *(gint32*)val : *(guint32*)val;
6076 break;
6077 case 8:
6078 v = is_signed ? *(gint64*)val : *(guint64*)val;
6079 break;
6080 default:
6081 g_assert_not_reached ();
6084 /* Set value on the stack or in the return ctx */
6085 if (reg_locations [reg]) {
6086 /* Saved on the stack */
6087 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6088 *(reg_locations [reg]) = v;
6089 } else {
6090 /* Not saved yet */
6091 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6092 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6095 // FIXME: Move these to mono-context.h/c.
6096 mono_arch_context_set_int_reg (ctx, reg, v);
6097 #else
6098 // FIXME: Can't set registers, so we disable linears
6099 NOT_IMPLEMENTED;
6100 #endif
6101 break;
6103 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6104 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6105 addr += (gint32)var->offset;
6107 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6109 if (t->byref) {
6110 addr = *(guint8**)addr;
6112 if (!addr)
6113 break;
6116 // FIXME: Write barriers
6117 mono_gc_memmove_atomic (addr, val, size);
6118 break;
6119 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6120 /* Same as regoffset, but with an indirection */
6121 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6122 addr += (gint32)var->offset;
6124 gaddr = (guint8 *)*(gpointer*)addr;
6125 g_assert (gaddr);
6126 // FIXME: Write barriers
6127 mono_gc_memmove_atomic (gaddr, val, size);
6128 break;
6129 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6130 NOT_IMPLEMENTED;
6131 break;
6132 default:
6133 g_assert_not_reached ();
6137 static void
6138 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6140 int size;
6142 if (t->byref) {
6143 addr = *(gpointer*)addr;
6144 g_assert (addr);
6147 if (MONO_TYPE_IS_REFERENCE (t))
6148 size = sizeof (gpointer);
6149 else
6150 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6152 memcpy (addr, val_buf, size);
6155 static void
6156 clear_event_request (int req_id, int etype)
6158 int i;
6160 mono_loader_lock ();
6161 for (i = 0; i < event_requests->len; ++i) {
6162 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6164 if (req->id == req_id && req->event_kind == etype) {
6165 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6166 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6167 if (req->event_kind == EVENT_KIND_STEP) {
6168 mono_de_cancel_ss ();
6170 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6171 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6172 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6173 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6174 g_ptr_array_remove_index_fast (event_requests, i);
6175 g_free (req);
6176 break;
6179 mono_loader_unlock ();
6182 static void
6183 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6185 int i;
6187 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6188 m->kind = MOD_KIND_NONE;
6189 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6190 int count = 0, match_count = 0, pos;
6191 MonoAssembly **newassemblies;
6193 for (i = 0; m->data.assemblies [i]; ++i) {
6194 count ++;
6195 if (m->data.assemblies [i] == assembly)
6196 match_count ++;
6199 if (match_count) {
6200 // +1 because we don't know length and we use last element to check for end
6201 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6203 pos = 0;
6204 for (i = 0; i < count; ++i)
6205 if (m->data.assemblies [i] != assembly)
6206 newassemblies [pos ++] = m->data.assemblies [i];
6207 g_assert (pos == count - match_count);
6208 g_free (m->data.assemblies);
6209 m->data.assemblies = newassemblies;
6214 static void
6215 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6217 int i;
6219 for (i = 0; i < req->nmodifiers; ++i) {
6220 Modifier *m = &req->modifiers [i];
6222 clear_assembly_from_modifier (req, m, assembly);
6227 * clear_event_requests_for_assembly:
6229 * Clear all events requests which reference ASSEMBLY.
6231 static void
6232 clear_event_requests_for_assembly (MonoAssembly *assembly)
6234 int i;
6235 gboolean found;
6237 mono_loader_lock ();
6238 found = TRUE;
6239 while (found) {
6240 found = FALSE;
6241 for (i = 0; i < event_requests->len; ++i) {
6242 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6244 clear_assembly_from_modifiers (req, assembly);
6246 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6247 clear_event_request (req->id, req->event_kind);
6248 found = TRUE;
6249 break;
6252 if (req->event_kind == EVENT_KIND_STEP)
6253 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6256 mono_loader_unlock ();
6260 * type_comes_from_assembly:
6262 * GHRFunc that returns TRUE if klass comes from assembly
6264 static gboolean
6265 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6267 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6271 * clear_types_for_assembly:
6273 * Clears types from loaded_classes for a given assembly
6275 static void
6276 clear_types_for_assembly (MonoAssembly *assembly)
6278 MonoDomain *domain = mono_domain_get ();
6279 AgentDomainInfo *info = NULL;
6281 if (!domain || !domain_jit_info (domain))
6282 /* Can happen during shutdown */
6283 return;
6285 info = get_agent_domain_info (domain);
6287 mono_loader_lock ();
6288 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6289 mono_loader_unlock ();
6292 static void
6293 dispose_vm (void)
6295 /* Clear all event requests */
6296 mono_loader_lock ();
6297 while (event_requests->len > 0) {
6298 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6300 clear_event_request (req->id, req->event_kind);
6302 mono_loader_unlock ();
6304 while (suspend_count > 0)
6305 resume_vm ();
6306 disconnected = TRUE;
6307 vm_start_event_sent = FALSE;
6310 static void
6311 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6313 MonoThread *thread = (MonoThread *)value;
6314 gboolean *ret = (gboolean *)user_data;
6315 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6316 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6317 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6318 *ret = TRUE;
6319 return;
6324 static void
6325 add_thread (gpointer key, gpointer value, gpointer user_data)
6327 MonoThread *thread = (MonoThread *)value;
6328 Buffer *buf = (Buffer *)user_data;
6329 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6330 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6331 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6332 return;
6334 buffer_add_objid (buf, (MonoObject*)thread);
6338 static ErrorCode
6339 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6341 ERROR_DECL (error);
6342 guint8 *end = invoke->endp;
6343 MonoMethod *m;
6344 int i, nargs;
6345 ErrorCode err;
6346 MonoMethodSignature *sig;
6347 guint8 **arg_buf;
6348 void **args;
6349 MonoObject *this_arg, *res, *exc = NULL;
6350 MonoDomain *domain;
6351 guint8 *this_buf;
6352 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6353 MonoLMFExt ext;
6354 #endif
6355 MonoStopwatch watch;
6357 if (invoke->method) {
6359 * Invoke this method directly, currently only Environment.Exit () is supported.
6361 this_arg = NULL;
6362 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>");
6364 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6365 mono_error_assert_ok (error);
6366 g_assert_not_reached ();
6369 m = decode_methodid (p, &p, end, &domain, &err);
6370 if (err != ERR_NONE)
6371 return err;
6372 sig = mono_method_signature_internal (m);
6374 if (m_class_is_valuetype (m->klass))
6375 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6376 else
6377 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6379 if (m->is_generic) {
6380 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));
6381 return ERR_INVALID_ARGUMENT;
6382 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6383 /* Should be null */
6384 int type = decode_byte (p, &p, end);
6385 if (type != VALUE_TYPE_ID_NULL) {
6386 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6387 return ERR_INVALID_ARGUMENT;
6389 memset (this_buf, 0, mono_class_instance_size (m->klass));
6390 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6391 /* Could be null */
6392 guint8 *tmp_p;
6394 int type = decode_byte (p, &tmp_p, end);
6395 if (type == VALUE_TYPE_ID_NULL) {
6396 memset (this_buf, 0, mono_class_instance_size (m->klass));
6397 p = tmp_p;
6398 } else {
6399 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6400 if (err != ERR_NONE)
6401 return err;
6403 } else {
6404 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6405 if (err != ERR_NONE)
6406 return err;
6409 if (!m_class_is_valuetype (m->klass))
6410 this_arg = *(MonoObject**)this_buf;
6411 else
6412 this_arg = NULL;
6414 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6415 if (!this_arg) {
6416 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6417 return ERR_INVALID_ARGUMENT;
6419 m = mono_object_get_virtual_method_internal (this_arg, m);
6420 /* Transform this to the format the rest of the code expects it to be */
6421 if (m_class_is_valuetype (m->klass)) {
6422 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6423 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6425 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6426 if (!this_arg) {
6427 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6428 return ERR_INVALID_ARGUMENT;
6430 m = mono_object_get_virtual_method_internal (this_arg, m);
6431 if (m_class_is_valuetype (m->klass)) {
6432 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6433 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6437 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>");
6439 if (this_arg && this_arg->vtable->domain != domain)
6440 NOT_IMPLEMENTED;
6442 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6443 if (!strcmp (m->name, ".ctor")) {
6444 if (mono_class_is_abstract (m->klass))
6445 return ERR_INVALID_ARGUMENT;
6446 else {
6447 ERROR_DECL (error);
6448 this_arg = mono_object_new_checked (domain, m->klass, error);
6449 mono_error_assert_ok (error);
6451 } else {
6452 return ERR_INVALID_ARGUMENT;
6456 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6457 return ERR_INVALID_ARGUMENT;
6459 nargs = decode_int (p, &p, end);
6460 if (nargs != sig->param_count)
6461 return ERR_INVALID_ARGUMENT;
6462 /* Use alloca to get gc tracking */
6463 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6464 memset (arg_buf, 0, nargs * sizeof (gpointer));
6465 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6466 for (i = 0; i < nargs; ++i) {
6467 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6468 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6469 if (err != ERR_NONE)
6470 break;
6471 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6472 NOT_IMPLEMENTED;
6474 if (sig->params [i]->byref) {
6475 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6476 *(gpointer*)arg_buf [i] = args [i];
6477 args [i] = arg_buf [i];
6479 } else {
6480 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6481 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6482 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6483 if (err != ERR_NONE)
6484 break;
6485 if (mono_class_is_nullable (arg_class)) {
6486 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6487 mono_error_assert_ok (error);
6488 } else {
6489 args [i] = arg_buf [i];
6494 if (i < nargs)
6495 return err;
6497 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6498 tls->disable_breakpoints = TRUE;
6499 else
6500 tls->disable_breakpoints = FALSE;
6503 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6505 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6506 if (invoke->has_ctx) {
6507 /* Setup our lmf */
6508 memset (&ext, 0, sizeof (ext));
6509 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6510 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6512 mono_push_lmf (&ext);
6514 #endif
6516 mono_stopwatch_start (&watch);
6517 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6518 if (!is_ok (error) && exc == NULL) {
6519 exc = (MonoObject*) mono_error_convert_to_exception (error);
6520 } else {
6521 mono_error_cleanup (error); /* FIXME report error */
6523 mono_stopwatch_stop (&watch);
6524 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));
6525 if (exc) {
6526 buffer_add_byte (buf, 0);
6527 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6528 } else {
6529 gboolean out_this = FALSE;
6530 gboolean out_args = FALSE;
6532 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6533 out_this = TRUE;
6534 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6535 out_args = TRUE;
6536 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6537 if (m->string_ctor) {
6538 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6539 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6540 if (!strcmp (m->name, ".ctor")) {
6541 if (!m_class_is_valuetype (m->klass))
6542 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6543 else
6544 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6545 } else {
6546 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6548 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6549 if (sig->ret->byref) {
6550 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6551 buffer_add_value (buf, ret_byval, &res, domain);
6552 } else {
6553 buffer_add_value (buf, sig->ret, &res, domain);
6555 } 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) {
6556 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6557 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6558 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6560 g_assert (nullable_buf);
6561 mono_nullable_init (nullable_buf, res, k);
6562 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6563 } else {
6564 g_assert (res);
6566 if (sig->ret->byref) {
6567 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6568 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6569 } else {
6570 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6573 } else {
6574 NOT_IMPLEMENTED;
6576 if (out_this)
6577 /* Return the new value of the receiver after the call */
6578 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6579 if (out_args) {
6580 buffer_add_int (buf, nargs);
6581 for (i = 0; i < nargs; ++i) {
6582 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6583 buffer_add_value (buf, sig->params [i], &args [i], domain);
6584 else if (sig->params [i]->byref)
6585 /* add_value () does an indirection */
6586 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6587 else
6588 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6593 tls->disable_breakpoints = FALSE;
6595 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6596 if (invoke->has_ctx)
6597 mono_pop_lmf ((MonoLMF*)&ext);
6598 #endif
6600 *endp = p;
6601 // FIXME: byref arguments
6602 // FIXME: varargs
6603 return ERR_NONE;
6607 * invoke_method:
6609 * Invoke the method given by tls->pending_invoke in the current thread.
6611 static void
6612 invoke_method (void)
6614 DebuggerTlsData *tls;
6615 InvokeData *invoke;
6616 int id;
6617 int i, mindex;
6618 ErrorCode err;
6619 Buffer buf;
6620 MonoContext restore_ctx;
6621 guint8 *p;
6623 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6624 g_assert (tls);
6627 * Store the `InvokeData *' in `tls->invoke' until we're done with
6628 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6631 mono_loader_lock ();
6633 invoke = tls->pending_invoke;
6634 g_assert (invoke);
6635 tls->pending_invoke = NULL;
6637 invoke->last_invoke = tls->invoke;
6638 tls->invoke = invoke;
6640 mono_loader_unlock ();
6642 tls->frames_up_to_date = FALSE;
6644 id = invoke->id;
6646 p = invoke->p;
6647 err = ERR_NONE;
6648 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6649 buffer_init (&buf, 128);
6651 if (err) {
6652 /* Fail the other invokes as well */
6653 } else {
6654 err = do_invoke_method (tls, &buf, invoke, p, &p);
6657 if (tls->abort_requested) {
6658 if (CHECK_PROTOCOL_VERSION (2, 42))
6659 err = ERR_INVOKE_ABORTED;
6662 /* Start suspending before sending the reply */
6663 if (mindex == invoke->nmethods - 1) {
6664 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6665 for (i = 0; i < invoke->suspend_count; ++i)
6666 suspend_vm ();
6670 send_reply_packet (id, err, &buf);
6672 buffer_free (&buf);
6675 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6677 if (invoke->has_ctx)
6678 save_thread_context (&restore_ctx);
6680 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6681 g_assert (tls->resume_count);
6682 tls->resume_count -= invoke->suspend_count;
6685 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6688 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6690 * It is possible that mono_thread_internal_abort () was called
6691 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6692 * because we reset the abort here.
6695 mono_loader_lock ();
6697 if (tls->abort_requested)
6698 mono_thread_internal_reset_abort (tls->thread);
6700 tls->invoke = tls->invoke->last_invoke;
6701 tls->abort_requested = FALSE;
6703 mono_loader_unlock ();
6705 g_free (invoke->p);
6706 g_free (invoke);
6709 static gboolean
6710 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6712 MonoThread *thread = (MonoThread *)value;
6713 DebuggerTlsData *tls;
6714 gboolean res;
6716 mono_loader_lock ();
6717 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6718 g_assert (tls);
6719 res = tls->really_suspended;
6720 mono_loader_unlock ();
6722 return res;
6725 static GPtrArray*
6726 get_source_files_for_type (MonoClass *klass)
6728 gpointer iter = NULL;
6729 MonoMethod *method;
6730 MonoDebugSourceInfo *sinfo;
6731 GPtrArray *files;
6732 int i, j;
6734 files = g_ptr_array_new ();
6736 while ((method = mono_class_get_methods (klass, &iter))) {
6737 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6738 GPtrArray *source_file_list;
6740 if (minfo) {
6741 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6742 for (j = 0; j < source_file_list->len; ++j) {
6743 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6744 for (i = 0; i < files->len; ++i)
6745 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6746 break;
6747 if (i == files->len)
6748 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6750 g_ptr_array_free (source_file_list, TRUE);
6754 return files;
6758 typedef struct {
6759 MonoTypeNameParse *info;
6760 gboolean ignore_case;
6761 GPtrArray *res_classes;
6762 GPtrArray *res_domains;
6763 } GetTypesArgs;
6765 static void
6766 get_types (gpointer key, gpointer value, gpointer user_data)
6768 MonoAssembly *ass;
6769 gboolean type_resolve;
6770 MonoType *t;
6771 GSList *tmp;
6772 MonoDomain *domain = (MonoDomain*)key;
6773 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6775 mono_domain_assemblies_lock (domain);
6776 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6777 ass = (MonoAssembly *)tmp->data;
6779 if (ass->image) {
6780 ERROR_DECL (probe_type_error);
6781 /* FIXME really okay to call while holding locks? */
6782 t = mono_reflection_get_type_checked (ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6783 mono_error_cleanup (probe_type_error);
6784 if (t) {
6785 g_ptr_array_add (ud->res_classes, mono_type_get_class_internal (t));
6786 g_ptr_array_add (ud->res_domains, domain);
6790 mono_domain_assemblies_unlock (domain);
6793 typedef struct {
6794 gboolean ignore_case;
6795 char *basename;
6796 GPtrArray *res_classes;
6797 GPtrArray *res_domains;
6798 } GetTypesForSourceFileArgs;
6800 static void
6801 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6803 GHashTableIter iter;
6804 GSList *class_list = NULL;
6805 MonoClass *klass = NULL;
6806 GPtrArray *files = NULL;
6808 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6809 MonoDomain *domain = (MonoDomain*)key;
6811 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6813 /* Update 'source_file_to_class' cache */
6814 g_hash_table_iter_init (&iter, info->loaded_classes);
6815 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6816 if (!g_hash_table_lookup (info->source_files, klass)) {
6817 files = get_source_files_for_type (klass);
6818 g_hash_table_insert (info->source_files, klass, files);
6820 for (int i = 0; i < files->len; ++i) {
6821 char *s = (char *)g_ptr_array_index (files, i);
6822 char *s2 = dbg_path_get_basename (s);
6823 char *s3;
6825 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6826 if (!class_list) {
6827 class_list = g_slist_prepend (class_list, klass);
6828 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6829 } else {
6830 class_list = g_slist_prepend (class_list, klass);
6831 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6834 /* The _ignorecase hash contains the lowercase path */
6835 s3 = strdup_tolower (s2);
6836 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6837 if (!class_list) {
6838 class_list = g_slist_prepend (class_list, klass);
6839 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6840 } else {
6841 class_list = g_slist_prepend (class_list, klass);
6842 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6845 g_free (s2);
6846 g_free (s3);
6851 if (ud->ignore_case) {
6852 char *s;
6854 s = strdup_tolower (ud->basename);
6855 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6856 g_free (s);
6857 } else {
6858 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6861 for (GSList *l = class_list; l; l = l->next) {
6862 klass = (MonoClass *)l->data;
6864 g_ptr_array_add (ud->res_classes, klass);
6865 g_ptr_array_add (ud->res_domains, domain);
6869 static ErrorCode
6870 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6872 switch (command) {
6873 case CMD_VM_VERSION: {
6874 char *build_info, *version;
6876 build_info = mono_get_runtime_build_info ();
6877 version = g_strdup_printf ("mono %s", build_info);
6879 buffer_add_string (buf, version); /* vm version */
6880 buffer_add_int (buf, MAJOR_VERSION);
6881 buffer_add_int (buf, MINOR_VERSION);
6882 g_free (build_info);
6883 g_free (version);
6884 break;
6886 case CMD_VM_SET_PROTOCOL_VERSION: {
6887 major_version = decode_int (p, &p, end);
6888 minor_version = decode_int (p, &p, end);
6889 protocol_version_set = TRUE;
6890 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6891 break;
6893 case CMD_VM_ALL_THREADS: {
6894 // FIXME: Domains
6895 gboolean remove_gc_finalizing;
6896 mono_loader_lock ();
6897 int count = mono_g_hash_table_size (tid_to_thread_obj);
6898 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
6899 if (remove_gc_finalizing)
6900 count--;
6901 buffer_add_int (buf, count);
6902 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6904 mono_loader_unlock ();
6905 break;
6907 case CMD_VM_SUSPEND:
6908 suspend_vm ();
6909 wait_for_suspend ();
6910 break;
6911 case CMD_VM_RESUME:
6912 if (suspend_count == 0)
6913 return ERR_NOT_SUSPENDED;
6914 resume_vm ();
6915 clear_suspended_objs ();
6916 break;
6917 case CMD_VM_DISPOSE:
6918 dispose_vm ();
6919 break;
6920 case CMD_VM_EXIT: {
6921 MonoInternalThread *thread;
6922 DebuggerTlsData *tls;
6923 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6924 MonoClass *env_class;
6925 #endif
6926 MonoMethod *exit_method = NULL;
6927 gpointer *args;
6928 int exit_code;
6930 exit_code = decode_int (p, &p, end);
6932 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6934 /* Have to send a reply before exiting */
6935 send_reply_packet (id, 0, buf);
6937 /* Clear all event requests */
6938 mono_loader_lock ();
6939 while (event_requests->len > 0) {
6940 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6942 clear_event_request (req->id, req->event_kind);
6944 mono_loader_unlock ();
6947 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6948 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6949 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6950 * better than doing the shutdown ourselves, since it avoids various races.
6953 suspend_vm ();
6954 wait_for_suspend ();
6956 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6957 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6958 if (env_class) {
6959 ERROR_DECL (error);
6960 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
6961 mono_error_assert_ok (error);
6963 #endif
6965 mono_loader_lock ();
6966 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6967 mono_loader_unlock ();
6969 if (thread && exit_method) {
6970 mono_loader_lock ();
6971 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6972 mono_loader_unlock ();
6974 args = g_new0 (gpointer, 1);
6975 args [0] = g_malloc (sizeof (int));
6976 *(int*)(args [0]) = exit_code;
6978 tls->pending_invoke = g_new0 (InvokeData, 1);
6979 tls->pending_invoke->method = exit_method;
6980 tls->pending_invoke->args = args;
6981 tls->pending_invoke->nmethods = 1;
6983 while (suspend_count > 0)
6984 resume_vm ();
6985 } else {
6987 * No thread found, do it ourselves.
6988 * FIXME: This can race with normal shutdown etc.
6990 while (suspend_count > 0)
6991 resume_vm ();
6993 if (!mono_runtime_try_shutdown ())
6994 break;
6996 mono_environment_exitcode_set (exit_code);
6998 /* Suspend all managed threads since the runtime is going away */
6999 #ifndef ENABLE_NETCORE
7000 DEBUG_PRINTF (1, "Suspending all threads...\n");
7001 mono_thread_suspend_all_other_threads ();
7002 #endif
7003 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7004 mono_runtime_quit_internal ();
7005 transport_close2 ();
7006 DEBUG_PRINTF (1, "Exiting...\n");
7008 exit (exit_code);
7010 break;
7012 case CMD_VM_INVOKE_METHOD:
7013 case CMD_VM_INVOKE_METHODS: {
7014 int objid = decode_objid (p, &p, end);
7015 MonoThread *thread;
7016 DebuggerTlsData *tls;
7017 int i, count, flags, nmethods;
7018 ErrorCode err;
7020 err = get_object (objid, (MonoObject**)&thread);
7021 if (err != ERR_NONE)
7022 return err;
7024 flags = decode_int (p, &p, end);
7026 if (command == CMD_VM_INVOKE_METHODS)
7027 nmethods = decode_int (p, &p, end);
7028 else
7029 nmethods = 1;
7031 // Wait for suspending if it already started
7032 if (suspend_count)
7033 wait_for_suspend ();
7034 if (!is_suspended ())
7035 return ERR_NOT_SUSPENDED;
7037 mono_loader_lock ();
7038 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7039 mono_loader_unlock ();
7040 g_assert (tls);
7042 if (!tls->really_suspended)
7043 /* The thread is still running native code, can't do invokes */
7044 return ERR_NOT_SUSPENDED;
7047 * Store the invoke data into tls, the thread will execute it after it is
7048 * resumed.
7050 if (tls->pending_invoke)
7051 return ERR_NOT_SUSPENDED;
7052 tls->pending_invoke = g_new0 (InvokeData, 1);
7053 tls->pending_invoke->id = id;
7054 tls->pending_invoke->flags = flags;
7055 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7056 memcpy (tls->pending_invoke->p, p, end - p);
7057 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7058 tls->pending_invoke->suspend_count = suspend_count;
7059 tls->pending_invoke->nmethods = nmethods;
7061 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7062 resume_thread (THREAD_TO_INTERNAL (thread));
7064 else {
7065 count = suspend_count;
7066 for (i = 0; i < count; ++i)
7067 resume_vm ();
7069 break;
7071 case CMD_VM_ABORT_INVOKE: {
7072 int objid = decode_objid (p, &p, end);
7073 MonoThread *thread;
7074 DebuggerTlsData *tls;
7075 int invoke_id;
7076 ErrorCode err;
7078 err = get_object (objid, (MonoObject**)&thread);
7079 if (err != ERR_NONE)
7080 return err;
7082 invoke_id = decode_int (p, &p, end);
7084 mono_loader_lock ();
7085 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7086 g_assert (tls);
7088 if (tls->abort_requested) {
7089 DEBUG_PRINTF (1, "Abort already requested.\n");
7090 mono_loader_unlock ();
7091 break;
7095 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7096 * actually the correct invocation.
7098 * Careful, we do not stop the thread that's doing the invocation, so we can't
7099 * inspect its stack. However, invoke_method() also acquires the loader lock
7100 * when it's done, so we're safe here.
7104 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7105 mono_loader_unlock ();
7106 return ERR_NO_INVOCATION;
7109 tls->abort_requested = TRUE;
7111 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7112 mono_loader_unlock ();
7113 break;
7116 case CMD_VM_SET_KEEPALIVE: {
7117 int timeout = decode_int (p, &p, end);
7118 agent_config.keepalive = timeout;
7119 // FIXME:
7120 #ifndef DISABLE_SOCKET_TRANSPORT
7121 set_keepalive ();
7122 #else
7123 NOT_IMPLEMENTED;
7124 #endif
7125 break;
7127 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7128 int i;
7129 char *fname, *basename;
7130 gboolean ignore_case;
7131 GPtrArray *res_classes, *res_domains;
7133 fname = decode_string (p, &p, end);
7134 ignore_case = decode_byte (p, &p, end);
7136 basename = dbg_path_get_basename (fname);
7138 res_classes = g_ptr_array_new ();
7139 res_domains = g_ptr_array_new ();
7141 mono_loader_lock ();
7142 GetTypesForSourceFileArgs args;
7143 memset (&args, 0, sizeof (args));
7144 args.ignore_case = ignore_case;
7145 args.basename = basename;
7146 args.res_classes = res_classes;
7147 args.res_domains = res_domains;
7148 mono_de_foreach_domain (get_types_for_source_file, &args);
7149 mono_loader_unlock ();
7151 g_free (fname);
7152 g_free (basename);
7154 buffer_add_int (buf, res_classes->len);
7155 for (i = 0; i < res_classes->len; ++i)
7156 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7157 g_ptr_array_free (res_classes, TRUE);
7158 g_ptr_array_free (res_domains, TRUE);
7159 break;
7161 case CMD_VM_GET_TYPES: {
7162 ERROR_DECL (error);
7163 int i;
7164 char *name;
7165 gboolean ignore_case;
7166 GPtrArray *res_classes, *res_domains;
7167 MonoTypeNameParse info;
7169 name = decode_string (p, &p, end);
7170 ignore_case = decode_byte (p, &p, end);
7172 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7173 mono_error_cleanup (error);
7174 g_free (name);
7175 mono_reflection_free_type_info (&info);
7176 return ERR_INVALID_ARGUMENT;
7179 res_classes = g_ptr_array_new ();
7180 res_domains = g_ptr_array_new ();
7182 mono_loader_lock ();
7184 GetTypesArgs args;
7185 memset (&args, 0, sizeof (args));
7186 args.info = &info;
7187 args.ignore_case = ignore_case;
7188 args.res_classes = res_classes;
7189 args.res_domains = res_domains;
7191 mono_de_foreach_domain (get_types, &args);
7193 mono_loader_unlock ();
7195 g_free (name);
7196 mono_reflection_free_type_info (&info);
7198 buffer_add_int (buf, res_classes->len);
7199 for (i = 0; i < res_classes->len; ++i)
7200 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7201 g_ptr_array_free (res_classes, TRUE);
7202 g_ptr_array_free (res_domains, TRUE);
7203 break;
7205 case CMD_VM_START_BUFFERING:
7206 case CMD_VM_STOP_BUFFERING:
7207 /* Handled in the main loop */
7208 break;
7209 default:
7210 return ERR_NOT_IMPLEMENTED;
7213 return ERR_NONE;
7216 static ErrorCode
7217 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7219 ErrorCode err;
7220 ERROR_DECL (error);
7222 switch (command) {
7223 case CMD_EVENT_REQUEST_SET: {
7224 EventRequest *req;
7225 int i, event_kind, suspend_policy, nmodifiers;
7226 ModifierKind mod;
7227 MonoMethod *method;
7228 long location = 0;
7229 MonoThread *step_thread;
7230 int step_thread_id = 0;
7231 StepDepth depth = STEP_DEPTH_INTO;
7232 StepSize size = STEP_SIZE_MIN;
7233 StepFilter filter = STEP_FILTER_NONE;
7234 MonoDomain *domain;
7235 Modifier *modifier;
7237 event_kind = decode_byte (p, &p, end);
7238 suspend_policy = decode_byte (p, &p, end);
7239 nmodifiers = decode_byte (p, &p, end);
7241 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7242 req->id = mono_atomic_inc_i32 (&event_request_id);
7243 req->event_kind = event_kind;
7244 req->suspend_policy = suspend_policy;
7245 req->nmodifiers = nmodifiers;
7247 method = NULL;
7248 for (i = 0; i < nmodifiers; ++i) {
7249 mod = (ModifierKind)decode_byte (p, &p, end);
7251 req->modifiers [i].kind = mod;
7252 if (mod == MOD_KIND_COUNT) {
7253 req->modifiers [i].data.count = decode_int (p, &p, end);
7254 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7255 method = decode_methodid (p, &p, end, &domain, &err);
7256 if (err != ERR_NONE)
7257 return err;
7258 location = decode_long (p, &p, end);
7259 } else if (mod == MOD_KIND_STEP) {
7260 step_thread_id = decode_id (p, &p, end);
7261 size = (StepSize)decode_int (p, &p, end);
7262 depth = (StepDepth)decode_int (p, &p, end);
7263 if (CHECK_PROTOCOL_VERSION (2, 16))
7264 filter = (StepFilter)decode_int (p, &p, end);
7265 req->modifiers [i].data.filter = filter;
7266 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7267 /* Treat STEP_THOUGH the same as HIDDEN */
7268 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7269 } else if (mod == MOD_KIND_THREAD_ONLY) {
7270 int id = decode_id (p, &p, end);
7272 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7273 if (err != ERR_NONE) {
7274 g_free (req);
7275 return err;
7277 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7278 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7280 if (err != ERR_NONE)
7281 return err;
7282 req->modifiers [i].caught = decode_byte (p, &p, end);
7283 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7284 if (CHECK_PROTOCOL_VERSION (2, 25))
7285 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7286 else
7287 req->modifiers [i].subclasses = TRUE;
7288 if (exc_class) {
7289 req->modifiers [i].data.exc_class = exc_class;
7291 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7292 g_free (req);
7293 return ERR_INVALID_ARGUMENT;
7296 if (CHECK_PROTOCOL_VERSION (2, 54)) {
7297 req->modifiers [i].not_filtered_feature = decode_byte (p, &p, end);
7298 req->modifiers [i].everything_else = decode_byte (p, &p, end);
7299 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" : "");
7300 } else {
7301 req->modifiers [i].not_filtered_feature = FALSE;
7302 req->modifiers [i].everything_else = FALSE;
7303 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" : "");
7306 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7307 int n = decode_int (p, &p, end);
7308 int j;
7310 // +1 because we don't know length and we use last element to check for end
7311 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7312 for (j = 0; j < n; ++j) {
7313 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7314 if (err != ERR_NONE) {
7315 g_free (req->modifiers [i].data.assemblies);
7316 return err;
7319 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7320 int n = decode_int (p, &p, end);
7321 int j;
7323 modifier = &req->modifiers [i];
7324 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7325 for (j = 0; j < n; ++j) {
7326 char *s = decode_string (p, &p, end);
7327 char *s2;
7329 if (s) {
7330 s2 = strdup_tolower (s);
7331 g_hash_table_insert (modifier->data.source_files, s2, s2);
7332 g_free (s);
7335 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7336 int n = decode_int (p, &p, end);
7337 int j;
7339 modifier = &req->modifiers [i];
7340 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7341 for (j = 0; j < n; ++j) {
7342 char *s = decode_string (p, &p, end);
7344 if (s)
7345 g_hash_table_insert (modifier->data.type_names, s, s);
7347 } else {
7348 g_free (req);
7349 return ERR_NOT_IMPLEMENTED;
7353 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7354 g_assert (method);
7356 req->info = mono_de_set_breakpoint (method, location, req, error);
7357 if (!is_ok (error)) {
7358 g_free (req);
7359 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7360 mono_error_cleanup (error);
7361 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7363 } else if (req->event_kind == EVENT_KIND_STEP) {
7364 g_assert (step_thread_id);
7366 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7367 if (err != ERR_NONE) {
7368 g_free (req);
7369 return err;
7372 mono_loader_lock ();
7373 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7374 mono_loader_unlock ();
7375 g_assert (tls);
7377 if (tls->terminated) {
7378 /* if the thread is already terminated ignore the single step */
7379 buffer_add_int (buf, req->id);
7380 return ERR_NONE;
7383 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7384 if (err != ERR_NONE) {
7385 g_free (req);
7386 return err;
7388 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7389 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7390 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7391 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7392 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7393 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7394 } else {
7395 if (req->nmodifiers) {
7396 g_free (req);
7397 return ERR_NOT_IMPLEMENTED;
7401 mono_loader_lock ();
7402 g_ptr_array_add (event_requests, req);
7404 if (agent_config.defer) {
7405 /* Transmit cached data to the client on receipt of the event request */
7406 switch (req->event_kind) {
7407 case EVENT_KIND_APPDOMAIN_CREATE:
7408 /* Emit load events for currently loaded domains */
7409 mono_de_foreach_domain (emit_appdomain_load, NULL);
7410 break;
7411 case EVENT_KIND_ASSEMBLY_LOAD:
7412 /* Emit load events for currently loaded assemblies */
7413 mono_domain_foreach (send_assemblies_for_domain, NULL);
7414 break;
7415 case EVENT_KIND_THREAD_START:
7416 /* Emit start events for currently started threads */
7417 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7418 break;
7419 case EVENT_KIND_TYPE_LOAD:
7420 /* Emit type load events for currently loaded types */
7421 mono_domain_foreach (send_types_for_domain, NULL);
7422 break;
7423 default:
7424 break;
7427 mono_loader_unlock ();
7429 buffer_add_int (buf, req->id);
7430 break;
7432 case CMD_EVENT_REQUEST_CLEAR: {
7433 int etype = decode_byte (p, &p, end);
7434 int req_id = decode_int (p, &p, end);
7436 // FIXME: Make a faster mapping from req_id to request
7437 mono_loader_lock ();
7438 clear_event_request (req_id, etype);
7439 mono_loader_unlock ();
7440 break;
7442 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7443 int i;
7445 mono_loader_lock ();
7446 i = 0;
7447 while (i < event_requests->len) {
7448 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7450 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7451 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7453 g_ptr_array_remove_index_fast (event_requests, i);
7454 g_free (req);
7455 } else {
7456 i ++;
7459 mono_loader_unlock ();
7460 break;
7462 default:
7463 return ERR_NOT_IMPLEMENTED;
7466 return ERR_NONE;
7469 static ErrorCode
7470 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7472 ErrorCode err;
7473 MonoDomain *domain;
7475 switch (command) {
7476 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7477 buffer_add_domainid (buf, mono_get_root_domain ());
7478 break;
7480 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7481 domain = decode_domainid (p, &p, end, NULL, &err);
7482 if (err != ERR_NONE)
7483 return err;
7484 buffer_add_string (buf, domain->friendly_name);
7485 break;
7487 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7488 GSList *tmp;
7489 MonoAssembly *ass;
7490 int count;
7492 domain = decode_domainid (p, &p, end, NULL, &err);
7493 if (err != ERR_NONE)
7494 return err;
7495 mono_domain_assemblies_lock (domain);
7496 count = 0;
7497 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7498 count ++;
7500 buffer_add_int (buf, count);
7501 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7502 ass = (MonoAssembly *)tmp->data;
7503 buffer_add_assemblyid (buf, domain, ass);
7505 mono_domain_assemblies_unlock (domain);
7506 break;
7508 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7509 domain = decode_domainid (p, &p, end, NULL, &err);
7510 if (err != ERR_NONE)
7511 return err;
7513 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7514 break;
7516 case CMD_APPDOMAIN_GET_CORLIB: {
7517 domain = decode_domainid (p, &p, end, NULL, &err);
7518 if (err != ERR_NONE)
7519 return err;
7521 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7522 break;
7524 case CMD_APPDOMAIN_CREATE_STRING: {
7525 char *s;
7526 MonoString *o;
7527 ERROR_DECL (error);
7529 domain = decode_domainid (p, &p, end, NULL, &err);
7530 if (err != ERR_NONE)
7531 return err;
7532 s = decode_string (p, &p, end);
7534 o = mono_string_new_checked (domain, s, error);
7535 if (!is_ok (error)) {
7536 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7537 mono_error_cleanup (error);
7538 return ERR_INVALID_OBJECT;
7540 buffer_add_objid (buf, (MonoObject*)o);
7541 break;
7543 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7544 ERROR_DECL (error);
7545 MonoArray *arr;
7546 gpointer elem;
7547 domain = decode_domainid (p, &p, end, NULL, &err);
7548 uintptr_t size = 0;
7549 int len = decode_int (p, &p, end);
7550 size = len;
7551 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7552 elem = mono_array_addr_internal (arr, guint8, 0);
7553 memcpy (elem, p, len);
7554 p += len;
7555 buffer_add_objid (buf, (MonoObject*) arr);
7556 break;
7558 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7559 ERROR_DECL (error);
7560 MonoClass *klass;
7561 MonoDomain *domain2;
7562 MonoObject *o;
7564 domain = decode_domainid (p, &p, end, NULL, &err);
7565 if (err != ERR_NONE)
7566 return err;
7567 klass = decode_typeid (p, &p, end, &domain2, &err);
7568 if (err != ERR_NONE)
7569 return err;
7571 // FIXME:
7572 g_assert (domain == domain2);
7574 o = mono_object_new_checked (domain, klass, error);
7575 mono_error_assert_ok (error);
7577 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7578 if (err != ERR_NONE)
7579 return err;
7581 buffer_add_objid (buf, o);
7582 break;
7584 default:
7585 return ERR_NOT_IMPLEMENTED;
7588 return ERR_NONE;
7591 static ErrorCode
7592 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7594 HANDLE_FUNCTION_ENTER();
7595 ErrorCode err = ERR_NONE;
7596 error_init (error);
7597 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7598 if (MONO_HANDLE_IS_NULL (o)) {
7599 err = ERR_INVALID_OBJECT;
7600 goto leave;
7602 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7603 leave:
7604 HANDLE_FUNCTION_RETURN_VAL (err);
7608 static ErrorCode
7609 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7611 ErrorCode err;
7612 MonoAssembly *ass;
7613 MonoDomain *domain;
7615 ass = decode_assemblyid (p, &p, end, &domain, &err);
7616 if (err != ERR_NONE)
7617 return err;
7619 switch (command) {
7620 case CMD_ASSEMBLY_GET_LOCATION: {
7621 buffer_add_string (buf, mono_image_get_filename (ass->image));
7622 break;
7624 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7625 guint32 token;
7626 MonoMethod *m;
7628 if (ass->image->dynamic) {
7629 buffer_add_id (buf, 0);
7630 } else {
7631 token = mono_image_get_entry_point (ass->image);
7632 if (token == 0) {
7633 buffer_add_id (buf, 0);
7634 } else {
7635 ERROR_DECL (error);
7636 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7637 if (!m)
7638 mono_error_cleanup (error); /* FIXME don't swallow the error */
7639 buffer_add_methodid (buf, domain, m);
7642 break;
7644 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7645 buffer_add_moduleid (buf, domain, ass->image);
7646 break;
7648 case CMD_ASSEMBLY_GET_OBJECT: {
7649 ERROR_DECL (error);
7650 err = get_assembly_object_command (domain, ass, buf, error);
7651 mono_error_cleanup (error);
7652 return err;
7654 case CMD_ASSEMBLY_GET_DOMAIN: {
7655 buffer_add_domainid (buf, domain);
7656 break;
7658 case CMD_ASSEMBLY_GET_TYPE: {
7659 ERROR_DECL (error);
7660 char *s = decode_string (p, &p, end);
7661 gboolean ignorecase = decode_byte (p, &p, end);
7662 MonoTypeNameParse info;
7663 MonoType *t;
7664 gboolean type_resolve, res;
7665 MonoDomain *d = mono_domain_get ();
7667 /* This is needed to be able to find referenced assemblies */
7668 res = mono_domain_set_fast (domain, FALSE);
7669 g_assert (res);
7671 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7672 mono_error_cleanup (error);
7673 t = NULL;
7674 } else {
7675 if (info.assembly.name)
7676 NOT_IMPLEMENTED;
7677 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7678 if (!is_ok (error)) {
7679 mono_error_cleanup (error); /* FIXME don't swallow the error */
7680 mono_reflection_free_type_info (&info);
7681 g_free (s);
7682 return ERR_INVALID_ARGUMENT;
7685 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7686 mono_reflection_free_type_info (&info);
7687 g_free (s);
7689 mono_domain_set_fast (d, TRUE);
7691 break;
7693 case CMD_ASSEMBLY_GET_NAME: {
7694 gchar *name;
7695 MonoAssembly *mass = ass;
7697 name = g_strdup_printf (
7698 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7699 mass->aname.name,
7700 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7701 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7702 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7703 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7705 buffer_add_string (buf, name);
7706 g_free (name);
7707 break;
7709 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7710 MonoImage* image = ass->image;
7711 if (ass->dynamic) {
7712 return ERR_NOT_IMPLEMENTED;
7714 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7715 break;
7717 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7718 buffer_add_byte (buf, ass->dynamic);
7719 break;
7721 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7722 MonoImage* image = ass->image;
7723 MonoDebugHandle* handle = mono_debug_get_handle (image);
7724 if (!handle) {
7725 return ERR_INVALID_ARGUMENT;
7727 MonoPPDBFile* ppdb = handle->ppdb;
7728 if (ppdb) {
7729 image = mono_ppdb_get_image (ppdb);
7730 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7731 } else {
7732 buffer_add_byte_array (buf, NULL, 0);
7734 break;
7736 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7737 if (ass->dynamic) {
7738 return ERR_NOT_IMPLEMENTED;
7740 guint32 token = decode_int (p, &p, end);
7741 ERROR_DECL (error);
7742 error_init (error);
7743 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7744 if (!is_ok (error)) {
7745 mono_error_cleanup (error);
7746 return ERR_INVALID_ARGUMENT;
7748 buffer_add_typeid (buf, domain, mono_class);
7749 mono_error_cleanup (error);
7750 break;
7752 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7753 if (ass->dynamic) {
7754 return ERR_NOT_IMPLEMENTED;
7756 guint32 token = decode_int (p, &p, end);
7757 ERROR_DECL (error);
7758 error_init (error);
7759 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7760 if (!is_ok (error)) {
7761 mono_error_cleanup (error);
7762 return ERR_INVALID_ARGUMENT;
7764 buffer_add_methodid (buf, domain, mono_method);
7765 mono_error_cleanup (error);
7766 break;
7768 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7769 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7770 break;
7772 default:
7773 return ERR_NOT_IMPLEMENTED;
7776 return ERR_NONE;
7779 static ErrorCode
7780 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7782 ErrorCode err;
7783 MonoDomain *domain;
7785 switch (command) {
7786 case CMD_MODULE_GET_INFO: {
7787 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7788 char *basename, *sourcelink = NULL;
7790 if (CHECK_PROTOCOL_VERSION (2, 48))
7791 sourcelink = mono_debug_image_get_sourcelink (image);
7793 basename = g_path_get_basename (image->name);
7794 buffer_add_string (buf, basename); // name
7795 buffer_add_string (buf, image->module_name); // scopename
7796 buffer_add_string (buf, image->name); // fqname
7797 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7798 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7799 if (CHECK_PROTOCOL_VERSION (2, 48))
7800 buffer_add_string (buf, sourcelink);
7801 g_free (basename);
7802 g_free (sourcelink);
7803 break;
7805 default:
7806 return ERR_NOT_IMPLEMENTED;
7809 return ERR_NONE;
7812 static ErrorCode
7813 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7815 ErrorCode err;
7816 MonoDomain *domain;
7818 switch (command) {
7819 case CMD_FIELD_GET_INFO: {
7820 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7822 buffer_add_string (buf, f->name);
7823 buffer_add_typeid (buf, domain, f->parent);
7824 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7825 buffer_add_int (buf, f->type->attrs);
7826 break;
7828 default:
7829 return ERR_NOT_IMPLEMENTED;
7832 return ERR_NONE;
7835 static void
7836 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7838 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7839 /* Special case these so the client doesn't have to handle Type objects */
7841 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7842 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
7843 } else if (MONO_TYPE_IS_REFERENCE (t))
7844 buffer_add_value (buf, t, &val, domain);
7845 else
7846 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
7849 static ErrorCode
7850 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7852 int i, j;
7853 int nattrs = 0;
7855 if (!cinfo) {
7856 buffer_add_int (buf, 0);
7857 return ERR_NONE;
7860 SETUP_ICALL_FUNCTION;
7862 for (i = 0; i < cinfo->num_attrs; ++i) {
7863 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7864 nattrs ++;
7866 buffer_add_int (buf, nattrs);
7868 for (i = 0; i < cinfo->num_attrs; ++i) {
7869 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7870 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7871 MonoArray *typed_args, *named_args;
7872 MonoArrayHandleOut typed_args_h, named_args_h;
7873 MonoObjectHandle val_h;
7874 MonoType *t;
7875 CattrNamedArg *arginfo = NULL;
7876 ERROR_DECL (error);
7878 SETUP_ICALL_FRAME;
7879 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
7880 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
7881 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
7883 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
7884 if (!is_ok (error)) {
7885 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
7886 mono_error_cleanup (error);
7887 CLEAR_ICALL_FRAME;
7888 return ERR_LOADER_ERROR;
7890 typed_args = MONO_HANDLE_RAW (typed_args_h);
7891 named_args = MONO_HANDLE_RAW (named_args_h);
7893 buffer_add_methodid (buf, domain, attr->ctor);
7895 /* Ctor args */
7896 if (typed_args) {
7897 buffer_add_int (buf, mono_array_length_internal (typed_args));
7898 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
7899 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
7900 MONO_HANDLE_ASSIGN_RAW (val_h, val);
7902 t = mono_method_signature_internal (attr->ctor)->params [j];
7904 buffer_add_cattr_arg (buf, t, domain, val);
7906 } else {
7907 buffer_add_int (buf, 0);
7910 /* Named args */
7911 if (named_args) {
7912 buffer_add_int (buf, mono_array_length_internal (named_args));
7914 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
7915 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
7916 MONO_HANDLE_ASSIGN_RAW (val_h, val);
7918 if (arginfo [j].prop) {
7919 buffer_add_byte (buf, 0x54);
7920 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7921 } else if (arginfo [j].field) {
7922 buffer_add_byte (buf, 0x53);
7923 buffer_add_fieldid (buf, domain, arginfo [j].field);
7924 } else {
7925 g_assert_not_reached ();
7928 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7930 } else {
7931 buffer_add_int (buf, 0);
7933 g_free (arginfo);
7935 CLEAR_ICALL_FRAME;
7939 return ERR_NONE;
7942 /* FIXME: Code duplication with icall.c */
7943 static void
7944 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7946 int i;
7947 MonoClass *ic;
7949 mono_class_setup_interfaces (klass, error);
7950 if (!is_ok (error))
7951 return;
7953 int klass_interface_count = m_class_get_interface_count (klass);
7954 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
7955 for (i = 0; i < klass_interface_count; i++) {
7956 ic = klass_interfaces [i];
7957 g_hash_table_insert (ifaces, ic, ic);
7959 collect_interfaces (ic, ifaces, error);
7960 if (!is_ok (error))
7961 return;
7965 static ErrorCode
7966 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7968 HANDLE_FUNCTION_ENTER ();
7970 ERROR_DECL (error);
7971 MonoClass *nested;
7972 MonoType *type;
7973 gpointer iter;
7974 guint8 b;
7975 int nnested;
7976 ErrorCode err;
7977 char *name;
7978 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
7980 switch (command) {
7981 case CMD_TYPE_GET_INFO: {
7982 buffer_add_string (buf, m_class_get_name_space (klass));
7983 buffer_add_string (buf, m_class_get_name (klass));
7984 // FIXME: byref
7985 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7986 buffer_add_string (buf, name);
7987 g_free (name);
7988 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
7989 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
7990 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
7991 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
7992 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
7993 else
7994 buffer_add_id (buf, 0);
7995 buffer_add_int (buf, m_class_get_type_token (klass));
7996 buffer_add_byte (buf, m_class_get_rank (klass));
7997 buffer_add_int (buf, mono_class_get_flags (klass));
7998 b = 0;
7999 type = m_class_get_byval_arg (klass);
8000 // FIXME: Can't decide whenever a class represents a byref type
8001 if (FALSE)
8002 b |= (1 << 0);
8003 if (type->type == MONO_TYPE_PTR)
8004 b |= (1 << 1);
8005 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8006 b |= (1 << 2);
8007 if (type->type == MONO_TYPE_VALUETYPE)
8008 b |= (1 << 3);
8009 if (m_class_is_enumtype (klass))
8010 b |= (1 << 4);
8011 if (mono_class_is_gtd (klass))
8012 b |= (1 << 5);
8013 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8014 b |= (1 << 6);
8015 buffer_add_byte (buf, b);
8016 nnested = 0;
8017 iter = NULL;
8018 while ((nested = mono_class_get_nested_types (klass, &iter)))
8019 nnested ++;
8020 buffer_add_int (buf, nnested);
8021 iter = NULL;
8022 while ((nested = mono_class_get_nested_types (klass, &iter)))
8023 buffer_add_typeid (buf, domain, nested);
8024 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8025 if (mono_class_is_gtd (klass))
8026 buffer_add_typeid (buf, domain, klass);
8027 else if (mono_class_is_ginst (klass))
8028 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8029 else
8030 buffer_add_id (buf, 0);
8032 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8033 int count, i;
8035 if (mono_class_is_ginst (klass)) {
8036 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8038 count = inst->type_argc;
8039 buffer_add_int (buf, count);
8040 for (i = 0; i < count; i++)
8041 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8042 } else if (mono_class_is_gtd (klass)) {
8043 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8044 MonoClass *pklass;
8046 count = container->type_argc;
8047 buffer_add_int (buf, count);
8048 for (i = 0; i < count; i++) {
8049 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8050 buffer_add_typeid (buf, domain, pklass);
8052 } else {
8053 buffer_add_int (buf, 0);
8056 break;
8058 case CMD_TYPE_GET_METHODS: {
8059 int nmethods;
8060 int i = 0;
8061 gpointer iter = NULL;
8062 MonoMethod *m;
8064 mono_class_setup_methods (klass);
8066 nmethods = mono_class_num_methods (klass);
8068 buffer_add_int (buf, nmethods);
8070 while ((m = mono_class_get_methods (klass, &iter))) {
8071 buffer_add_methodid (buf, domain, m);
8072 i ++;
8074 g_assert (i == nmethods);
8075 break;
8077 case CMD_TYPE_GET_FIELDS: {
8078 int nfields;
8079 int i = 0;
8080 gpointer iter = NULL;
8081 MonoClassField *f;
8083 nfields = mono_class_num_fields (klass);
8085 buffer_add_int (buf, nfields);
8087 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8088 buffer_add_fieldid (buf, domain, f);
8089 buffer_add_string (buf, f->name);
8090 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8091 buffer_add_int (buf, f->type->attrs);
8092 i ++;
8094 g_assert (i == nfields);
8095 break;
8097 case CMD_TYPE_GET_PROPERTIES: {
8098 int nprops;
8099 int i = 0;
8100 gpointer iter = NULL;
8101 MonoProperty *p;
8103 nprops = mono_class_num_properties (klass);
8105 buffer_add_int (buf, nprops);
8107 while ((p = mono_class_get_properties (klass, &iter))) {
8108 buffer_add_propertyid (buf, domain, p);
8109 buffer_add_string (buf, p->name);
8110 buffer_add_methodid (buf, domain, p->get);
8111 buffer_add_methodid (buf, domain, p->set);
8112 buffer_add_int (buf, p->attrs);
8113 i ++;
8115 g_assert (i == nprops);
8116 break;
8118 case CMD_TYPE_GET_CATTRS: {
8119 MonoClass *attr_klass;
8120 MonoCustomAttrInfo *cinfo;
8122 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8123 /* attr_klass can be NULL */
8124 if (err != ERR_NONE)
8125 goto exit;
8127 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8128 if (!is_ok (error)) {
8129 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8130 goto loader_error;
8133 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8134 if (err != ERR_NONE)
8135 goto exit;
8136 break;
8138 case CMD_TYPE_GET_FIELD_CATTRS: {
8139 MonoClass *attr_klass;
8140 MonoCustomAttrInfo *cinfo;
8141 MonoClassField *field;
8143 field = decode_fieldid (p, &p, end, NULL, &err);
8144 if (err != ERR_NONE)
8145 goto exit;
8146 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8147 if (err != ERR_NONE)
8148 goto exit;
8150 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8151 if (!is_ok (error)) {
8152 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8153 goto loader_error;
8156 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8157 if (err != ERR_NONE)
8158 goto exit;
8159 break;
8161 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8162 MonoClass *attr_klass;
8163 MonoCustomAttrInfo *cinfo;
8164 MonoProperty *prop;
8166 prop = decode_propertyid (p, &p, end, NULL, &err);
8167 if (err != ERR_NONE)
8168 goto exit;
8169 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8170 if (err != ERR_NONE)
8171 goto exit;
8173 cinfo = mono_custom_attrs_from_property_checked (klass, prop, 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_VALUES:
8185 case CMD_TYPE_GET_VALUES_2: {
8186 guint8 *val;
8187 MonoClassField *f;
8188 MonoVTable *vtable;
8189 MonoClass *k;
8190 int len, i;
8191 gboolean found;
8192 MonoThread *thread_obj;
8193 MonoInternalThread *thread = NULL;
8194 guint32 special_static_type;
8196 if (command == CMD_TYPE_GET_VALUES_2) {
8197 int objid = decode_objid (p, &p, end);
8199 err = get_object (objid, (MonoObject**)&thread_obj);
8200 if (err != ERR_NONE)
8201 goto exit;
8203 thread = THREAD_TO_INTERNAL (thread_obj);
8206 len = decode_int (p, &p, end);
8207 for (i = 0; i < len; ++i) {
8208 f = decode_fieldid (p, &p, end, NULL, &err);
8209 if (err != ERR_NONE)
8210 goto exit;
8212 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8213 goto invalid_fieldid;
8215 special_static_type = mono_class_field_get_special_static_type (f);
8216 if (special_static_type != SPECIAL_STATIC_NONE) {
8217 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8218 goto invalid_fieldid;
8221 /* Check that the field belongs to the object */
8222 found = FALSE;
8223 for (k = klass; k; k = m_class_get_parent (k)) {
8224 if (k == f->parent) {
8225 found = TRUE;
8226 break;
8229 if (!found)
8230 goto invalid_fieldid;
8232 vtable = mono_class_vtable_checked (domain, f->parent, error);
8233 goto_if_nok (error, invalid_fieldid);
8235 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8236 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, string_handle, error);
8237 goto_if_nok (error, invalid_fieldid);
8239 buffer_add_value (buf, f->type, val, domain);
8240 g_free (val);
8242 break;
8244 case CMD_TYPE_SET_VALUES: {
8245 guint8 *val;
8246 MonoClassField *f;
8247 MonoVTable *vtable;
8248 MonoClass *k;
8249 int len, i;
8250 gboolean found;
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 if (mono_class_field_is_special_static (f))
8262 goto invalid_fieldid;
8264 /* Check that the field belongs to the object */
8265 found = FALSE;
8266 for (k = klass; k; k = m_class_get_parent (k)) {
8267 if (k == f->parent) {
8268 found = TRUE;
8269 break;
8272 if (!found)
8273 goto invalid_fieldid;
8275 // FIXME: Check for literal/const
8277 vtable = mono_class_vtable_checked (domain, f->parent, error);
8278 goto_if_nok (error, invalid_fieldid);
8280 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8281 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8282 if (err != ERR_NONE) {
8283 g_free (val);
8284 goto exit;
8286 if (MONO_TYPE_IS_REFERENCE (f->type))
8287 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8288 else
8289 mono_field_static_set_value_internal (vtable, f, val);
8290 g_free (val);
8292 break;
8294 case CMD_TYPE_GET_OBJECT: {
8295 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8296 if (!is_ok (error)) {
8297 mono_error_cleanup (error);
8298 goto invalid_object;
8300 buffer_add_objid (buf, o);
8301 break;
8303 case CMD_TYPE_GET_SOURCE_FILES:
8304 case CMD_TYPE_GET_SOURCE_FILES_2: {
8305 char *source_file, *base;
8306 GPtrArray *files;
8307 int i;
8309 files = get_source_files_for_type (klass);
8311 buffer_add_int (buf, files->len);
8312 for (i = 0; i < files->len; ++i) {
8313 source_file = (char *)g_ptr_array_index (files, i);
8314 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8315 buffer_add_string (buf, source_file);
8316 } else {
8317 base = dbg_path_get_basename (source_file);
8318 buffer_add_string (buf, base);
8319 g_free (base);
8321 g_free (source_file);
8323 g_ptr_array_free (files, TRUE);
8324 break;
8326 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8327 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8329 if (err != ERR_NONE)
8330 goto exit;
8331 if (mono_class_is_assignable_from_internal (klass, oklass))
8332 buffer_add_byte (buf, 1);
8333 else
8334 buffer_add_byte (buf, 0);
8335 break;
8337 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8338 char *name = decode_string (p, &p, end);
8339 int i, flags = decode_int (p, &p, end);
8340 int mlisttype;
8341 if (CHECK_PROTOCOL_VERSION (2, 48))
8342 mlisttype = decode_int (p, &p, end);
8343 else
8344 mlisttype = 0; // MLISTTYPE_All
8345 ERROR_DECL (error);
8346 GPtrArray *array;
8348 error_init (error);
8349 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8350 if (!is_ok (error)) {
8351 mono_error_cleanup (error);
8352 goto loader_error;
8354 buffer_add_int (buf, array->len);
8355 for (i = 0; i < array->len; ++i) {
8356 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8357 buffer_add_methodid (buf, domain, method);
8360 g_ptr_array_free (array, TRUE);
8361 g_free (name);
8362 break;
8364 case CMD_TYPE_GET_INTERFACES: {
8365 MonoClass *parent;
8366 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8367 MonoClass *tclass, *iface;
8368 GHashTableIter iter;
8370 tclass = klass;
8372 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8373 mono_class_setup_interfaces (parent, error);
8374 goto_if_nok (error, loader_error);
8376 collect_interfaces (parent, iface_hash, error);
8377 goto_if_nok (error, loader_error);
8380 buffer_add_int (buf, g_hash_table_size (iface_hash));
8382 g_hash_table_iter_init (&iter, iface_hash);
8383 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8384 buffer_add_typeid (buf, domain, iface);
8385 g_hash_table_destroy (iface_hash);
8386 break;
8388 case CMD_TYPE_GET_INTERFACE_MAP: {
8389 int tindex, ioffset;
8390 gboolean variance_used;
8391 MonoClass *iclass;
8392 int len, nmethods, i;
8393 gpointer iter;
8394 MonoMethod *method;
8396 len = decode_int (p, &p, end);
8397 mono_class_setup_vtable (klass);
8399 for (tindex = 0; tindex < len; ++tindex) {
8400 iclass = decode_typeid (p, &p, end, NULL, &err);
8401 if (err != ERR_NONE)
8402 goto exit;
8404 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8405 if (ioffset == -1)
8406 goto invalid_argument;
8408 nmethods = mono_class_num_methods (iclass);
8409 buffer_add_int (buf, nmethods);
8411 iter = NULL;
8412 while ((method = mono_class_get_methods (iclass, &iter))) {
8413 buffer_add_methodid (buf, domain, method);
8415 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8416 for (i = 0; i < nmethods; ++i)
8417 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8419 break;
8421 case CMD_TYPE_IS_INITIALIZED: {
8422 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8423 goto_if_nok (error, loader_error);
8425 if (vtable)
8426 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8427 else
8428 buffer_add_int (buf, 0);
8429 break;
8431 case CMD_TYPE_CREATE_INSTANCE: {
8432 ERROR_DECL (error);
8433 MonoObject *obj;
8435 obj = mono_object_new_checked (domain, klass, error);
8436 mono_error_assert_ok (error);
8437 buffer_add_objid (buf, obj);
8438 break;
8440 case CMD_TYPE_GET_VALUE_SIZE: {
8441 int32_t value_size;
8443 value_size = mono_class_value_size (klass, NULL);
8444 buffer_add_int (buf, value_size);
8445 break;
8447 default:
8448 err = ERR_NOT_IMPLEMENTED;
8449 goto exit;
8452 err = ERR_NONE;
8453 goto exit;
8454 invalid_argument:
8455 err = ERR_INVALID_ARGUMENT;
8456 goto exit;
8457 invalid_fieldid:
8458 err = ERR_INVALID_FIELDID;
8459 goto exit;
8460 invalid_object:
8461 err = ERR_INVALID_OBJECT;
8462 goto exit;
8463 loader_error:
8464 err = ERR_LOADER_ERROR;
8465 goto exit;
8466 exit:
8467 HANDLE_FUNCTION_RETURN_VAL (err);
8470 static ErrorCode
8471 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8473 MonoClass *klass;
8474 MonoDomain *old_domain;
8475 MonoDomain *domain;
8476 ErrorCode err;
8478 klass = decode_typeid (p, &p, end, &domain, &err);
8479 if (err != ERR_NONE)
8480 return err;
8482 old_domain = mono_domain_get ();
8484 mono_domain_set_fast (domain, TRUE);
8486 err = type_commands_internal (command, klass, domain, p, end, buf);
8488 mono_domain_set_fast (old_domain, TRUE);
8490 return err;
8493 static ErrorCode
8494 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8496 MonoMethodHeader *header;
8497 ErrorCode err;
8499 switch (command) {
8500 case CMD_METHOD_GET_NAME: {
8501 buffer_add_string (buf, method->name);
8502 break;
8504 case CMD_METHOD_GET_DECLARING_TYPE: {
8505 buffer_add_typeid (buf, domain, method->klass);
8506 break;
8508 case CMD_METHOD_GET_DEBUG_INFO: {
8509 ERROR_DECL (error);
8510 MonoDebugMethodInfo *minfo;
8511 char *source_file;
8512 int i, j, n_il_offsets;
8513 int *source_files;
8514 GPtrArray *source_file_list;
8515 MonoSymSeqPoint *sym_seq_points;
8517 header = mono_method_get_header_checked (method, error);
8518 if (!header) {
8519 mono_error_cleanup (error); /* FIXME don't swallow the error */
8520 buffer_add_int (buf, 0);
8521 buffer_add_string (buf, "");
8522 buffer_add_int (buf, 0);
8523 break;
8526 minfo = mono_debug_lookup_method (method);
8527 if (!minfo) {
8528 buffer_add_int (buf, header->code_size);
8529 buffer_add_string (buf, "");
8530 buffer_add_int (buf, 0);
8531 mono_metadata_free_mh (header);
8532 break;
8535 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8536 buffer_add_int (buf, header->code_size);
8537 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8538 buffer_add_int (buf, source_file_list->len);
8539 for (i = 0; i < source_file_list->len; ++i) {
8540 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8541 buffer_add_string (buf, sinfo->source_file);
8542 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8543 for (j = 0; j < 16; ++j)
8544 buffer_add_byte (buf, sinfo->hash [j]);
8547 } else {
8548 buffer_add_string (buf, source_file);
8550 buffer_add_int (buf, n_il_offsets);
8551 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8552 for (i = 0; i < n_il_offsets; ++i) {
8553 MonoSymSeqPoint *sp = &sym_seq_points [i];
8554 const char *srcfile = "";
8556 if (source_files [i] != -1) {
8557 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8558 srcfile = sinfo->source_file;
8560 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);
8561 buffer_add_int (buf, sp->il_offset);
8562 buffer_add_int (buf, sp->line);
8563 if (CHECK_PROTOCOL_VERSION (2, 13))
8564 buffer_add_int (buf, source_files [i]);
8565 if (CHECK_PROTOCOL_VERSION (2, 19))
8566 buffer_add_int (buf, sp->column);
8567 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8568 buffer_add_int (buf, sp->end_line);
8569 buffer_add_int (buf, sp->end_column);
8572 g_free (source_file);
8573 g_free (source_files);
8574 g_free (sym_seq_points);
8575 g_ptr_array_free (source_file_list, TRUE);
8576 mono_metadata_free_mh (header);
8577 break;
8579 case CMD_METHOD_GET_PARAM_INFO: {
8580 MonoMethodSignature *sig = mono_method_signature_internal (method);
8581 guint32 i;
8582 char **names;
8584 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8586 /* FIXME: Use a smaller encoding */
8587 buffer_add_int (buf, sig->call_convention);
8588 buffer_add_int (buf, sig->param_count);
8589 buffer_add_int (buf, sig->generic_param_count);
8590 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8591 for (i = 0; i < sig->param_count; ++i) {
8592 /* FIXME: vararg */
8593 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8596 /* Emit parameter names */
8597 names = g_new (char *, sig->param_count);
8598 mono_method_get_param_names (method, (const char **) names);
8599 for (i = 0; i < sig->param_count; ++i)
8600 buffer_add_string (buf, names [i]);
8601 g_free (names);
8603 break;
8605 case CMD_METHOD_GET_LOCALS_INFO: {
8606 ERROR_DECL (error);
8607 int i, num_locals;
8608 MonoDebugLocalsInfo *locals;
8609 int *locals_map = NULL;
8611 header = mono_method_get_header_checked (method, error);
8612 if (!header) {
8613 mono_error_cleanup (error); /* FIXME don't swallow the error */
8614 return ERR_INVALID_ARGUMENT;
8617 locals = mono_debug_lookup_locals (method);
8618 if (!locals) {
8619 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8620 /* Scopes */
8621 buffer_add_int (buf, 1);
8622 buffer_add_int (buf, 0);
8623 buffer_add_int (buf, header->code_size);
8625 buffer_add_int (buf, header->num_locals);
8626 /* Types */
8627 for (i = 0; i < header->num_locals; ++i) {
8628 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8630 /* Names */
8631 for (i = 0; i < header->num_locals; ++i) {
8632 char lname [128];
8633 sprintf (lname, "V_%d", i);
8634 buffer_add_string (buf, lname);
8636 /* Scopes */
8637 for (i = 0; i < header->num_locals; ++i) {
8638 buffer_add_int (buf, 0);
8639 buffer_add_int (buf, header->code_size);
8641 } else {
8642 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8643 /* Scopes */
8644 buffer_add_int (buf, locals->num_blocks);
8645 int last_start = 0;
8646 for (i = 0; i < locals->num_blocks; ++i) {
8647 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8648 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8649 last_start = locals->code_blocks [i].start_offset;
8653 num_locals = locals->num_locals;
8654 buffer_add_int (buf, num_locals);
8656 /* Types */
8657 for (i = 0; i < num_locals; ++i) {
8658 g_assert (locals->locals [i].index < header->num_locals);
8659 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8661 /* Names */
8662 for (i = 0; i < num_locals; ++i)
8663 buffer_add_string (buf, locals->locals [i].name);
8664 /* Scopes */
8665 for (i = 0; i < num_locals; ++i) {
8666 if (locals->locals [i].block) {
8667 buffer_add_int (buf, locals->locals [i].block->start_offset);
8668 buffer_add_int (buf, locals->locals [i].block->end_offset);
8669 } else {
8670 buffer_add_int (buf, 0);
8671 buffer_add_int (buf, header->code_size);
8675 mono_metadata_free_mh (header);
8677 if (locals)
8678 mono_debug_free_locals (locals);
8679 g_free (locals_map);
8681 break;
8683 case CMD_METHOD_GET_INFO:
8684 buffer_add_int (buf, method->flags);
8685 buffer_add_int (buf, method->iflags);
8686 buffer_add_int (buf, method->token);
8687 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8688 guint8 attrs = 0;
8689 if (method->is_generic)
8690 attrs |= (1 << 0);
8691 if (mono_method_signature_internal (method)->generic_param_count)
8692 attrs |= (1 << 1);
8693 buffer_add_byte (buf, attrs);
8694 if (method->is_generic || method->is_inflated) {
8695 MonoMethod *result;
8697 if (method->is_generic) {
8698 result = method;
8699 } else {
8700 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8702 result = imethod->declaring;
8703 if (imethod->context.class_inst) {
8704 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8705 /*Generic methods gets the context of the GTD.*/
8706 if (mono_class_get_context (klass)) {
8707 ERROR_DECL (error);
8708 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8709 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8714 buffer_add_methodid (buf, domain, result);
8715 } else {
8716 buffer_add_id (buf, 0);
8718 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8719 if (mono_method_signature_internal (method)->generic_param_count) {
8720 int count, i;
8722 if (method->is_inflated) {
8723 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8724 if (inst) {
8725 count = inst->type_argc;
8726 buffer_add_int (buf, count);
8728 for (i = 0; i < count; i++)
8729 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8730 } else {
8731 buffer_add_int (buf, 0);
8733 } else if (method->is_generic) {
8734 MonoGenericContainer *container = mono_method_get_generic_container (method);
8736 count = mono_method_signature_internal (method)->generic_param_count;
8737 buffer_add_int (buf, count);
8738 for (i = 0; i < count; i++) {
8739 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8740 MonoClass *pklass = mono_class_create_generic_parameter (param);
8741 buffer_add_typeid (buf, domain, pklass);
8743 } else {
8744 buffer_add_int (buf, 0);
8746 } else {
8747 buffer_add_int (buf, 0);
8751 break;
8752 case CMD_METHOD_GET_BODY: {
8753 ERROR_DECL (error);
8754 int i;
8756 header = mono_method_get_header_checked (method, error);
8757 if (!header) {
8758 mono_error_cleanup (error); /* FIXME don't swallow the error */
8759 buffer_add_int (buf, 0);
8761 if (CHECK_PROTOCOL_VERSION (2, 18))
8762 buffer_add_int (buf, 0);
8763 } else {
8764 buffer_add_int (buf, header->code_size);
8765 for (i = 0; i < header->code_size; ++i)
8766 buffer_add_byte (buf, header->code [i]);
8768 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8769 buffer_add_int (buf, header->num_clauses);
8770 for (i = 0; i < header->num_clauses; ++i) {
8771 MonoExceptionClause *clause = &header->clauses [i];
8773 buffer_add_int (buf, clause->flags);
8774 buffer_add_int (buf, clause->try_offset);
8775 buffer_add_int (buf, clause->try_len);
8776 buffer_add_int (buf, clause->handler_offset);
8777 buffer_add_int (buf, clause->handler_len);
8778 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8779 buffer_add_typeid (buf, domain, clause->data.catch_class);
8780 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8781 buffer_add_int (buf, clause->data.filter_offset);
8785 mono_metadata_free_mh (header);
8788 break;
8790 case CMD_METHOD_RESOLVE_TOKEN: {
8791 guint32 token = decode_int (p, &p, end);
8793 // FIXME: Generics
8794 switch (mono_metadata_token_code (token)) {
8795 case MONO_TOKEN_STRING: {
8796 ERROR_DECL (error);
8797 MonoString *s;
8798 char *s2;
8800 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8801 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8803 s2 = mono_string_to_utf8_checked_internal (s, error);
8804 mono_error_assert_ok (error);
8806 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8807 buffer_add_string (buf, s2);
8808 g_free (s2);
8809 break;
8811 default: {
8812 ERROR_DECL (error);
8813 gpointer val;
8814 MonoClass *handle_class;
8816 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8817 val = mono_method_get_wrapper_data (method, token);
8818 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8820 if (handle_class == NULL) {
8821 // Can't figure out the token type
8822 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8823 break;
8825 } else {
8826 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8827 if (!val)
8828 g_error ("Could not load token due to %s", mono_error_get_message (error));
8831 if (handle_class == mono_defaults.typehandle_class) {
8832 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8833 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8834 buffer_add_typeid (buf, domain, (MonoClass *) val);
8835 else
8836 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8837 } else if (handle_class == mono_defaults.fieldhandle_class) {
8838 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8839 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8840 } else if (handle_class == mono_defaults.methodhandle_class) {
8841 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8842 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8843 } else if (handle_class == mono_defaults.string_class) {
8844 char *s;
8846 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8847 mono_error_assert_ok (error);
8848 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8849 buffer_add_string (buf, s);
8850 g_free (s);
8851 } else {
8852 g_assert_not_reached ();
8854 break;
8857 break;
8859 case CMD_METHOD_GET_CATTRS: {
8860 ERROR_DECL (error);
8861 MonoClass *attr_klass;
8862 MonoCustomAttrInfo *cinfo;
8864 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8865 /* attr_klass can be NULL */
8866 if (err != ERR_NONE)
8867 return err;
8869 cinfo = mono_custom_attrs_from_method_checked (method, error);
8870 if (!is_ok (error)) {
8871 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8872 return ERR_LOADER_ERROR;
8875 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
8876 if (err != ERR_NONE)
8877 return err;
8878 break;
8880 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8881 ERROR_DECL (error);
8882 MonoType **type_argv;
8883 int i, type_argc;
8884 MonoDomain *d;
8885 MonoClass *klass;
8886 MonoGenericInst *ginst;
8887 MonoGenericContext tmp_context;
8888 MonoMethod *inflated;
8890 type_argc = decode_int (p, &p, end);
8891 type_argv = g_new0 (MonoType*, type_argc);
8892 for (i = 0; i < type_argc; ++i) {
8893 klass = decode_typeid (p, &p, end, &d, &err);
8894 if (err != ERR_NONE) {
8895 g_free (type_argv);
8896 return err;
8898 if (domain != d) {
8899 g_free (type_argv);
8900 return ERR_INVALID_ARGUMENT;
8902 type_argv [i] = m_class_get_byval_arg (klass);
8904 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8905 g_free (type_argv);
8906 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8907 tmp_context.method_inst = ginst;
8909 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
8910 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8911 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8912 return ERR_INVALID_ARGUMENT;
8913 buffer_add_methodid (buf, domain, inflated);
8914 break;
8916 default:
8917 return ERR_NOT_IMPLEMENTED;
8920 return ERR_NONE;
8923 static ErrorCode
8924 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8926 ErrorCode err;
8927 MonoDomain *old_domain;
8928 MonoDomain *domain;
8929 MonoMethod *method;
8931 method = decode_methodid (p, &p, end, &domain, &err);
8932 if (err != ERR_NONE)
8933 return err;
8935 old_domain = mono_domain_get ();
8937 mono_domain_set_fast (domain, TRUE);
8939 err = method_commands_internal (command, method, domain, p, end, buf);
8941 mono_domain_set_fast (old_domain, TRUE);
8943 return err;
8946 static ErrorCode
8947 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8949 int objid = decode_objid (p, &p, end);
8950 ErrorCode err;
8951 MonoThread *thread_obj;
8952 MonoInternalThread *thread;
8954 err = get_object (objid, (MonoObject**)&thread_obj);
8955 if (err != ERR_NONE)
8956 return err;
8958 thread = THREAD_TO_INTERNAL (thread_obj);
8960 switch (command) {
8961 case CMD_THREAD_GET_NAME: {
8962 char *s = mono_thread_get_name_utf8 (thread_obj);
8964 if (!s) {
8965 buffer_add_int (buf, 0);
8966 } else {
8967 const size_t len = strlen (s);
8968 buffer_add_int (buf, len);
8969 buffer_add_data (buf, (guint8*)s, len);
8970 g_free (s);
8972 break;
8974 case CMD_THREAD_GET_FRAME_INFO: {
8975 DebuggerTlsData *tls;
8976 int i, start_frame, length;
8978 // Wait for suspending if it already started
8979 // FIXME: Races with suspend_count
8980 while (!is_suspended ()) {
8981 if (suspend_count)
8982 wait_for_suspend ();
8985 if (suspend_count)
8986 wait_for_suspend ();
8987 if (!is_suspended ())
8988 return ERR_NOT_SUSPENDED;
8991 start_frame = decode_int (p, &p, end);
8992 length = decode_int (p, &p, end);
8994 if (start_frame != 0 || length != -1)
8995 return ERR_NOT_IMPLEMENTED;
8997 mono_loader_lock ();
8998 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8999 mono_loader_unlock ();
9000 g_assert (tls);
9002 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
9004 buffer_add_int (buf, tls->frame_count);
9005 for (i = 0; i < tls->frame_count; ++i) {
9006 buffer_add_int (buf, tls->frames [i]->id);
9007 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
9008 buffer_add_int (buf, tls->frames [i]->il_offset);
9010 * Instead of passing the frame type directly to the client, we associate
9011 * it with the previous frame using a set of flags. This avoids lots of
9012 * conditional code in the client, since a frame whose type isn't
9013 * FRAME_TYPE_MANAGED has no method, location, etc.
9015 buffer_add_byte (buf, tls->frames [i]->flags);
9018 break;
9020 case CMD_THREAD_GET_STATE:
9021 buffer_add_int (buf, thread->state);
9022 break;
9023 case CMD_THREAD_GET_INFO:
9024 buffer_add_byte (buf, thread->threadpool_thread);
9025 break;
9026 case CMD_THREAD_GET_ID:
9027 buffer_add_long (buf, (guint64)(gsize)thread);
9028 break;
9029 case CMD_THREAD_GET_TID:
9030 buffer_add_long (buf, (guint64)thread->tid);
9031 break;
9032 case CMD_THREAD_SET_IP: {
9033 DebuggerTlsData *tls;
9034 MonoMethod *method;
9035 MonoDomain *domain;
9036 MonoSeqPointInfo *seq_points;
9037 SeqPoint sp;
9038 gboolean found_sp;
9039 gint64 il_offset;
9041 method = decode_methodid (p, &p, end, &domain, &err);
9042 if (err != ERR_NONE)
9043 return err;
9044 il_offset = decode_long (p, &p, end);
9046 while (!is_suspended ()) {
9047 if (suspend_count)
9048 wait_for_suspend ();
9051 mono_loader_lock ();
9052 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9053 mono_loader_unlock ();
9054 g_assert (tls);
9056 compute_frame_info (thread, tls, FALSE);
9057 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9058 return ERR_INVALID_ARGUMENT;
9060 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9062 g_assert (seq_points);
9064 if (!found_sp)
9065 return ERR_INVALID_ARGUMENT;
9067 // FIXME: Check that the ip change is safe
9069 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);
9071 if (tls->frames [0]->de.ji->is_interp) {
9072 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
9073 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);
9074 } else {
9075 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9077 break;
9079 case CMD_THREAD_ELAPSED_TIME: {
9080 DebuggerTlsData *tls;
9081 mono_loader_lock ();
9082 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9083 mono_loader_unlock ();
9084 g_assert (tls);
9085 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9086 break;
9088 default:
9089 return ERR_NOT_IMPLEMENTED;
9092 return ERR_NONE;
9095 static ErrorCode
9096 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9098 int objid;
9099 ErrorCode err;
9100 MonoThread *thread_obj;
9101 MonoInternalThread *thread;
9102 int pos, i, len, frame_idx;
9103 DebuggerTlsData *tls;
9104 StackFrame *frame;
9105 MonoDebugMethodJitInfo *jit;
9106 MonoMethodSignature *sig;
9107 gssize id;
9108 MonoMethodHeader *header;
9110 objid = decode_objid (p, &p, end);
9111 err = get_object (objid, (MonoObject**)&thread_obj);
9112 if (err != ERR_NONE)
9113 return err;
9115 thread = THREAD_TO_INTERNAL (thread_obj);
9117 id = decode_id (p, &p, end);
9119 mono_loader_lock ();
9120 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9121 mono_loader_unlock ();
9122 g_assert (tls);
9124 for (i = 0; i < tls->frame_count; ++i) {
9125 if (tls->frames [i]->id == id)
9126 break;
9128 if (i == tls->frame_count)
9129 return ERR_INVALID_FRAMEID;
9131 /* The thread is still running native code, can't get frame variables info */
9132 if (!tls->really_suspended && !tls->async_state.valid)
9133 return ERR_NOT_SUSPENDED;
9134 frame_idx = i;
9135 frame = tls->frames [frame_idx];
9137 /* This is supported for frames without has_ctx etc. set */
9138 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9139 if (CHECK_PROTOCOL_VERSION (2, 38))
9140 buffer_add_domainid (buf, frame->de.domain);
9141 return ERR_NONE;
9144 if (!frame->has_ctx)
9145 return ERR_ABSENT_INFORMATION;
9147 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9148 return ERR_ABSENT_INFORMATION;
9150 jit = frame->jit;
9152 sig = mono_method_signature_internal (frame->actual_method);
9154 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9156 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9158 return ERR_ABSENT_INFORMATION;
9160 switch (command) {
9161 case CMD_STACK_FRAME_GET_VALUES: {
9162 ERROR_DECL (error);
9163 len = decode_int (p, &p, end);
9164 header = mono_method_get_header_checked (frame->actual_method, error);
9165 mono_error_assert_ok (error); /* FIXME report error */
9167 for (i = 0; i < len; ++i) {
9168 pos = decode_int (p, &p, end);
9170 if (pos < 0) {
9171 pos = - pos - 1;
9173 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9175 if (frame->de.ji->is_interp) {
9176 guint8 *addr;
9178 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9180 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9181 } else {
9182 g_assert (pos >= 0 && pos < jit->num_params);
9184 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9186 } else {
9187 MonoDebugLocalsInfo *locals;
9189 locals = mono_debug_lookup_locals (frame->de.method);
9190 if (locals) {
9191 g_assert (pos < locals->num_locals);
9192 pos = locals->locals [pos].index;
9193 mono_debug_free_locals (locals);
9196 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9198 if (frame->de.ji->is_interp) {
9199 guint8 *addr;
9201 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9203 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9204 } else {
9205 g_assert (pos >= 0 && pos < jit->num_locals);
9207 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9211 mono_metadata_free_mh (header);
9212 break;
9214 case CMD_STACK_FRAME_GET_THIS: {
9215 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9216 return ERR_ABSENT_INFORMATION;
9217 if (m_class_is_valuetype (frame->api_method->klass)) {
9218 if (!sig->hasthis) {
9219 MonoObject *p = NULL;
9220 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
9221 } else {
9222 if (frame->de.ji->is_interp) {
9223 guint8 *addr;
9225 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9227 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9228 } else {
9229 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9232 } else {
9233 if (!sig->hasthis) {
9234 MonoObject *p = NULL;
9235 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9236 } else {
9237 if (frame->de.ji->is_interp) {
9238 guint8 *addr;
9240 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9242 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9243 } else {
9244 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9248 break;
9250 case CMD_STACK_FRAME_SET_VALUES: {
9251 ERROR_DECL (error);
9252 guint8 *val_buf;
9253 MonoType *t;
9254 MonoDebugVarInfo *var = NULL;
9255 gboolean is_arg = FALSE;
9257 len = decode_int (p, &p, end);
9258 header = mono_method_get_header_checked (frame->actual_method, error);
9259 mono_error_assert_ok (error); /* FIXME report error */
9261 for (i = 0; i < len; ++i) {
9262 pos = decode_int (p, &p, end);
9264 if (pos < 0) {
9265 pos = - pos - 1;
9267 g_assert (pos >= 0 && pos < jit->num_params);
9269 t = sig->params [pos];
9270 var = &jit->params [pos];
9271 is_arg = TRUE;
9272 } else {
9273 MonoDebugLocalsInfo *locals;
9275 locals = mono_debug_lookup_locals (frame->de.method);
9276 if (locals) {
9277 g_assert (pos < locals->num_locals);
9278 pos = locals->locals [pos].index;
9279 mono_debug_free_locals (locals);
9281 g_assert (pos >= 0 && pos < jit->num_locals);
9283 t = header->locals [pos];
9284 var = &jit->locals [pos];
9287 if (MONO_TYPE_IS_REFERENCE (t))
9288 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9289 else
9290 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9291 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9292 if (err != ERR_NONE)
9293 return err;
9295 if (frame->de.ji->is_interp) {
9296 guint8 *addr;
9298 if (is_arg)
9299 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9300 else
9301 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9302 set_interp_var (t, addr, val_buf);
9303 } else {
9304 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9307 mono_metadata_free_mh (header);
9308 break;
9310 case CMD_STACK_FRAME_GET_DOMAIN: {
9311 if (CHECK_PROTOCOL_VERSION (2, 38))
9312 buffer_add_domainid (buf, frame->de.domain);
9313 break;
9315 case CMD_STACK_FRAME_SET_THIS: {
9316 guint8 *val_buf;
9317 MonoType *t;
9318 MonoDebugVarInfo *var;
9320 t = m_class_get_byval_arg (frame->actual_method->klass);
9321 /* Checked by the sender */
9322 g_assert (MONO_TYPE_ISSTRUCT (t));
9324 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9325 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9326 if (err != ERR_NONE)
9327 return err;
9329 if (frame->de.ji->is_interp) {
9330 guint8 *addr;
9332 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9333 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9334 } else {
9335 var = jit->this_var;
9336 g_assert (var);
9338 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);
9340 break;
9342 default:
9343 return ERR_NOT_IMPLEMENTED;
9346 return ERR_NONE;
9349 static ErrorCode
9350 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9352 MonoArray *arr;
9353 int objid, index, len, i, esize;
9354 ErrorCode err;
9355 gpointer elem;
9357 objid = decode_objid (p, &p, end);
9358 err = get_object (objid, (MonoObject**)&arr);
9359 if (err != ERR_NONE)
9360 return err;
9362 switch (command) {
9363 case CMD_ARRAY_REF_GET_LENGTH:
9364 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9365 if (!arr->bounds) {
9366 buffer_add_int (buf, arr->max_length);
9367 buffer_add_int (buf, 0);
9368 } else {
9369 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9370 buffer_add_int (buf, arr->bounds [i].length);
9371 buffer_add_int (buf, arr->bounds [i].lower_bound);
9374 break;
9375 case CMD_ARRAY_REF_GET_VALUES:
9376 index = decode_int (p, &p, end);
9377 len = decode_int (p, &p, end);
9379 g_assert (index >= 0 && len >= 0);
9380 // Reordered to avoid integer overflow
9381 g_assert (!(index > arr->max_length - len));
9383 esize = mono_array_element_size (arr->obj.vtable->klass);
9384 for (i = index; i < index + len; ++i) {
9385 elem = (gpointer*)((char*)arr->vector + (i * esize));
9386 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9388 break;
9389 case CMD_ARRAY_REF_SET_VALUES:
9390 index = decode_int (p, &p, end);
9391 len = decode_int (p, &p, end);
9393 g_assert (index >= 0 && len >= 0);
9394 // Reordered to avoid integer overflow
9395 g_assert (!(index > arr->max_length - len));
9397 esize = mono_array_element_size (arr->obj.vtable->klass);
9398 for (i = index; i < index + len; ++i) {
9399 elem = (gpointer*)((char*)arr->vector + (i * esize));
9401 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);
9403 break;
9404 default:
9405 return ERR_NOT_IMPLEMENTED;
9408 return ERR_NONE;
9411 static ErrorCode
9412 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9414 int objid;
9415 ErrorCode err;
9416 MonoString *str;
9417 char *s;
9418 int i, index, length;
9419 gunichar2 *c;
9420 gboolean use_utf16 = FALSE;
9422 objid = decode_objid (p, &p, end);
9423 err = get_object (objid, (MonoObject**)&str);
9424 if (err != ERR_NONE)
9425 return err;
9427 switch (command) {
9428 case CMD_STRING_REF_GET_VALUE:
9429 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9430 for (i = 0; i < mono_string_length_internal (str); ++i)
9431 if (mono_string_chars_internal (str)[i] == 0)
9432 use_utf16 = TRUE;
9433 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9435 if (use_utf16) {
9436 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9437 buffer_add_data (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9438 } else {
9439 ERROR_DECL (error);
9440 s = mono_string_to_utf8_checked_internal (str, error);
9441 if (!is_ok (error)) {
9442 if (s)
9443 g_free (s);
9445 return ERR_INVALID_ARGUMENT;
9447 buffer_add_string (buf, s);
9448 g_free (s);
9450 break;
9451 case CMD_STRING_REF_GET_LENGTH:
9452 buffer_add_long (buf, mono_string_length_internal (str));
9453 break;
9454 case CMD_STRING_REF_GET_CHARS:
9455 index = decode_long (p, &p, end);
9456 length = decode_long (p, &p, end);
9457 if (index > mono_string_length_internal (str) - length)
9458 return ERR_INVALID_ARGUMENT;
9459 c = mono_string_chars_internal (str) + index;
9460 for (i = 0; i < length; ++i)
9461 buffer_add_short (buf, c [i]);
9462 break;
9463 default:
9464 return ERR_NOT_IMPLEMENTED;
9467 return ERR_NONE;
9470 static ErrorCode
9471 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9473 ErrorCode err;
9474 gint64 addr;
9475 MonoClass* klass;
9476 MonoDomain* domain = NULL;
9478 switch (command) {
9479 case CMD_POINTER_GET_VALUE:
9480 addr = decode_long (p, &p, end);
9481 klass = decode_typeid (p, &p, end, &domain, &err);
9482 if (err != ERR_NONE)
9483 return err;
9485 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9486 return ERR_INVALID_ARGUMENT;
9488 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (klass)), (gpointer)addr, domain);
9490 break;
9491 default:
9492 return ERR_NOT_IMPLEMENTED;
9495 return ERR_NONE;
9498 static ErrorCode
9499 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9501 HANDLE_FUNCTION_ENTER ();
9503 ERROR_DECL (error);
9504 int objid;
9505 ErrorCode err;
9506 MonoObject *obj;
9507 int len, i;
9508 MonoClassField *f;
9509 MonoClass *k;
9510 gboolean found;
9511 gboolean remote_obj = FALSE;
9512 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
9514 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9515 objid = decode_objid (p, &p, end);
9516 err = get_object (objid, &obj);
9517 if (err != ERR_NONE)
9518 buffer_add_int (buf, 1);
9519 else
9520 buffer_add_int (buf, 0);
9521 err = ERR_NONE;
9522 goto exit;
9525 objid = decode_objid (p, &p, end);
9526 err = get_object (objid, &obj);
9527 if (err != ERR_NONE)
9528 goto exit;
9530 MonoClass *obj_type;
9532 obj_type = obj->vtable->klass;
9533 if (mono_class_is_transparent_proxy (obj_type)) {
9534 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9535 remote_obj = TRUE;
9538 g_assert (obj_type);
9540 switch (command) {
9541 case CMD_OBJECT_REF_GET_TYPE:
9542 /* This handles transparent proxies too */
9543 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9544 break;
9545 case CMD_OBJECT_REF_GET_VALUES:
9546 len = decode_int (p, &p, end);
9548 for (i = 0; i < len; ++i) {
9549 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9550 if (err != ERR_NONE)
9551 goto exit;
9553 /* Check that the field belongs to the object */
9554 found = FALSE;
9555 for (k = obj_type; k; k = m_class_get_parent (k)) {
9556 if (k == f->parent) {
9557 found = TRUE;
9558 break;
9561 if (!found)
9562 goto invalid_fieldid;
9564 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9565 guint8 *val;
9566 MonoVTable *vtable;
9568 if (mono_class_field_is_special_static (f))
9569 goto invalid_fieldid;
9571 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9572 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9573 if (!is_ok (error)) {
9574 mono_error_cleanup (error);
9575 goto invalid_object;
9577 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9578 mono_field_static_get_value_checked (vtable, f, val, string_handle, error);
9579 if (!is_ok (error)) {
9580 mono_error_cleanup (error); /* FIXME report the error */
9581 goto invalid_object;
9583 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9584 g_free (val);
9585 } else {
9586 void *field_value = NULL;
9587 #ifndef DISABLE_REMOTING
9588 void *field_storage = NULL;
9589 #endif
9590 if (remote_obj) {
9591 #ifndef DISABLE_REMOTING
9592 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9593 if (!is_ok (error)) {
9594 mono_error_cleanup (error); /* FIXME report the error */
9595 goto invalid_object;
9597 #else
9598 g_assert_not_reached ();
9599 #endif
9600 } else
9601 field_value = (guint8*)obj + f->offset;
9603 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9606 break;
9607 case CMD_OBJECT_REF_SET_VALUES:
9608 len = decode_int (p, &p, end);
9610 for (i = 0; i < len; ++i) {
9611 f = decode_fieldid (p, &p, end, NULL, &err);
9612 if (err != ERR_NONE)
9613 goto exit;
9615 /* Check that the field belongs to the object */
9616 found = FALSE;
9617 for (k = obj_type; k; k = m_class_get_parent (k)) {
9618 if (k == f->parent) {
9619 found = TRUE;
9620 break;
9623 if (!found)
9624 goto invalid_fieldid;
9626 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9627 guint8 *val;
9628 MonoVTable *vtable;
9630 if (mono_class_field_is_special_static (f))
9631 goto invalid_fieldid;
9633 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9634 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9635 if (!is_ok (error)) {
9636 mono_error_cleanup (error);
9637 goto invalid_fieldid;
9640 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9641 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9642 if (err != ERR_NONE) {
9643 g_free (val);
9644 goto exit;
9646 mono_field_static_set_value_internal (vtable, f, val);
9647 g_free (val);
9648 } else {
9649 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9650 if (err != ERR_NONE)
9651 goto exit;
9654 break;
9655 case CMD_OBJECT_REF_GET_ADDRESS:
9656 buffer_add_long (buf, (gssize)obj);
9657 break;
9658 case CMD_OBJECT_REF_GET_DOMAIN:
9659 buffer_add_domainid (buf, obj->vtable->domain);
9660 break;
9661 case CMD_OBJECT_REF_GET_INFO:
9662 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9663 buffer_add_domainid (buf, obj->vtable->domain);
9664 break;
9665 default:
9666 err = ERR_NOT_IMPLEMENTED;
9667 goto exit;
9670 err = ERR_NONE;
9671 goto exit;
9672 invalid_fieldid:
9673 err = ERR_INVALID_FIELDID;
9674 goto exit;
9675 invalid_object:
9676 err = ERR_INVALID_OBJECT;
9677 goto exit;
9678 exit:
9679 HANDLE_FUNCTION_RETURN_VAL (err);
9682 static const char*
9683 command_set_to_string (CommandSet command_set)
9685 switch (command_set) {
9686 case CMD_SET_VM:
9687 return "VM";
9688 case CMD_SET_OBJECT_REF:
9689 return "OBJECT_REF";
9690 case CMD_SET_STRING_REF:
9691 return "STRING_REF";
9692 case CMD_SET_THREAD:
9693 return "THREAD";
9694 case CMD_SET_ARRAY_REF:
9695 return "ARRAY_REF";
9696 case CMD_SET_EVENT_REQUEST:
9697 return "EVENT_REQUEST";
9698 case CMD_SET_STACK_FRAME:
9699 return "STACK_FRAME";
9700 case CMD_SET_APPDOMAIN:
9701 return "APPDOMAIN";
9702 case CMD_SET_ASSEMBLY:
9703 return "ASSEMBLY";
9704 case CMD_SET_METHOD:
9705 return "METHOD";
9706 case CMD_SET_TYPE:
9707 return "TYPE";
9708 case CMD_SET_MODULE:
9709 return "MODULE";
9710 case CMD_SET_FIELD:
9711 return "FIELD";
9712 case CMD_SET_EVENT:
9713 return "EVENT";
9714 case CMD_SET_POINTER:
9715 return "POINTER";
9716 default:
9717 return "";
9721 static const char* vm_cmds_str [] = {
9722 "VERSION",
9723 "ALL_THREADS",
9724 "SUSPEND",
9725 "RESUME",
9726 "EXIT",
9727 "DISPOSE",
9728 "INVOKE_METHOD",
9729 "SET_PROTOCOL_VERSION",
9730 "ABORT_INVOKE",
9731 "SET_KEEPALIVE"
9732 "GET_TYPES_FOR_SOURCE_FILE",
9733 "GET_TYPES",
9734 "INVOKE_METHODS"
9737 static const char* thread_cmds_str[] = {
9738 "GET_FRAME_INFO",
9739 "GET_NAME",
9740 "GET_STATE",
9741 "GET_INFO",
9742 "GET_ID",
9743 "GET_TID",
9744 "SET_IP"
9747 static const char* event_cmds_str[] = {
9748 "REQUEST_SET",
9749 "REQUEST_CLEAR",
9750 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9753 static const char* appdomain_cmds_str[] = {
9754 "GET_ROOT_DOMAIN",
9755 "GET_FRIENDLY_NAME",
9756 "GET_ASSEMBLIES",
9757 "GET_ENTRY_ASSEMBLY",
9758 "CREATE_STRING",
9759 "GET_CORLIB",
9760 "CREATE_BOXED_VALUE",
9761 "CREATE_BYTE_ARRAY",
9764 static const char* assembly_cmds_str[] = {
9765 "GET_LOCATION",
9766 "GET_ENTRY_POINT",
9767 "GET_MANIFEST_MODULE",
9768 "GET_OBJECT",
9769 "GET_TYPE",
9770 "GET_NAME",
9771 "GET_DOMAIN",
9772 "HAS_DEBUG_INFO"
9775 static const char* module_cmds_str[] = {
9776 "GET_INFO",
9779 static const char* field_cmds_str[] = {
9780 "GET_INFO",
9783 static const char* method_cmds_str[] = {
9784 "GET_NAME",
9785 "GET_DECLARING_TYPE",
9786 "GET_DEBUG_INFO",
9787 "GET_PARAM_INFO",
9788 "GET_LOCALS_INFO",
9789 "GET_INFO",
9790 "GET_BODY",
9791 "RESOLVE_TOKEN",
9792 "GET_CATTRS ",
9793 "MAKE_GENERIC_METHOD"
9796 static const char* type_cmds_str[] = {
9797 "GET_INFO",
9798 "GET_METHODS",
9799 "GET_FIELDS",
9800 "GET_VALUES",
9801 "GET_OBJECT",
9802 "GET_SOURCE_FILES",
9803 "SET_VALUES",
9804 "IS_ASSIGNABLE_FROM",
9805 "GET_PROPERTIES ",
9806 "GET_CATTRS",
9807 "GET_FIELD_CATTRS",
9808 "GET_PROPERTY_CATTRS",
9809 "GET_SOURCE_FILES_2",
9810 "GET_VALUES_2",
9811 "GET_METHODS_BY_NAME_FLAGS",
9812 "GET_INTERFACES",
9813 "GET_INTERFACE_MAP",
9814 "IS_INITIALIZED",
9815 "CREATE_INSTANCE",
9816 "GET_VALUE_SIZE"
9819 static const char* stack_frame_cmds_str[] = {
9820 "GET_VALUES",
9821 "GET_THIS",
9822 "SET_VALUES",
9823 "GET_DOMAIN",
9824 "SET_THIS"
9827 static const char* array_cmds_str[] = {
9828 "GET_LENGTH",
9829 "GET_VALUES",
9830 "SET_VALUES",
9833 static const char* string_cmds_str[] = {
9834 "GET_VALUE",
9835 "GET_LENGTH",
9836 "GET_CHARS"
9839 static const char* pointer_cmds_str[] = {
9840 "GET_VALUE"
9843 static const char* object_cmds_str[] = {
9844 "GET_TYPE",
9845 "GET_VALUES",
9846 "IS_COLLECTED",
9847 "GET_ADDRESS",
9848 "GET_DOMAIN",
9849 "SET_VALUES",
9850 "GET_INFO",
9853 static const char*
9854 cmd_to_string (CommandSet set, int command)
9856 const char **cmds;
9857 int cmds_len = 0;
9859 switch (set) {
9860 case CMD_SET_VM:
9861 cmds = vm_cmds_str;
9862 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9863 break;
9864 case CMD_SET_OBJECT_REF:
9865 cmds = object_cmds_str;
9866 cmds_len = G_N_ELEMENTS (object_cmds_str);
9867 break;
9868 case CMD_SET_STRING_REF:
9869 cmds = string_cmds_str;
9870 cmds_len = G_N_ELEMENTS (string_cmds_str);
9871 break;
9872 case CMD_SET_THREAD:
9873 cmds = thread_cmds_str;
9874 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9875 break;
9876 case CMD_SET_ARRAY_REF:
9877 cmds = array_cmds_str;
9878 cmds_len = G_N_ELEMENTS (array_cmds_str);
9879 break;
9880 case CMD_SET_EVENT_REQUEST:
9881 cmds = event_cmds_str;
9882 cmds_len = G_N_ELEMENTS (event_cmds_str);
9883 break;
9884 case CMD_SET_STACK_FRAME:
9885 cmds = stack_frame_cmds_str;
9886 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9887 break;
9888 case CMD_SET_APPDOMAIN:
9889 cmds = appdomain_cmds_str;
9890 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9891 break;
9892 case CMD_SET_ASSEMBLY:
9893 cmds = assembly_cmds_str;
9894 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9895 break;
9896 case CMD_SET_METHOD:
9897 cmds = method_cmds_str;
9898 cmds_len = G_N_ELEMENTS (method_cmds_str);
9899 break;
9900 case CMD_SET_TYPE:
9901 cmds = type_cmds_str;
9902 cmds_len = G_N_ELEMENTS (type_cmds_str);
9903 break;
9904 case CMD_SET_MODULE:
9905 cmds = module_cmds_str;
9906 cmds_len = G_N_ELEMENTS (module_cmds_str);
9907 break;
9908 case CMD_SET_FIELD:
9909 cmds = field_cmds_str;
9910 cmds_len = G_N_ELEMENTS (field_cmds_str);
9911 break;
9912 case CMD_SET_EVENT:
9913 cmds = event_cmds_str;
9914 cmds_len = G_N_ELEMENTS (event_cmds_str);
9915 break;
9916 case CMD_SET_POINTER:
9917 cmds = pointer_cmds_str;
9918 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
9919 break;
9920 default:
9921 return NULL;
9923 if (command > 0 && command <= cmds_len)
9924 return cmds [command - 1];
9925 else
9926 return NULL;
9929 static gboolean
9930 wait_for_attach (void)
9932 #ifndef DISABLE_SOCKET_TRANSPORT
9933 if (listen_fd == -1) {
9934 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9935 return FALSE;
9938 /* Block and wait for client connection */
9939 conn_fd = socket_transport_accept (listen_fd);
9941 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9942 if (conn_fd == -1) {
9943 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9944 return FALSE;
9946 #else
9947 g_assert_not_reached ();
9948 #endif
9950 /* Handshake */
9951 disconnected = !transport_handshake ();
9952 if (disconnected) {
9953 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9954 return FALSE;
9957 return TRUE;
9961 * debugger_thread:
9963 * This thread handles communication with the debugger client using a JDWP
9964 * like protocol.
9966 static gsize WINAPI
9967 debugger_thread (void *arg)
9969 int res, len, id, flags, command = 0;
9970 CommandSet command_set = (CommandSet)0;
9971 guint8 header [HEADER_LENGTH];
9972 guint8 *data, *p, *end;
9973 Buffer buf;
9974 ErrorCode err;
9975 gboolean no_reply;
9976 gboolean attach_failed = FALSE;
9978 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9980 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
9982 debugger_thread_id = mono_native_thread_id_get ();
9984 MonoInternalThread *internal = mono_thread_internal_current ();
9985 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
9987 internal->state |= ThreadState_Background;
9988 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9990 if (agent_config.defer) {
9991 if (!wait_for_attach ()) {
9992 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9993 attach_failed = TRUE; // Don't abort process when we can't listen
9994 } else {
9995 mono_set_is_debugger_attached (TRUE);
9996 /* Send start event to client */
9997 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9999 } else {
10000 mono_set_is_debugger_attached (TRUE);
10003 while (!attach_failed) {
10004 res = transport_recv (header, HEADER_LENGTH);
10006 /* This will break if the socket is closed during shutdown too */
10007 if (res != HEADER_LENGTH) {
10008 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10009 command_set = (CommandSet)0;
10010 command = 0;
10011 dispose_vm ();
10012 break;
10013 } else {
10014 p = header;
10015 end = header + HEADER_LENGTH;
10017 len = decode_int (p, &p, end);
10018 id = decode_int (p, &p, end);
10019 flags = decode_byte (p, &p, end);
10020 command_set = (CommandSet)decode_byte (p, &p, end);
10021 command = decode_byte (p, &p, end);
10024 g_assert (flags == 0);
10025 const char *cmd_str;
10026 char cmd_num [256];
10028 cmd_str = cmd_to_string (command_set, command);
10029 if (!cmd_str) {
10030 sprintf (cmd_num, "%d", command);
10031 cmd_str = cmd_num;
10034 if (log_level) {
10035 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);
10038 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10039 if (len - HEADER_LENGTH > 0)
10041 res = transport_recv (data, len - HEADER_LENGTH);
10042 if (res != len - HEADER_LENGTH) {
10043 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10044 break;
10048 p = data;
10049 end = data + (len - HEADER_LENGTH);
10051 buffer_init (&buf, 128);
10053 err = ERR_NONE;
10054 no_reply = FALSE;
10056 /* Process the request */
10057 switch (command_set) {
10058 case CMD_SET_VM:
10059 err = vm_commands (command, id, p, end, &buf);
10060 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10061 /* Sent after the invoke is complete */
10062 no_reply = TRUE;
10063 break;
10064 case CMD_SET_EVENT_REQUEST:
10065 err = event_commands (command, p, end, &buf);
10066 break;
10067 case CMD_SET_APPDOMAIN:
10068 err = domain_commands (command, p, end, &buf);
10069 break;
10070 case CMD_SET_ASSEMBLY:
10071 err = assembly_commands (command, p, end, &buf);
10072 break;
10073 case CMD_SET_MODULE:
10074 err = module_commands (command, p, end, &buf);
10075 break;
10076 case CMD_SET_FIELD:
10077 err = field_commands (command, p, end, &buf);
10078 break;
10079 case CMD_SET_TYPE:
10080 err = type_commands (command, p, end, &buf);
10081 break;
10082 case CMD_SET_METHOD:
10083 err = method_commands (command, p, end, &buf);
10084 break;
10085 case CMD_SET_THREAD:
10086 err = thread_commands (command, p, end, &buf);
10087 break;
10088 case CMD_SET_STACK_FRAME:
10089 err = frame_commands (command, p, end, &buf);
10090 break;
10091 case CMD_SET_ARRAY_REF:
10092 err = array_commands (command, p, end, &buf);
10093 break;
10094 case CMD_SET_STRING_REF:
10095 err = string_commands (command, p, end, &buf);
10096 break;
10097 case CMD_SET_POINTER:
10098 err = pointer_commands (command, p, end, &buf);
10099 break;
10100 case CMD_SET_OBJECT_REF:
10101 err = object_commands (command, p, end, &buf);
10102 break;
10103 default:
10104 err = ERR_NOT_IMPLEMENTED;
10107 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10108 buffer_replies = TRUE;
10111 if (!no_reply) {
10112 if (buffer_replies) {
10113 buffer_reply_packet (id, err, &buf);
10114 } else {
10115 send_reply_packet (id, err, &buf);
10116 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10120 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10122 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10123 send_buffered_reply_packets ();
10124 buffer_replies = FALSE;
10127 g_free (data);
10128 buffer_free (&buf);
10130 if (log_each_step) {
10131 char *debugger_log = mono_debugger_state_str ();
10132 if (debugger_log) {
10133 fprintf (stderr, "Debugger state: %s\n", debugger_log);
10134 g_free (debugger_log);
10138 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10139 break;
10142 mono_set_is_debugger_attached (FALSE);
10144 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10145 debugger_thread_exited = TRUE;
10146 mono_coop_cond_signal (&debugger_thread_exited_cond);
10147 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10149 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10151 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10152 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10153 ERROR_DECL (error);
10154 start_debugger_thread (error);
10155 mono_error_cleanup (error);
10158 return 0;
10161 void
10162 mono_debugger_agent_init (void)
10164 MonoDebuggerCallbacks cbs;
10166 memset (&cbs, 0, sizeof (MonoDebuggerCallbacks));
10167 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10168 cbs.parse_options = debugger_agent_parse_options;
10169 cbs.init = debugger_agent_init;
10170 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10171 cbs.single_step_event = debugger_agent_single_step_event;
10172 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10173 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10174 cbs.free_domain_info = debugger_agent_free_domain_info;
10175 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10176 cbs.handle_exception = debugger_agent_handle_exception;
10177 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10178 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10179 cbs.user_break = debugger_agent_user_break;
10180 cbs.debug_log = debugger_agent_debug_log;
10181 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10182 cbs.send_crash = mono_debugger_agent_send_crash;
10184 mini_install_dbg_callbacks (&cbs);
10187 void
10188 mono_debugger_agent_parse_options (char *options)
10190 sdb_options = options;
10193 #endif /* DISABLE_SDB */