[image] Create MonoImageStorage to own the image raw data (#13892)
[mono-project.git] / mono / mini / debugger-agent.c
blob8c123adac9c088f228a25e1f9d40a54c165b1d43
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/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/assembly-internals.h>
64 #include <mono/metadata/runtime.h>
65 #include <mono/metadata/verify-internals.h>
66 #include <mono/metadata/reflection-internals.h>
67 #include <mono/metadata/w32socket.h>
68 #include <mono/utils/mono-coop-mutex.h>
69 #include <mono/utils/mono-coop-semaphore.h>
70 #include <mono/utils/mono-error-internals.h>
71 #include <mono/utils/mono-stack-unwinding.h>
72 #include <mono/utils/mono-time.h>
73 #include <mono/utils/mono-threads.h>
74 #include <mono/utils/networking.h>
75 #include <mono/utils/mono-proclib.h>
76 #include <mono/utils/w32api.h>
77 #include "debugger-state-machine.h"
78 #include "debugger-agent.h"
79 #include "mini.h"
80 #include "seq-points.h"
81 #include "aot-runtime.h"
82 #include "mini-runtime.h"
83 #include "interp/interp.h"
84 #include "debugger-engine.h"
85 #include "mono/metadata/debug-mono-ppdb.h"
88 * On iOS we can't use System.Environment.Exit () as it will do the wrong
89 * shutdown sequence.
91 #if !defined (TARGET_IOS)
92 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
93 #endif
95 #ifndef DISABLE_SDB
97 #include <mono/utils/mono-os-mutex.h>
99 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
101 typedef struct {
102 gboolean enabled;
103 char *transport;
104 char *address;
105 int log_level;
106 char *log_file;
107 gboolean suspend;
108 gboolean server;
109 gboolean onuncaught;
110 GSList *onthrow;
111 int timeout;
112 char *launch;
113 gboolean embedding;
114 gboolean defer;
115 int keepalive;
116 gboolean setpgid;
117 } AgentConfig;
119 typedef struct
121 //Must be the first field to ensure pointer equivalence
122 DbgEngineStackFrame de;
123 int id;
124 guint32 il_offset;
126 * If method is gshared, this is the actual instance, otherwise this is equal to
127 * method.
129 MonoMethod *actual_method;
131 * This is the method which is visible to debugger clients. Same as method,
132 * except for native-to-managed wrappers.
134 MonoMethod *api_method;
135 MonoContext ctx;
136 MonoDebugMethodJitInfo *jit;
137 MonoInterpFrameHandle interp_frame;
138 gpointer frame_addr;
139 int flags;
140 host_mgreg_t *reg_locations [MONO_MAX_IREGS];
142 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
143 * the frame can become invalid.
145 gboolean has_ctx;
146 } StackFrame;
148 typedef struct _InvokeData InvokeData;
150 struct _InvokeData
152 int id;
153 int flags;
154 guint8 *p;
155 guint8 *endp;
156 /* This is the context which needs to be restored after the invoke */
157 MonoContext ctx;
158 gboolean has_ctx;
160 * If this is set, invoke this method with the arguments given by ARGS.
162 MonoMethod *method;
163 gpointer *args;
164 guint32 suspend_count;
165 int nmethods;
167 InvokeData *last_invoke;
170 struct _DebuggerTlsData {
171 MonoThreadUnwindState context;
173 /* This is computed on demand when it is requested using the wire protocol */
174 /* It is freed up when the thread is resumed */
175 int frame_count;
176 StackFrame **frames;
178 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
179 * re-compute it.
181 gboolean frames_up_to_date;
183 * Points to data about a pending invoke which needs to be executed after the thread
184 * resumes.
186 InvokeData *pending_invoke;
188 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
189 * native code.
191 gboolean suspended;
193 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
194 * within a finite amount of time.
196 gboolean suspending;
198 * Set to TRUE if this thread is suspended in suspend_current ().
200 gboolean really_suspended;
201 /* Used to pass the context to the breakpoint/single step handler */
202 MonoContext handler_ctx;
203 /* Whenever thread_stop () was called for this thread */
204 gboolean terminated;
206 /* Whenever to disable breakpoints (used during invokes) */
207 gboolean disable_breakpoints;
210 * Number of times this thread has been resumed using resume_thread ().
212 guint32 resume_count;
214 MonoInternalThread *thread;
215 intptr_t thread_id;
218 * Information about the frame which transitioned to native code for running
219 * threads.
221 StackFrameInfo async_last_frame;
224 * The context where the stack walk can be started for running threads.
226 MonoThreadUnwindState async_state;
229 * The context used for filter clauses
231 MonoThreadUnwindState filter_state;
233 gboolean abort_requested;
236 * The current mono_runtime_invoke_checked invocation.
238 InvokeData *invoke;
240 StackFrameInfo catch_frame;
241 gboolean has_catch_frame;
244 * The context which needs to be restored after handling a single step/breakpoint
245 * event. This is the same as the ctx at step/breakpoint site, but includes changes
246 * to caller saved registers done by set_var ().
248 MonoThreadUnwindState restore_state;
249 /* Frames computed from restore_state */
250 int restore_frame_count;
251 StackFrame **restore_frames;
253 /* The currently unloading appdomain */
254 MonoDomain *domain_unloading;
256 // The state that the debugger expects the thread to be in
257 MonoDebuggerThreadState thread_state;
258 MonoStopwatch step_time;
261 typedef struct {
262 const char *name;
263 void (*connect) (const char *address);
264 void (*close1) (void);
265 void (*close2) (void);
266 gboolean (*send) (void *buf, int len);
267 int (*recv) (void *buf, int len);
268 } DebuggerTransport;
271 * Wire Protocol definitions
274 #define HEADER_LENGTH 11
276 #define MAJOR_VERSION 2
277 #define MINOR_VERSION 51
279 typedef enum {
280 CMD_SET_VM = 1,
281 CMD_SET_OBJECT_REF = 9,
282 CMD_SET_STRING_REF = 10,
283 CMD_SET_THREAD = 11,
284 CMD_SET_ARRAY_REF = 13,
285 CMD_SET_EVENT_REQUEST = 15,
286 CMD_SET_STACK_FRAME = 16,
287 CMD_SET_APPDOMAIN = 20,
288 CMD_SET_ASSEMBLY = 21,
289 CMD_SET_METHOD = 22,
290 CMD_SET_TYPE = 23,
291 CMD_SET_MODULE = 24,
292 CMD_SET_FIELD = 25,
293 CMD_SET_EVENT = 64,
294 CMD_SET_POINTER = 65
295 } CommandSet;
297 typedef enum {
298 SUSPEND_POLICY_NONE = 0,
299 SUSPEND_POLICY_EVENT_THREAD = 1,
300 SUSPEND_POLICY_ALL = 2
301 } SuspendPolicy;
303 typedef enum {
304 ERR_NONE = 0,
305 ERR_INVALID_OBJECT = 20,
306 ERR_INVALID_FIELDID = 25,
307 ERR_INVALID_FRAMEID = 30,
308 ERR_NOT_IMPLEMENTED = 100,
309 ERR_NOT_SUSPENDED = 101,
310 ERR_INVALID_ARGUMENT = 102,
311 ERR_UNLOADED = 103,
312 ERR_NO_INVOCATION = 104,
313 ERR_ABSENT_INFORMATION = 105,
314 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
315 ERR_INVOKE_ABORTED = 107,
316 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
317 } ErrorCode;
319 typedef enum {
320 TOKEN_TYPE_STRING = 0,
321 TOKEN_TYPE_TYPE = 1,
322 TOKEN_TYPE_FIELD = 2,
323 TOKEN_TYPE_METHOD = 3,
324 TOKEN_TYPE_UNKNOWN = 4
325 } DebuggerTokenType;
327 typedef enum {
328 VALUE_TYPE_ID_NULL = 0xf0,
329 VALUE_TYPE_ID_TYPE = 0xf1,
330 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
331 } ValueTypeId;
333 typedef enum {
334 FRAME_FLAG_DEBUGGER_INVOKE = 1,
335 FRAME_FLAG_NATIVE_TRANSITION = 2
336 } StackFrameFlags;
338 typedef enum {
339 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
340 INVOKE_FLAG_SINGLE_THREADED = 2,
341 INVOKE_FLAG_RETURN_OUT_THIS = 4,
342 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
343 INVOKE_FLAG_VIRTUAL = 16
344 } InvokeFlags;
346 typedef enum {
347 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
348 } BindingFlagsExtensions;
350 typedef enum {
351 CMD_VM_VERSION = 1,
352 CMD_VM_ALL_THREADS = 2,
353 CMD_VM_SUSPEND = 3,
354 CMD_VM_RESUME = 4,
355 CMD_VM_EXIT = 5,
356 CMD_VM_DISPOSE = 6,
357 CMD_VM_INVOKE_METHOD = 7,
358 CMD_VM_SET_PROTOCOL_VERSION = 8,
359 CMD_VM_ABORT_INVOKE = 9,
360 CMD_VM_SET_KEEPALIVE = 10,
361 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
362 CMD_VM_GET_TYPES = 12,
363 CMD_VM_INVOKE_METHODS = 13,
364 CMD_VM_START_BUFFERING = 14,
365 CMD_VM_STOP_BUFFERING = 15
366 } CmdVM;
368 typedef enum {
369 CMD_THREAD_GET_FRAME_INFO = 1,
370 CMD_THREAD_GET_NAME = 2,
371 CMD_THREAD_GET_STATE = 3,
372 CMD_THREAD_GET_INFO = 4,
373 CMD_THREAD_GET_ID = 5,
374 CMD_THREAD_GET_TID = 6,
375 CMD_THREAD_SET_IP = 7,
376 CMD_THREAD_ELAPSED_TIME = 8
377 } CmdThread;
379 typedef enum {
380 CMD_EVENT_REQUEST_SET = 1,
381 CMD_EVENT_REQUEST_CLEAR = 2,
382 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
383 } CmdEvent;
385 typedef enum {
386 CMD_COMPOSITE = 100
387 } CmdComposite;
389 typedef enum {
390 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
391 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
392 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
393 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
394 CMD_APPDOMAIN_CREATE_STRING = 5,
395 CMD_APPDOMAIN_GET_CORLIB = 6,
396 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
397 } CmdAppDomain;
399 typedef enum {
400 CMD_ASSEMBLY_GET_LOCATION = 1,
401 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
402 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
403 CMD_ASSEMBLY_GET_OBJECT = 4,
404 CMD_ASSEMBLY_GET_TYPE = 5,
405 CMD_ASSEMBLY_GET_NAME = 6,
406 CMD_ASSEMBLY_GET_DOMAIN = 7,
407 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
408 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
409 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
410 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
411 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
412 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13
413 } CmdAssembly;
415 typedef enum {
416 CMD_MODULE_GET_INFO = 1,
417 } CmdModule;
419 typedef enum {
420 CMD_FIELD_GET_INFO = 1,
421 } CmdField;
423 typedef enum {
424 CMD_METHOD_GET_NAME = 1,
425 CMD_METHOD_GET_DECLARING_TYPE = 2,
426 CMD_METHOD_GET_DEBUG_INFO = 3,
427 CMD_METHOD_GET_PARAM_INFO = 4,
428 CMD_METHOD_GET_LOCALS_INFO = 5,
429 CMD_METHOD_GET_INFO = 6,
430 CMD_METHOD_GET_BODY = 7,
431 CMD_METHOD_RESOLVE_TOKEN = 8,
432 CMD_METHOD_GET_CATTRS = 9,
433 CMD_METHOD_MAKE_GENERIC_METHOD = 10
434 } CmdMethod;
436 typedef enum {
437 CMD_TYPE_GET_INFO = 1,
438 CMD_TYPE_GET_METHODS = 2,
439 CMD_TYPE_GET_FIELDS = 3,
440 CMD_TYPE_GET_VALUES = 4,
441 CMD_TYPE_GET_OBJECT = 5,
442 CMD_TYPE_GET_SOURCE_FILES = 6,
443 CMD_TYPE_SET_VALUES = 7,
444 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
445 CMD_TYPE_GET_PROPERTIES = 9,
446 CMD_TYPE_GET_CATTRS = 10,
447 CMD_TYPE_GET_FIELD_CATTRS = 11,
448 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
449 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
450 CMD_TYPE_GET_VALUES_2 = 14,
451 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
452 CMD_TYPE_GET_INTERFACES = 16,
453 CMD_TYPE_GET_INTERFACE_MAP = 17,
454 CMD_TYPE_IS_INITIALIZED = 18,
455 CMD_TYPE_CREATE_INSTANCE = 19,
456 CMD_TYPE_GET_VALUE_SIZE = 20
457 } CmdType;
459 typedef enum {
460 CMD_STACK_FRAME_GET_VALUES = 1,
461 CMD_STACK_FRAME_GET_THIS = 2,
462 CMD_STACK_FRAME_SET_VALUES = 3,
463 CMD_STACK_FRAME_GET_DOMAIN = 4,
464 CMD_STACK_FRAME_SET_THIS = 5,
465 } CmdStackFrame;
467 typedef enum {
468 CMD_ARRAY_REF_GET_LENGTH = 1,
469 CMD_ARRAY_REF_GET_VALUES = 2,
470 CMD_ARRAY_REF_SET_VALUES = 3,
471 } CmdArray;
473 typedef enum {
474 CMD_STRING_REF_GET_VALUE = 1,
475 CMD_STRING_REF_GET_LENGTH = 2,
476 CMD_STRING_REF_GET_CHARS = 3
477 } CmdString;
479 typedef enum {
480 CMD_POINTER_GET_VALUE = 1
481 } CmdPointer;
483 typedef enum {
484 CMD_OBJECT_REF_GET_TYPE = 1,
485 CMD_OBJECT_REF_GET_VALUES = 2,
486 CMD_OBJECT_REF_IS_COLLECTED = 3,
487 CMD_OBJECT_REF_GET_ADDRESS = 4,
488 CMD_OBJECT_REF_GET_DOMAIN = 5,
489 CMD_OBJECT_REF_SET_VALUES = 6,
490 CMD_OBJECT_REF_GET_INFO = 7,
491 } CmdObject;
494 * Contains additional information for an event
496 typedef struct {
497 /* For EVENT_KIND_EXCEPTION */
498 MonoObject *exc;
499 MonoContext catch_ctx;
500 gboolean caught;
501 /* For EVENT_KIND_USER_LOG */
502 int level;
503 char *category, *message;
504 /* For EVENT_KIND_TYPE_LOAD */
505 MonoClass *klass;
506 /* For EVENT_KIND_CRASH */
507 char *dump;
508 MonoStackHash *hashes;
509 } EventInfo;
511 typedef struct {
512 guint8 *buf, *p, *end;
513 } Buffer;
515 typedef struct ReplyPacket {
516 int id;
517 int error;
518 Buffer *data;
519 } ReplyPacket;
521 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
523 #ifdef HOST_ANDROID
524 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
525 #else
526 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
527 #endif
529 #ifdef HOST_WIN32
530 #define get_last_sock_error() WSAGetLastError()
531 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
532 #define MONO_EINTR WSAEINTR
533 #else
534 #define get_last_sock_error() errno
535 #define MONO_EWOULDBLOCK EWOULDBLOCK
536 #define MONO_EINTR EINTR
537 #endif
539 #define CHECK_PROTOCOL_VERSION(major,minor) \
540 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
543 * Globals
546 static AgentConfig agent_config;
549 * Whenever the agent is fully initialized.
550 * When using the onuncaught or onthrow options, only some parts of the agent are
551 * initialized on startup, and the full initialization which includes connection
552 * establishment and the startup of the agent thread is only done in response to
553 * an event.
555 static gint32 inited;
557 #ifndef DISABLE_SOCKET_TRANSPORT
558 static int conn_fd;
559 static int listen_fd;
560 #endif
562 static int packet_id = 0;
564 static int objref_id = 0;
566 static int event_request_id = 0;
568 static int frame_id = 0;
570 static GPtrArray *event_requests;
572 static MonoNativeTlsKey debugger_tls_id;
574 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
576 /* Maps MonoInternalThread -> DebuggerTlsData */
577 /* Protected by the loader lock */
578 static MonoGHashTable *thread_to_tls;
580 /* Maps tid -> MonoInternalThread */
581 /* Protected by the loader lock */
582 static MonoGHashTable *tid_to_thread;
584 /* Maps tid -> MonoThread (not MonoInternalThread) */
585 /* Protected by the loader lock */
586 static MonoGHashTable *tid_to_thread_obj;
588 static MonoNativeThreadId debugger_thread_id;
590 static MonoThreadHandle *debugger_thread_handle;
592 static int log_level;
594 static gboolean embedding;
596 static FILE *log_file;
598 /* Assemblies whose assembly load event has no been sent yet */
599 /* Protected by the dbg lock */
600 static GPtrArray *pending_assembly_loads;
602 /* Whenever the debugger thread has exited */
603 static gboolean debugger_thread_exited;
605 /* Cond variable used to wait for debugger_thread_exited becoming true */
606 static MonoCoopCond debugger_thread_exited_cond;
608 /* Mutex for the cond var above */
609 static MonoCoopMutex debugger_thread_exited_mutex;
611 /* The protocol version of the client */
612 static int major_version, minor_version;
614 /* Whenever the variables above are set by the client */
615 static gboolean protocol_version_set;
617 /* The number of times the runtime is suspended */
618 static gint32 suspend_count;
620 /* Whenever to buffer reply messages and send them together */
621 static gboolean buffer_replies;
623 /* Buffered reply packets */
624 static ReplyPacket reply_packets [128];
625 static int nreply_packets;
627 #define dbg_lock mono_de_lock
628 #define dbg_unlock mono_de_unlock
630 static void transport_init (void);
631 static void transport_connect (const char *address);
632 static gboolean transport_handshake (void);
633 static void register_transport (DebuggerTransport *trans);
635 static gsize WINAPI debugger_thread (void *arg);
637 static void runtime_initialized (MonoProfiler *prof);
639 static void runtime_shutdown (MonoProfiler *prof);
641 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
643 static void thread_end (MonoProfiler *prof, uintptr_t tid);
645 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
647 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
649 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
651 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
653 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
655 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
657 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
659 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
661 static void emit_assembly_load (gpointer assembly, gpointer user_data);
663 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
665 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
667 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
669 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
671 static void suspend_current (void);
673 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
675 static void clear_types_for_assembly (MonoAssembly *assembly);
677 static void process_profiler_event (EventKind event, gpointer arg);
679 /* Submodule init/cleanup */
680 static void event_requests_cleanup (void);
682 static void objrefs_init (void);
683 static void objrefs_cleanup (void);
685 static void ids_init (void);
686 static void ids_cleanup (void);
688 static void suspend_init (void);
690 static void start_debugger_thread (MonoError *error);
691 static void stop_debugger_thread (void);
693 static void finish_agent_init (gboolean on_startup);
695 static void process_profiler_event (EventKind event, gpointer arg);
697 static void invalidate_frames (DebuggerTlsData *tls);
699 /* Callbacks used by debugger-engine */
700 static MonoContext* tls_get_restore_state (void *the_tls);
701 static gboolean try_process_suspend (void *tls, MonoContext *ctx);
702 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
703 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
704 static void ss_discard_frame_context (void *the_tls);
705 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
706 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
707 static int ensure_runtime_is_suspended (void);
708 static int get_this_async_id (DbgEngineStackFrame *frame);
709 static gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame);
710 static MonoMethod* get_notify_debugger_of_wait_completion_method (void);
711 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
712 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
713 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
714 static void ss_args_destroy (SingleStepArgs *ss_args);
716 #ifndef DISABLE_SOCKET_TRANSPORT
717 static void
718 register_socket_transport (void);
719 #endif
721 static inline gboolean
722 is_debugger_thread (void)
724 MonoInternalThread *internal;
726 internal = mono_thread_internal_current ();
727 if (!internal)
728 return FALSE;
730 return internal->debugger_thread;
733 static int
734 parse_address (char *address, char **host, int *port)
736 char *pos = strchr (address, ':');
738 if (pos == NULL || pos == address)
739 return 1;
741 size_t len = pos - address;
742 *host = (char *)g_malloc (len + 1);
743 memcpy (*host, address, len);
744 (*host) [len] = '\0';
746 *port = atoi (pos + 1);
748 return 0;
751 static void
752 print_usage (void)
754 g_printerr ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
755 g_printerr ("Available options:\n");
756 g_printerr (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
757 g_printerr (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
758 g_printerr (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
759 g_printerr (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
760 g_printerr (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
761 g_printerr (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
762 g_printerr (" server=y/n\t\t\tWhether to listen for a client connection.\n");
763 g_printerr (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
764 g_printerr (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
765 g_printerr (" help\t\t\t\tPrint this help.\n");
768 static gboolean
769 parse_flag (const char *option, char *flag)
771 if (!strcmp (flag, "y"))
772 return TRUE;
773 else if (!strcmp (flag, "n"))
774 return FALSE;
775 else {
776 g_printerr ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
777 exit (1);
778 return FALSE;
782 static void
783 debugger_agent_parse_options (char *options)
785 char **args, **ptr;
786 char *host;
787 int port;
788 char *extra;
790 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
791 g_printerr ("--debugger-agent is not supported on this platform.\n");
792 exit (1);
793 #endif
795 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
796 if (extra) {
797 options = g_strdup_printf ("%s,%s", options, extra);
798 g_free (extra);
801 agent_config.enabled = TRUE;
802 agent_config.suspend = TRUE;
803 agent_config.server = FALSE;
804 agent_config.defer = FALSE;
805 agent_config.address = NULL;
807 //agent_config.log_level = 10;
809 args = g_strsplit (options, ",", -1);
810 for (ptr = args; ptr && *ptr; ptr ++) {
811 char *arg = *ptr;
813 if (strncmp (arg, "transport=", 10) == 0) {
814 agent_config.transport = g_strdup (arg + 10);
815 } else if (strncmp (arg, "address=", 8) == 0) {
816 agent_config.address = g_strdup (arg + 8);
817 } else if (strncmp (arg, "loglevel=", 9) == 0) {
818 agent_config.log_level = atoi (arg + 9);
819 } else if (strncmp (arg, "logfile=", 8) == 0) {
820 agent_config.log_file = g_strdup (arg + 8);
821 } else if (strncmp (arg, "suspend=", 8) == 0) {
822 agent_config.suspend = parse_flag ("suspend", arg + 8);
823 } else if (strncmp (arg, "server=", 7) == 0) {
824 agent_config.server = parse_flag ("server", arg + 7);
825 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
826 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
827 } else if (strncmp (arg, "onthrow=", 8) == 0) {
828 /* We support multiple onthrow= options */
829 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
830 } else if (strncmp (arg, "onthrow", 7) == 0) {
831 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
832 } else if (strncmp (arg, "help", 4) == 0) {
833 print_usage ();
834 exit (0);
835 } else if (strncmp (arg, "timeout=", 8) == 0) {
836 agent_config.timeout = atoi (arg + 8);
837 } else if (strncmp (arg, "launch=", 7) == 0) {
838 agent_config.launch = g_strdup (arg + 7);
839 } else if (strncmp (arg, "embedding=", 10) == 0) {
840 agent_config.embedding = atoi (arg + 10) == 1;
841 } else if (strncmp (arg, "keepalive=", 10) == 0) {
842 agent_config.keepalive = atoi (arg + 10);
843 } else if (strncmp (arg, "setpgid=", 8) == 0) {
844 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
845 } else {
846 print_usage ();
847 exit (1);
851 if (agent_config.server && !agent_config.suspend) {
852 /* Waiting for deferred attachment */
853 agent_config.defer = TRUE;
854 if (agent_config.address == NULL) {
855 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
859 //agent_config.log_level = 0;
861 if (agent_config.transport == NULL) {
862 g_printerr ("debugger-agent: The 'transport' option is mandatory.\n");
863 exit (1);
866 if (agent_config.address == NULL && !agent_config.server) {
867 g_printerr ("debugger-agent: The 'address' option is mandatory.\n");
868 exit (1);
871 // FIXME:
872 if (!strcmp (agent_config.transport, "dt_socket")) {
873 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
874 g_printerr ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
875 exit (1);
880 void
881 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
883 g_assertf (tls, "Cannot get state of null thread", NULL);
885 g_assert (tls->thread_state == expected);
887 tls->thread_state = set;
889 return;
892 MonoDebuggerThreadState
893 mono_debugger_get_thread_state (DebuggerTlsData *tls)
895 g_assertf (tls, "Cannot get state of null thread", NULL);
897 return tls->thread_state;
900 gsize
901 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
903 if (!tls)
904 return 0;
906 return tls->thread_id;
909 // Only call this function with the loader lock held
910 MonoGHashTable *
911 mono_debugger_get_thread_states (void)
913 return thread_to_tls;
916 gboolean
917 mono_debugger_is_disconnected (void)
919 return disconnected;
922 static void
923 debugger_agent_init (void)
925 if (!agent_config.enabled)
926 return;
928 DebuggerEngineCallbacks cbs;
929 memset (&cbs, 0, sizeof (cbs));
930 cbs.tls_get_restore_state = tls_get_restore_state;
931 cbs.try_process_suspend = try_process_suspend;
932 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
933 cbs.begin_single_step_processing = begin_single_step_processing;
934 cbs.ss_discard_frame_context = ss_discard_frame_context;
935 cbs.ss_calculate_framecount = ss_calculate_framecount;
936 cbs.ensure_jit = ensure_jit;
937 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
938 cbs.get_this_async_id = get_this_async_id;
939 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
940 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
941 cbs.create_breakpoint_events = create_breakpoint_events;
942 cbs.process_breakpoint_events = process_breakpoint_events;
943 cbs.ss_create_init_args = ss_create_init_args;
944 cbs.ss_args_destroy = ss_args_destroy;
946 mono_de_init (&cbs);
948 transport_init ();
950 /* Need to know whenever a thread has acquired the loader mutex */
951 mono_loader_lock_track_ownership (TRUE);
953 event_requests = g_ptr_array_new ();
955 mono_coop_mutex_init (&debugger_thread_exited_mutex);
956 mono_coop_cond_init (&debugger_thread_exited_cond);
958 MonoProfilerHandle prof = mono_profiler_create (NULL);
959 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
960 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
961 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
962 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
963 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
964 mono_profiler_set_thread_started_callback (prof, thread_startup);
965 mono_profiler_set_thread_stopped_callback (prof, thread_end);
966 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
967 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
968 mono_profiler_set_jit_done_callback (prof, jit_done);
969 mono_profiler_set_jit_failed_callback (prof, jit_failed);
971 mono_native_tls_alloc (&debugger_tls_id, NULL);
973 /* Needed by the hash_table_new_type () call below */
974 mono_gc_base_init ();
976 thread_to_tls = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash_internal, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger TLS Table");
978 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
980 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Object Table");
982 pending_assembly_loads = g_ptr_array_new ();
984 log_level = agent_config.log_level;
986 embedding = agent_config.embedding;
987 disconnected = TRUE;
989 if (agent_config.log_file) {
990 log_file = fopen (agent_config.log_file, "w+");
991 if (!log_file) {
992 g_printerr ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
993 exit (1);
995 } else {
996 log_file = stdout;
998 mono_de_set_log_level (log_level, log_file);
1000 ids_init ();
1001 objrefs_init ();
1002 suspend_init ();
1004 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1006 * This is needed because currently we don't handle liveness info.
1008 mini_get_debug_options ()->mdb_optimizations = TRUE;
1010 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1011 /* This is needed because we can't set local variables in registers yet */
1012 mono_disable_optimizations (MONO_OPT_LINEARS);
1013 #endif
1016 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1017 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1018 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1019 * workaround.
1021 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1023 #ifdef HAVE_SETPGID
1024 if (agent_config.setpgid)
1025 setpgid (0, 0);
1026 #endif
1028 if (!agent_config.onuncaught && !agent_config.onthrow)
1029 finish_agent_init (TRUE);
1033 * finish_agent_init:
1035 * Finish the initialization of the agent. This involves connecting the transport
1036 * and starting the agent thread. This is either done at startup, or
1037 * in response to some event like an unhandled exception.
1039 static void
1040 finish_agent_init (gboolean on_startup)
1042 int res;
1044 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1045 return;
1047 if (agent_config.launch) {
1048 char *argv [16];
1050 // FIXME: Generated address
1051 // FIXME: Races with transport_connect ()
1053 argv [0] = agent_config.launch;
1054 argv [1] = agent_config.transport;
1055 argv [2] = agent_config.address;
1056 argv [3] = NULL;
1058 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1059 if (!res) {
1060 g_printerr ("Failed to execute '%s'.\n", agent_config.launch);
1061 exit (1);
1065 transport_connect (agent_config.address);
1067 if (!on_startup) {
1068 /* Do some which is usually done after sending the VMStart () event */
1069 vm_start_event_sent = TRUE;
1070 ERROR_DECL (error);
1071 start_debugger_thread (error);
1072 mono_error_assert_ok (error);
1076 static void
1077 mono_debugger_agent_cleanup (void)
1079 if (!inited)
1080 return;
1082 stop_debugger_thread ();
1084 event_requests_cleanup ();
1085 objrefs_cleanup ();
1086 ids_cleanup ();
1088 mono_de_cleanup ();
1092 * SOCKET TRANSPORT
1095 #ifndef DISABLE_SOCKET_TRANSPORT
1098 * recv_length:
1100 * recv() + handle incomplete reads and EINTR
1102 static int
1103 socket_transport_recv (void *buf, int len)
1105 int res;
1106 int total = 0;
1107 int fd = conn_fd;
1108 int flags = 0;
1109 static gint64 last_keepalive;
1110 gint64 msecs;
1112 MONO_ENTER_GC_SAFE;
1114 do {
1115 again:
1116 res = recv (fd, (char *) buf + total, len - total, flags);
1117 if (res > 0)
1118 total += res;
1119 if (agent_config.keepalive) {
1120 gboolean need_keepalive = FALSE;
1121 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1122 need_keepalive = TRUE;
1123 } else if (res == -1) {
1124 /* This could happen if recv () is interrupted repeatedly */
1125 msecs = mono_msec_ticks ();
1126 if (msecs - last_keepalive >= agent_config.keepalive) {
1127 need_keepalive = TRUE;
1128 last_keepalive = msecs;
1131 if (need_keepalive) {
1132 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1133 goto again;
1136 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1138 MONO_EXIT_GC_SAFE;
1140 return total;
1143 static void
1144 set_keepalive (void)
1146 struct timeval tv;
1147 int result;
1149 if (!agent_config.keepalive || !conn_fd)
1150 return;
1152 tv.tv_sec = agent_config.keepalive / 1000;
1153 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1155 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1156 g_assert (result >= 0);
1159 static int
1160 socket_transport_accept (int socket_fd)
1162 MONO_ENTER_GC_SAFE;
1163 conn_fd = accept (socket_fd, NULL, NULL);
1164 MONO_EXIT_GC_SAFE;
1166 if (conn_fd == -1) {
1167 g_printerr ("debugger-agent: Unable to listen on %d\n", socket_fd);
1168 } else {
1169 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1172 return conn_fd;
1175 static gboolean
1176 socket_transport_send (void *data, int len)
1178 int res;
1180 MONO_ENTER_GC_SAFE;
1182 do {
1183 res = send (conn_fd, (const char*)data, len, 0);
1184 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1186 MONO_EXIT_GC_SAFE;
1188 if (res != len)
1189 return FALSE;
1190 else
1191 return TRUE;
1195 * socket_transport_connect:
1197 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1199 static void
1200 socket_transport_connect (const char *address)
1202 MonoAddressInfo *result;
1203 MonoAddressEntry *rp;
1204 int sfd = -1, s, res;
1205 char *host;
1206 int port;
1208 if (agent_config.address) {
1209 res = parse_address (agent_config.address, &host, &port);
1210 g_assert (res == 0);
1211 } else {
1212 host = NULL;
1213 port = 0;
1216 conn_fd = -1;
1217 listen_fd = -1;
1219 if (host) {
1221 mono_network_init ();
1223 /* Obtain address(es) matching host/port */
1224 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1225 if (s != 0) {
1226 g_printerr ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1227 exit (1);
1231 if (agent_config.server) {
1232 /* Wait for a connection */
1233 if (!host) {
1234 struct sockaddr_in addr;
1235 socklen_t addrlen;
1237 /* No address, generate one */
1238 sfd = socket (AF_INET, SOCK_STREAM, 0);
1239 g_assert (sfd);
1241 /* This will bind the socket to a random port */
1242 res = listen (sfd, 16);
1243 if (res == -1) {
1244 g_printerr ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1245 exit (1);
1247 listen_fd = sfd;
1249 addrlen = sizeof (addr);
1250 memset (&addr, 0, sizeof (addr));
1251 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1252 g_assert (res == 0);
1254 host = (char*)"127.0.0.1";
1255 port = ntohs (addr.sin_port);
1257 /* Emit the address to stdout */
1258 /* FIXME: Should print another interface, not localhost */
1259 printf ("%s:%d\n", host, port);
1260 } else {
1261 /* Listen on the provided address */
1262 for (rp = result->entries; rp != NULL; rp = rp->next) {
1263 MonoSocketAddress sockaddr;
1264 socklen_t sock_len;
1265 int n = 1;
1267 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1269 sfd = socket (rp->family, rp->socktype,
1270 rp->protocol);
1271 if (sfd == -1)
1272 continue;
1274 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1275 continue;
1277 res = bind (sfd, &sockaddr.addr, sock_len);
1278 if (res == -1)
1279 continue;
1281 res = listen (sfd, 16);
1282 if (res == -1)
1283 continue;
1284 listen_fd = sfd;
1285 break;
1288 mono_free_address_info (result);
1291 if (agent_config.defer)
1292 return;
1294 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1296 if (agent_config.timeout) {
1297 fd_set readfds;
1298 struct timeval tv;
1300 tv.tv_sec = 0;
1301 tv.tv_usec = agent_config.timeout * 1000;
1302 FD_ZERO (&readfds);
1303 FD_SET (sfd, &readfds);
1305 MONO_ENTER_GC_SAFE;
1306 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1307 MONO_EXIT_GC_SAFE;
1309 if (res == 0) {
1310 g_printerr ("debugger-agent: Timed out waiting to connect.\n");
1311 exit (1);
1315 conn_fd = socket_transport_accept (sfd);
1316 if (conn_fd == -1)
1317 exit (1);
1319 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1320 } else {
1321 /* Connect to the specified address */
1322 /* FIXME: Respect the timeout */
1323 for (rp = result->entries; rp != NULL; rp = rp->next) {
1324 MonoSocketAddress sockaddr;
1325 socklen_t sock_len;
1327 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1329 sfd = socket (rp->family, rp->socktype,
1330 rp->protocol);
1331 if (sfd == -1)
1332 continue;
1334 MONO_ENTER_GC_SAFE;
1335 res = connect (sfd, &sockaddr.addr, sock_len);
1336 MONO_EXIT_GC_SAFE;
1338 if (res != -1)
1339 break; /* Success */
1341 MONO_ENTER_GC_SAFE;
1342 #ifdef HOST_WIN32
1343 closesocket (sfd);
1344 #else
1345 close (sfd);
1346 #endif
1347 MONO_EXIT_GC_SAFE;
1350 if (rp == 0) {
1351 g_printerr ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1352 exit (1);
1355 conn_fd = sfd;
1357 mono_free_address_info (result);
1360 if (!transport_handshake ())
1361 exit (1);
1364 static void
1365 socket_transport_close1 (void)
1367 /* This will interrupt the agent thread */
1368 /* Close the read part only so it can still send back replies */
1369 /* Also shut down the connection listener so that we can exit normally */
1370 #ifdef HOST_WIN32
1371 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1372 shutdown (conn_fd, SD_BOTH);
1373 shutdown (listen_fd, SD_BOTH);
1374 closesocket (listen_fd);
1375 #else
1376 shutdown (conn_fd, SHUT_RD);
1377 shutdown (listen_fd, SHUT_RDWR);
1378 MONO_ENTER_GC_SAFE;
1379 close (listen_fd);
1380 MONO_EXIT_GC_SAFE;
1381 #endif
1384 static void
1385 socket_transport_close2 (void)
1387 #ifdef HOST_WIN32
1388 shutdown (conn_fd, SD_BOTH);
1389 #else
1390 shutdown (conn_fd, SHUT_RDWR);
1391 #endif
1394 static void
1395 register_socket_transport (void)
1397 DebuggerTransport trans;
1399 trans.name = "dt_socket";
1400 trans.connect = socket_transport_connect;
1401 trans.close1 = socket_transport_close1;
1402 trans.close2 = socket_transport_close2;
1403 trans.send = socket_transport_send;
1404 trans.recv = socket_transport_recv;
1406 register_transport (&trans);
1410 * socket_fd_transport_connect:
1413 static void
1414 socket_fd_transport_connect (const char *address)
1416 int res;
1418 res = sscanf (address, "%d", &conn_fd);
1419 if (res != 1) {
1420 g_printerr ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1421 exit (1);
1424 if (!transport_handshake ())
1425 exit (1);
1428 static void
1429 register_socket_fd_transport (void)
1431 DebuggerTransport trans;
1433 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1434 trans.name = "socket-fd";
1435 trans.connect = socket_fd_transport_connect;
1436 trans.close1 = socket_transport_close1;
1437 trans.close2 = socket_transport_close2;
1438 trans.send = socket_transport_send;
1439 trans.recv = socket_transport_recv;
1441 register_transport (&trans);
1444 #endif /* DISABLE_SOCKET_TRANSPORT */
1447 * TRANSPORT CODE
1450 #define MAX_TRANSPORTS 16
1452 static DebuggerTransport *transport;
1454 static DebuggerTransport transports [MAX_TRANSPORTS];
1455 static int ntransports;
1457 MONO_API void
1458 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1460 void
1461 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1463 register_transport (trans);
1466 static void
1467 register_transport (DebuggerTransport *trans)
1469 g_assert (ntransports < MAX_TRANSPORTS);
1471 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1472 ntransports ++;
1475 static void
1476 transport_init (void)
1478 int i;
1480 #ifndef DISABLE_SOCKET_TRANSPORT
1481 register_socket_transport ();
1482 register_socket_fd_transport ();
1483 #endif
1485 for (i = 0; i < ntransports; ++i) {
1486 if (!strcmp (agent_config.transport, transports [i].name))
1487 break;
1489 if (i == ntransports) {
1490 g_printerr ("debugger-agent: The supported values for the 'transport' option are: ");
1491 for (i = 0; i < ntransports; ++i)
1492 g_printerr ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1493 g_printerr ("\n");
1494 exit (1);
1496 transport = &transports [i];
1499 void
1500 transport_connect (const char *address)
1502 transport->connect (address);
1505 static void
1506 transport_close1 (void)
1508 transport->close1 ();
1511 static void
1512 transport_close2 (void)
1514 transport->close2 ();
1517 static int
1518 transport_send (void *buf, int len)
1520 return transport->send (buf, len);
1523 static int
1524 transport_recv (void *buf, int len)
1526 return transport->recv (buf, len);
1529 gboolean
1530 mono_debugger_agent_transport_handshake (void)
1532 return transport_handshake ();
1535 static gboolean
1536 transport_handshake (void)
1538 char handshake_msg [128];
1539 guint8 buf [128];
1540 int res;
1542 disconnected = TRUE;
1544 /* Write handshake message */
1545 sprintf (handshake_msg, "DWP-Handshake");
1547 do {
1548 res = transport_send (handshake_msg, strlen (handshake_msg));
1549 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1551 g_assert (res != -1);
1553 /* Read answer */
1554 res = transport_recv (buf, strlen (handshake_msg));
1555 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1556 g_printerr ("debugger-agent: DWP handshake failed.\n");
1557 return FALSE;
1561 * To support older clients, the client sends its protocol version after connecting
1562 * using a command. Until that is received, default to our protocol version.
1564 major_version = MAJOR_VERSION;
1565 minor_version = MINOR_VERSION;
1566 protocol_version_set = FALSE;
1568 #ifndef DISABLE_SOCKET_TRANSPORT
1569 // FIXME: Move this somewhere else
1571 * Set TCP_NODELAY on the socket so the client receives events/command
1572 * results immediately.
1574 if (conn_fd) {
1575 int flag = 1;
1576 int result = setsockopt (conn_fd,
1577 IPPROTO_TCP,
1578 TCP_NODELAY,
1579 (char *) &flag,
1580 sizeof(int));
1581 g_assert (result >= 0);
1584 set_keepalive ();
1585 #endif
1587 disconnected = FALSE;
1588 return TRUE;
1591 static void
1592 stop_debugger_thread (void)
1594 if (!inited)
1595 return;
1597 transport_close1 ();
1600 * Wait for the thread to exit.
1602 * If we continue with the shutdown without waiting for it, then the client might
1603 * not receive an answer to its last command like a resume.
1605 if (!is_debugger_thread ()) {
1606 do {
1607 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1608 if (!debugger_thread_exited)
1609 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1610 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1611 } while (!debugger_thread_exited);
1613 if (debugger_thread_handle)
1614 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1617 transport_close2 ();
1620 static void
1621 start_debugger_thread (MonoError *error)
1623 MonoInternalThread *thread;
1625 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1626 return_if_nok (error);
1628 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1629 g_assert (debugger_thread_handle);
1634 * Functions to decode protocol data
1637 static inline int
1638 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1640 *endbuf = buf + 1;
1641 g_assert (*endbuf <= limit);
1642 return buf [0];
1645 static inline int
1646 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1648 *endbuf = buf + 4;
1649 g_assert (*endbuf <= limit);
1651 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1654 static inline gint64
1655 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1657 guint32 high = decode_int (buf, &buf, limit);
1658 guint32 low = decode_int (buf, &buf, limit);
1660 *endbuf = buf;
1662 return ((((guint64)high) << 32) | ((guint64)low));
1665 static inline int
1666 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 return decode_int (buf, endbuf, limit);
1671 static inline char*
1672 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1674 int len = decode_int (buf, &buf, limit);
1675 char *s;
1677 if (len < 0) {
1678 *endbuf = buf;
1679 return NULL;
1682 s = (char *)g_malloc (len + 1);
1683 g_assert (s);
1685 memcpy (s, buf, len);
1686 s [len] = '\0';
1687 buf += len;
1688 *endbuf = buf;
1690 return s;
1694 * Functions to encode protocol data
1697 static inline void
1698 buffer_init (Buffer *buf, int size)
1700 buf->buf = (guint8 *)g_malloc (size);
1701 buf->p = buf->buf;
1702 buf->end = buf->buf + size;
1705 static inline int
1706 buffer_len (Buffer *buf)
1708 return buf->p - buf->buf;
1711 static inline void
1712 buffer_make_room (Buffer *buf, int size)
1714 if (buf->end - buf->p < size) {
1715 int new_size = buf->end - buf->buf + size + 32;
1716 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1717 size = buf->p - buf->buf;
1718 buf->buf = p;
1719 buf->p = p + size;
1720 buf->end = buf->buf + new_size;
1724 static inline void
1725 buffer_add_byte (Buffer *buf, guint8 val)
1727 buffer_make_room (buf, 1);
1728 buf->p [0] = val;
1729 buf->p++;
1732 static inline void
1733 buffer_add_short (Buffer *buf, guint32 val)
1735 buffer_make_room (buf, 2);
1736 buf->p [0] = (val >> 8) & 0xff;
1737 buf->p [1] = (val >> 0) & 0xff;
1738 buf->p += 2;
1741 static inline void
1742 buffer_add_int (Buffer *buf, guint32 val)
1744 buffer_make_room (buf, 4);
1745 buf->p [0] = (val >> 24) & 0xff;
1746 buf->p [1] = (val >> 16) & 0xff;
1747 buf->p [2] = (val >> 8) & 0xff;
1748 buf->p [3] = (val >> 0) & 0xff;
1749 buf->p += 4;
1752 static inline void
1753 buffer_add_long (Buffer *buf, guint64 l)
1755 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1756 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1759 static inline void
1760 buffer_add_id (Buffer *buf, int id)
1762 buffer_add_int (buf, (guint64)id);
1765 static inline void
1766 buffer_add_data (Buffer *buf, guint8 *data, int len)
1768 buffer_make_room (buf, len);
1769 memcpy (buf->p, data, len);
1770 buf->p += len;
1773 static inline void
1774 buffer_add_string (Buffer *buf, const char *str)
1776 int len;
1778 if (str == NULL) {
1779 buffer_add_int (buf, 0);
1780 } else {
1781 len = strlen (str);
1782 buffer_add_int (buf, len);
1783 buffer_add_data (buf, (guint8*)str, len);
1787 static inline void
1788 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1790 buffer_add_int (buf, arr_len);
1791 buffer_add_data (buf, bytes, arr_len);
1794 static inline void
1795 buffer_add_buffer (Buffer *buf, Buffer *data)
1797 buffer_add_data (buf, data->buf, buffer_len (data));
1800 static inline void
1801 buffer_free (Buffer *buf)
1803 g_free (buf->buf);
1806 static gboolean
1807 send_packet (int command_set, int command, Buffer *data)
1809 Buffer buf;
1810 int len, id;
1811 gboolean res;
1813 id = mono_atomic_inc_i32 (&packet_id);
1815 len = data->p - data->buf + 11;
1816 buffer_init (&buf, len);
1817 buffer_add_int (&buf, len);
1818 buffer_add_int (&buf, id);
1819 buffer_add_byte (&buf, 0); /* flags */
1820 buffer_add_byte (&buf, command_set);
1821 buffer_add_byte (&buf, command);
1822 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1824 res = transport_send (buf.buf, len);
1826 buffer_free (&buf);
1828 return res;
1831 static gboolean
1832 send_reply_packets (int npackets, ReplyPacket *packets)
1834 Buffer buf;
1835 int i, len;
1836 gboolean res;
1838 len = 0;
1839 for (i = 0; i < npackets; ++i)
1840 len += buffer_len (packets [i].data) + 11;
1841 buffer_init (&buf, len);
1842 for (i = 0; i < npackets; ++i) {
1843 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1844 buffer_add_int (&buf, packets [i].id);
1845 buffer_add_byte (&buf, 0x80); /* flags */
1846 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1847 buffer_add_byte (&buf, packets [i].error);
1848 buffer_add_buffer (&buf, packets [i].data);
1851 res = transport_send (buf.buf, len);
1853 buffer_free (&buf);
1855 return res;
1858 static gboolean
1859 send_reply_packet (int id, int error, Buffer *data)
1861 ReplyPacket packet;
1863 memset (&packet, 0, sizeof (ReplyPacket));
1864 packet.id = id;
1865 packet.error = error;
1866 packet.data = data;
1868 return send_reply_packets (1, &packet);
1871 static void
1872 send_buffered_reply_packets (void)
1874 int i;
1876 send_reply_packets (nreply_packets, reply_packets);
1877 for (i = 0; i < nreply_packets; ++i)
1878 buffer_free (reply_packets [i].data);
1879 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1880 nreply_packets = 0;
1883 static void
1884 buffer_reply_packet (int id, int error, Buffer *data)
1886 ReplyPacket *p;
1888 if (nreply_packets == 128)
1889 send_buffered_reply_packets ();
1891 p = &reply_packets [nreply_packets];
1892 p->id = id;
1893 p->error = error;
1894 p->data = g_new0 (Buffer, 1);
1895 buffer_init (p->data, buffer_len (data));
1896 buffer_add_buffer (p->data, data);
1897 nreply_packets ++;
1901 /* Maps objid -> ObjRef */
1902 /* Protected by the loader lock */
1903 static GHashTable *objrefs;
1904 /* Protected by the loader lock */
1905 static GHashTable *obj_to_objref;
1906 /* Protected by the dbg lock */
1907 static MonoGHashTable *suspended_objs;
1911 static void
1912 objrefs_init (void)
1914 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1915 obj_to_objref = g_hash_table_new (NULL, NULL);
1916 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash_internal, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Suspended Object Table");
1919 static void
1920 objrefs_cleanup (void)
1922 g_hash_table_destroy (objrefs);
1923 objrefs = NULL;
1927 * Return an ObjRef for OBJ.
1929 static ObjRef*
1930 get_objref (MonoObject *obj)
1932 ObjRef *ref;
1933 GSList *reflist = NULL, *l;
1934 int hash = 0;
1936 if (obj == NULL)
1937 return NULL;
1939 if (suspend_count) {
1941 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1943 dbg_lock ();
1944 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1945 dbg_unlock ();
1948 mono_loader_lock ();
1950 /* FIXME: The tables can grow indefinitely */
1952 if (mono_gc_is_moving ()) {
1954 * Objects can move, so use a hash table mapping hash codes to lists of
1955 * ObjRef structures.
1957 hash = mono_object_hash_internal (obj);
1959 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1960 for (l = reflist; l; l = l->next) {
1961 ref = (ObjRef *)l->data;
1962 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1963 mono_loader_unlock ();
1964 return ref;
1967 } else {
1968 /* Use a hash table with masked pointers to internalize object references */
1969 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1970 /* ref might refer to a different object with the same addr which was GCd */
1971 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
1972 mono_loader_unlock ();
1973 return ref;
1977 ref = g_new0 (ObjRef, 1);
1978 ref->id = mono_atomic_inc_i32 (&objref_id);
1979 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
1981 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1983 if (mono_gc_is_moving ()) {
1984 reflist = g_slist_append (reflist, ref);
1985 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1986 } else {
1987 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1990 mono_loader_unlock ();
1992 return ref;
1995 static gboolean
1996 true_pred (gpointer key, gpointer value, gpointer user_data)
1998 return TRUE;
2001 static void
2002 clear_suspended_objs (void)
2004 dbg_lock ();
2005 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2006 dbg_unlock ();
2009 static inline int
2010 get_objid (MonoObject *obj)
2012 if (!obj)
2013 return 0;
2014 else
2015 return get_objref (obj)->id;
2019 * Set OBJ to the object identified by OBJID.
2020 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2021 * collected.
2023 static ErrorCode
2024 get_object_allow_null (int objid, MonoObject **obj)
2026 ObjRef *ref;
2028 if (objid == 0) {
2029 *obj = NULL;
2030 return ERR_NONE;
2033 if (!objrefs)
2034 return ERR_INVALID_OBJECT;
2036 mono_loader_lock ();
2038 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2040 if (ref) {
2041 *obj = mono_gchandle_get_target_internal (ref->handle);
2042 mono_loader_unlock ();
2043 if (!(*obj))
2044 return ERR_INVALID_OBJECT;
2045 return ERR_NONE;
2046 } else {
2047 mono_loader_unlock ();
2048 return ERR_INVALID_OBJECT;
2052 static ErrorCode
2053 get_object (int objid, MonoObject **obj)
2055 ErrorCode err = get_object_allow_null (objid, obj);
2057 if (err != ERR_NONE)
2058 return err;
2059 if (!(*obj))
2060 return ERR_INVALID_OBJECT;
2061 return ERR_NONE;
2064 static inline int
2065 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2067 return decode_id (buf, endbuf, limit);
2070 static inline void
2071 buffer_add_objid (Buffer *buf, MonoObject *o)
2073 buffer_add_id (buf, get_objid (o));
2077 * IDS
2080 typedef enum {
2081 ID_ASSEMBLY = 0,
2082 ID_MODULE = 1,
2083 ID_TYPE = 2,
2084 ID_METHOD = 3,
2085 ID_FIELD = 4,
2086 ID_DOMAIN = 5,
2087 ID_PROPERTY = 6,
2088 ID_NUM
2089 } IdType;
2092 * Represents a runtime structure accessible to the debugger client
2094 typedef struct {
2095 /* Unique id used in the wire protocol */
2096 int id;
2097 /* Domain of the runtime structure, NULL if the domain was unloaded */
2098 MonoDomain *domain;
2099 union {
2100 gpointer val;
2101 MonoClass *klass;
2102 MonoMethod *method;
2103 MonoImage *image;
2104 MonoAssembly *assembly;
2105 MonoClassField *field;
2106 MonoDomain *domain;
2107 MonoProperty *property;
2108 } data;
2109 } Id;
2111 typedef struct {
2112 /* Maps runtime structure -> Id */
2113 /* Protected by the dbg lock */
2114 GHashTable *val_to_id [ID_NUM];
2115 /* Classes whose class load event has been sent */
2116 /* Protected by the loader lock */
2117 GHashTable *loaded_classes;
2118 /* Maps MonoClass->GPtrArray of file names */
2119 GHashTable *source_files;
2120 /* Maps source file basename -> GSList of classes */
2121 GHashTable *source_file_to_class;
2122 /* Same with ignore-case */
2123 GHashTable *source_file_to_class_ignorecase;
2124 } AgentDomainInfo;
2126 /* Maps id -> Id */
2127 /* Protected by the dbg lock */
2128 static GPtrArray *ids [ID_NUM];
2130 static void
2131 ids_init (void)
2133 int i;
2135 for (i = 0; i < ID_NUM; ++i)
2136 ids [i] = g_ptr_array_new ();
2139 static void
2140 ids_cleanup (void)
2142 int i, j;
2144 for (i = 0; i < ID_NUM; ++i) {
2145 if (ids [i]) {
2146 for (j = 0; j < ids [i]->len; ++j)
2147 g_free (g_ptr_array_index (ids [i], j));
2148 g_ptr_array_free (ids [i], TRUE);
2150 ids [i] = NULL;
2154 static void
2155 debugger_agent_free_domain_info (MonoDomain *domain)
2157 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2158 int i, j;
2159 GHashTableIter iter;
2160 GPtrArray *file_names;
2161 char *basename;
2162 GSList *l;
2164 if (info) {
2165 for (i = 0; i < ID_NUM; ++i)
2166 g_hash_table_destroy (info->val_to_id [i]);
2167 g_hash_table_destroy (info->loaded_classes);
2169 g_hash_table_iter_init (&iter, info->source_files);
2170 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2171 for (i = 0; i < file_names->len; ++i)
2172 g_free (g_ptr_array_index (file_names, i));
2173 g_ptr_array_free (file_names, TRUE);
2176 g_hash_table_iter_init (&iter, info->source_file_to_class);
2177 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2178 g_free (basename);
2179 g_slist_free (l);
2182 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2183 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2184 g_free (basename);
2185 g_slist_free (l);
2188 g_free (info);
2191 domain_jit_info (domain)->agent_info = NULL;
2193 /* Clear ids referencing structures in the domain */
2194 dbg_lock ();
2195 for (i = 0; i < ID_NUM; ++i) {
2196 if (ids [i]) {
2197 for (j = 0; j < ids [i]->len; ++j) {
2198 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2199 if (id->domain == domain)
2200 id->domain = NULL;
2204 dbg_unlock ();
2206 mono_de_domain_remove (domain);
2209 static AgentDomainInfo*
2210 get_agent_domain_info (MonoDomain *domain)
2212 AgentDomainInfo *info = NULL;
2214 mono_domain_lock (domain);
2216 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2217 if (!info) {
2218 info = g_new0 (AgentDomainInfo, 1);
2219 domain_jit_info (domain)->agent_info = info;
2220 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2221 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2222 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2223 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2226 mono_domain_unlock (domain);
2228 return info;
2231 static int
2232 get_id (MonoDomain *domain, IdType type, gpointer val)
2234 Id *id;
2235 AgentDomainInfo *info;
2237 if (val == NULL)
2238 return 0;
2240 info = get_agent_domain_info (domain);
2242 dbg_lock ();
2244 if (info->val_to_id [type] == NULL)
2245 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2247 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2248 if (id) {
2249 dbg_unlock ();
2250 return id->id;
2253 id = g_new0 (Id, 1);
2254 /* Reserve id 0 */
2255 id->id = ids [type]->len + 1;
2256 id->domain = domain;
2257 id->data.val = val;
2259 g_hash_table_insert (info->val_to_id [type], val, id);
2260 g_ptr_array_add (ids [type], id);
2262 dbg_unlock ();
2264 return id->id;
2267 static inline gpointer
2268 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2270 Id *res;
2272 int id = decode_id (buf, endbuf, limit);
2274 *err = ERR_NONE;
2275 if (domain)
2276 *domain = NULL;
2278 if (id == 0)
2279 return NULL;
2281 // FIXME: error handling
2282 dbg_lock ();
2283 g_assert (id > 0 && id <= ids [type]->len);
2285 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2286 dbg_unlock ();
2288 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2289 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2290 *err = ERR_UNLOADED;
2291 return NULL;
2294 if (domain)
2295 *domain = res->domain;
2297 return res->data.val;
2300 static inline int
2301 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2303 int id = get_id (domain, type, val);
2305 buffer_add_id (buf, id);
2306 return id;
2309 static inline MonoClass*
2310 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2312 MonoClass *klass;
2314 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2315 if (G_UNLIKELY (log_level >= 2) && klass) {
2316 char *s;
2318 s = mono_type_full_name (m_class_get_byval_arg (klass));
2319 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2320 g_free (s);
2322 return klass;
2325 static inline MonoAssembly*
2326 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2328 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2331 static inline MonoImage*
2332 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2334 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2337 static inline MonoMethod*
2338 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2340 MonoMethod *m;
2342 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2343 if (G_UNLIKELY (log_level >= 2) && m) {
2344 char *s;
2346 s = mono_method_full_name (m, TRUE);
2347 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2348 g_free (s);
2350 return m;
2353 static inline MonoClassField*
2354 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2356 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2359 static inline MonoDomain*
2360 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2362 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2365 static inline MonoProperty*
2366 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2368 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2371 static inline void
2372 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2374 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2375 if (G_UNLIKELY (log_level >= 2) && klass) {
2376 char *s;
2378 s = mono_type_full_name (m_class_get_byval_arg (klass));
2379 if (is_debugger_thread ())
2380 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2381 else
2382 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2383 g_free (s);
2387 static inline void
2388 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2390 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2391 if (G_UNLIKELY (log_level >= 2) && method) {
2392 char *s;
2394 s = mono_method_full_name (method, 1);
2395 if (is_debugger_thread ())
2396 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2397 else
2398 DEBUG_PRINTF (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2399 g_free (s);
2403 static inline void
2404 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2406 int id;
2408 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2409 if (G_UNLIKELY (log_level >= 2) && assembly)
2410 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2413 static inline void
2414 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2416 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2419 static inline void
2420 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2422 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2425 static inline void
2426 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2428 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2431 static inline void
2432 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2434 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2437 static void invoke_method (void);
2440 * SUSPEND/RESUME
2443 static MonoJitInfo*
2444 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2446 MonoJitInfo *ji;
2448 if (out_ip)
2449 *out_ip = ip;
2451 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2452 if (!ji) {
2453 /* Could be an interpreter method */
2455 MonoLMF *lmf = mono_get_lmf ();
2456 MonoInterpFrameHandle *frame;
2458 g_assert (((gsize)lmf->previous_lmf) & 2);
2459 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2461 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2462 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2463 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2464 if (domain)
2465 *domain = mono_domain_get ();
2466 if (out_ip)
2467 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2469 return ji;
2473 * save_thread_context:
2475 * Set CTX as the current threads context which is used for computing stack traces.
2476 * This function is signal-safe.
2478 static void
2479 save_thread_context (MonoContext *ctx)
2481 DebuggerTlsData *tls;
2483 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2484 g_assert (tls);
2486 if (ctx)
2487 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2488 else
2489 mono_thread_state_init_from_current (&tls->context);
2492 /* Number of threads suspended */
2494 * If this is equal to the size of thread_to_tls, the runtime is considered
2495 * suspended.
2497 static gint32 threads_suspend_count;
2499 static MonoCoopMutex suspend_mutex;
2501 /* Cond variable used to wait for suspend_count becoming 0 */
2502 static MonoCoopCond suspend_cond;
2504 /* Semaphore used to wait for a thread becoming suspended */
2505 static MonoCoopSem suspend_sem;
2507 static void
2508 suspend_init (void)
2510 mono_coop_mutex_init (&suspend_mutex);
2511 mono_coop_cond_init (&suspend_cond);
2512 mono_coop_sem_init (&suspend_sem, 0);
2515 typedef struct
2517 StackFrameInfo last_frame;
2518 gboolean last_frame_set;
2519 MonoContext ctx;
2520 gpointer lmf;
2521 MonoDomain *domain;
2522 } GetLastFrameUserData;
2524 static gboolean
2525 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2527 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2529 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2530 return FALSE;
2532 if (!data->last_frame_set) {
2533 /* Store the last frame */
2534 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2535 data->last_frame_set = TRUE;
2536 return FALSE;
2537 } else {
2538 /* Store the context/lmf for the frame above the last frame */
2539 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2540 data->lmf = info->lmf;
2541 data->domain = info->domain;
2542 return TRUE;
2546 static void
2547 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2549 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2551 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2552 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2553 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2554 to->valid = TRUE;
2558 * thread_interrupt:
2560 * Process interruption of a thread. This should be signal safe.
2562 * This always runs in the debugger thread.
2564 static void
2565 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2567 gpointer ip;
2568 MonoNativeThreadId tid;
2570 g_assert (info);
2572 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2573 tid = mono_thread_info_get_tid (info);
2575 // FIXME: Races when the thread leaves managed code before hitting a single step
2576 // event.
2578 if (ji && !ji->is_trampoline) {
2579 /* Running managed code, will be suspended by the single step code */
2580 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2581 } else {
2583 * Running native code, will be suspended when it returns to/enters
2584 * managed code. Treat it as already suspended.
2585 * This might interrupt the code in mono_de_process_single_step (), we use the
2586 * tls->suspending flag to avoid races when that happens.
2588 if (!tls->suspended && !tls->suspending) {
2589 GetLastFrameUserData data;
2591 // FIXME: printf is not signal safe, but this is only used during
2592 // debugger debugging
2593 if (ip)
2594 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2595 //save_thread_context (&ctx);
2597 if (!tls->thread)
2598 /* Already terminated */
2599 return;
2602 * We are in a difficult position: we want to be able to provide stack
2603 * traces for this thread, but we can't use the current ctx+lmf, since
2604 * the thread is still running, so it might return to managed code,
2605 * making these invalid.
2606 * So we start a stack walk and save the first frame, along with the
2607 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2608 * suspended when it returns to managed code, so the parent's ctx should
2609 * remain valid.
2611 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2613 data.last_frame_set = FALSE;
2614 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2615 if (data.last_frame_set) {
2616 gpointer jit_tls = tls->thread->thread_info->jit_data;
2618 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2620 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2622 * Store the current lmf instead of the parent one, since that
2623 * contains the interp exit data.
2625 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2628 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2629 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2630 } else {
2631 tls->async_state.valid = FALSE;
2634 mono_memory_barrier ();
2636 tls->suspended = TRUE;
2637 mono_coop_sem_post (&suspend_sem);
2643 * reset_native_thread_suspend_state:
2645 * Reset the suspended flag and state on native threads
2647 static void
2648 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2650 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2652 if (!tls->really_suspended && tls->suspended) {
2653 tls->suspended = FALSE;
2655 * The thread might still be running if it was executing native code, so the state won't be invalided by
2656 * suspend_current ().
2658 tls->context.valid = FALSE;
2659 tls->async_state.valid = FALSE;
2660 invalidate_frames (tls);
2664 typedef struct {
2665 DebuggerTlsData *tls;
2666 gboolean valid_info;
2667 } InterruptData;
2669 static SuspendThreadResult
2670 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2672 InterruptData *data = (InterruptData *)user_data;
2673 MonoJitInfo *ji;
2675 data->valid_info = TRUE;
2676 ji = mono_jit_info_table_find_internal (
2677 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2678 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2679 TRUE,
2680 TRUE);
2682 /* This is signal safe */
2683 thread_interrupt (data->tls, info, ji);
2684 return MonoResumeThread;
2688 * notify_thread:
2690 * Notify a thread that it needs to suspend.
2692 static void
2693 notify_thread (gpointer key, gpointer value, gpointer user_data)
2695 MonoInternalThread *thread = (MonoInternalThread *)key;
2696 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2697 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2699 if (mono_thread_internal_is_current (thread) || tls->terminated)
2700 return;
2702 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2704 /* This is _not_ equivalent to mono_thread_internal_abort () */
2705 InterruptData interrupt_data = { 0 };
2706 interrupt_data.tls = tls;
2708 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2709 if (!interrupt_data.valid_info) {
2710 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2712 * Attached thread which died without detaching.
2714 tls->terminated = TRUE;
2718 static void
2719 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2721 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2722 MonoJitInfo *ji;
2723 MonoMethod *method;
2725 if (mono_loader_lock_is_owned_by_self ()) {
2727 * Shortcut for the check in suspend_current (). This speeds up processing
2728 * when executing long running code inside the loader lock, i.e. assembly load
2729 * hooks.
2731 return;
2734 if (is_debugger_thread ())
2735 return;
2737 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2738 if (suspend_count - tls->resume_count > 0)
2739 tls->suspending = TRUE;
2741 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2743 if (suspend_count - tls->resume_count == 0) {
2745 * We are executing a single threaded invoke but the single step for
2746 * suspending is still active.
2747 * FIXME: This slows down single threaded invokes.
2749 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2750 return;
2753 ji = get_top_method_ji (ip, NULL, NULL);
2754 g_assert (ji);
2755 /* Can't suspend in these methods */
2756 method = jinfo_get_method (ji);
2757 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2758 return;
2760 save_thread_context (ctx);
2762 suspend_current ();
2766 /* Conditionally call process_suspend depending oh the current state */
2767 static gboolean
2768 try_process_suspend (void *the_tls, MonoContext *ctx)
2770 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2772 if (suspend_count > 0) {
2773 /* Fastpath during invokes, see in process_suspend () */
2774 if (suspend_count - tls->resume_count == 0)
2775 return FALSE;
2776 process_suspend (tls, ctx);
2777 return TRUE;
2779 return FALSE;
2783 * suspend_vm:
2785 * Increase the suspend count of the VM. While the suspend count is greater
2786 * than 0, runtime threads are suspended at certain points during execution.
2788 static void
2789 suspend_vm (void)
2791 gboolean tp_suspend = FALSE;
2792 mono_loader_lock ();
2794 mono_coop_mutex_lock (&suspend_mutex);
2796 suspend_count ++;
2798 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2800 if (suspend_count == 1) {
2801 // FIXME: Is it safe to call this inside the lock ?
2802 mono_de_start_single_stepping ();
2803 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2806 mono_coop_mutex_unlock (&suspend_mutex);
2808 if (suspend_count == 1)
2810 * Suspend creation of new threadpool threads, since they cannot run
2812 tp_suspend = TRUE;
2813 mono_loader_unlock ();
2815 if (tp_suspend)
2816 mono_threadpool_suspend ();
2820 * resume_vm:
2822 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2823 * are resumed.
2825 static void
2826 resume_vm (void)
2828 g_assert (is_debugger_thread ());
2829 gboolean tp_resume = FALSE;
2831 mono_loader_lock ();
2833 mono_coop_mutex_lock (&suspend_mutex);
2835 g_assert (suspend_count > 0);
2836 suspend_count --;
2838 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2840 if (suspend_count == 0) {
2841 // FIXME: Is it safe to call this inside the lock ?
2842 mono_de_stop_single_stepping ();
2843 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2846 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2847 mono_coop_cond_broadcast (&suspend_cond);
2849 mono_coop_mutex_unlock (&suspend_mutex);
2850 //g_assert (err == 0);
2852 if (suspend_count == 0)
2853 tp_resume = TRUE;
2854 mono_loader_unlock ();
2856 if (tp_resume)
2857 mono_threadpool_resume ();
2861 * resume_thread:
2863 * Resume just one thread.
2865 static void
2866 resume_thread (MonoInternalThread *thread)
2868 DebuggerTlsData *tls;
2870 g_assert (is_debugger_thread ());
2872 mono_loader_lock ();
2874 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2875 g_assert (tls);
2877 mono_coop_mutex_lock (&suspend_mutex);
2879 g_assert (suspend_count > 0);
2881 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2883 tls->resume_count += suspend_count;
2886 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2887 * but only the one whose resume_count field is > 0 will be resumed.
2889 mono_coop_cond_broadcast (&suspend_cond);
2891 mono_coop_mutex_unlock (&suspend_mutex);
2892 //g_assert (err == 0);
2894 mono_loader_unlock ();
2897 static void
2898 free_frames (StackFrame **frames, int nframes)
2900 int i;
2902 for (i = 0; i < nframes; ++i) {
2903 if (frames [i]->jit)
2904 mono_debug_free_method_jit_info (frames [i]->jit);
2905 g_free (frames [i]);
2907 g_free (frames);
2910 static void
2911 invalidate_frames (DebuggerTlsData *tls)
2913 mono_loader_lock ();
2915 if (!tls)
2916 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2917 g_assert (tls);
2919 free_frames (tls->frames, tls->frame_count);
2920 tls->frame_count = 0;
2921 tls->frames = NULL;
2923 free_frames (tls->restore_frames, tls->restore_frame_count);
2924 tls->restore_frame_count = 0;
2925 tls->restore_frames = NULL;
2927 mono_loader_unlock ();
2931 * suspend_current:
2933 * Suspend the current thread until the runtime is resumed. If the thread has a
2934 * pending invoke, then the invoke is executed before this function returns.
2936 static void
2937 suspend_current (void)
2939 DebuggerTlsData *tls;
2941 g_assert (!is_debugger_thread ());
2943 if (mono_loader_lock_is_owned_by_self ()) {
2945 * If we own the loader mutex, can't suspend until we release it, since the
2946 * whole runtime can deadlock otherwise.
2948 return;
2951 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2952 g_assert (tls);
2954 gboolean do_resume = FALSE;
2955 while (!do_resume) {
2956 mono_coop_mutex_lock (&suspend_mutex);
2958 tls->suspending = FALSE;
2959 tls->really_suspended = TRUE;
2961 if (!tls->suspended) {
2962 tls->suspended = TRUE;
2963 mono_coop_sem_post (&suspend_sem);
2966 mono_debugger_log_suspend (tls);
2967 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2969 while (suspend_count - tls->resume_count > 0) {
2970 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2973 tls->suspended = FALSE;
2974 tls->really_suspended = FALSE;
2976 threads_suspend_count --;
2978 mono_coop_mutex_unlock (&suspend_mutex);
2980 mono_debugger_log_resume (tls);
2981 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2983 if (tls->pending_invoke) {
2984 /* Save the original context */
2985 tls->pending_invoke->has_ctx = TRUE;
2986 tls->pending_invoke->ctx = tls->context.ctx;
2988 invoke_method ();
2990 /* Have to suspend again */
2991 } else {
2992 do_resume = TRUE;
2996 /* The frame info becomes invalid after a resume */
2997 tls->context.valid = FALSE;
2998 tls->async_state.valid = FALSE;
2999 invalidate_frames (tls);
3000 mono_stopwatch_start (&tls->step_time);
3003 static void
3004 count_thread (gpointer key, gpointer value, gpointer user_data)
3006 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3008 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3009 *(int*)user_data = *(int*)user_data + 1;
3012 static int
3013 count_threads_to_wait_for (void)
3015 int count = 0;
3017 mono_loader_lock ();
3018 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3019 mono_loader_unlock ();
3021 return count;
3025 * wait_for_suspend:
3027 * Wait until the runtime is completely suspended.
3029 static void
3030 wait_for_suspend (void)
3032 int nthreads, nwait, err;
3033 gboolean waited = FALSE;
3035 // FIXME: Threads starting/stopping ?
3036 mono_loader_lock ();
3037 nthreads = mono_g_hash_table_size (thread_to_tls);
3038 mono_loader_unlock ();
3040 while (TRUE) {
3041 nwait = count_threads_to_wait_for ();
3042 if (nwait) {
3043 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3044 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3045 g_assert (err == 0);
3046 waited = TRUE;
3047 } else {
3048 break;
3052 if (waited)
3053 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3057 * is_suspended:
3059 * Return whenever the runtime is suspended.
3061 static gboolean
3062 is_suspended (void)
3064 return count_threads_to_wait_for () == 0;
3067 static void
3068 no_seq_points_found (MonoMethod *method, int offset)
3071 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3073 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3076 typedef struct {
3077 DebuggerTlsData *tls;
3078 GSList *frames;
3079 gboolean set_debugger_flag;
3080 } ComputeFramesUserData;
3082 static gboolean
3083 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3085 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3086 StackFrame *frame;
3087 MonoMethod *method, *actual_method, *api_method;
3088 SeqPoint sp;
3089 int flags = 0;
3091 mono_loader_lock ();
3092 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3093 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3094 /* Mark the last frame as an invoke frame */
3095 if (ud->frames)
3096 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3097 else
3098 ud->set_debugger_flag = TRUE;
3100 mono_loader_unlock ();
3101 return FALSE;
3104 if (info->ji)
3105 method = jinfo_get_method (info->ji);
3106 else
3107 method = info->method;
3108 actual_method = info->actual_method;
3109 api_method = method;
3111 if (!method) {
3112 mono_loader_unlock ();
3113 return FALSE;
3116 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3117 mono_loader_unlock ();
3118 return FALSE;
3121 if (info->il_offset == -1) {
3122 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3123 if (ud->frames == NULL) {
3124 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3125 info->il_offset = sp.il_offset;
3127 if (info->il_offset == -1)
3128 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3131 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);
3133 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3134 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3135 /* Older clients can't handle this flag */
3136 mono_loader_unlock ();
3137 return FALSE;
3139 api_method = mono_marshal_method_from_wrapper (method);
3140 if (!api_method) {
3141 mono_loader_unlock ();
3142 return FALSE;
3144 actual_method = api_method;
3145 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3148 if (ud->set_debugger_flag) {
3149 g_assert (g_slist_length (ud->frames) == 0);
3150 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3151 ud->set_debugger_flag = FALSE;
3154 frame = g_new0 (StackFrame, 1);
3155 frame->de.ji = info->ji;
3156 frame->de.domain = info->domain;
3157 frame->de.method = method;
3158 frame->de.native_offset = info->native_offset;
3160 frame->actual_method = actual_method;
3161 frame->api_method = api_method;
3162 frame->il_offset = info->il_offset;
3163 frame->flags = flags;
3164 frame->interp_frame = info->interp_frame;
3165 frame->frame_addr = info->frame_addr;
3166 if (info->reg_locations)
3167 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3168 if (ctx) {
3169 frame->ctx = *ctx;
3170 frame->has_ctx = TRUE;
3173 ud->frames = g_slist_append (ud->frames, frame);
3175 mono_loader_unlock ();
3176 return FALSE;
3179 static gboolean
3180 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3182 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3185 * 'tls->filter_ctx' is the location of the throw site.
3187 * mono_walk_stack() will never actually hit the throw site, but unwind
3188 * directly from the filter to the call site; we abort stack unwinding here
3189 * once this happens and resume from the throw site.
3191 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3192 return TRUE;
3194 return process_frame (info, ctx, user_data);
3198 * Return a malloc-ed list of StackFrame structures.
3200 static StackFrame**
3201 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3203 ComputeFramesUserData user_data;
3204 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3205 StackFrame **res;
3206 int i, nframes;
3207 GSList *l;
3209 user_data.tls = tls;
3210 user_data.frames = NULL;
3212 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3214 nframes = g_slist_length (user_data.frames);
3215 res = g_new0 (StackFrame*, nframes);
3216 l = user_data.frames;
3217 for (i = 0; i < nframes; ++i) {
3218 res [i] = (StackFrame *)l->data;
3219 l = l->next;
3221 *out_nframes = nframes;
3223 return res;
3226 static void
3227 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3229 ComputeFramesUserData user_data;
3230 GSList *tmp;
3231 int i, findex, new_frame_count;
3232 StackFrame **new_frames, *f;
3233 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3235 // FIXME: Locking on tls
3236 if (tls->frames && tls->frames_up_to_date && !force_update)
3237 return;
3239 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3241 user_data.tls = tls;
3242 user_data.frames = NULL;
3243 if (tls->terminated) {
3244 tls->frame_count = 0;
3245 return;
3246 } if (!tls->really_suspended && tls->async_state.valid) {
3247 /* Have to use the state saved by the signal handler */
3248 process_frame (&tls->async_last_frame, NULL, &user_data);
3249 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3250 } else if (tls->filter_state.valid) {
3252 * We are inside an exception filter.
3254 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3256 if (tls->context.valid) {
3257 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3258 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3261 * After that, we resume unwinding from the location where the exception has been thrown.
3263 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3264 } else if (tls->context.valid) {
3265 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3266 } else {
3267 // FIXME:
3268 tls->frame_count = 0;
3269 return;
3272 new_frame_count = g_slist_length (user_data.frames);
3273 new_frames = g_new0 (StackFrame*, new_frame_count);
3274 findex = 0;
3275 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3276 f = (StackFrame *)tmp->data;
3279 * Reuse the id for already existing stack frames, so invokes don't invalidate
3280 * the still valid stack frames.
3282 for (i = 0; i < tls->frame_count; ++i) {
3283 if (tls->frames [i]->frame_addr == f->frame_addr) {
3284 f->id = tls->frames [i]->id;
3285 break;
3289 if (i >= tls->frame_count)
3290 f->id = mono_atomic_inc_i32 (&frame_id);
3292 new_frames [findex ++] = f;
3295 g_slist_free (user_data.frames);
3297 invalidate_frames (tls);
3299 tls->frames = new_frames;
3300 tls->frame_count = new_frame_count;
3301 tls->frames_up_to_date = TRUE;
3305 * GHFunc to emit an appdomain creation event
3306 * @param key Don't care
3307 * @param value A loaded appdomain
3308 * @param user_data Don't care
3310 static void
3311 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3313 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3314 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3318 * GHFunc to emit a thread start event
3319 * @param key A thread id
3320 * @param value A thread object
3321 * @param user_data Don't care
3323 static void
3324 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3326 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3327 process_profiler_event (EVENT_KIND_THREAD_START, value);
3331 * GFunc to emit an assembly load event
3332 * @param value A loaded assembly
3333 * @param user_data Don't care
3335 static void
3336 emit_assembly_load (gpointer value, gpointer user_data)
3338 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3342 * GFunc to emit a type load event
3343 * @param value A loaded type
3344 * @param user_data Don't care
3346 static void
3347 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3349 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3352 static char*
3353 strdup_tolower (char *s)
3355 char *s2, *p;
3357 s2 = g_strdup (s);
3358 for (p = s2; *p; ++p)
3359 *p = tolower (*p);
3360 return s2;
3364 * Same as g_path_get_basename () but handles windows paths as well,
3365 * which can occur in .mdb files created by pdb2mdb.
3367 static char*
3368 dbg_path_get_basename (const char *filename)
3370 char *r;
3372 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3373 return g_path_get_basename (filename);
3375 /* From gpath.c */
3377 /* No separator -> filename */
3378 r = (char*)strrchr (filename, '\\');
3379 if (r == NULL)
3380 return g_strdup (filename);
3382 /* Trailing slash, remove component */
3383 if (r [1] == 0){
3384 char *copy = g_strdup (filename);
3385 copy [r-filename] = 0;
3386 r = strrchr (copy, '\\');
3388 if (r == NULL){
3389 g_free (copy);
3390 return g_strdup ("/");
3392 r = g_strdup (&r[1]);
3393 g_free (copy);
3394 return r;
3397 return g_strdup (&r[1]);
3400 static void
3401 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3403 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3404 ERROR_DECL (error);
3405 MonoCustomAttrInfo *ainfo;
3407 if (ji->dbg_attrs_inited)
3408 return;
3410 if (!hidden_klass)
3411 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3413 if (!step_through_klass)
3414 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3416 if (!non_user_klass)
3417 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3419 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3420 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3421 if (ainfo) {
3422 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3423 ji->dbg_hidden = TRUE;
3424 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3425 ji->dbg_step_through = TRUE;
3426 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3427 ji->dbg_non_user_code = TRUE;
3428 mono_custom_attrs_free (ainfo);
3431 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3432 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3433 if (ainfo) {
3434 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3435 ji->dbg_step_through = TRUE;
3436 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3437 ji->dbg_non_user_code = TRUE;
3438 mono_custom_attrs_free (ainfo);
3441 mono_memory_barrier ();
3442 ji->dbg_attrs_inited = TRUE;
3446 * EVENT HANDLING
3450 * create_event_list:
3452 * Return a list of event request ids matching EVENT, starting from REQS, which
3453 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3454 * policy.
3455 * We return request ids, instead of requests, to simplify threading, since
3456 * requests could be deleted anytime when the loader lock is not held.
3457 * LOCKING: Assumes the loader lock is held.
3459 static GSList*
3460 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3462 int i, j;
3463 GSList *events = NULL;
3465 *suspend_policy = SUSPEND_POLICY_NONE;
3467 if (!reqs)
3468 reqs = event_requests;
3470 if (!reqs)
3471 return NULL;
3473 for (i = 0; i < reqs->len; ++i) {
3474 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3475 if (req->event_kind == event) {
3476 gboolean filtered = FALSE;
3478 /* Apply filters */
3479 for (j = 0; j < req->nmodifiers; ++j) {
3480 Modifier *mod = &req->modifiers [j];
3482 if (mod->kind == MOD_KIND_COUNT) {
3483 filtered = TRUE;
3484 if (mod->data.count > 0) {
3485 if (mod->data.count > 0) {
3486 mod->data.count --;
3487 if (mod->data.count == 0)
3488 filtered = FALSE;
3491 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3492 if (mod->data.thread != mono_thread_internal_current ())
3493 filtered = TRUE;
3494 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3495 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3496 filtered = TRUE;
3497 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3498 filtered = TRUE;
3499 if (ei->caught && !mod->caught)
3500 filtered = TRUE;
3501 if (!ei->caught && !mod->uncaught)
3502 filtered = TRUE;
3503 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3504 int k;
3505 gboolean found = FALSE;
3506 MonoAssembly **assemblies = mod->data.assemblies;
3508 if (assemblies) {
3509 for (k = 0; assemblies [k]; ++k)
3510 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3511 found = TRUE;
3513 if (!found)
3514 filtered = TRUE;
3515 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3516 gpointer iter = NULL;
3517 MonoMethod *method;
3518 MonoDebugSourceInfo *sinfo;
3519 char *source_file, *s;
3520 gboolean found = FALSE;
3521 int i;
3522 GPtrArray *source_file_list;
3524 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3525 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3527 if (minfo) {
3528 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3529 for (i = 0; i < source_file_list->len; ++i) {
3530 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3532 * Do a case-insesitive match by converting the file name to
3533 * lowercase.
3535 s = strdup_tolower (sinfo->source_file);
3536 if (g_hash_table_lookup (mod->data.source_files, s))
3537 found = TRUE;
3538 else {
3539 char *s2 = dbg_path_get_basename (sinfo->source_file);
3540 char *s3 = strdup_tolower (s2);
3542 if (g_hash_table_lookup (mod->data.source_files, s3))
3543 found = TRUE;
3544 g_free (s2);
3545 g_free (s3);
3547 g_free (s);
3549 g_ptr_array_free (source_file_list, TRUE);
3552 if (!found)
3553 filtered = TRUE;
3554 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3555 char *s;
3557 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3558 if (!g_hash_table_lookup (mod->data.type_names, s))
3559 filtered = TRUE;
3560 g_free (s);
3561 } else if (mod->kind == MOD_KIND_STEP) {
3562 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3563 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3564 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3565 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3566 filtered = TRUE;
3567 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3568 init_jit_info_dbg_attrs (ji);
3569 if (ji->dbg_hidden)
3570 filtered = TRUE;
3572 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3573 init_jit_info_dbg_attrs (ji);
3574 if (ji->dbg_step_through)
3575 filtered = TRUE;
3577 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3578 init_jit_info_dbg_attrs (ji);
3579 if (ji->dbg_non_user_code)
3580 filtered = TRUE;
3585 if (!filtered) {
3586 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3587 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3592 /* Send a VM START/DEATH event by default */
3593 if (event == EVENT_KIND_VM_START)
3594 events = g_slist_append (events, GINT_TO_POINTER (0));
3595 if (event == EVENT_KIND_VM_DEATH)
3596 events = g_slist_append (events, GINT_TO_POINTER (0));
3598 return events;
3601 static G_GNUC_UNUSED const char*
3602 event_to_string (EventKind event)
3604 switch (event) {
3605 case EVENT_KIND_VM_START: return "VM_START";
3606 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3607 case EVENT_KIND_THREAD_START: return "THREAD_START";
3608 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3609 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3610 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3611 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3612 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3613 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3614 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3615 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3616 case EVENT_KIND_STEP: return "STEP";
3617 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3618 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3619 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3620 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3621 case EVENT_KIND_USER_LOG: return "USER_LOG";
3622 case EVENT_KIND_CRASH: return "CRASH";
3623 default:
3624 g_assert_not_reached ();
3625 return "";
3630 * process_event:
3632 * Send an event to the client, suspending the vm if needed.
3633 * LOCKING: Since this can suspend the calling thread, no locks should be held
3634 * by the caller.
3635 * The EVENTS list is freed by this function.
3637 static void
3638 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3640 Buffer buf;
3641 GSList *l;
3642 MonoDomain *domain = mono_domain_get ();
3643 MonoThread *thread = NULL;
3644 MonoObject *keepalive_obj = NULL;
3645 gboolean send_success = FALSE;
3646 static int ecount;
3647 int nevents;
3649 if (!inited) {
3650 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3651 return;
3654 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3655 // FIXME: We miss those events
3656 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3657 return;
3660 if (vm_death_event_sent) {
3661 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3662 return;
3665 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3666 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3667 return;
3670 if (disconnected) {
3671 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3672 return;
3675 if (event == EVENT_KIND_KEEPALIVE)
3676 suspend_policy = SUSPEND_POLICY_NONE;
3677 else {
3678 if (events == NULL)
3679 return;
3681 if (agent_config.defer) {
3682 if (is_debugger_thread ()) {
3683 /* Don't suspend on events from the debugger thread */
3684 suspend_policy = SUSPEND_POLICY_NONE;
3686 } else {
3687 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3688 // FIXME: Send these with a NULL thread, don't suspend the current thread
3689 return;
3693 nevents = g_slist_length (events);
3694 buffer_init (&buf, 128);
3695 buffer_add_byte (&buf, suspend_policy);
3696 buffer_add_int (&buf, nevents);
3698 for (l = events; l; l = l->next) {
3699 buffer_add_byte (&buf, event); // event kind
3700 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3702 ecount ++;
3704 if (event == EVENT_KIND_VM_DEATH) {
3705 thread = NULL;
3706 } else {
3707 if (!thread)
3708 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3710 if (event == EVENT_KIND_VM_START && arg != NULL)
3711 thread = (MonoThread *)arg;
3714 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3716 switch (event) {
3717 case EVENT_KIND_THREAD_START:
3718 case EVENT_KIND_THREAD_DEATH:
3719 break;
3720 case EVENT_KIND_APPDOMAIN_CREATE:
3721 case EVENT_KIND_APPDOMAIN_UNLOAD:
3722 buffer_add_domainid (&buf, (MonoDomain *)arg);
3723 break;
3724 case EVENT_KIND_METHOD_ENTRY:
3725 case EVENT_KIND_METHOD_EXIT:
3726 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3727 break;
3728 case EVENT_KIND_ASSEMBLY_LOAD:
3729 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3730 break;
3731 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3732 DebuggerTlsData *tls;
3734 /* The domain the assembly belonged to is not equal to the current domain */
3735 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3736 g_assert (tls);
3737 g_assert (tls->domain_unloading);
3739 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3740 break;
3742 case EVENT_KIND_TYPE_LOAD:
3743 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3744 break;
3745 case EVENT_KIND_BREAKPOINT:
3746 case EVENT_KIND_STEP: {
3747 DebuggerTlsData *tls;
3748 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3749 g_assert (tls);
3750 mono_stopwatch_stop (&tls->step_time);
3751 MonoMethod *method = (MonoMethod *)arg;
3753 buffer_add_methodid (&buf, domain, method);
3754 buffer_add_long (&buf, il_offset);
3755 break;
3757 case EVENT_KIND_VM_START:
3758 buffer_add_domainid (&buf, mono_get_root_domain ());
3759 break;
3760 case EVENT_KIND_VM_DEATH:
3761 if (CHECK_PROTOCOL_VERSION (2, 27))
3762 buffer_add_int (&buf, mono_environment_exitcode_get ());
3763 break;
3764 case EVENT_KIND_CRASH: {
3765 EventInfo *ei = (EventInfo *)arg;
3766 buffer_add_long (&buf, ei->hashes->offset_free_hash);
3767 buffer_add_string (&buf, ei->dump);
3768 break;
3770 case EVENT_KIND_EXCEPTION: {
3771 EventInfo *ei = (EventInfo *)arg;
3772 buffer_add_objid (&buf, ei->exc);
3774 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3775 * later after the suspension. (#12494).
3777 keepalive_obj = ei->exc;
3778 break;
3780 case EVENT_KIND_USER_BREAK: {
3781 DebuggerTlsData *tls;
3782 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3783 g_assert (tls);
3784 mono_stopwatch_stop (&tls->step_time);
3785 break;
3787 case EVENT_KIND_USER_LOG: {
3788 EventInfo *ei = (EventInfo *)arg;
3789 buffer_add_int (&buf, ei->level);
3790 buffer_add_string (&buf, ei->category ? ei->category : "");
3791 buffer_add_string (&buf, ei->message ? ei->message : "");
3792 break;
3794 case EVENT_KIND_KEEPALIVE:
3795 suspend_policy = SUSPEND_POLICY_NONE;
3796 break;
3797 default:
3798 g_assert_not_reached ();
3802 if (event == EVENT_KIND_VM_START) {
3803 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3804 if (!agent_config.defer) {
3805 ERROR_DECL (error);
3806 start_debugger_thread (error);
3807 mono_error_assert_ok (error);
3811 if (event == EVENT_KIND_VM_DEATH) {
3812 vm_death_event_sent = TRUE;
3813 suspend_policy = SUSPEND_POLICY_NONE;
3816 if (mono_runtime_is_shutting_down ())
3817 suspend_policy = SUSPEND_POLICY_NONE;
3819 if (suspend_policy != SUSPEND_POLICY_NONE) {
3821 * Save the thread context and start suspending before sending the packet,
3822 * since we could be receiving the resume request before send_packet ()
3823 * returns.
3825 save_thread_context (ctx);
3826 suspend_vm ();
3828 if (keepalive_obj)
3829 /* This will keep this object alive */
3830 get_objref (keepalive_obj);
3833 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3835 if (send_success) {
3836 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3837 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
3840 buffer_free (&buf);
3842 g_slist_free (events);
3843 events = NULL;
3845 if (!send_success) {
3846 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3847 return;
3850 if (event == EVENT_KIND_VM_START) {
3851 vm_start_event_sent = TRUE;
3854 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);
3856 switch (suspend_policy) {
3857 case SUSPEND_POLICY_NONE:
3858 break;
3859 case SUSPEND_POLICY_ALL:
3860 suspend_current ();
3861 break;
3862 case SUSPEND_POLICY_EVENT_THREAD:
3863 NOT_IMPLEMENTED;
3864 break;
3865 default:
3866 g_assert_not_reached ();
3870 static void
3871 process_profiler_event (EventKind event, gpointer arg)
3873 int suspend_policy;
3874 GSList *events;
3875 EventInfo ei, *ei_arg = NULL;
3877 if (event == EVENT_KIND_TYPE_LOAD) {
3878 ei.klass = (MonoClass *)arg;
3879 ei_arg = &ei;
3882 mono_loader_lock ();
3883 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3884 mono_loader_unlock ();
3886 process_event (event, arg, 0, NULL, events, suspend_policy);
3889 static void
3890 runtime_initialized (MonoProfiler *prof)
3892 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3893 if (agent_config.defer) {
3894 ERROR_DECL (error);
3895 start_debugger_thread (error);
3896 mono_error_assert_ok (error);
3900 static void
3901 runtime_shutdown (MonoProfiler *prof)
3903 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3905 mono_debugger_agent_cleanup ();
3908 static void
3909 thread_startup (MonoProfiler *prof, uintptr_t tid)
3911 MonoInternalThread *thread = mono_thread_internal_current ();
3912 MonoInternalThread *old_thread;
3913 DebuggerTlsData *tls;
3915 if (is_debugger_thread ())
3916 return;
3918 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3920 mono_loader_lock ();
3921 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3922 mono_loader_unlock ();
3923 if (old_thread) {
3924 if (thread == old_thread) {
3926 * For some reason, thread_startup () might be called for the same thread
3927 * multiple times (attach ?).
3929 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3930 return;
3931 } else {
3933 * thread_end () might not be called for some threads, and the tid could
3934 * get reused.
3936 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3937 mono_loader_lock ();
3938 mono_g_hash_table_remove (thread_to_tls, old_thread);
3939 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3940 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3941 mono_loader_unlock ();
3945 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3946 g_assert (!tls);
3947 // FIXME: Free this somewhere
3948 tls = g_new0 (DebuggerTlsData, 1);
3949 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
3950 tls->thread = thread;
3951 // Do so we have thread id even after termination
3952 tls->thread_id = (intptr_t) thread->tid;
3953 mono_native_tls_set_value (debugger_tls_id, tls);
3955 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3957 mono_loader_lock ();
3958 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3959 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3960 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3961 mono_loader_unlock ();
3963 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3966 * suspend_vm () could have missed this thread, so wait for a resume.
3969 suspend_current ();
3972 static void
3973 thread_end (MonoProfiler *prof, uintptr_t tid)
3975 MonoInternalThread *thread;
3976 DebuggerTlsData *tls = NULL;
3978 mono_loader_lock ();
3979 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3980 if (thread) {
3981 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3982 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3983 if (tls) {
3984 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3985 tls->terminated = TRUE;
3986 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3987 MONO_GC_UNREGISTER_ROOT (tls->thread);
3988 tls->thread = NULL;
3991 mono_loader_unlock ();
3993 /* We might be called for threads started before we registered the start callback */
3994 if (thread) {
3995 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3997 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
4000 * This can happen on darwin since we deregister threads using pthread dtors.
4001 * process_profiler_event () and the code it calls cannot handle a null TLS value.
4003 return;
4006 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4010 static void
4011 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4013 mono_de_domain_add (domain);
4015 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4018 static void
4019 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4021 DebuggerTlsData *tls;
4023 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4024 if (is_debugger_thread ())
4025 return;
4028 * Remember the currently unloading appdomain as it is needed to generate
4029 * proper ids for unloading assemblies.
4031 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4032 g_assert (tls);
4033 tls->domain_unloading = domain;
4036 static void
4037 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4039 DebuggerTlsData *tls;
4041 if (is_debugger_thread ())
4042 return;
4044 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4045 g_assert (tls);
4046 tls->domain_unloading = NULL;
4048 mono_de_clear_breakpoints_for_domain (domain);
4050 mono_loader_lock ();
4051 /* Invalidate each thread's frame stack */
4052 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4053 mono_loader_unlock ();
4055 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4059 * invalidate_each_thread:
4061 * A GHFunc to invalidate frames.
4062 * value must be a DebuggerTlsData*
4064 static void
4065 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4067 invalidate_frames ((DebuggerTlsData *)value);
4070 static void
4071 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4073 /* Sent later in jit_end () */
4074 dbg_lock ();
4075 g_ptr_array_add (pending_assembly_loads, assembly);
4076 dbg_unlock ();
4079 static void
4080 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4082 if (is_debugger_thread ())
4083 return;
4085 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4087 clear_event_requests_for_assembly (assembly);
4088 clear_types_for_assembly (assembly);
4091 static void
4092 send_type_load (MonoClass *klass)
4094 gboolean type_load = FALSE;
4095 MonoDomain *domain = mono_domain_get ();
4096 AgentDomainInfo *info = NULL;
4098 info = get_agent_domain_info (domain);
4100 mono_loader_lock ();
4102 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4103 type_load = TRUE;
4104 g_hash_table_insert (info->loaded_classes, klass, klass);
4107 mono_loader_unlock ();
4109 if (type_load)
4110 emit_type_load (klass, klass, NULL);
4114 * Emit load events for all types currently loaded in the domain.
4115 * Takes the loader and domain locks.
4116 * user_data is unused.
4118 static void
4119 send_types_for_domain (MonoDomain *domain, void *user_data)
4121 MonoDomain* old_domain;
4122 AgentDomainInfo *info = NULL;
4124 info = get_agent_domain_info (domain);
4125 g_assert (info);
4127 old_domain = mono_domain_get ();
4129 mono_domain_set (domain, TRUE);
4131 mono_loader_lock ();
4132 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4133 mono_loader_unlock ();
4135 mono_domain_set (old_domain, TRUE);
4138 static void
4139 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4141 GSList *tmp;
4142 MonoDomain* old_domain;
4144 old_domain = mono_domain_get ();
4146 mono_domain_set (domain, TRUE);
4148 mono_domain_assemblies_lock (domain);
4149 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4150 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4151 emit_assembly_load (ass, NULL);
4153 mono_domain_assemblies_unlock (domain);
4155 mono_domain_set (old_domain, TRUE);
4158 static void
4159 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4161 jit_end (prof, method, jinfo);
4164 static void
4165 jit_failed (MonoProfiler *prof, MonoMethod *method)
4167 jit_end (prof, method, NULL);
4170 static void
4171 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4174 * We emit type load events when the first method of the type is JITted,
4175 * since the class load profiler callbacks might be called with the
4176 * loader lock held. They could also occur in the debugger thread.
4177 * Same for assembly load events.
4179 while (TRUE) {
4180 MonoAssembly *assembly = NULL;
4182 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4183 dbg_lock ();
4184 if (pending_assembly_loads->len > 0) {
4185 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4186 g_ptr_array_remove_index (pending_assembly_loads, 0);
4188 dbg_unlock ();
4190 if (assembly) {
4191 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4192 } else {
4193 break;
4197 send_type_load (method->klass);
4199 if (jinfo)
4200 mono_de_add_pending_breakpoints (method, jinfo);
4204 * SINGLE STEPPING
4207 static void
4208 event_requests_cleanup (void)
4210 mono_loader_lock ();
4211 int i = 0;
4212 while (i < event_requests->len) {
4213 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4215 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4216 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4217 g_ptr_array_remove_index_fast (event_requests, i);
4218 g_free (req);
4219 } else {
4220 i ++;
4223 mono_loader_unlock ();
4227 * ss_calculate_framecount:
4229 * Ensure DebuggerTlsData fields are filled out.
4231 static void
4232 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4234 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4236 if (force_use_ctx || !tls->context.valid)
4237 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4238 compute_frame_info (tls->thread, tls, FALSE);
4239 if (frames)
4240 *frames = (DbgEngineStackFrame**)tls->frames;
4241 if (nframes)
4242 *nframes = tls->frame_count;
4246 * ss_discard_frame_data:
4248 * Discard frame data and invalidate any context
4250 static void
4251 ss_discard_frame_context (void *the_tls)
4253 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4254 tls->context.valid = FALSE;
4255 tls->async_state.valid = FALSE;
4256 invalidate_frames (tls);
4259 static MonoContext*
4260 tls_get_restore_state (void *the_tls)
4262 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4264 return &tls->restore_state.ctx;
4267 static gboolean
4268 ensure_jit (DbgEngineStackFrame* the_frame)
4270 StackFrame *frame = (StackFrame*)the_frame;
4271 if (!frame->jit) {
4272 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4273 if (!frame->jit && frame->api_method->is_inflated)
4274 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4275 if (!frame->jit) {
4276 char *s;
4278 /* This could happen for aot images with no jit debug info */
4279 s = mono_method_full_name (frame->api_method, TRUE);
4280 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4281 g_free (s);
4282 return FALSE;
4285 return TRUE;
4288 static gboolean
4289 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4291 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4294 static gpointer
4295 get_this_addr (DbgEngineStackFrame *the_frame)
4297 StackFrame *frame = (StackFrame *)the_frame;
4298 if (frame->de.ji->is_interp)
4299 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4301 MonoDebugVarInfo *var = frame->jit->this_var;
4302 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4303 return NULL;
4305 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4306 addr += (gint32)var->offset;
4307 return addr;
4310 static MonoMethod*
4311 get_set_notification_method (MonoClass* async_builder_class)
4313 ERROR_DECL (error);
4314 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, 1, FALSE, error);
4315 mono_error_assert_ok (error);
4316 if (array->len == 0) {
4317 g_ptr_array_free (array, TRUE);
4318 return NULL;
4320 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4321 g_ptr_array_free (array, TRUE);
4322 return set_notification_method;
4325 static MonoMethod*
4326 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4328 ERROR_DECL (error);
4329 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, 1, FALSE, error);
4330 mono_error_assert_ok (error);
4331 g_assert (array->len == 1);
4332 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4333 g_ptr_array_free (array, TRUE);
4334 return method;
4337 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4338 static gpointer
4339 get_async_method_builder (DbgEngineStackFrame *frame)
4341 MonoObject *this_obj;
4342 MonoClassField *builder_field;
4343 gpointer builder;
4344 gpointer this_addr;
4346 builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4347 g_assert (builder_field);
4349 this_addr = get_this_addr (frame);
4350 if (!this_addr)
4351 return NULL;
4353 if (m_class_is_valuetype (frame->method->klass)) {
4354 builder = mono_vtype_get_field_addr (*(guint8**)this_addr, builder_field);
4355 } else {
4356 this_obj = *(MonoObject**)this_addr;
4357 builder = (char*)this_obj + builder_field->offset;
4360 return builder;
4363 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4364 //since thread probably changed...
4365 static int
4366 get_this_async_id (DbgEngineStackFrame *frame)
4368 MonoClassField *builder_field;
4369 gpointer builder;
4370 MonoMethod *method;
4371 MonoObject *ex;
4372 ERROR_DECL (error);
4373 MonoObject *obj;
4374 gboolean old_disable_breakpoints = FALSE;
4375 DebuggerTlsData *tls;
4378 * FRAME points to a method in a state machine class/struct.
4379 * Call the ObjectIdForDebugger method of the associated method builder type.
4381 builder = get_async_method_builder (frame);
4382 if (!builder)
4383 return 0;
4385 builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4386 g_assert (builder_field);
4388 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4389 if (tls) {
4390 old_disable_breakpoints = tls->disable_breakpoints;
4391 tls->disable_breakpoints = TRUE;
4394 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4395 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4396 mono_error_assert_ok (error);
4398 if (tls)
4399 tls->disable_breakpoints = old_disable_breakpoints;
4401 return get_objid (obj);
4404 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4405 // false if not(AsyncVoidBuilder)
4406 static gboolean
4407 set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame)
4409 MonoClassField *builder_field = mono_class_get_field_from_name_full (frame->method->klass, "<>t__builder", NULL);
4410 g_assert (builder_field);
4411 gpointer builder = get_async_method_builder (frame);
4412 g_assert (builder);
4414 void* args [1];
4415 gboolean arg = TRUE;
4416 ERROR_DECL (error);
4417 args [0] = &arg;
4418 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type_internal (builder_field->type));
4419 if (method == NULL)
4420 return FALSE;
4421 mono_runtime_invoke_checked (method, builder, args, error);
4422 mono_error_assert_ok (error);
4423 return TRUE;
4426 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4428 static MonoMethod*
4429 get_notify_debugger_of_wait_completion_method (void)
4431 if (notify_debugger_of_wait_completion_method_cache != NULL)
4432 return notify_debugger_of_wait_completion_method_cache;
4433 ERROR_DECL (error);
4434 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4435 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error);
4436 mono_error_assert_ok (error);
4437 g_assert (array->len == 1);
4438 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4439 g_ptr_array_free (array, TRUE);
4440 return notify_debugger_of_wait_completion_method_cache;
4443 static gboolean
4444 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4446 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4449 * Skip the instruction causing the breakpoint signal.
4451 if (from_signal)
4452 mono_arch_skip_breakpoint (ctx, ji);
4454 if (tls->disable_breakpoints)
4455 return FALSE;
4456 return TRUE;
4459 typedef struct {
4460 GSList *bp_events, *ss_events, *enter_leave_events;
4461 EventKind kind;
4462 int suspend_policy;
4463 } BreakPointEvents;
4465 static void*
4466 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4468 int suspend_policy = 0;
4469 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4470 if (ss_reqs && ss_reqs->len > 0)
4471 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4472 else if (bp_reqs && bp_reqs->len > 0)
4473 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4474 else if (kind != EVENT_KIND_BREAKPOINT)
4475 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4477 evts->kind = kind;
4478 evts->suspend_policy = suspend_policy;
4479 return evts;
4482 static void
4483 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4485 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4487 * FIXME: The first event will suspend, so the second will only be sent after the
4488 * resume.
4490 if (evts->ss_events)
4491 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4492 if (evts->bp_events)
4493 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4494 if (evts->enter_leave_events)
4495 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4497 g_free (evts);
4500 /* Process a breakpoint/single step event after resuming from a signal handler */
4501 static void
4502 process_signal_event (void (*func) (void*, gboolean))
4504 DebuggerTlsData *tls;
4505 MonoThreadUnwindState orig_restore_state;
4506 MonoContext ctx;
4508 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4509 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4510 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4511 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4513 func (tls, TRUE);
4515 /* This is called when resuming from a signal handler, so it shouldn't return */
4516 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4517 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4518 mono_restore_context (&ctx);
4519 g_assert_not_reached ();
4522 static void
4523 process_breakpoint_from_signal (void)
4525 process_signal_event (mono_de_process_breakpoint);
4528 static void
4529 resume_from_signal_handler (void *sigctx, void *func)
4531 DebuggerTlsData *tls;
4532 MonoContext ctx;
4534 /* Save the original context in TLS */
4535 // FIXME: This might not work on an altstack ?
4536 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4537 if (!tls)
4538 g_printerr ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4539 g_assert (tls);
4541 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4542 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4543 // clob:c could be added to op_seq_point.
4545 mono_sigctx_to_monoctx (sigctx, &ctx);
4546 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4547 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4548 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4549 #else
4550 MONO_CONTEXT_SET_IP (&ctx, func);
4551 #endif
4552 mono_monoctx_to_sigctx (&ctx, sigctx);
4555 static void
4556 debugger_agent_breakpoint_hit (void *sigctx)
4559 * We are called from a signal handler, and running code there causes all kinds of
4560 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4561 * So set up the signal context to return to the real breakpoint handler function.
4563 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4566 typedef struct {
4567 gboolean found;
4568 MonoContext *ctx;
4569 } UserBreakCbData;
4571 static gboolean
4572 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4574 UserBreakCbData *data = (UserBreakCbData*)user_data;
4576 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4577 data->found = TRUE;
4578 return TRUE;
4580 if (frame->managed) {
4581 data->found = TRUE;
4582 *data->ctx = *ctx;
4584 return TRUE;
4586 return FALSE;
4590 * Called by System.Diagnostics.Debugger:Break ().
4592 static void
4593 debugger_agent_user_break (void)
4595 if (agent_config.enabled) {
4596 MonoContext ctx;
4597 int suspend_policy;
4598 GSList *events;
4599 UserBreakCbData data;
4601 memset (&data, 0, sizeof (UserBreakCbData));
4602 data.ctx = &ctx;
4604 /* Obtain a context */
4605 MONO_CONTEXT_SET_IP (&ctx, NULL);
4606 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4607 g_assert (data.found);
4609 mono_loader_lock ();
4610 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4611 mono_loader_unlock ();
4613 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4614 } else if (mini_debug_options.native_debugger_break) {
4615 G_BREAKPOINT ();
4619 static void
4620 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4622 if (from_signal)
4623 mono_arch_skip_single_step (ctx);
4626 static void
4627 process_single_step (void)
4629 process_signal_event (mono_de_process_single_step);
4633 * debugger_agent_single_step_event:
4635 * Called from a signal handler to handle a single step event.
4637 static void
4638 debugger_agent_single_step_event (void *sigctx)
4640 /* Resume to process_single_step through the signal context */
4642 // FIXME: Since step out/over is implemented using step in, the step in case should
4643 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4644 // here
4646 if (is_debugger_thread ()) {
4648 * This could happen despite our best effors when the runtime calls
4649 * assembly/type resolve hooks.
4650 * FIXME: Breakpoints too.
4652 MonoContext ctx;
4654 mono_sigctx_to_monoctx (sigctx, &ctx);
4655 mono_arch_skip_single_step (&ctx);
4656 mono_monoctx_to_sigctx (&ctx, sigctx);
4657 return;
4660 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4663 static void
4664 debugger_agent_single_step_from_context (MonoContext *ctx)
4666 DebuggerTlsData *tls;
4667 MonoThreadUnwindState orig_restore_state;
4669 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4670 /* Fastpath during invokes, see in process_suspend () */
4671 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4672 return;
4674 if (is_debugger_thread ())
4675 return;
4677 g_assert (tls);
4679 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4680 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4681 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4682 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4684 mono_de_process_single_step (tls, FALSE);
4686 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4687 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4690 static void
4691 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4693 DebuggerTlsData *tls;
4694 MonoThreadUnwindState orig_restore_state;
4695 guint8 *orig_ip;
4697 if (is_debugger_thread ())
4698 return;
4700 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4701 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4703 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4704 g_assert (tls);
4705 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4706 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4707 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4709 mono_de_process_breakpoint (tls, FALSE);
4711 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4712 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4713 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4714 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4717 static void
4718 ss_args_destroy (SingleStepArgs *ss_args)
4720 if (ss_args->frames)
4721 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
4724 static int
4725 ensure_runtime_is_suspended (void)
4727 if (suspend_count == 0)
4728 return ERR_NOT_SUSPENDED;
4730 wait_for_suspend ();
4732 return ERR_NONE;
4735 static int
4736 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
4738 MonoSeqPointInfo *info = NULL;
4739 gboolean found_sp;
4740 MonoMethod *method = NULL;
4741 MonoDebugMethodInfo *minfo;
4742 gboolean step_to_catch = FALSE;
4743 gboolean set_ip = FALSE;
4744 StackFrame **frames = NULL;
4745 int nframes = 0;
4747 mono_loader_lock ();
4748 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4749 mono_loader_unlock ();
4750 g_assert (tls);
4751 if (!tls->context.valid) {
4752 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
4753 return ERR_INVALID_ARGUMENT;
4756 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
4758 * Need to start single stepping from restore_state and not from the current state
4760 set_ip = TRUE;
4761 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
4764 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4766 if (tls->has_catch_frame) {
4767 StackFrameInfo frame;
4770 * We are stopped at a throw site. Stepping should go to the catch site.
4772 frame = tls->catch_frame;
4773 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
4776 * Find the seq point corresponding to the landing site ip, which is the first seq
4777 * point after ip.
4779 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
4780 if (!found_sp)
4781 no_seq_points_found (frame.method, frame.native_offset);
4782 g_assert (found_sp);
4784 method = frame.method;
4786 step_to_catch = TRUE;
4787 /* This make sure the seq point is not skipped by process_single_step () */
4788 ss_req->last_sp = NULL;
4791 if (!step_to_catch) {
4792 StackFrame *frame = NULL;
4794 if (set_ip) {
4795 if (frames && nframes)
4796 frame = frames [0];
4797 } else {
4798 compute_frame_info (ss_req->thread, tls, FALSE);
4800 if (tls->frame_count)
4801 frame = tls->frames [0];
4804 if (ss_req->size == STEP_SIZE_LINE) {
4805 if (frame) {
4806 ss_req->last_method = frame->de.method;
4807 ss_req->last_line = -1;
4809 minfo = mono_debug_lookup_method (frame->de.method);
4810 if (minfo && frame->il_offset != -1) {
4811 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
4813 if (loc) {
4814 ss_req->last_line = loc->row;
4815 g_free (loc);
4821 if (frame) {
4822 if (!method && frame->il_offset != -1) {
4823 /* FIXME: Sort the table and use a binary search */
4824 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
4825 if (!found_sp)
4826 no_seq_points_found (frame->de.method, frame->de.native_offset);
4827 g_assert (found_sp);
4828 method = frame->de.method;
4833 ss_req->start_method = method;
4835 args->method = method;
4836 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
4837 args->tls = tls;
4838 args->step_to_catch = step_to_catch;
4839 args->info = info;
4840 args->frames = (DbgEngineStackFrame**)frames;
4841 args->nframes = nframes;
4843 return ERR_NONE;
4846 static void
4847 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
4849 GSList *l;
4850 gboolean found = TRUE;
4852 while (found) {
4853 found = FALSE;
4854 for (l = req->bps; l; l = l->next) {
4855 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
4856 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
4857 req->bps = g_slist_delete_link (req->bps, l);
4858 found = TRUE;
4859 break;
4866 * This takes a lot of locks and stuff. Do this at the end, after
4867 * other things have dumped us, so that getting stuck here won't
4868 * prevent seeing other crash information
4870 static void
4871 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
4873 #ifndef DISABLE_CRASH_REPORTING
4874 int suspend_policy;
4875 GSList *events;
4876 EventInfo ei;
4878 if (!agent_config.enabled)
4879 return;
4881 // Don't send the event if the client doesn't expect it
4882 if (!CHECK_PROTOCOL_VERSION (2, 49))
4883 return;
4885 // It doesn't make sense to wait for lldb/gdb to finish if we're not
4886 // actually enabled. Therefore we do the wait here.
4887 sleep (pause);
4889 // Don't heap allocate when we can avoid it
4890 EventRequest request;
4891 memset (&request, 0, sizeof (request));
4892 request.event_kind = EVENT_KIND_CRASH;
4894 gpointer pdata [1];
4895 pdata [0] = &request;
4896 GPtrArray array;
4897 memset (&array, 0, sizeof (array));
4898 array.pdata = pdata;
4899 array.len = 1;
4901 mono_loader_lock ();
4902 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
4903 mono_loader_unlock ();
4905 ei.dump = json_dump;
4906 ei.hashes = hashes;
4908 g_assert (events != NULL);
4910 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
4912 // Don't die before it is sent.
4913 sleep (4);
4914 #endif
4918 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
4920 static void
4921 debugger_agent_debug_log (int level, MonoStringHandle category, MonoStringHandle message)
4923 ERROR_DECL (error);
4924 int suspend_policy;
4925 GSList *events;
4926 EventInfo ei;
4928 if (!agent_config.enabled)
4929 return;
4931 mono_loader_lock ();
4932 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
4933 mono_loader_unlock ();
4935 ei.level = level;
4936 ei.category = NULL;
4937 if (!MONO_HANDLE_IS_NULL (category)) {
4938 ei.category = mono_string_handle_to_utf8 (category, error);
4939 mono_error_cleanup (error);
4941 ei.message = NULL;
4942 if (!MONO_HANDLE_IS_NULL (message)) {
4943 ei.message = mono_string_handle_to_utf8 (message, error);
4944 mono_error_cleanup (error);
4947 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
4949 g_free (ei.category);
4950 g_free (ei.message);
4953 static gboolean
4954 debugger_agent_debug_log_is_enabled (void)
4956 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
4957 return agent_config.enabled;
4960 static void
4961 debugger_agent_unhandled_exception (MonoException *exc)
4963 int suspend_policy;
4964 GSList *events;
4965 EventInfo ei;
4967 if (!inited)
4968 return;
4970 memset (&ei, 0, sizeof (EventInfo));
4971 ei.exc = (MonoObject*)exc;
4973 mono_loader_lock ();
4974 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
4975 mono_loader_unlock ();
4977 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
4980 static void
4981 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4982 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
4984 int i, j, suspend_policy;
4985 GSList *events;
4986 MonoJitInfo *ji, *catch_ji;
4987 EventInfo ei;
4988 DebuggerTlsData *tls = NULL;
4990 if (thread_to_tls != NULL) {
4991 MonoInternalThread *thread = mono_thread_internal_current ();
4993 mono_loader_lock ();
4994 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4995 mono_loader_unlock ();
4997 if (tls && tls->abort_requested)
4998 return;
4999 if (tls && tls->disable_breakpoints)
5000 return;
5003 memset (&ei, 0, sizeof (EventInfo));
5005 /* Just-In-Time debugging */
5006 if (!catch_ctx) {
5007 if (agent_config.onuncaught && !inited) {
5008 finish_agent_init (FALSE);
5011 * Send an unsolicited EXCEPTION event with a dummy request id.
5013 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5014 ei.exc = (MonoObject*)exc;
5015 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5016 return;
5018 } else if (agent_config.onthrow && !inited) {
5019 GSList *l;
5020 gboolean found = FALSE;
5022 for (l = agent_config.onthrow; l; l = l->next) {
5023 char *ex_type = (char *)l->data;
5024 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5026 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5027 found = TRUE;
5029 g_free (f);
5032 if (found) {
5033 finish_agent_init (FALSE);
5036 * Send an unsolicited EXCEPTION event with a dummy request id.
5038 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5039 ei.exc = (MonoObject*)exc;
5040 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5041 return;
5045 if (!inited)
5046 return;
5048 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5049 if (catch_frame)
5050 catch_ji = catch_frame->ji;
5051 else
5052 catch_ji = NULL;
5054 ei.exc = (MonoObject*)exc;
5055 ei.caught = catch_ctx != NULL;
5057 mono_loader_lock ();
5059 /* Treat exceptions which are caught in non-user code as unhandled */
5060 for (i = 0; i < event_requests->len; ++i) {
5061 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5062 if (req->event_kind != EVENT_KIND_EXCEPTION)
5063 continue;
5065 for (j = 0; j < req->nmodifiers; ++j) {
5066 Modifier *mod = &req->modifiers [j];
5068 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5069 int k;
5070 gboolean found = FALSE;
5071 MonoAssembly **assemblies = mod->data.assemblies;
5073 if (assemblies) {
5074 for (k = 0; assemblies [k]; ++k)
5075 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5076 found = TRUE;
5078 if (!found)
5079 ei.caught = FALSE;
5084 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5085 mono_loader_unlock ();
5087 if (tls && ei.caught && catch_ctx) {
5088 if (catch_frame) {
5089 tls->has_catch_frame = TRUE;
5090 tls->catch_frame = *catch_frame;
5091 } else {
5092 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5096 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5098 if (tls)
5099 tls->has_catch_frame = FALSE;
5102 static void
5103 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5105 DebuggerTlsData *tls;
5107 if (!inited)
5108 return;
5110 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5111 if (!tls)
5112 return;
5115 * We're about to invoke an exception filter during the first pass of exception handling.
5117 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5118 * 'orig_ctx' is the context where the exception has been thrown.
5121 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5123 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5124 * the call site (line 37) and then continue to Main(), but it would never
5125 * include the throw site (line 32).
5127 * Since exception filters are invoked during the first pass of exception handling,
5128 * the stack frames of the throw site are still intact, so we should include them
5129 * in a stack trace.
5131 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5133 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5134 * but report the location of the 'throw' to the user.
5138 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5141 static void
5142 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5144 DebuggerTlsData *tls;
5146 if (!inited)
5147 return;
5149 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5150 if (!tls)
5151 return;
5153 tls->filter_state.valid = FALSE;
5157 * buffer_add_value_full:
5159 * Add the encoding of the value at ADDR described by T to the buffer.
5160 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5161 * vtypes.
5163 static void
5164 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5165 gboolean as_vtype, GHashTable *parent_vtypes)
5167 MonoObject *obj;
5168 gboolean boxed_vtype = FALSE;
5170 if (t->byref) {
5171 if (!(*(void**)addr)) {
5172 /* This can happen with compiler generated locals */
5173 //printf ("%s\n", mono_type_full_name (t));
5174 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5175 return;
5177 g_assert (*(void**)addr);
5178 addr = *(void**)addr;
5181 if (as_vtype) {
5182 switch (t->type) {
5183 case MONO_TYPE_BOOLEAN:
5184 case MONO_TYPE_I1:
5185 case MONO_TYPE_U1:
5186 case MONO_TYPE_CHAR:
5187 case MONO_TYPE_I2:
5188 case MONO_TYPE_U2:
5189 case MONO_TYPE_I4:
5190 case MONO_TYPE_U4:
5191 case MONO_TYPE_R4:
5192 case MONO_TYPE_I8:
5193 case MONO_TYPE_U8:
5194 case MONO_TYPE_R8:
5195 case MONO_TYPE_I:
5196 case MONO_TYPE_U:
5197 case MONO_TYPE_PTR:
5198 goto handle_vtype;
5199 break;
5200 default:
5201 break;
5205 switch (t->type) {
5206 case MONO_TYPE_VOID:
5207 buffer_add_byte (buf, t->type);
5208 break;
5209 case MONO_TYPE_BOOLEAN:
5210 case MONO_TYPE_I1:
5211 case MONO_TYPE_U1:
5212 buffer_add_byte (buf, t->type);
5213 buffer_add_int (buf, *(gint8*)addr);
5214 break;
5215 case MONO_TYPE_CHAR:
5216 case MONO_TYPE_I2:
5217 case MONO_TYPE_U2:
5218 buffer_add_byte (buf, t->type);
5219 buffer_add_int (buf, *(gint16*)addr);
5220 break;
5221 case MONO_TYPE_I4:
5222 case MONO_TYPE_U4:
5223 case MONO_TYPE_R4:
5224 buffer_add_byte (buf, t->type);
5225 buffer_add_int (buf, *(gint32*)addr);
5226 break;
5227 case MONO_TYPE_I8:
5228 case MONO_TYPE_U8:
5229 case MONO_TYPE_R8:
5230 buffer_add_byte (buf, t->type);
5231 buffer_add_long (buf, *(gint64*)addr);
5232 break;
5233 case MONO_TYPE_I:
5234 case MONO_TYPE_U:
5235 /* Treat it as a vtype */
5236 goto handle_vtype;
5237 case MONO_TYPE_PTR: {
5238 gssize val = *(gssize*)addr;
5240 buffer_add_byte (buf, t->type);
5241 buffer_add_long (buf, val);
5242 if (CHECK_PROTOCOL_VERSION(2, 46))
5243 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5244 break;
5246 handle_ref:
5247 case MONO_TYPE_STRING:
5248 case MONO_TYPE_SZARRAY:
5249 case MONO_TYPE_OBJECT:
5250 case MONO_TYPE_CLASS:
5251 case MONO_TYPE_ARRAY:
5252 obj = *(MonoObject**)addr;
5254 if (!obj) {
5255 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5256 } else {
5257 if (m_class_is_valuetype (obj->vtable->klass)) {
5258 t = m_class_get_byval_arg (obj->vtable->klass);
5259 addr = mono_object_unbox_internal (obj);
5260 boxed_vtype = TRUE;
5261 goto handle_vtype;
5262 } else if (m_class_get_rank (obj->vtable->klass)) {
5263 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5264 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5265 buffer_add_byte (buf, MONO_TYPE_CLASS);
5266 } else {
5267 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5269 buffer_add_objid (buf, obj);
5271 break;
5272 handle_vtype:
5273 case MONO_TYPE_VALUETYPE:
5274 case MONO_TYPE_TYPEDBYREF: {
5275 int nfields;
5276 gpointer iter;
5277 MonoClassField *f;
5278 MonoClass *klass = mono_class_from_mono_type_internal (t);
5279 int vtype_index;
5281 if (boxed_vtype) {
5283 * Handle boxed vtypes recursively referencing themselves using fields.
5285 if (!parent_vtypes)
5286 parent_vtypes = g_hash_table_new (NULL, NULL);
5287 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5288 if (vtype_index) {
5289 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5290 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5291 buffer_add_int (buf, vtype_index - 1);
5292 } else {
5293 /* The client can't handle PARENT_VTYPE */
5294 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5296 break;
5297 } else {
5298 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5302 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5303 buffer_add_byte (buf, m_class_is_enumtype (klass));
5304 buffer_add_typeid (buf, domain, klass);
5306 nfields = 0;
5307 iter = NULL;
5308 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5309 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5310 continue;
5311 if (mono_field_is_deleted (f))
5312 continue;
5313 nfields ++;
5315 buffer_add_int (buf, nfields);
5317 iter = NULL;
5318 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5319 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5320 continue;
5321 if (mono_field_is_deleted (f))
5322 continue;
5323 buffer_add_value_full (buf, f->type, mono_vtype_get_field_addr (addr, f), domain, FALSE, parent_vtypes);
5326 if (boxed_vtype) {
5327 g_hash_table_remove (parent_vtypes, addr);
5328 if (g_hash_table_size (parent_vtypes) == 0) {
5329 g_hash_table_destroy (parent_vtypes);
5330 parent_vtypes = NULL;
5333 break;
5335 case MONO_TYPE_GENERICINST:
5336 if (mono_type_generic_inst_is_valuetype (t)) {
5337 goto handle_vtype;
5338 } else {
5339 goto handle_ref;
5341 break;
5342 default:
5343 NOT_IMPLEMENTED;
5347 static void
5348 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5350 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5353 static gboolean
5354 obj_is_of_type (MonoObject *obj, MonoType *t)
5356 MonoClass *klass = obj->vtable->klass;
5357 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5358 if (mono_class_is_transparent_proxy (klass)) {
5359 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5360 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5361 return TRUE;
5364 return FALSE;
5366 return TRUE;
5369 static ErrorCode
5370 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5372 static ErrorCode
5373 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5375 guint8 *addr = (guint8*)void_addr;
5376 guint8 *buf = (guint8*)void_buf;
5377 gboolean is_enum;
5378 MonoClass *klass;
5379 MonoClassField *f;
5380 int nfields;
5381 gpointer iter = NULL;
5382 MonoDomain *d;
5383 ErrorCode err;
5385 is_enum = decode_byte (buf, &buf, limit);
5386 /* Enums are sent as a normal vtype */
5387 if (is_enum)
5388 return ERR_NOT_IMPLEMENTED;
5389 klass = decode_typeid (buf, &buf, limit, &d, &err);
5390 if (err != ERR_NONE)
5391 return err;
5393 if (t && klass != mono_class_from_mono_type_internal (t)) {
5394 char *name = mono_type_full_name (t);
5395 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5396 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5397 g_free (name);
5398 g_free (name2);
5399 return ERR_INVALID_ARGUMENT;
5402 nfields = decode_int (buf, &buf, limit);
5403 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5404 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5405 continue;
5406 if (mono_field_is_deleted (f))
5407 continue;
5408 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5409 if (err != ERR_NONE)
5410 return err;
5411 nfields --;
5413 g_assert (nfields == 0);
5415 *endbuf = buf;
5417 return ERR_NONE;
5420 static ErrorCode
5421 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5423 ErrorCode err;
5425 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5426 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5427 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5428 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5429 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5430 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5431 char *name = mono_type_full_name (t);
5432 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5433 g_free (name);
5434 return ERR_INVALID_ARGUMENT;
5437 switch (t->type) {
5438 case MONO_TYPE_BOOLEAN:
5439 *(guint8*)addr = decode_int (buf, &buf, limit);
5440 break;
5441 case MONO_TYPE_CHAR:
5442 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5443 break;
5444 case MONO_TYPE_I1:
5445 *(gint8*)addr = decode_int (buf, &buf, limit);
5446 break;
5447 case MONO_TYPE_U1:
5448 *(guint8*)addr = decode_int (buf, &buf, limit);
5449 break;
5450 case MONO_TYPE_I2:
5451 *(gint16*)addr = decode_int (buf, &buf, limit);
5452 break;
5453 case MONO_TYPE_U2:
5454 *(guint16*)addr = decode_int (buf, &buf, limit);
5455 break;
5456 case MONO_TYPE_I4:
5457 *(gint32*)addr = decode_int (buf, &buf, limit);
5458 break;
5459 case MONO_TYPE_U4:
5460 *(guint32*)addr = decode_int (buf, &buf, limit);
5461 break;
5462 case MONO_TYPE_I8:
5463 *(gint64*)addr = decode_long (buf, &buf, limit);
5464 break;
5465 case MONO_TYPE_U8:
5466 *(guint64*)addr = decode_long (buf, &buf, limit);
5467 break;
5468 case MONO_TYPE_R4:
5469 *(guint32*)addr = decode_int (buf, &buf, limit);
5470 break;
5471 case MONO_TYPE_R8:
5472 *(guint64*)addr = decode_long (buf, &buf, limit);
5473 break;
5474 case MONO_TYPE_PTR:
5475 /* We send these as I8, so we get them back as such */
5476 g_assert (type == MONO_TYPE_I8);
5477 *(gssize*)addr = decode_long (buf, &buf, limit);
5478 break;
5479 case MONO_TYPE_GENERICINST:
5480 if (MONO_TYPE_ISSTRUCT (t)) {
5481 /* The client sends these as a valuetype */
5482 goto handle_vtype;
5483 } else {
5484 goto handle_ref;
5486 break;
5487 case MONO_TYPE_I:
5488 case MONO_TYPE_U:
5489 /* We send these as vtypes, so we get them back as such */
5490 g_assert (type == MONO_TYPE_VALUETYPE);
5491 /* Fall through */
5492 handle_vtype:
5493 case MONO_TYPE_VALUETYPE:
5494 if (type == MONO_TYPE_OBJECT) {
5495 /* Boxed vtype */
5496 int objid = decode_objid (buf, &buf, limit);
5497 ErrorCode err;
5498 MonoObject *obj;
5500 err = get_object (objid, (MonoObject**)&obj);
5501 if (err != ERR_NONE)
5502 return err;
5503 if (!obj)
5504 return ERR_INVALID_ARGUMENT;
5505 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5506 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5507 return ERR_INVALID_ARGUMENT;
5509 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5510 } else {
5511 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5512 if (err != ERR_NONE)
5513 return err;
5515 break;
5516 handle_ref:
5517 default:
5518 if (MONO_TYPE_IS_REFERENCE (t)) {
5519 if (type == MONO_TYPE_OBJECT) {
5520 int objid = decode_objid (buf, &buf, limit);
5521 ErrorCode err;
5522 MonoObject *obj;
5524 err = get_object (objid, (MonoObject**)&obj);
5525 if (err != ERR_NONE)
5526 return err;
5528 if (obj) {
5529 if (!obj_is_of_type (obj, t)) {
5530 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5531 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5532 return ERR_INVALID_ARGUMENT;
5536 if (obj && obj->vtable->domain != domain)
5537 return ERR_INVALID_ARGUMENT;
5539 mono_gc_wbarrier_generic_store_internal (addr, obj);
5540 } else if (type == VALUE_TYPE_ID_NULL) {
5541 *(MonoObject**)addr = NULL;
5542 } else if (type == MONO_TYPE_VALUETYPE) {
5543 ERROR_DECL (error);
5544 guint8 *buf2;
5545 gboolean is_enum;
5546 MonoClass *klass;
5547 MonoDomain *d;
5548 guint8 *vtype_buf;
5549 int vtype_buf_size;
5551 /* This can happen when round-tripping boxed vtypes */
5553 * Obtain vtype class.
5554 * Same as the beginning of the handle_vtype case above.
5556 buf2 = buf;
5557 is_enum = decode_byte (buf, &buf, limit);
5558 if (is_enum)
5559 return ERR_NOT_IMPLEMENTED;
5560 klass = decode_typeid (buf, &buf, limit, &d, &err);
5561 if (err != ERR_NONE)
5562 return err;
5564 /* Decode the vtype into a temporary buffer, then box it. */
5565 vtype_buf_size = mono_class_value_size (klass, NULL);
5566 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5567 g_assert (vtype_buf);
5569 buf = buf2;
5570 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5571 if (err != ERR_NONE) {
5572 g_free (vtype_buf);
5573 return err;
5575 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5576 mono_error_cleanup (error);
5577 g_free (vtype_buf);
5578 } else {
5579 char *name = mono_type_full_name (t);
5580 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5581 g_free (name);
5582 return ERR_INVALID_ARGUMENT;
5584 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5585 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5586 m_class_is_enumtype (t->data.generic_class->container_class)){
5587 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5588 if (err != ERR_NONE)
5589 return err;
5590 } else {
5591 NOT_IMPLEMENTED;
5593 break;
5596 *endbuf = buf;
5598 return ERR_NONE;
5601 static ErrorCode
5602 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5604 guint8 *addr = (guint8*)void_addr;
5605 guint8 *buf = (guint8*)void_buf;
5607 ERROR_DECL (error);
5608 ErrorCode err;
5609 int type = decode_byte (buf, &buf, limit);
5611 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5612 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5613 guint8 *nullable_buf;
5616 * First try decoding it as a Nullable`1
5618 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5619 if (err == ERR_NONE)
5620 return err;
5623 * Then try decoding as a primitive value or null.
5625 if (targ->type == type) {
5626 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
5627 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
5628 if (err != ERR_NONE) {
5629 g_free (nullable_buf);
5630 return err;
5632 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
5633 if (!is_ok (error)) {
5634 mono_error_cleanup (error);
5635 return ERR_INVALID_OBJECT;
5637 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
5638 g_free (nullable_buf);
5639 *endbuf = buf;
5640 return ERR_NONE;
5641 } else if (type == VALUE_TYPE_ID_NULL) {
5642 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
5643 *endbuf = buf;
5644 return ERR_NONE;
5648 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5651 static void
5652 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5654 guint32 flags;
5655 int reg;
5656 guint8 *addr, *gaddr;
5657 host_mgreg_t reg_val;
5659 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5660 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5662 switch (flags) {
5663 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5664 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5666 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL);
5667 break;
5668 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5669 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5670 addr += (gint32)var->offset;
5672 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5674 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
5675 break;
5676 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5677 NOT_IMPLEMENTED;
5678 break;
5679 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5680 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5681 /* Same as regoffset, but with an indirection */
5682 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5683 addr += (gint32)var->offset;
5685 gaddr = (guint8 *)*(gpointer*)addr;
5686 g_assert (gaddr);
5687 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
5688 break;
5689 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5690 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5691 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5692 MonoGSharedVtMethodRuntimeInfo *info;
5693 guint8 *locals;
5694 int idx;
5696 idx = reg;
5698 g_assert (info_var);
5699 g_assert (locals_var);
5701 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5702 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5703 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5704 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5705 addr += (gint32)info_var->offset;
5706 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
5707 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5708 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
5709 } else {
5710 g_assert_not_reached ();
5712 g_assert (info);
5714 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5715 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5716 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5717 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5718 addr += (gint32)locals_var->offset;
5719 locals = (guint8 *)*(gpointer*)addr;
5720 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5721 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5722 } else {
5723 g_assert_not_reached ();
5725 g_assert (locals);
5727 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5729 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
5730 break;
5733 default:
5734 g_assert_not_reached ();
5738 static void
5739 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
5741 guint32 flags;
5742 int reg, size;
5743 guint8 *addr, *gaddr;
5745 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5746 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5748 if (MONO_TYPE_IS_REFERENCE (t))
5749 size = sizeof (gpointer);
5750 else
5751 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
5753 switch (flags) {
5754 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5755 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5756 host_mgreg_t v;
5757 gboolean is_signed = FALSE;
5759 if (t->byref) {
5760 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5762 if (addr) {
5763 // FIXME: Write barriers
5764 mono_gc_memmove_atomic (addr, val, size);
5766 break;
5769 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5770 is_signed = TRUE;
5772 switch (size) {
5773 case 1:
5774 v = is_signed ? *(gint8*)val : *(guint8*)val;
5775 break;
5776 case 2:
5777 v = is_signed ? *(gint16*)val : *(guint16*)val;
5778 break;
5779 case 4:
5780 v = is_signed ? *(gint32*)val : *(guint32*)val;
5781 break;
5782 case 8:
5783 v = is_signed ? *(gint64*)val : *(guint64*)val;
5784 break;
5785 default:
5786 g_assert_not_reached ();
5789 /* Set value on the stack or in the return ctx */
5790 if (reg_locations [reg]) {
5791 /* Saved on the stack */
5792 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
5793 *(reg_locations [reg]) = v;
5794 } else {
5795 /* Not saved yet */
5796 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
5797 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5800 // FIXME: Move these to mono-context.h/c.
5801 mono_arch_context_set_int_reg (ctx, reg, v);
5802 #else
5803 // FIXME: Can't set registers, so we disable linears
5804 NOT_IMPLEMENTED;
5805 #endif
5806 break;
5808 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5809 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5810 addr += (gint32)var->offset;
5812 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5814 if (t->byref) {
5815 addr = *(guint8**)addr;
5817 if (!addr)
5818 break;
5821 // FIXME: Write barriers
5822 mono_gc_memmove_atomic (addr, val, size);
5823 break;
5824 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5825 /* Same as regoffset, but with an indirection */
5826 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5827 addr += (gint32)var->offset;
5829 gaddr = (guint8 *)*(gpointer*)addr;
5830 g_assert (gaddr);
5831 // FIXME: Write barriers
5832 mono_gc_memmove_atomic (gaddr, val, size);
5833 break;
5834 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5835 NOT_IMPLEMENTED;
5836 break;
5837 default:
5838 g_assert_not_reached ();
5842 static void
5843 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
5845 int size;
5847 if (t->byref) {
5848 addr = *(gpointer*)addr;
5849 g_assert (addr);
5852 if (MONO_TYPE_IS_REFERENCE (t))
5853 size = sizeof (gpointer);
5854 else
5855 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
5857 memcpy (addr, val_buf, size);
5860 static void
5861 clear_event_request (int req_id, int etype)
5863 int i;
5865 mono_loader_lock ();
5866 for (i = 0; i < event_requests->len; ++i) {
5867 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5869 if (req->id == req_id && req->event_kind == etype) {
5870 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5871 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
5872 if (req->event_kind == EVENT_KIND_STEP) {
5873 mono_de_cancel_ss ();
5875 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5876 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
5877 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5878 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
5879 g_ptr_array_remove_index_fast (event_requests, i);
5880 g_free (req);
5881 break;
5884 mono_loader_unlock ();
5887 static void
5888 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
5890 int i;
5892 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
5893 m->kind = MOD_KIND_NONE;
5894 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5895 int count = 0, match_count = 0, pos;
5896 MonoAssembly **newassemblies;
5898 for (i = 0; m->data.assemblies [i]; ++i) {
5899 count ++;
5900 if (m->data.assemblies [i] == assembly)
5901 match_count ++;
5904 if (match_count) {
5905 // +1 because we don't know length and we use last element to check for end
5906 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
5908 pos = 0;
5909 for (i = 0; i < count; ++i)
5910 if (m->data.assemblies [i] != assembly)
5911 newassemblies [pos ++] = m->data.assemblies [i];
5912 g_assert (pos == count - match_count);
5913 g_free (m->data.assemblies);
5914 m->data.assemblies = newassemblies;
5919 static void
5920 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
5922 int i;
5924 for (i = 0; i < req->nmodifiers; ++i) {
5925 Modifier *m = &req->modifiers [i];
5927 clear_assembly_from_modifier (req, m, assembly);
5932 * clear_event_requests_for_assembly:
5934 * Clear all events requests which reference ASSEMBLY.
5936 static void
5937 clear_event_requests_for_assembly (MonoAssembly *assembly)
5939 int i;
5940 gboolean found;
5942 mono_loader_lock ();
5943 found = TRUE;
5944 while (found) {
5945 found = FALSE;
5946 for (i = 0; i < event_requests->len; ++i) {
5947 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5949 clear_assembly_from_modifiers (req, assembly);
5951 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
5952 clear_event_request (req->id, req->event_kind);
5953 found = TRUE;
5954 break;
5957 if (req->event_kind == EVENT_KIND_STEP)
5958 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
5961 mono_loader_unlock ();
5965 * type_comes_from_assembly:
5967 * GHRFunc that returns TRUE if klass comes from assembly
5969 static gboolean
5970 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5972 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
5976 * clear_types_for_assembly:
5978 * Clears types from loaded_classes for a given assembly
5980 static void
5981 clear_types_for_assembly (MonoAssembly *assembly)
5983 MonoDomain *domain = mono_domain_get ();
5984 AgentDomainInfo *info = NULL;
5986 if (!domain || !domain_jit_info (domain))
5987 /* Can happen during shutdown */
5988 return;
5990 info = get_agent_domain_info (domain);
5992 mono_loader_lock ();
5993 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5994 mono_loader_unlock ();
5997 static void
5998 add_thread (gpointer key, gpointer value, gpointer user_data)
6000 MonoInternalThread *thread = (MonoInternalThread *)value;
6001 Buffer *buf = (Buffer *)user_data;
6003 buffer_add_objid (buf, (MonoObject*)thread);
6006 static ErrorCode
6007 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6009 ERROR_DECL (error);
6010 guint8 *end = invoke->endp;
6011 MonoMethod *m;
6012 int i, nargs;
6013 ErrorCode err;
6014 MonoMethodSignature *sig;
6015 guint8 **arg_buf;
6016 void **args;
6017 MonoObject *this_arg, *res, *exc = NULL;
6018 MonoDomain *domain;
6019 guint8 *this_buf;
6020 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6021 MonoLMFExt ext;
6022 #endif
6023 MonoStopwatch watch;
6025 if (invoke->method) {
6027 * Invoke this method directly, currently only Environment.Exit () is supported.
6029 this_arg = NULL;
6030 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>");
6032 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6033 mono_error_assert_ok (error);
6034 g_assert_not_reached ();
6037 m = decode_methodid (p, &p, end, &domain, &err);
6038 if (err != ERR_NONE)
6039 return err;
6040 sig = mono_method_signature_internal (m);
6042 if (m_class_is_valuetype (m->klass))
6043 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6044 else
6045 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6047 if (m->is_generic) {
6048 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));
6049 return ERR_INVALID_ARGUMENT;
6050 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6051 /* Should be null */
6052 int type = decode_byte (p, &p, end);
6053 if (type != VALUE_TYPE_ID_NULL) {
6054 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6055 return ERR_INVALID_ARGUMENT;
6057 memset (this_buf, 0, mono_class_instance_size (m->klass));
6058 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6059 /* Could be null */
6060 guint8 *tmp_p;
6062 int type = decode_byte (p, &tmp_p, end);
6063 if (type == VALUE_TYPE_ID_NULL) {
6064 memset (this_buf, 0, mono_class_instance_size (m->klass));
6065 p = tmp_p;
6066 } else {
6067 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6068 if (err != ERR_NONE)
6069 return err;
6071 } else {
6072 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6073 if (err != ERR_NONE)
6074 return err;
6077 if (!m_class_is_valuetype (m->klass))
6078 this_arg = *(MonoObject**)this_buf;
6079 else
6080 this_arg = NULL;
6082 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6083 if (!this_arg) {
6084 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6085 return ERR_INVALID_ARGUMENT;
6087 m = mono_object_get_virtual_method_internal (this_arg, m);
6088 /* Transform this to the format the rest of the code expects it to be */
6089 if (m_class_is_valuetype (m->klass)) {
6090 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6091 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6093 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6094 if (!this_arg) {
6095 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6096 return ERR_INVALID_ARGUMENT;
6098 m = mono_object_get_virtual_method_internal (this_arg, m);
6099 if (m_class_is_valuetype (m->klass)) {
6100 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6101 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6105 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>");
6107 if (this_arg && this_arg->vtable->domain != domain)
6108 NOT_IMPLEMENTED;
6110 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6111 if (!strcmp (m->name, ".ctor")) {
6112 if (mono_class_is_abstract (m->klass))
6113 return ERR_INVALID_ARGUMENT;
6114 else {
6115 ERROR_DECL (error);
6116 this_arg = mono_object_new_checked (domain, m->klass, error);
6117 mono_error_assert_ok (error);
6119 } else {
6120 return ERR_INVALID_ARGUMENT;
6124 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6125 return ERR_INVALID_ARGUMENT;
6127 nargs = decode_int (p, &p, end);
6128 if (nargs != sig->param_count)
6129 return ERR_INVALID_ARGUMENT;
6130 /* Use alloca to get gc tracking */
6131 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6132 memset (arg_buf, 0, nargs * sizeof (gpointer));
6133 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6134 for (i = 0; i < nargs; ++i) {
6135 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6136 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6137 if (err != ERR_NONE)
6138 break;
6139 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6140 NOT_IMPLEMENTED;
6142 if (sig->params [i]->byref) {
6143 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6144 *(gpointer*)arg_buf [i] = args [i];
6145 args [i] = arg_buf [i];
6147 } else {
6148 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6149 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6150 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6151 if (err != ERR_NONE)
6152 break;
6153 if (mono_class_is_nullable (arg_class)) {
6154 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6155 mono_error_assert_ok (error);
6156 } else {
6157 args [i] = arg_buf [i];
6162 if (i < nargs)
6163 return err;
6165 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6166 tls->disable_breakpoints = TRUE;
6167 else
6168 tls->disable_breakpoints = FALSE;
6171 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6173 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6174 if (invoke->has_ctx) {
6175 /* Setup our lmf */
6176 memset (&ext, 0, sizeof (ext));
6177 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6178 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6180 mono_push_lmf (&ext);
6182 #endif
6184 mono_stopwatch_start (&watch);
6185 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6186 if (!mono_error_ok (error) && exc == NULL) {
6187 exc = (MonoObject*) mono_error_convert_to_exception (error);
6188 } else {
6189 mono_error_cleanup (error); /* FIXME report error */
6191 mono_stopwatch_stop (&watch);
6192 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));
6193 if (exc) {
6194 buffer_add_byte (buf, 0);
6195 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6196 } else {
6197 gboolean out_this = FALSE;
6198 gboolean out_args = FALSE;
6200 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6201 out_this = TRUE;
6202 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6203 out_args = TRUE;
6204 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6205 if (m->string_ctor) {
6206 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6207 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6208 if (!strcmp (m->name, ".ctor")) {
6209 if (!m_class_is_valuetype (m->klass))
6210 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6211 else
6212 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6213 } else {
6214 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6216 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6217 if (sig->ret->byref) {
6218 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6219 buffer_add_value (buf, ret_byval, &res, domain);
6220 } else {
6221 buffer_add_value (buf, sig->ret, &res, domain);
6223 } 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) {
6224 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6225 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6226 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6228 g_assert (nullable_buf);
6229 mono_nullable_init (nullable_buf, res, k);
6230 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6231 } else {
6232 g_assert (res);
6234 if (sig->ret->byref) {
6235 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6236 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6237 } else {
6238 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6241 } else {
6242 NOT_IMPLEMENTED;
6244 if (out_this)
6245 /* Return the new value of the receiver after the call */
6246 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6247 if (out_args) {
6248 buffer_add_int (buf, nargs);
6249 for (i = 0; i < nargs; ++i) {
6250 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6251 buffer_add_value (buf, sig->params [i], &args [i], domain);
6252 else if (sig->params [i]->byref)
6253 /* add_value () does an indirection */
6254 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6255 else
6256 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6261 tls->disable_breakpoints = FALSE;
6263 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6264 if (invoke->has_ctx)
6265 mono_pop_lmf ((MonoLMF*)&ext);
6266 #endif
6268 *endp = p;
6269 // FIXME: byref arguments
6270 // FIXME: varargs
6271 return ERR_NONE;
6275 * invoke_method:
6277 * Invoke the method given by tls->pending_invoke in the current thread.
6279 static void
6280 invoke_method (void)
6282 DebuggerTlsData *tls;
6283 InvokeData *invoke;
6284 int id;
6285 int i, mindex;
6286 ErrorCode err;
6287 Buffer buf;
6288 MonoContext restore_ctx;
6289 guint8 *p;
6291 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6292 g_assert (tls);
6295 * Store the `InvokeData *' in `tls->invoke' until we're done with
6296 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6299 mono_loader_lock ();
6301 invoke = tls->pending_invoke;
6302 g_assert (invoke);
6303 tls->pending_invoke = NULL;
6305 invoke->last_invoke = tls->invoke;
6306 tls->invoke = invoke;
6308 mono_loader_unlock ();
6310 tls->frames_up_to_date = FALSE;
6312 id = invoke->id;
6314 p = invoke->p;
6315 err = ERR_NONE;
6316 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6317 buffer_init (&buf, 128);
6319 if (err) {
6320 /* Fail the other invokes as well */
6321 } else {
6322 err = do_invoke_method (tls, &buf, invoke, p, &p);
6325 if (tls->abort_requested) {
6326 if (CHECK_PROTOCOL_VERSION (2, 42))
6327 err = ERR_INVOKE_ABORTED;
6330 /* Start suspending before sending the reply */
6331 if (mindex == invoke->nmethods - 1) {
6332 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6333 for (i = 0; i < invoke->suspend_count; ++i)
6334 suspend_vm ();
6338 send_reply_packet (id, err, &buf);
6340 buffer_free (&buf);
6343 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6345 if (invoke->has_ctx)
6346 save_thread_context (&restore_ctx);
6348 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6349 g_assert (tls->resume_count);
6350 tls->resume_count -= invoke->suspend_count;
6353 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6356 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6358 * It is possible that mono_thread_internal_abort () was called
6359 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6360 * because we reset the abort here.
6363 mono_loader_lock ();
6365 if (tls->abort_requested)
6366 mono_thread_internal_reset_abort (tls->thread);
6368 tls->invoke = tls->invoke->last_invoke;
6369 tls->abort_requested = FALSE;
6371 mono_loader_unlock ();
6373 g_free (invoke->p);
6374 g_free (invoke);
6377 static gboolean
6378 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6380 MonoThread *thread = (MonoThread *)value;
6381 DebuggerTlsData *tls;
6382 gboolean res;
6384 mono_loader_lock ();
6385 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6386 g_assert (tls);
6387 res = tls->really_suspended;
6388 mono_loader_unlock ();
6390 return res;
6393 static GPtrArray*
6394 get_source_files_for_type (MonoClass *klass)
6396 gpointer iter = NULL;
6397 MonoMethod *method;
6398 MonoDebugSourceInfo *sinfo;
6399 GPtrArray *files;
6400 int i, j;
6402 files = g_ptr_array_new ();
6404 while ((method = mono_class_get_methods (klass, &iter))) {
6405 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6406 GPtrArray *source_file_list;
6408 if (minfo) {
6409 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6410 for (j = 0; j < source_file_list->len; ++j) {
6411 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6412 for (i = 0; i < files->len; ++i)
6413 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6414 break;
6415 if (i == files->len)
6416 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6418 g_ptr_array_free (source_file_list, TRUE);
6422 return files;
6426 typedef struct {
6427 MonoTypeNameParse *info;
6428 gboolean ignore_case;
6429 GPtrArray *res_classes;
6430 GPtrArray *res_domains;
6431 } GetTypesArgs;
6433 static void
6434 get_types (gpointer key, gpointer value, gpointer user_data)
6436 MonoAssembly *ass;
6437 gboolean type_resolve;
6438 MonoType *t;
6439 GSList *tmp;
6440 MonoDomain *domain = (MonoDomain*)key;
6441 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6443 mono_domain_assemblies_lock (domain);
6444 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6445 ass = (MonoAssembly *)tmp->data;
6447 if (ass->image) {
6448 ERROR_DECL (probe_type_error);
6449 /* FIXME really okay to call while holding locks? */
6450 t = mono_reflection_get_type_checked (ass->image, ass->image, ud->info, ud->ignore_case, &type_resolve, probe_type_error);
6451 mono_error_cleanup (probe_type_error);
6452 if (t) {
6453 g_ptr_array_add (ud->res_classes, mono_type_get_class (t));
6454 g_ptr_array_add (ud->res_domains, domain);
6458 mono_domain_assemblies_unlock (domain);
6461 typedef struct {
6462 gboolean ignore_case;
6463 char *basename;
6464 GPtrArray *res_classes;
6465 GPtrArray *res_domains;
6466 } GetTypesForSourceFileArgs;
6468 static void
6469 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6471 GHashTableIter iter;
6472 GSList *class_list = NULL;
6473 MonoClass *klass = NULL;
6474 GPtrArray *files = NULL;
6476 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6477 MonoDomain *domain = (MonoDomain*)key;
6479 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6481 /* Update 'source_file_to_class' cache */
6482 g_hash_table_iter_init (&iter, info->loaded_classes);
6483 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6484 if (!g_hash_table_lookup (info->source_files, klass)) {
6485 files = get_source_files_for_type (klass);
6486 g_hash_table_insert (info->source_files, klass, files);
6488 for (int i = 0; i < files->len; ++i) {
6489 char *s = (char *)g_ptr_array_index (files, i);
6490 char *s2 = dbg_path_get_basename (s);
6491 char *s3;
6493 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6494 if (!class_list) {
6495 class_list = g_slist_prepend (class_list, klass);
6496 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6497 } else {
6498 class_list = g_slist_prepend (class_list, klass);
6499 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6502 /* The _ignorecase hash contains the lowercase path */
6503 s3 = strdup_tolower (s2);
6504 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6505 if (!class_list) {
6506 class_list = g_slist_prepend (class_list, klass);
6507 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6508 } else {
6509 class_list = g_slist_prepend (class_list, klass);
6510 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6513 g_free (s2);
6514 g_free (s3);
6519 if (ud->ignore_case) {
6520 char *s;
6522 s = strdup_tolower (ud->basename);
6523 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6524 g_free (s);
6525 } else {
6526 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6529 for (GSList *l = class_list; l; l = l->next) {
6530 klass = (MonoClass *)l->data;
6532 g_ptr_array_add (ud->res_classes, klass);
6533 g_ptr_array_add (ud->res_domains, domain);
6537 static ErrorCode
6538 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6540 switch (command) {
6541 case CMD_VM_VERSION: {
6542 char *build_info, *version;
6544 build_info = mono_get_runtime_build_info ();
6545 version = g_strdup_printf ("mono %s", build_info);
6547 buffer_add_string (buf, version); /* vm version */
6548 buffer_add_int (buf, MAJOR_VERSION);
6549 buffer_add_int (buf, MINOR_VERSION);
6550 g_free (build_info);
6551 g_free (version);
6552 break;
6554 case CMD_VM_SET_PROTOCOL_VERSION: {
6555 major_version = decode_int (p, &p, end);
6556 minor_version = decode_int (p, &p, end);
6557 protocol_version_set = TRUE;
6558 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6559 break;
6561 case CMD_VM_ALL_THREADS: {
6562 // FIXME: Domains
6563 mono_loader_lock ();
6564 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6565 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6566 mono_loader_unlock ();
6567 break;
6569 case CMD_VM_SUSPEND:
6570 suspend_vm ();
6571 wait_for_suspend ();
6572 break;
6573 case CMD_VM_RESUME:
6574 if (suspend_count == 0)
6575 return ERR_NOT_SUSPENDED;
6576 resume_vm ();
6577 clear_suspended_objs ();
6578 break;
6579 case CMD_VM_DISPOSE:
6580 /* Clear all event requests */
6581 mono_loader_lock ();
6582 while (event_requests->len > 0) {
6583 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6585 clear_event_request (req->id, req->event_kind);
6587 mono_loader_unlock ();
6589 while (suspend_count > 0)
6590 resume_vm ();
6591 disconnected = TRUE;
6592 vm_start_event_sent = FALSE;
6593 break;
6594 case CMD_VM_EXIT: {
6595 MonoInternalThread *thread;
6596 DebuggerTlsData *tls;
6597 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6598 MonoClass *env_class;
6599 #endif
6600 MonoMethod *exit_method = NULL;
6601 gpointer *args;
6602 int exit_code;
6604 exit_code = decode_int (p, &p, end);
6606 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6608 /* Have to send a reply before exiting */
6609 send_reply_packet (id, 0, buf);
6611 /* Clear all event requests */
6612 mono_loader_lock ();
6613 while (event_requests->len > 0) {
6614 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6616 clear_event_request (req->id, req->event_kind);
6618 mono_loader_unlock ();
6621 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6622 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6623 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6624 * better than doing the shutdown ourselves, since it avoids various races.
6627 suspend_vm ();
6628 wait_for_suspend ();
6630 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6631 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6632 if (env_class) {
6633 ERROR_DECL (error);
6634 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
6635 mono_error_assert_ok (error);
6637 #endif
6639 mono_loader_lock ();
6640 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6641 mono_loader_unlock ();
6643 if (thread && exit_method) {
6644 mono_loader_lock ();
6645 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6646 mono_loader_unlock ();
6648 args = g_new0 (gpointer, 1);
6649 args [0] = g_malloc (sizeof (int));
6650 *(int*)(args [0]) = exit_code;
6652 tls->pending_invoke = g_new0 (InvokeData, 1);
6653 tls->pending_invoke->method = exit_method;
6654 tls->pending_invoke->args = args;
6655 tls->pending_invoke->nmethods = 1;
6657 while (suspend_count > 0)
6658 resume_vm ();
6659 } else {
6661 * No thread found, do it ourselves.
6662 * FIXME: This can race with normal shutdown etc.
6664 while (suspend_count > 0)
6665 resume_vm ();
6667 if (!mono_runtime_try_shutdown ())
6668 break;
6670 mono_environment_exitcode_set (exit_code);
6672 /* Suspend all managed threads since the runtime is going away */
6673 DEBUG_PRINTF (1, "Suspending all threads...\n");
6674 mono_thread_suspend_all_other_threads ();
6675 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6676 mono_runtime_quit ();
6677 transport_close2 ();
6678 DEBUG_PRINTF (1, "Exiting...\n");
6680 exit (exit_code);
6682 break;
6684 case CMD_VM_INVOKE_METHOD:
6685 case CMD_VM_INVOKE_METHODS: {
6686 int objid = decode_objid (p, &p, end);
6687 MonoThread *thread;
6688 DebuggerTlsData *tls;
6689 int i, count, flags, nmethods;
6690 ErrorCode err;
6692 err = get_object (objid, (MonoObject**)&thread);
6693 if (err != ERR_NONE)
6694 return err;
6696 flags = decode_int (p, &p, end);
6698 if (command == CMD_VM_INVOKE_METHODS)
6699 nmethods = decode_int (p, &p, end);
6700 else
6701 nmethods = 1;
6703 // Wait for suspending if it already started
6704 if (suspend_count)
6705 wait_for_suspend ();
6706 if (!is_suspended ())
6707 return ERR_NOT_SUSPENDED;
6709 mono_loader_lock ();
6710 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6711 mono_loader_unlock ();
6712 g_assert (tls);
6714 if (!tls->really_suspended)
6715 /* The thread is still running native code, can't do invokes */
6716 return ERR_NOT_SUSPENDED;
6719 * Store the invoke data into tls, the thread will execute it after it is
6720 * resumed.
6722 if (tls->pending_invoke)
6723 return ERR_NOT_SUSPENDED;
6724 tls->pending_invoke = g_new0 (InvokeData, 1);
6725 tls->pending_invoke->id = id;
6726 tls->pending_invoke->flags = flags;
6727 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
6728 memcpy (tls->pending_invoke->p, p, end - p);
6729 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6730 tls->pending_invoke->suspend_count = suspend_count;
6731 tls->pending_invoke->nmethods = nmethods;
6733 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6734 resume_thread (THREAD_TO_INTERNAL (thread));
6736 else {
6737 count = suspend_count;
6738 for (i = 0; i < count; ++i)
6739 resume_vm ();
6741 break;
6743 case CMD_VM_ABORT_INVOKE: {
6744 int objid = decode_objid (p, &p, end);
6745 MonoThread *thread;
6746 DebuggerTlsData *tls;
6747 int invoke_id;
6748 ErrorCode err;
6750 err = get_object (objid, (MonoObject**)&thread);
6751 if (err != ERR_NONE)
6752 return err;
6754 invoke_id = decode_int (p, &p, end);
6756 mono_loader_lock ();
6757 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6758 g_assert (tls);
6760 if (tls->abort_requested) {
6761 DEBUG_PRINTF (1, "Abort already requested.\n");
6762 mono_loader_unlock ();
6763 break;
6767 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
6768 * actually the correct invocation.
6770 * Careful, we do not stop the thread that's doing the invocation, so we can't
6771 * inspect its stack. However, invoke_method() also acquires the loader lock
6772 * when it's done, so we're safe here.
6776 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6777 mono_loader_unlock ();
6778 return ERR_NO_INVOCATION;
6781 tls->abort_requested = TRUE;
6783 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
6784 mono_loader_unlock ();
6785 break;
6788 case CMD_VM_SET_KEEPALIVE: {
6789 int timeout = decode_int (p, &p, end);
6790 agent_config.keepalive = timeout;
6791 // FIXME:
6792 #ifndef DISABLE_SOCKET_TRANSPORT
6793 set_keepalive ();
6794 #else
6795 NOT_IMPLEMENTED;
6796 #endif
6797 break;
6799 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6800 int i;
6801 char *fname, *basename;
6802 gboolean ignore_case;
6803 GPtrArray *res_classes, *res_domains;
6805 fname = decode_string (p, &p, end);
6806 ignore_case = decode_byte (p, &p, end);
6808 basename = dbg_path_get_basename (fname);
6810 res_classes = g_ptr_array_new ();
6811 res_domains = g_ptr_array_new ();
6813 mono_loader_lock ();
6814 GetTypesForSourceFileArgs args;
6815 memset (&args, 0, sizeof (args));
6816 args.ignore_case = ignore_case;
6817 args.basename = basename;
6818 args.res_classes = res_classes;
6819 args.res_domains = res_domains;
6820 mono_de_foreach_domain (get_types_for_source_file, &args);
6821 mono_loader_unlock ();
6823 g_free (fname);
6824 g_free (basename);
6826 buffer_add_int (buf, res_classes->len);
6827 for (i = 0; i < res_classes->len; ++i)
6828 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
6829 g_ptr_array_free (res_classes, TRUE);
6830 g_ptr_array_free (res_domains, TRUE);
6831 break;
6833 case CMD_VM_GET_TYPES: {
6834 ERROR_DECL (error);
6835 int i;
6836 char *name;
6837 gboolean ignore_case;
6838 GPtrArray *res_classes, *res_domains;
6839 MonoTypeNameParse info;
6841 name = decode_string (p, &p, end);
6842 ignore_case = decode_byte (p, &p, end);
6844 if (!mono_reflection_parse_type_checked (name, &info, error)) {
6845 mono_error_cleanup (error);
6846 g_free (name);
6847 mono_reflection_free_type_info (&info);
6848 return ERR_INVALID_ARGUMENT;
6851 res_classes = g_ptr_array_new ();
6852 res_domains = g_ptr_array_new ();
6854 mono_loader_lock ();
6856 GetTypesArgs args;
6857 memset (&args, 0, sizeof (args));
6858 args.info = &info;
6859 args.ignore_case = ignore_case;
6860 args.res_classes = res_classes;
6861 args.res_domains = res_domains;
6863 mono_de_foreach_domain (get_types, &args);
6865 mono_loader_unlock ();
6867 g_free (name);
6868 mono_reflection_free_type_info (&info);
6870 buffer_add_int (buf, res_classes->len);
6871 for (i = 0; i < res_classes->len; ++i)
6872 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
6873 g_ptr_array_free (res_classes, TRUE);
6874 g_ptr_array_free (res_domains, TRUE);
6875 break;
6877 case CMD_VM_START_BUFFERING:
6878 case CMD_VM_STOP_BUFFERING:
6879 /* Handled in the main loop */
6880 break;
6881 default:
6882 return ERR_NOT_IMPLEMENTED;
6885 return ERR_NONE;
6888 static ErrorCode
6889 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6891 ErrorCode err;
6892 ERROR_DECL (error);
6894 switch (command) {
6895 case CMD_EVENT_REQUEST_SET: {
6896 EventRequest *req;
6897 int i, event_kind, suspend_policy, nmodifiers;
6898 ModifierKind mod;
6899 MonoMethod *method;
6900 long location = 0;
6901 MonoThread *step_thread;
6902 int step_thread_id = 0;
6903 StepDepth depth = STEP_DEPTH_INTO;
6904 StepSize size = STEP_SIZE_MIN;
6905 StepFilter filter = STEP_FILTER_NONE;
6906 MonoDomain *domain;
6907 Modifier *modifier;
6909 event_kind = decode_byte (p, &p, end);
6910 suspend_policy = decode_byte (p, &p, end);
6911 nmodifiers = decode_byte (p, &p, end);
6913 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6914 req->id = mono_atomic_inc_i32 (&event_request_id);
6915 req->event_kind = event_kind;
6916 req->suspend_policy = suspend_policy;
6917 req->nmodifiers = nmodifiers;
6919 method = NULL;
6920 for (i = 0; i < nmodifiers; ++i) {
6921 mod = (ModifierKind)decode_byte (p, &p, end);
6923 req->modifiers [i].kind = mod;
6924 if (mod == MOD_KIND_COUNT) {
6925 req->modifiers [i].data.count = decode_int (p, &p, end);
6926 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6927 method = decode_methodid (p, &p, end, &domain, &err);
6928 if (err != ERR_NONE)
6929 return err;
6930 location = decode_long (p, &p, end);
6931 } else if (mod == MOD_KIND_STEP) {
6932 step_thread_id = decode_id (p, &p, end);
6933 size = (StepSize)decode_int (p, &p, end);
6934 depth = (StepDepth)decode_int (p, &p, end);
6935 if (CHECK_PROTOCOL_VERSION (2, 16))
6936 filter = (StepFilter)decode_int (p, &p, end);
6937 req->modifiers [i].data.filter = filter;
6938 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
6939 /* Treat STEP_THOUGH the same as HIDDEN */
6940 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
6941 } else if (mod == MOD_KIND_THREAD_ONLY) {
6942 int id = decode_id (p, &p, end);
6944 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6945 if (err != ERR_NONE) {
6946 g_free (req);
6947 return err;
6949 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6950 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6952 if (err != ERR_NONE)
6953 return err;
6954 req->modifiers [i].caught = decode_byte (p, &p, end);
6955 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6956 if (CHECK_PROTOCOL_VERSION (2, 25))
6957 req->modifiers [i].subclasses = decode_byte (p, &p, end);
6958 else
6959 req->modifiers [i].subclasses = TRUE;
6960 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" : "");
6961 if (exc_class) {
6962 req->modifiers [i].data.exc_class = exc_class;
6964 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
6965 g_free (req);
6966 return ERR_INVALID_ARGUMENT;
6969 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6970 int n = decode_int (p, &p, end);
6971 int j;
6973 // +1 because we don't know length and we use last element to check for end
6974 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
6975 for (j = 0; j < n; ++j) {
6976 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6977 if (err != ERR_NONE) {
6978 g_free (req->modifiers [i].data.assemblies);
6979 return err;
6982 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6983 int n = decode_int (p, &p, end);
6984 int j;
6986 modifier = &req->modifiers [i];
6987 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6988 for (j = 0; j < n; ++j) {
6989 char *s = decode_string (p, &p, end);
6990 char *s2;
6992 if (s) {
6993 s2 = strdup_tolower (s);
6994 g_hash_table_insert (modifier->data.source_files, s2, s2);
6995 g_free (s);
6998 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6999 int n = decode_int (p, &p, end);
7000 int j;
7002 modifier = &req->modifiers [i];
7003 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7004 for (j = 0; j < n; ++j) {
7005 char *s = decode_string (p, &p, end);
7007 if (s)
7008 g_hash_table_insert (modifier->data.type_names, s, s);
7010 } else {
7011 g_free (req);
7012 return ERR_NOT_IMPLEMENTED;
7016 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7017 g_assert (method);
7019 req->info = mono_de_set_breakpoint (method, location, req, error);
7020 if (!mono_error_ok (error)) {
7021 g_free (req);
7022 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7023 mono_error_cleanup (error);
7024 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7026 } else if (req->event_kind == EVENT_KIND_STEP) {
7027 g_assert (step_thread_id);
7029 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7030 if (err != ERR_NONE) {
7031 g_free (req);
7032 return err;
7035 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7036 if (err != ERR_NONE) {
7037 g_free (req);
7038 return err;
7040 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7041 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7042 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7043 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7044 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7045 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7046 } else {
7047 if (req->nmodifiers) {
7048 g_free (req);
7049 return ERR_NOT_IMPLEMENTED;
7053 mono_loader_lock ();
7054 g_ptr_array_add (event_requests, req);
7056 if (agent_config.defer) {
7057 /* Transmit cached data to the client on receipt of the event request */
7058 switch (req->event_kind) {
7059 case EVENT_KIND_APPDOMAIN_CREATE:
7060 /* Emit load events for currently loaded domains */
7061 mono_de_foreach_domain (emit_appdomain_load, NULL);
7062 break;
7063 case EVENT_KIND_ASSEMBLY_LOAD:
7064 /* Emit load events for currently loaded assemblies */
7065 mono_domain_foreach (send_assemblies_for_domain, NULL);
7066 break;
7067 case EVENT_KIND_THREAD_START:
7068 /* Emit start events for currently started threads */
7069 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7070 break;
7071 case EVENT_KIND_TYPE_LOAD:
7072 /* Emit type load events for currently loaded types */
7073 mono_domain_foreach (send_types_for_domain, NULL);
7074 break;
7075 default:
7076 break;
7079 mono_loader_unlock ();
7081 buffer_add_int (buf, req->id);
7082 break;
7084 case CMD_EVENT_REQUEST_CLEAR: {
7085 int etype = decode_byte (p, &p, end);
7086 int req_id = decode_int (p, &p, end);
7088 // FIXME: Make a faster mapping from req_id to request
7089 mono_loader_lock ();
7090 clear_event_request (req_id, etype);
7091 mono_loader_unlock ();
7092 break;
7094 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7095 int i;
7097 mono_loader_lock ();
7098 i = 0;
7099 while (i < event_requests->len) {
7100 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7102 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7103 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7105 g_ptr_array_remove_index_fast (event_requests, i);
7106 g_free (req);
7107 } else {
7108 i ++;
7111 mono_loader_unlock ();
7112 break;
7114 default:
7115 return ERR_NOT_IMPLEMENTED;
7118 return ERR_NONE;
7121 static ErrorCode
7122 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7124 ErrorCode err;
7125 MonoDomain *domain;
7127 switch (command) {
7128 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7129 buffer_add_domainid (buf, mono_get_root_domain ());
7130 break;
7132 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7133 domain = decode_domainid (p, &p, end, NULL, &err);
7134 if (err != ERR_NONE)
7135 return err;
7136 buffer_add_string (buf, domain->friendly_name);
7137 break;
7139 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7140 GSList *tmp;
7141 MonoAssembly *ass;
7142 int count;
7144 domain = decode_domainid (p, &p, end, NULL, &err);
7145 if (err != ERR_NONE)
7146 return err;
7147 mono_loader_lock ();
7148 count = 0;
7149 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7150 count ++;
7152 buffer_add_int (buf, count);
7153 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7154 ass = (MonoAssembly *)tmp->data;
7155 buffer_add_assemblyid (buf, domain, ass);
7157 mono_loader_unlock ();
7158 break;
7160 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7161 domain = decode_domainid (p, &p, end, NULL, &err);
7162 if (err != ERR_NONE)
7163 return err;
7165 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7166 break;
7168 case CMD_APPDOMAIN_GET_CORLIB: {
7169 domain = decode_domainid (p, &p, end, NULL, &err);
7170 if (err != ERR_NONE)
7171 return err;
7173 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7174 break;
7176 case CMD_APPDOMAIN_CREATE_STRING: {
7177 char *s;
7178 MonoString *o;
7179 ERROR_DECL (error);
7181 domain = decode_domainid (p, &p, end, NULL, &err);
7182 if (err != ERR_NONE)
7183 return err;
7184 s = decode_string (p, &p, end);
7186 o = mono_string_new_checked (domain, s, error);
7187 if (!is_ok (error)) {
7188 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7189 mono_error_cleanup (error);
7190 return ERR_INVALID_OBJECT;
7192 buffer_add_objid (buf, (MonoObject*)o);
7193 break;
7195 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7196 ERROR_DECL (error);
7197 MonoClass *klass;
7198 MonoDomain *domain2;
7199 MonoObject *o;
7201 domain = decode_domainid (p, &p, end, NULL, &err);
7202 if (err != ERR_NONE)
7203 return err;
7204 klass = decode_typeid (p, &p, end, &domain2, &err);
7205 if (err != ERR_NONE)
7206 return err;
7208 // FIXME:
7209 g_assert (domain == domain2);
7211 o = mono_object_new_checked (domain, klass, error);
7212 mono_error_assert_ok (error);
7214 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7215 if (err != ERR_NONE)
7216 return err;
7218 buffer_add_objid (buf, o);
7219 break;
7221 default:
7222 return ERR_NOT_IMPLEMENTED;
7225 return ERR_NONE;
7228 static ErrorCode
7229 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7231 HANDLE_FUNCTION_ENTER();
7232 ErrorCode err = ERR_NONE;
7233 error_init (error);
7234 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7235 if (MONO_HANDLE_IS_NULL (o)) {
7236 err = ERR_INVALID_OBJECT;
7237 goto leave;
7239 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7240 leave:
7241 HANDLE_FUNCTION_RETURN_VAL (err);
7245 static ErrorCode
7246 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7248 ErrorCode err;
7249 MonoAssembly *ass;
7250 MonoDomain *domain;
7252 ass = decode_assemblyid (p, &p, end, &domain, &err);
7253 if (err != ERR_NONE)
7254 return err;
7256 switch (command) {
7257 case CMD_ASSEMBLY_GET_LOCATION: {
7258 buffer_add_string (buf, mono_image_get_filename (ass->image));
7259 break;
7261 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7262 guint32 token;
7263 MonoMethod *m;
7265 if (ass->image->dynamic) {
7266 buffer_add_id (buf, 0);
7267 } else {
7268 token = mono_image_get_entry_point (ass->image);
7269 if (token == 0) {
7270 buffer_add_id (buf, 0);
7271 } else {
7272 ERROR_DECL (error);
7273 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7274 if (!m)
7275 mono_error_cleanup (error); /* FIXME don't swallow the error */
7276 buffer_add_methodid (buf, domain, m);
7279 break;
7281 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7282 buffer_add_moduleid (buf, domain, ass->image);
7283 break;
7285 case CMD_ASSEMBLY_GET_OBJECT: {
7286 ERROR_DECL (error);
7287 err = get_assembly_object_command (domain, ass, buf, error);
7288 mono_error_cleanup (error);
7289 return err;
7291 case CMD_ASSEMBLY_GET_DOMAIN: {
7292 buffer_add_domainid (buf, domain);
7293 break;
7295 case CMD_ASSEMBLY_GET_TYPE: {
7296 ERROR_DECL (error);
7297 char *s = decode_string (p, &p, end);
7298 gboolean ignorecase = decode_byte (p, &p, end);
7299 MonoTypeNameParse info;
7300 MonoType *t;
7301 gboolean type_resolve, res;
7302 MonoDomain *d = mono_domain_get ();
7304 /* This is needed to be able to find referenced assemblies */
7305 res = mono_domain_set (domain, FALSE);
7306 g_assert (res);
7308 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7309 mono_error_cleanup (error);
7310 t = NULL;
7311 } else {
7312 if (info.assembly.name)
7313 NOT_IMPLEMENTED;
7314 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, error);
7315 if (!is_ok (error)) {
7316 mono_error_cleanup (error); /* FIXME don't swallow the error */
7317 mono_reflection_free_type_info (&info);
7318 g_free (s);
7319 return ERR_INVALID_ARGUMENT;
7322 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7323 mono_reflection_free_type_info (&info);
7324 g_free (s);
7326 mono_domain_set (d, TRUE);
7328 break;
7330 case CMD_ASSEMBLY_GET_NAME: {
7331 gchar *name;
7332 MonoAssembly *mass = ass;
7334 name = g_strdup_printf (
7335 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7336 mass->aname.name,
7337 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7338 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7339 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7340 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7342 buffer_add_string (buf, name);
7343 g_free (name);
7344 break;
7346 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7347 MonoImage* image = ass->image;
7348 if (ass->dynamic) {
7349 return ERR_NOT_IMPLEMENTED;
7351 buffer_add_byte_array (buf, (guint8*)m_image_get_raw_data (image), m_image_get_raw_data_len (image));
7352 break;
7354 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7355 buffer_add_byte (buf, ass->dynamic);
7356 break;
7358 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7359 MonoImage* image = ass->image;
7360 MonoDebugHandle* handle = mono_debug_get_handle (image);
7361 if (!handle) {
7362 return ERR_INVALID_ARGUMENT;
7364 MonoPPDBFile* ppdb = handle->ppdb;
7365 if (ppdb) {
7366 image = mono_ppdb_get_image (ppdb);
7367 buffer_add_byte_array (buf, (guint8*)m_image_get_raw_data (image), m_image_get_raw_data_len (image));
7368 } else {
7369 buffer_add_byte_array (buf, NULL, 0);
7371 break;
7373 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7374 if (ass->dynamic) {
7375 return ERR_NOT_IMPLEMENTED;
7377 guint32 token = decode_int (p, &p, end);
7378 ERROR_DECL (error);
7379 error_init (error);
7380 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7381 if (!is_ok (error)) {
7382 mono_error_cleanup (error);
7383 return ERR_INVALID_ARGUMENT;
7385 buffer_add_typeid (buf, domain, mono_class);
7386 mono_error_cleanup (error);
7387 break;
7389 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7390 if (ass->dynamic) {
7391 return ERR_NOT_IMPLEMENTED;
7393 guint32 token = decode_int (p, &p, end);
7394 ERROR_DECL (error);
7395 error_init (error);
7396 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7397 if (!is_ok (error)) {
7398 mono_error_cleanup (error);
7399 return ERR_INVALID_ARGUMENT;
7401 buffer_add_methodid (buf, domain, mono_method);
7402 mono_error_cleanup (error);
7403 break;
7405 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7406 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7407 break;
7409 default:
7410 return ERR_NOT_IMPLEMENTED;
7413 return ERR_NONE;
7416 static ErrorCode
7417 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7419 ErrorCode err;
7420 MonoDomain *domain;
7422 switch (command) {
7423 case CMD_MODULE_GET_INFO: {
7424 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7425 char *basename, *sourcelink = NULL;
7427 if (CHECK_PROTOCOL_VERSION (2, 48))
7428 sourcelink = mono_debug_image_get_sourcelink (image);
7430 basename = g_path_get_basename (image->name);
7431 buffer_add_string (buf, basename); // name
7432 buffer_add_string (buf, image->module_name); // scopename
7433 buffer_add_string (buf, image->name); // fqname
7434 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7435 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7436 if (CHECK_PROTOCOL_VERSION (2, 48))
7437 buffer_add_string (buf, sourcelink);
7438 g_free (basename);
7439 g_free (sourcelink);
7440 break;
7442 default:
7443 return ERR_NOT_IMPLEMENTED;
7446 return ERR_NONE;
7449 static ErrorCode
7450 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7452 ErrorCode err;
7453 MonoDomain *domain;
7455 switch (command) {
7456 case CMD_FIELD_GET_INFO: {
7457 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7459 buffer_add_string (buf, f->name);
7460 buffer_add_typeid (buf, domain, f->parent);
7461 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7462 buffer_add_int (buf, f->type->attrs);
7463 break;
7465 default:
7466 return ERR_NOT_IMPLEMENTED;
7469 return ERR_NONE;
7472 static void
7473 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7475 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7476 /* Special case these so the client doesn't have to handle Type objects */
7478 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7479 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
7480 } else if (MONO_TYPE_IS_REFERENCE (t))
7481 buffer_add_value (buf, t, &val, domain);
7482 else
7483 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
7486 static ErrorCode
7487 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7489 int i, j;
7490 int nattrs = 0;
7492 if (!cinfo) {
7493 buffer_add_int (buf, 0);
7494 return ERR_NONE;
7497 for (i = 0; i < cinfo->num_attrs; ++i) {
7498 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7499 nattrs ++;
7501 buffer_add_int (buf, nattrs);
7503 for (i = 0; i < cinfo->num_attrs; ++i) {
7504 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7505 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7506 MonoArray *typed_args, *named_args;
7507 MonoType *t;
7508 CattrNamedArg *arginfo = NULL;
7509 ERROR_DECL (error);
7511 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, error);
7512 if (!mono_error_ok (error)) {
7513 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
7514 mono_error_cleanup (error);
7515 return ERR_LOADER_ERROR;
7518 buffer_add_methodid (buf, domain, attr->ctor);
7520 /* Ctor args */
7521 if (typed_args) {
7522 buffer_add_int (buf, mono_array_length_internal (typed_args));
7523 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
7524 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
7526 t = mono_method_signature_internal (attr->ctor)->params [j];
7528 buffer_add_cattr_arg (buf, t, domain, val);
7530 } else {
7531 buffer_add_int (buf, 0);
7534 /* Named args */
7535 if (named_args) {
7536 buffer_add_int (buf, mono_array_length_internal (named_args));
7538 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
7539 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
7541 if (arginfo [j].prop) {
7542 buffer_add_byte (buf, 0x54);
7543 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7544 } else if (arginfo [j].field) {
7545 buffer_add_byte (buf, 0x53);
7546 buffer_add_fieldid (buf, domain, arginfo [j].field);
7547 } else {
7548 g_assert_not_reached ();
7551 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7553 } else {
7554 buffer_add_int (buf, 0);
7556 g_free (arginfo);
7560 return ERR_NONE;
7563 /* FIXME: Code duplication with icall.c */
7564 static void
7565 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7567 int i;
7568 MonoClass *ic;
7570 mono_class_setup_interfaces (klass, error);
7571 if (!mono_error_ok (error))
7572 return;
7574 int klass_interface_count = m_class_get_interface_count (klass);
7575 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
7576 for (i = 0; i < klass_interface_count; i++) {
7577 ic = klass_interfaces [i];
7578 g_hash_table_insert (ifaces, ic, ic);
7580 collect_interfaces (ic, ifaces, error);
7581 if (!mono_error_ok (error))
7582 return;
7586 static ErrorCode
7587 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7589 ERROR_DECL (error);
7590 MonoClass *nested;
7591 MonoType *type;
7592 gpointer iter;
7593 guint8 b;
7594 int nnested;
7595 ErrorCode err;
7596 char *name;
7598 switch (command) {
7599 case CMD_TYPE_GET_INFO: {
7600 buffer_add_string (buf, m_class_get_name_space (klass));
7601 buffer_add_string (buf, m_class_get_name (klass));
7602 // FIXME: byref
7603 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7604 buffer_add_string (buf, name);
7605 g_free (name);
7606 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
7607 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
7608 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
7609 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
7610 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
7611 else
7612 buffer_add_id (buf, 0);
7613 buffer_add_int (buf, m_class_get_type_token (klass));
7614 buffer_add_byte (buf, m_class_get_rank (klass));
7615 buffer_add_int (buf, mono_class_get_flags (klass));
7616 b = 0;
7617 type = m_class_get_byval_arg (klass);
7618 // FIXME: Can't decide whenever a class represents a byref type
7619 if (FALSE)
7620 b |= (1 << 0);
7621 if (type->type == MONO_TYPE_PTR)
7622 b |= (1 << 1);
7623 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7624 b |= (1 << 2);
7625 if (type->type == MONO_TYPE_VALUETYPE)
7626 b |= (1 << 3);
7627 if (m_class_is_enumtype (klass))
7628 b |= (1 << 4);
7629 if (mono_class_is_gtd (klass))
7630 b |= (1 << 5);
7631 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
7632 b |= (1 << 6);
7633 buffer_add_byte (buf, b);
7634 nnested = 0;
7635 iter = NULL;
7636 while ((nested = mono_class_get_nested_types (klass, &iter)))
7637 nnested ++;
7638 buffer_add_int (buf, nnested);
7639 iter = NULL;
7640 while ((nested = mono_class_get_nested_types (klass, &iter)))
7641 buffer_add_typeid (buf, domain, nested);
7642 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7643 if (mono_class_is_gtd (klass))
7644 buffer_add_typeid (buf, domain, klass);
7645 else if (mono_class_is_ginst (klass))
7646 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
7647 else
7648 buffer_add_id (buf, 0);
7650 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7651 int count, i;
7653 if (mono_class_is_ginst (klass)) {
7654 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
7656 count = inst->type_argc;
7657 buffer_add_int (buf, count);
7658 for (i = 0; i < count; i++)
7659 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
7660 } else if (mono_class_is_gtd (klass)) {
7661 MonoGenericContainer *container = mono_class_get_generic_container (klass);
7662 MonoClass *pklass;
7664 count = container->type_argc;
7665 buffer_add_int (buf, count);
7666 for (i = 0; i < count; i++) {
7667 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
7668 buffer_add_typeid (buf, domain, pklass);
7670 } else {
7671 buffer_add_int (buf, 0);
7674 break;
7676 case CMD_TYPE_GET_METHODS: {
7677 int nmethods;
7678 int i = 0;
7679 gpointer iter = NULL;
7680 MonoMethod *m;
7682 mono_class_setup_methods (klass);
7684 nmethods = mono_class_num_methods (klass);
7686 buffer_add_int (buf, nmethods);
7688 while ((m = mono_class_get_methods (klass, &iter))) {
7689 buffer_add_methodid (buf, domain, m);
7690 i ++;
7692 g_assert (i == nmethods);
7693 break;
7695 case CMD_TYPE_GET_FIELDS: {
7696 int nfields;
7697 int i = 0;
7698 gpointer iter = NULL;
7699 MonoClassField *f;
7701 nfields = mono_class_num_fields (klass);
7703 buffer_add_int (buf, nfields);
7705 while ((f = mono_class_get_fields_internal (klass, &iter))) {
7706 buffer_add_fieldid (buf, domain, f);
7707 buffer_add_string (buf, f->name);
7708 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7709 buffer_add_int (buf, f->type->attrs);
7710 i ++;
7712 g_assert (i == nfields);
7713 break;
7715 case CMD_TYPE_GET_PROPERTIES: {
7716 int nprops;
7717 int i = 0;
7718 gpointer iter = NULL;
7719 MonoProperty *p;
7721 nprops = mono_class_num_properties (klass);
7723 buffer_add_int (buf, nprops);
7725 while ((p = mono_class_get_properties (klass, &iter))) {
7726 buffer_add_propertyid (buf, domain, p);
7727 buffer_add_string (buf, p->name);
7728 buffer_add_methodid (buf, domain, p->get);
7729 buffer_add_methodid (buf, domain, p->set);
7730 buffer_add_int (buf, p->attrs);
7731 i ++;
7733 g_assert (i == nprops);
7734 break;
7736 case CMD_TYPE_GET_CATTRS: {
7737 MonoClass *attr_klass;
7738 MonoCustomAttrInfo *cinfo;
7740 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7741 /* attr_klass can be NULL */
7742 if (err != ERR_NONE)
7743 return err;
7745 cinfo = mono_custom_attrs_from_class_checked (klass, error);
7746 if (!is_ok (error)) {
7747 mono_error_cleanup (error); /* FIXME don't swallow the error message */
7748 return ERR_LOADER_ERROR;
7751 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
7752 if (err != ERR_NONE)
7753 return err;
7754 break;
7756 case CMD_TYPE_GET_FIELD_CATTRS: {
7757 MonoClass *attr_klass;
7758 MonoCustomAttrInfo *cinfo;
7759 MonoClassField *field;
7761 field = decode_fieldid (p, &p, end, NULL, &err);
7762 if (err != ERR_NONE)
7763 return err;
7764 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7765 if (err != ERR_NONE)
7766 return err;
7768 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
7769 if (!is_ok (error)) {
7770 mono_error_cleanup (error); /* FIXME don't swallow the error message */
7771 return ERR_LOADER_ERROR;
7774 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
7775 if (err != ERR_NONE)
7776 return err;
7777 break;
7779 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7780 MonoClass *attr_klass;
7781 MonoCustomAttrInfo *cinfo;
7782 MonoProperty *prop;
7784 prop = decode_propertyid (p, &p, end, NULL, &err);
7785 if (err != ERR_NONE)
7786 return err;
7787 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7788 if (err != ERR_NONE)
7789 return err;
7791 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
7792 if (!is_ok (error)) {
7793 mono_error_cleanup (error); /* FIXME don't swallow the error message */
7794 return ERR_LOADER_ERROR;
7797 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
7798 if (err != ERR_NONE)
7799 return err;
7800 break;
7802 case CMD_TYPE_GET_VALUES:
7803 case CMD_TYPE_GET_VALUES_2: {
7804 guint8 *val;
7805 MonoClassField *f;
7806 MonoVTable *vtable;
7807 MonoClass *k;
7808 int len, i;
7809 gboolean found;
7810 MonoThread *thread_obj;
7811 MonoInternalThread *thread = NULL;
7812 guint32 special_static_type;
7814 if (command == CMD_TYPE_GET_VALUES_2) {
7815 int objid = decode_objid (p, &p, end);
7816 ErrorCode err;
7818 err = get_object (objid, (MonoObject**)&thread_obj);
7819 if (err != ERR_NONE)
7820 return err;
7822 thread = THREAD_TO_INTERNAL (thread_obj);
7825 len = decode_int (p, &p, end);
7826 for (i = 0; i < len; ++i) {
7827 f = decode_fieldid (p, &p, end, NULL, &err);
7828 if (err != ERR_NONE)
7829 return err;
7831 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7832 return ERR_INVALID_FIELDID;
7833 special_static_type = mono_class_field_get_special_static_type (f);
7834 if (special_static_type != SPECIAL_STATIC_NONE) {
7835 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7836 return ERR_INVALID_FIELDID;
7839 /* Check that the field belongs to the object */
7840 found = FALSE;
7841 for (k = klass; k; k = m_class_get_parent (k)) {
7842 if (k == f->parent) {
7843 found = TRUE;
7844 break;
7847 if (!found)
7848 return ERR_INVALID_FIELDID;
7850 vtable = mono_class_vtable_checked (domain, f->parent, error);
7851 if (!is_ok (error))
7852 return ERR_INVALID_FIELDID;
7853 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
7854 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, error);
7855 if (!is_ok (error))
7856 return ERR_INVALID_FIELDID;
7857 buffer_add_value (buf, f->type, val, domain);
7858 g_free (val);
7860 break;
7862 case CMD_TYPE_SET_VALUES: {
7863 guint8 *val;
7864 MonoClassField *f;
7865 MonoVTable *vtable;
7866 MonoClass *k;
7867 int len, i;
7868 gboolean found;
7870 len = decode_int (p, &p, end);
7871 for (i = 0; i < len; ++i) {
7872 f = decode_fieldid (p, &p, end, NULL, &err);
7873 if (err != ERR_NONE)
7874 return err;
7876 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7877 return ERR_INVALID_FIELDID;
7878 if (mono_class_field_is_special_static (f))
7879 return ERR_INVALID_FIELDID;
7881 /* Check that the field belongs to the object */
7882 found = FALSE;
7883 for (k = klass; k; k = m_class_get_parent (k)) {
7884 if (k == f->parent) {
7885 found = TRUE;
7886 break;
7889 if (!found)
7890 return ERR_INVALID_FIELDID;
7892 // FIXME: Check for literal/const
7894 vtable = mono_class_vtable_checked (domain, f->parent, error);
7895 if (!is_ok (error))
7896 return ERR_INVALID_FIELDID;
7897 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
7898 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
7899 if (err != ERR_NONE) {
7900 g_free (val);
7901 return err;
7903 if (MONO_TYPE_IS_REFERENCE (f->type))
7904 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
7905 else
7906 mono_field_static_set_value_internal (vtable, f, val);
7907 g_free (val);
7909 break;
7911 case CMD_TYPE_GET_OBJECT: {
7912 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
7913 if (!mono_error_ok (error)) {
7914 mono_error_cleanup (error);
7915 return ERR_INVALID_OBJECT;
7917 buffer_add_objid (buf, o);
7918 break;
7920 case CMD_TYPE_GET_SOURCE_FILES:
7921 case CMD_TYPE_GET_SOURCE_FILES_2: {
7922 char *source_file, *base;
7923 GPtrArray *files;
7924 int i;
7926 files = get_source_files_for_type (klass);
7928 buffer_add_int (buf, files->len);
7929 for (i = 0; i < files->len; ++i) {
7930 source_file = (char *)g_ptr_array_index (files, i);
7931 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7932 buffer_add_string (buf, source_file);
7933 } else {
7934 base = dbg_path_get_basename (source_file);
7935 buffer_add_string (buf, base);
7936 g_free (base);
7938 g_free (source_file);
7940 g_ptr_array_free (files, TRUE);
7941 break;
7943 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7944 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7946 if (err != ERR_NONE)
7947 return err;
7948 if (mono_class_is_assignable_from_internal (klass, oklass))
7949 buffer_add_byte (buf, 1);
7950 else
7951 buffer_add_byte (buf, 0);
7952 break;
7954 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7955 char *name = decode_string (p, &p, end);
7956 int i, flags = decode_int (p, &p, end);
7957 int mlisttype;
7958 if (CHECK_PROTOCOL_VERSION (2, 48))
7959 mlisttype = decode_int (p, &p, end);
7960 else
7961 mlisttype = 0; // MLISTTYPE_All
7962 ERROR_DECL (error);
7963 GPtrArray *array;
7965 error_init (error);
7966 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
7967 if (!is_ok (error)) {
7968 mono_error_cleanup (error);
7969 return ERR_LOADER_ERROR;
7971 buffer_add_int (buf, array->len);
7972 for (i = 0; i < array->len; ++i) {
7973 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
7974 buffer_add_methodid (buf, domain, method);
7977 g_ptr_array_free (array, TRUE);
7978 g_free (name);
7979 break;
7981 case CMD_TYPE_GET_INTERFACES: {
7982 MonoClass *parent;
7983 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7984 MonoClass *tclass, *iface;
7985 GHashTableIter iter;
7987 tclass = klass;
7989 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
7990 mono_class_setup_interfaces (parent, error);
7991 if (!mono_error_ok (error))
7992 return ERR_LOADER_ERROR;
7993 collect_interfaces (parent, iface_hash, error);
7994 if (!mono_error_ok (error))
7995 return ERR_LOADER_ERROR;
7998 buffer_add_int (buf, g_hash_table_size (iface_hash));
8000 g_hash_table_iter_init (&iter, iface_hash);
8001 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8002 buffer_add_typeid (buf, domain, iface);
8003 g_hash_table_destroy (iface_hash);
8004 break;
8006 case CMD_TYPE_GET_INTERFACE_MAP: {
8007 int tindex, ioffset;
8008 gboolean variance_used;
8009 MonoClass *iclass;
8010 int len, nmethods, i;
8011 gpointer iter;
8012 MonoMethod *method;
8014 len = decode_int (p, &p, end);
8015 mono_class_setup_vtable (klass);
8017 for (tindex = 0; tindex < len; ++tindex) {
8018 iclass = decode_typeid (p, &p, end, NULL, &err);
8019 if (err != ERR_NONE)
8020 return err;
8022 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8023 if (ioffset == -1)
8024 return ERR_INVALID_ARGUMENT;
8026 nmethods = mono_class_num_methods (iclass);
8027 buffer_add_int (buf, nmethods);
8029 iter = NULL;
8030 while ((method = mono_class_get_methods (iclass, &iter))) {
8031 buffer_add_methodid (buf, domain, method);
8033 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8034 for (i = 0; i < nmethods; ++i)
8035 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8037 break;
8039 case CMD_TYPE_IS_INITIALIZED: {
8040 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8041 if (!is_ok (error))
8042 return ERR_LOADER_ERROR;
8044 if (vtable)
8045 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8046 else
8047 buffer_add_int (buf, 0);
8048 break;
8050 case CMD_TYPE_CREATE_INSTANCE: {
8051 ERROR_DECL (error);
8052 MonoObject *obj;
8054 obj = mono_object_new_checked (domain, klass, error);
8055 mono_error_assert_ok (error);
8056 buffer_add_objid (buf, obj);
8057 break;
8059 case CMD_TYPE_GET_VALUE_SIZE: {
8060 int32_t value_size;
8062 value_size = mono_class_value_size (klass, NULL);
8063 buffer_add_int (buf, value_size);
8064 break;
8066 default:
8067 return ERR_NOT_IMPLEMENTED;
8070 return ERR_NONE;
8073 static ErrorCode
8074 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8076 MonoClass *klass;
8077 MonoDomain *old_domain;
8078 MonoDomain *domain;
8079 ErrorCode err;
8081 klass = decode_typeid (p, &p, end, &domain, &err);
8082 if (err != ERR_NONE)
8083 return err;
8085 old_domain = mono_domain_get ();
8087 mono_domain_set (domain, TRUE);
8089 err = type_commands_internal (command, klass, domain, p, end, buf);
8091 mono_domain_set (old_domain, TRUE);
8093 return err;
8096 static ErrorCode
8097 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8099 MonoMethodHeader *header;
8100 ErrorCode err;
8102 switch (command) {
8103 case CMD_METHOD_GET_NAME: {
8104 buffer_add_string (buf, method->name);
8105 break;
8107 case CMD_METHOD_GET_DECLARING_TYPE: {
8108 buffer_add_typeid (buf, domain, method->klass);
8109 break;
8111 case CMD_METHOD_GET_DEBUG_INFO: {
8112 ERROR_DECL (error);
8113 MonoDebugMethodInfo *minfo;
8114 char *source_file;
8115 int i, j, n_il_offsets;
8116 int *source_files;
8117 GPtrArray *source_file_list;
8118 MonoSymSeqPoint *sym_seq_points;
8120 header = mono_method_get_header_checked (method, error);
8121 if (!header) {
8122 mono_error_cleanup (error); /* FIXME don't swallow the error */
8123 buffer_add_int (buf, 0);
8124 buffer_add_string (buf, "");
8125 buffer_add_int (buf, 0);
8126 break;
8129 minfo = mono_debug_lookup_method (method);
8130 if (!minfo) {
8131 buffer_add_int (buf, header->code_size);
8132 buffer_add_string (buf, "");
8133 buffer_add_int (buf, 0);
8134 mono_metadata_free_mh (header);
8135 break;
8138 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8139 buffer_add_int (buf, header->code_size);
8140 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8141 buffer_add_int (buf, source_file_list->len);
8142 for (i = 0; i < source_file_list->len; ++i) {
8143 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8144 buffer_add_string (buf, sinfo->source_file);
8145 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8146 for (j = 0; j < 16; ++j)
8147 buffer_add_byte (buf, sinfo->hash [j]);
8150 } else {
8151 buffer_add_string (buf, source_file);
8153 buffer_add_int (buf, n_il_offsets);
8154 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8155 for (i = 0; i < n_il_offsets; ++i) {
8156 MonoSymSeqPoint *sp = &sym_seq_points [i];
8157 const char *srcfile = "";
8159 if (source_files [i] != -1) {
8160 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8161 srcfile = sinfo->source_file;
8163 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);
8164 buffer_add_int (buf, sp->il_offset);
8165 buffer_add_int (buf, sp->line);
8166 if (CHECK_PROTOCOL_VERSION (2, 13))
8167 buffer_add_int (buf, source_files [i]);
8168 if (CHECK_PROTOCOL_VERSION (2, 19))
8169 buffer_add_int (buf, sp->column);
8170 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8171 buffer_add_int (buf, sp->end_line);
8172 buffer_add_int (buf, sp->end_column);
8175 g_free (source_file);
8176 g_free (source_files);
8177 g_free (sym_seq_points);
8178 g_ptr_array_free (source_file_list, TRUE);
8179 mono_metadata_free_mh (header);
8180 break;
8182 case CMD_METHOD_GET_PARAM_INFO: {
8183 MonoMethodSignature *sig = mono_method_signature_internal (method);
8184 guint32 i;
8185 char **names;
8187 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8189 /* FIXME: Use a smaller encoding */
8190 buffer_add_int (buf, sig->call_convention);
8191 buffer_add_int (buf, sig->param_count);
8192 buffer_add_int (buf, sig->generic_param_count);
8193 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8194 for (i = 0; i < sig->param_count; ++i) {
8195 /* FIXME: vararg */
8196 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8199 /* Emit parameter names */
8200 names = g_new (char *, sig->param_count);
8201 mono_method_get_param_names (method, (const char **) names);
8202 for (i = 0; i < sig->param_count; ++i)
8203 buffer_add_string (buf, names [i]);
8204 g_free (names);
8206 break;
8208 case CMD_METHOD_GET_LOCALS_INFO: {
8209 ERROR_DECL (error);
8210 int i, num_locals;
8211 MonoDebugLocalsInfo *locals;
8212 int *locals_map = NULL;
8214 header = mono_method_get_header_checked (method, error);
8215 if (!header) {
8216 mono_error_cleanup (error); /* FIXME don't swallow the error */
8217 return ERR_INVALID_ARGUMENT;
8220 locals = mono_debug_lookup_locals (method);
8221 if (!locals) {
8222 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8223 /* Scopes */
8224 buffer_add_int (buf, 1);
8225 buffer_add_int (buf, 0);
8226 buffer_add_int (buf, header->code_size);
8228 buffer_add_int (buf, header->num_locals);
8229 /* Types */
8230 for (i = 0; i < header->num_locals; ++i) {
8231 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8233 /* Names */
8234 for (i = 0; i < header->num_locals; ++i) {
8235 char lname [128];
8236 sprintf (lname, "V_%d", i);
8237 buffer_add_string (buf, lname);
8239 /* Scopes */
8240 for (i = 0; i < header->num_locals; ++i) {
8241 buffer_add_int (buf, 0);
8242 buffer_add_int (buf, header->code_size);
8244 } else {
8245 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8246 /* Scopes */
8247 buffer_add_int (buf, locals->num_blocks);
8248 int last_start = 0;
8249 for (i = 0; i < locals->num_blocks; ++i) {
8250 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8251 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8252 last_start = locals->code_blocks [i].start_offset;
8256 num_locals = locals->num_locals;
8257 buffer_add_int (buf, num_locals);
8259 /* Types */
8260 for (i = 0; i < num_locals; ++i) {
8261 g_assert (locals->locals [i].index < header->num_locals);
8262 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8264 /* Names */
8265 for (i = 0; i < num_locals; ++i)
8266 buffer_add_string (buf, locals->locals [i].name);
8267 /* Scopes */
8268 for (i = 0; i < num_locals; ++i) {
8269 if (locals->locals [i].block) {
8270 buffer_add_int (buf, locals->locals [i].block->start_offset);
8271 buffer_add_int (buf, locals->locals [i].block->end_offset);
8272 } else {
8273 buffer_add_int (buf, 0);
8274 buffer_add_int (buf, header->code_size);
8278 mono_metadata_free_mh (header);
8280 if (locals)
8281 mono_debug_free_locals (locals);
8282 g_free (locals_map);
8284 break;
8286 case CMD_METHOD_GET_INFO:
8287 buffer_add_int (buf, method->flags);
8288 buffer_add_int (buf, method->iflags);
8289 buffer_add_int (buf, method->token);
8290 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8291 guint8 attrs = 0;
8292 if (method->is_generic)
8293 attrs |= (1 << 0);
8294 if (mono_method_signature_internal (method)->generic_param_count)
8295 attrs |= (1 << 1);
8296 buffer_add_byte (buf, attrs);
8297 if (method->is_generic || method->is_inflated) {
8298 MonoMethod *result;
8300 if (method->is_generic) {
8301 result = method;
8302 } else {
8303 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8305 result = imethod->declaring;
8306 if (imethod->context.class_inst) {
8307 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8308 /*Generic methods gets the context of the GTD.*/
8309 if (mono_class_get_context (klass)) {
8310 ERROR_DECL (error);
8311 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8312 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
8317 buffer_add_methodid (buf, domain, result);
8318 } else {
8319 buffer_add_id (buf, 0);
8321 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8322 if (mono_method_signature_internal (method)->generic_param_count) {
8323 int count, i;
8325 if (method->is_inflated) {
8326 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8327 if (inst) {
8328 count = inst->type_argc;
8329 buffer_add_int (buf, count);
8331 for (i = 0; i < count; i++)
8332 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8333 } else {
8334 buffer_add_int (buf, 0);
8336 } else if (method->is_generic) {
8337 MonoGenericContainer *container = mono_method_get_generic_container (method);
8339 count = mono_method_signature_internal (method)->generic_param_count;
8340 buffer_add_int (buf, count);
8341 for (i = 0; i < count; i++) {
8342 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8343 MonoClass *pklass = mono_class_create_generic_parameter (param);
8344 buffer_add_typeid (buf, domain, pklass);
8346 } else {
8347 buffer_add_int (buf, 0);
8349 } else {
8350 buffer_add_int (buf, 0);
8354 break;
8355 case CMD_METHOD_GET_BODY: {
8356 ERROR_DECL (error);
8357 int i;
8359 header = mono_method_get_header_checked (method, error);
8360 if (!header) {
8361 mono_error_cleanup (error); /* FIXME don't swallow the error */
8362 buffer_add_int (buf, 0);
8364 if (CHECK_PROTOCOL_VERSION (2, 18))
8365 buffer_add_int (buf, 0);
8366 } else {
8367 buffer_add_int (buf, header->code_size);
8368 for (i = 0; i < header->code_size; ++i)
8369 buffer_add_byte (buf, header->code [i]);
8371 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8372 buffer_add_int (buf, header->num_clauses);
8373 for (i = 0; i < header->num_clauses; ++i) {
8374 MonoExceptionClause *clause = &header->clauses [i];
8376 buffer_add_int (buf, clause->flags);
8377 buffer_add_int (buf, clause->try_offset);
8378 buffer_add_int (buf, clause->try_len);
8379 buffer_add_int (buf, clause->handler_offset);
8380 buffer_add_int (buf, clause->handler_len);
8381 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8382 buffer_add_typeid (buf, domain, clause->data.catch_class);
8383 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8384 buffer_add_int (buf, clause->data.filter_offset);
8388 mono_metadata_free_mh (header);
8391 break;
8393 case CMD_METHOD_RESOLVE_TOKEN: {
8394 guint32 token = decode_int (p, &p, end);
8396 // FIXME: Generics
8397 switch (mono_metadata_token_code (token)) {
8398 case MONO_TOKEN_STRING: {
8399 ERROR_DECL (error);
8400 MonoString *s;
8401 char *s2;
8403 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8404 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8406 s2 = mono_string_to_utf8_checked_internal (s, error);
8407 mono_error_assert_ok (error);
8409 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8410 buffer_add_string (buf, s2);
8411 g_free (s2);
8412 break;
8414 default: {
8415 ERROR_DECL (error);
8416 gpointer val;
8417 MonoClass *handle_class;
8419 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8420 val = mono_method_get_wrapper_data (method, token);
8421 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8423 if (handle_class == NULL) {
8424 // Can't figure out the token type
8425 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8426 break;
8428 } else {
8429 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8430 if (!val)
8431 g_error ("Could not load token due to %s", mono_error_get_message (error));
8434 if (handle_class == mono_defaults.typehandle_class) {
8435 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8436 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8437 buffer_add_typeid (buf, domain, (MonoClass *) val);
8438 else
8439 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8440 } else if (handle_class == mono_defaults.fieldhandle_class) {
8441 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8442 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8443 } else if (handle_class == mono_defaults.methodhandle_class) {
8444 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8445 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8446 } else if (handle_class == mono_defaults.string_class) {
8447 char *s;
8449 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8450 mono_error_assert_ok (error);
8451 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8452 buffer_add_string (buf, s);
8453 g_free (s);
8454 } else {
8455 g_assert_not_reached ();
8457 break;
8460 break;
8462 case CMD_METHOD_GET_CATTRS: {
8463 ERROR_DECL (error);
8464 MonoClass *attr_klass;
8465 MonoCustomAttrInfo *cinfo;
8467 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8468 /* attr_klass can be NULL */
8469 if (err != ERR_NONE)
8470 return err;
8472 cinfo = mono_custom_attrs_from_method_checked (method, error);
8473 if (!is_ok (error)) {
8474 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8475 return ERR_LOADER_ERROR;
8478 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
8479 if (err != ERR_NONE)
8480 return err;
8481 break;
8483 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8484 ERROR_DECL (error);
8485 MonoType **type_argv;
8486 int i, type_argc;
8487 MonoDomain *d;
8488 MonoClass *klass;
8489 MonoGenericInst *ginst;
8490 MonoGenericContext tmp_context;
8491 MonoMethod *inflated;
8493 type_argc = decode_int (p, &p, end);
8494 type_argv = g_new0 (MonoType*, type_argc);
8495 for (i = 0; i < type_argc; ++i) {
8496 klass = decode_typeid (p, &p, end, &d, &err);
8497 if (err != ERR_NONE) {
8498 g_free (type_argv);
8499 return err;
8501 if (domain != d) {
8502 g_free (type_argv);
8503 return ERR_INVALID_ARGUMENT;
8505 type_argv [i] = m_class_get_byval_arg (klass);
8507 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8508 g_free (type_argv);
8509 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8510 tmp_context.method_inst = ginst;
8512 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
8513 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
8514 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8515 return ERR_INVALID_ARGUMENT;
8516 buffer_add_methodid (buf, domain, inflated);
8517 break;
8519 default:
8520 return ERR_NOT_IMPLEMENTED;
8523 return ERR_NONE;
8526 static ErrorCode
8527 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8529 ErrorCode err;
8530 MonoDomain *old_domain;
8531 MonoDomain *domain;
8532 MonoMethod *method;
8534 method = decode_methodid (p, &p, end, &domain, &err);
8535 if (err != ERR_NONE)
8536 return err;
8538 old_domain = mono_domain_get ();
8540 mono_domain_set (domain, TRUE);
8542 err = method_commands_internal (command, method, domain, p, end, buf);
8544 mono_domain_set (old_domain, TRUE);
8546 return err;
8549 static ErrorCode
8550 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8552 int objid = decode_objid (p, &p, end);
8553 ErrorCode err;
8554 MonoThread *thread_obj;
8555 MonoInternalThread *thread;
8557 err = get_object (objid, (MonoObject**)&thread_obj);
8558 if (err != ERR_NONE)
8559 return err;
8561 thread = THREAD_TO_INTERNAL (thread_obj);
8563 switch (command) {
8564 case CMD_THREAD_GET_NAME: {
8565 guint32 name_len;
8566 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8568 if (!s) {
8569 buffer_add_int (buf, 0);
8570 } else {
8571 char *name;
8572 glong len;
8574 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8575 g_assert (name);
8576 buffer_add_int (buf, len);
8577 buffer_add_data (buf, (guint8*)name, len);
8578 g_free (s);
8580 break;
8582 case CMD_THREAD_GET_FRAME_INFO: {
8583 DebuggerTlsData *tls;
8584 int i, start_frame, length;
8586 // Wait for suspending if it already started
8587 // FIXME: Races with suspend_count
8588 while (!is_suspended ()) {
8589 if (suspend_count)
8590 wait_for_suspend ();
8593 if (suspend_count)
8594 wait_for_suspend ();
8595 if (!is_suspended ())
8596 return ERR_NOT_SUSPENDED;
8599 start_frame = decode_int (p, &p, end);
8600 length = decode_int (p, &p, end);
8602 if (start_frame != 0 || length != -1)
8603 return ERR_NOT_IMPLEMENTED;
8605 mono_loader_lock ();
8606 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8607 mono_loader_unlock ();
8608 g_assert (tls);
8610 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
8612 buffer_add_int (buf, tls->frame_count);
8613 for (i = 0; i < tls->frame_count; ++i) {
8614 buffer_add_int (buf, tls->frames [i]->id);
8615 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
8616 buffer_add_int (buf, tls->frames [i]->il_offset);
8618 * Instead of passing the frame type directly to the client, we associate
8619 * it with the previous frame using a set of flags. This avoids lots of
8620 * conditional code in the client, since a frame whose type isn't
8621 * FRAME_TYPE_MANAGED has no method, location, etc.
8623 buffer_add_byte (buf, tls->frames [i]->flags);
8626 break;
8628 case CMD_THREAD_GET_STATE:
8629 buffer_add_int (buf, thread->state);
8630 break;
8631 case CMD_THREAD_GET_INFO:
8632 buffer_add_byte (buf, thread->threadpool_thread);
8633 break;
8634 case CMD_THREAD_GET_ID:
8635 buffer_add_long (buf, (guint64)(gsize)thread);
8636 break;
8637 case CMD_THREAD_GET_TID:
8638 buffer_add_long (buf, (guint64)thread->tid);
8639 break;
8640 case CMD_THREAD_SET_IP: {
8641 DebuggerTlsData *tls;
8642 MonoMethod *method;
8643 MonoDomain *domain;
8644 MonoSeqPointInfo *seq_points;
8645 SeqPoint sp;
8646 gboolean found_sp;
8647 gint64 il_offset;
8649 method = decode_methodid (p, &p, end, &domain, &err);
8650 if (err != ERR_NONE)
8651 return err;
8652 il_offset = decode_long (p, &p, end);
8654 while (!is_suspended ()) {
8655 if (suspend_count)
8656 wait_for_suspend ();
8659 mono_loader_lock ();
8660 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8661 mono_loader_unlock ();
8662 g_assert (tls);
8664 compute_frame_info (thread, tls, FALSE);
8665 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8666 return ERR_INVALID_ARGUMENT;
8668 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8670 g_assert (seq_points);
8672 if (!found_sp)
8673 return ERR_INVALID_ARGUMENT;
8675 // FIXME: Check that the ip change is safe
8677 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);
8679 if (tls->frames [0]->de.ji->is_interp) {
8680 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
8681 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);
8682 } else {
8683 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
8685 break;
8687 case CMD_THREAD_ELAPSED_TIME: {
8688 DebuggerTlsData *tls;
8689 mono_loader_lock ();
8690 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8691 mono_loader_unlock ();
8692 g_assert (tls);
8693 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
8694 break;
8696 default:
8697 return ERR_NOT_IMPLEMENTED;
8700 return ERR_NONE;
8703 static ErrorCode
8704 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8706 int objid;
8707 ErrorCode err;
8708 MonoThread *thread_obj;
8709 MonoInternalThread *thread;
8710 int pos, i, len, frame_idx;
8711 DebuggerTlsData *tls;
8712 StackFrame *frame;
8713 MonoDebugMethodJitInfo *jit;
8714 MonoMethodSignature *sig;
8715 gssize id;
8716 MonoMethodHeader *header;
8718 objid = decode_objid (p, &p, end);
8719 err = get_object (objid, (MonoObject**)&thread_obj);
8720 if (err != ERR_NONE)
8721 return err;
8723 thread = THREAD_TO_INTERNAL (thread_obj);
8725 id = decode_id (p, &p, end);
8727 mono_loader_lock ();
8728 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8729 mono_loader_unlock ();
8730 g_assert (tls);
8732 for (i = 0; i < tls->frame_count; ++i) {
8733 if (tls->frames [i]->id == id)
8734 break;
8736 if (i == tls->frame_count)
8737 return ERR_INVALID_FRAMEID;
8739 /* The thread is still running native code, can't get frame variables info */
8740 if (!tls->really_suspended && !tls->async_state.valid)
8741 return ERR_NOT_SUSPENDED;
8742 frame_idx = i;
8743 frame = tls->frames [frame_idx];
8745 /* This is supported for frames without has_ctx etc. set */
8746 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8747 if (CHECK_PROTOCOL_VERSION (2, 38))
8748 buffer_add_domainid (buf, frame->de.domain);
8749 return ERR_NONE;
8752 if (!frame->has_ctx)
8753 return ERR_ABSENT_INFORMATION;
8755 if (!ensure_jit ((DbgEngineStackFrame*)frame))
8756 return ERR_ABSENT_INFORMATION;
8758 jit = frame->jit;
8760 sig = mono_method_signature_internal (frame->actual_method);
8762 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
8764 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8766 return ERR_ABSENT_INFORMATION;
8768 switch (command) {
8769 case CMD_STACK_FRAME_GET_VALUES: {
8770 ERROR_DECL (error);
8771 len = decode_int (p, &p, end);
8772 header = mono_method_get_header_checked (frame->actual_method, error);
8773 mono_error_assert_ok (error); /* FIXME report error */
8775 for (i = 0; i < len; ++i) {
8776 pos = decode_int (p, &p, end);
8778 if (pos < 0) {
8779 pos = - pos - 1;
8781 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
8783 if (frame->de.ji->is_interp) {
8784 guint8 *addr;
8786 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
8788 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL);
8789 } else {
8790 g_assert (pos >= 0 && pos < jit->num_params);
8792 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
8794 } else {
8795 MonoDebugLocalsInfo *locals;
8797 locals = mono_debug_lookup_locals (frame->de.method);
8798 if (locals) {
8799 g_assert (pos < locals->num_locals);
8800 pos = locals->locals [pos].index;
8801 mono_debug_free_locals (locals);
8804 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
8806 if (frame->de.ji->is_interp) {
8807 guint8 *addr;
8809 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
8811 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL);
8812 } else {
8813 g_assert (pos >= 0 && pos < jit->num_locals);
8815 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
8819 mono_metadata_free_mh (header);
8820 break;
8822 case CMD_STACK_FRAME_GET_THIS: {
8823 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
8824 return ERR_ABSENT_INFORMATION;
8825 if (m_class_is_valuetype (frame->api_method->klass)) {
8826 if (!sig->hasthis) {
8827 MonoObject *p = NULL;
8828 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
8829 } else {
8830 if (frame->de.ji->is_interp) {
8831 guint8 *addr;
8833 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
8835 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL);
8836 } else {
8837 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
8840 } else {
8841 if (!sig->hasthis) {
8842 MonoObject *p = NULL;
8843 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
8844 } else {
8845 if (frame->de.ji->is_interp) {
8846 guint8 *addr;
8848 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
8850 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL);
8851 } else {
8852 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
8856 break;
8858 case CMD_STACK_FRAME_SET_VALUES: {
8859 ERROR_DECL (error);
8860 guint8 *val_buf;
8861 MonoType *t;
8862 MonoDebugVarInfo *var = NULL;
8863 gboolean is_arg = FALSE;
8865 len = decode_int (p, &p, end);
8866 header = mono_method_get_header_checked (frame->actual_method, error);
8867 mono_error_assert_ok (error); /* FIXME report error */
8869 for (i = 0; i < len; ++i) {
8870 pos = decode_int (p, &p, end);
8872 if (pos < 0) {
8873 pos = - pos - 1;
8875 g_assert (pos >= 0 && pos < jit->num_params);
8877 t = sig->params [pos];
8878 var = &jit->params [pos];
8879 is_arg = TRUE;
8880 } else {
8881 MonoDebugLocalsInfo *locals;
8883 locals = mono_debug_lookup_locals (frame->de.method);
8884 if (locals) {
8885 g_assert (pos < locals->num_locals);
8886 pos = locals->locals [pos].index;
8887 mono_debug_free_locals (locals);
8889 g_assert (pos >= 0 && pos < jit->num_locals);
8891 t = header->locals [pos];
8892 var = &jit->locals [pos];
8895 if (MONO_TYPE_IS_REFERENCE (t))
8896 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
8897 else
8898 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
8899 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
8900 if (err != ERR_NONE)
8901 return err;
8903 if (frame->de.ji->is_interp) {
8904 guint8 *addr;
8906 if (is_arg)
8907 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
8908 else
8909 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
8910 set_interp_var (t, addr, val_buf);
8911 } else {
8912 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
8915 mono_metadata_free_mh (header);
8916 break;
8918 case CMD_STACK_FRAME_GET_DOMAIN: {
8919 if (CHECK_PROTOCOL_VERSION (2, 38))
8920 buffer_add_domainid (buf, frame->de.domain);
8921 break;
8923 case CMD_STACK_FRAME_SET_THIS: {
8924 guint8 *val_buf;
8925 MonoType *t;
8926 MonoDebugVarInfo *var;
8928 t = m_class_get_byval_arg (frame->actual_method->klass);
8929 /* Checked by the sender */
8930 g_assert (MONO_TYPE_ISSTRUCT (t));
8932 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
8933 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
8934 if (err != ERR_NONE)
8935 return err;
8937 if (frame->de.ji->is_interp) {
8938 guint8 *addr;
8940 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
8941 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
8942 } else {
8943 var = jit->this_var;
8944 g_assert (var);
8946 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);
8948 break;
8950 default:
8951 return ERR_NOT_IMPLEMENTED;
8954 return ERR_NONE;
8957 static ErrorCode
8958 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8960 MonoArray *arr;
8961 int objid, index, len, i, esize;
8962 ErrorCode err;
8963 gpointer elem;
8965 objid = decode_objid (p, &p, end);
8966 err = get_object (objid, (MonoObject**)&arr);
8967 if (err != ERR_NONE)
8968 return err;
8970 switch (command) {
8971 case CMD_ARRAY_REF_GET_LENGTH:
8972 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
8973 if (!arr->bounds) {
8974 buffer_add_int (buf, arr->max_length);
8975 buffer_add_int (buf, 0);
8976 } else {
8977 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
8978 buffer_add_int (buf, arr->bounds [i].length);
8979 buffer_add_int (buf, arr->bounds [i].lower_bound);
8982 break;
8983 case CMD_ARRAY_REF_GET_VALUES:
8984 index = decode_int (p, &p, end);
8985 len = decode_int (p, &p, end);
8987 g_assert (index >= 0 && len >= 0);
8988 // Reordered to avoid integer overflow
8989 g_assert (!(index > arr->max_length - len));
8991 esize = mono_array_element_size (arr->obj.vtable->klass);
8992 for (i = index; i < index + len; ++i) {
8993 elem = (gpointer*)((char*)arr->vector + (i * esize));
8994 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
8996 break;
8997 case CMD_ARRAY_REF_SET_VALUES:
8998 index = decode_int (p, &p, end);
8999 len = decode_int (p, &p, end);
9001 g_assert (index >= 0 && len >= 0);
9002 // Reordered to avoid integer overflow
9003 g_assert (!(index > arr->max_length - len));
9005 esize = mono_array_element_size (arr->obj.vtable->klass);
9006 for (i = index; i < index + len; ++i) {
9007 elem = (gpointer*)((char*)arr->vector + (i * esize));
9009 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);
9011 break;
9012 default:
9013 return ERR_NOT_IMPLEMENTED;
9016 return ERR_NONE;
9019 static ErrorCode
9020 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9022 int objid;
9023 ErrorCode err;
9024 MonoString *str;
9025 char *s;
9026 int i, index, length;
9027 gunichar2 *c;
9028 gboolean use_utf16 = FALSE;
9030 objid = decode_objid (p, &p, end);
9031 err = get_object (objid, (MonoObject**)&str);
9032 if (err != ERR_NONE)
9033 return err;
9035 switch (command) {
9036 case CMD_STRING_REF_GET_VALUE:
9037 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9038 for (i = 0; i < mono_string_length_internal (str); ++i)
9039 if (mono_string_chars_internal (str)[i] == 0)
9040 use_utf16 = TRUE;
9041 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9043 if (use_utf16) {
9044 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9045 buffer_add_data (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9046 } else {
9047 ERROR_DECL (error);
9048 s = mono_string_to_utf8_checked_internal (str, error);
9049 if (!mono_error_ok (error)) {
9050 if (s)
9051 g_free (s);
9053 return ERR_INVALID_ARGUMENT;
9055 buffer_add_string (buf, s);
9056 g_free (s);
9058 break;
9059 case CMD_STRING_REF_GET_LENGTH:
9060 buffer_add_long (buf, mono_string_length_internal (str));
9061 break;
9062 case CMD_STRING_REF_GET_CHARS:
9063 index = decode_long (p, &p, end);
9064 length = decode_long (p, &p, end);
9065 if (index > mono_string_length_internal (str) - length)
9066 return ERR_INVALID_ARGUMENT;
9067 c = mono_string_chars_internal (str) + index;
9068 for (i = 0; i < length; ++i)
9069 buffer_add_short (buf, c [i]);
9070 break;
9071 default:
9072 return ERR_NOT_IMPLEMENTED;
9075 return ERR_NONE;
9078 static ErrorCode
9079 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9081 ErrorCode err;
9082 gint64 addr;
9083 MonoClass* klass;
9084 MonoDomain* domain = NULL;
9086 switch (command) {
9087 case CMD_POINTER_GET_VALUE:
9088 addr = decode_long (p, &p, end);
9089 klass = decode_typeid (p, &p, end, &domain, &err);
9090 if (err != ERR_NONE)
9091 return err;
9093 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9094 return ERR_INVALID_ARGUMENT;
9096 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (klass)), (gpointer)addr, domain);
9098 break;
9099 default:
9100 return ERR_NOT_IMPLEMENTED;
9103 return ERR_NONE;
9106 static ErrorCode
9107 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9109 ERROR_DECL (error);
9110 int objid;
9111 ErrorCode err;
9112 MonoObject *obj;
9113 int len, i;
9114 MonoClassField *f;
9115 MonoClass *k;
9116 gboolean found;
9118 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9119 objid = decode_objid (p, &p, end);
9120 err = get_object (objid, &obj);
9121 if (err != ERR_NONE)
9122 buffer_add_int (buf, 1);
9123 else
9124 buffer_add_int (buf, 0);
9125 return ERR_NONE;
9128 objid = decode_objid (p, &p, end);
9129 err = get_object (objid, &obj);
9130 if (err != ERR_NONE)
9131 return err;
9133 MonoClass *obj_type;
9134 gboolean remote_obj = FALSE;
9136 obj_type = obj->vtable->klass;
9137 if (mono_class_is_transparent_proxy (obj_type)) {
9138 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9139 remote_obj = TRUE;
9142 g_assert (obj_type);
9144 switch (command) {
9145 case CMD_OBJECT_REF_GET_TYPE:
9146 /* This handles transparent proxies too */
9147 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9148 break;
9149 case CMD_OBJECT_REF_GET_VALUES:
9150 len = decode_int (p, &p, end);
9152 for (i = 0; i < len; ++i) {
9153 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9154 if (err != ERR_NONE)
9155 return err;
9157 /* Check that the field belongs to the object */
9158 found = FALSE;
9159 for (k = obj_type; k; k = m_class_get_parent (k)) {
9160 if (k == f->parent) {
9161 found = TRUE;
9162 break;
9165 if (!found)
9166 return ERR_INVALID_FIELDID;
9168 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9169 guint8 *val;
9170 MonoVTable *vtable;
9172 if (mono_class_field_is_special_static (f))
9173 return ERR_INVALID_FIELDID;
9175 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9176 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9177 if (!is_ok (error)) {
9178 mono_error_cleanup (error);
9179 return ERR_INVALID_OBJECT;
9181 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9182 mono_field_static_get_value_checked (vtable, f, val, error);
9183 if (!is_ok (error)) {
9184 mono_error_cleanup (error); /* FIXME report the error */
9185 return ERR_INVALID_OBJECT;
9187 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9188 g_free (val);
9189 } else {
9190 void *field_value = NULL;
9192 if (remote_obj) {
9193 #ifndef DISABLE_REMOTING
9194 void *field_storage = NULL;
9195 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9196 if (!is_ok (error)) {
9197 mono_error_cleanup (error); /* FIXME report the error */
9198 return ERR_INVALID_OBJECT;
9200 #else
9201 g_assert_not_reached ();
9202 #endif
9203 } else
9204 field_value = (guint8*)obj + f->offset;
9206 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9209 break;
9210 case CMD_OBJECT_REF_SET_VALUES:
9211 len = decode_int (p, &p, end);
9213 for (i = 0; i < len; ++i) {
9214 f = decode_fieldid (p, &p, end, NULL, &err);
9215 if (err != ERR_NONE)
9216 return err;
9218 /* Check that the field belongs to the object */
9219 found = FALSE;
9220 for (k = obj_type; k; k = m_class_get_parent (k)) {
9221 if (k == f->parent) {
9222 found = TRUE;
9223 break;
9226 if (!found)
9227 return ERR_INVALID_FIELDID;
9229 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9230 guint8 *val;
9231 MonoVTable *vtable;
9233 if (mono_class_field_is_special_static (f))
9234 return ERR_INVALID_FIELDID;
9236 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9237 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9238 if (!is_ok (error)) {
9239 mono_error_cleanup (error);
9240 return ERR_INVALID_FIELDID;
9243 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9244 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9245 if (err != ERR_NONE) {
9246 g_free (val);
9247 return err;
9249 mono_field_static_set_value_internal (vtable, f, val);
9250 g_free (val);
9251 } else {
9252 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9253 if (err != ERR_NONE)
9254 return err;
9257 break;
9258 case CMD_OBJECT_REF_GET_ADDRESS:
9259 buffer_add_long (buf, (gssize)obj);
9260 break;
9261 case CMD_OBJECT_REF_GET_DOMAIN:
9262 buffer_add_domainid (buf, obj->vtable->domain);
9263 break;
9264 case CMD_OBJECT_REF_GET_INFO:
9265 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9266 buffer_add_domainid (buf, obj->vtable->domain);
9267 break;
9268 default:
9269 return ERR_NOT_IMPLEMENTED;
9272 return ERR_NONE;
9275 static const char*
9276 command_set_to_string (CommandSet command_set)
9278 switch (command_set) {
9279 case CMD_SET_VM:
9280 return "VM";
9281 case CMD_SET_OBJECT_REF:
9282 return "OBJECT_REF";
9283 case CMD_SET_STRING_REF:
9284 return "STRING_REF";
9285 case CMD_SET_THREAD:
9286 return "THREAD";
9287 case CMD_SET_ARRAY_REF:
9288 return "ARRAY_REF";
9289 case CMD_SET_EVENT_REQUEST:
9290 return "EVENT_REQUEST";
9291 case CMD_SET_STACK_FRAME:
9292 return "STACK_FRAME";
9293 case CMD_SET_APPDOMAIN:
9294 return "APPDOMAIN";
9295 case CMD_SET_ASSEMBLY:
9296 return "ASSEMBLY";
9297 case CMD_SET_METHOD:
9298 return "METHOD";
9299 case CMD_SET_TYPE:
9300 return "TYPE";
9301 case CMD_SET_MODULE:
9302 return "MODULE";
9303 case CMD_SET_FIELD:
9304 return "FIELD";
9305 case CMD_SET_EVENT:
9306 return "EVENT";
9307 case CMD_SET_POINTER:
9308 return "POINTER";
9309 default:
9310 return "";
9314 static const char* vm_cmds_str [] = {
9315 "VERSION",
9316 "ALL_THREADS",
9317 "SUSPEND",
9318 "RESUME",
9319 "EXIT",
9320 "DISPOSE",
9321 "INVOKE_METHOD",
9322 "SET_PROTOCOL_VERSION",
9323 "ABORT_INVOKE",
9324 "SET_KEEPALIVE"
9325 "GET_TYPES_FOR_SOURCE_FILE",
9326 "GET_TYPES",
9327 "INVOKE_METHODS"
9330 static const char* thread_cmds_str[] = {
9331 "GET_FRAME_INFO",
9332 "GET_NAME",
9333 "GET_STATE",
9334 "GET_INFO",
9335 "GET_ID",
9336 "GET_TID",
9337 "SET_IP"
9340 static const char* event_cmds_str[] = {
9341 "REQUEST_SET",
9342 "REQUEST_CLEAR",
9343 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9346 static const char* appdomain_cmds_str[] = {
9347 "GET_ROOT_DOMAIN",
9348 "GET_FRIENDLY_NAME",
9349 "GET_ASSEMBLIES",
9350 "GET_ENTRY_ASSEMBLY",
9351 "CREATE_STRING",
9352 "GET_CORLIB",
9353 "CREATE_BOXED_VALUE"
9356 static const char* assembly_cmds_str[] = {
9357 "GET_LOCATION",
9358 "GET_ENTRY_POINT",
9359 "GET_MANIFEST_MODULE",
9360 "GET_OBJECT",
9361 "GET_TYPE",
9362 "GET_NAME",
9363 "GET_DOMAIN",
9364 "HAS_DEBUG_INFO"
9367 static const char* module_cmds_str[] = {
9368 "GET_INFO",
9371 static const char* field_cmds_str[] = {
9372 "GET_INFO",
9375 static const char* method_cmds_str[] = {
9376 "GET_NAME",
9377 "GET_DECLARING_TYPE",
9378 "GET_DEBUG_INFO",
9379 "GET_PARAM_INFO",
9380 "GET_LOCALS_INFO",
9381 "GET_INFO",
9382 "GET_BODY",
9383 "RESOLVE_TOKEN",
9384 "GET_CATTRS ",
9385 "MAKE_GENERIC_METHOD"
9388 static const char* type_cmds_str[] = {
9389 "GET_INFO",
9390 "GET_METHODS",
9391 "GET_FIELDS",
9392 "GET_VALUES",
9393 "GET_OBJECT",
9394 "GET_SOURCE_FILES",
9395 "SET_VALUES",
9396 "IS_ASSIGNABLE_FROM",
9397 "GET_PROPERTIES ",
9398 "GET_CATTRS",
9399 "GET_FIELD_CATTRS",
9400 "GET_PROPERTY_CATTRS",
9401 "GET_SOURCE_FILES_2",
9402 "GET_VALUES_2",
9403 "GET_METHODS_BY_NAME_FLAGS",
9404 "GET_INTERFACES",
9405 "GET_INTERFACE_MAP",
9406 "IS_INITIALIZED",
9407 "CREATE_INSTANCE",
9408 "GET_VALUE_SIZE"
9411 static const char* stack_frame_cmds_str[] = {
9412 "GET_VALUES",
9413 "GET_THIS",
9414 "SET_VALUES",
9415 "GET_DOMAIN",
9416 "SET_THIS"
9419 static const char* array_cmds_str[] = {
9420 "GET_LENGTH",
9421 "GET_VALUES",
9422 "SET_VALUES",
9425 static const char* string_cmds_str[] = {
9426 "GET_VALUE",
9427 "GET_LENGTH",
9428 "GET_CHARS"
9431 static const char* pointer_cmds_str[] = {
9432 "GET_VALUE"
9435 static const char* object_cmds_str[] = {
9436 "GET_TYPE",
9437 "GET_VALUES",
9438 "IS_COLLECTED",
9439 "GET_ADDRESS",
9440 "GET_DOMAIN",
9441 "SET_VALUES",
9442 "GET_INFO",
9445 static const char*
9446 cmd_to_string (CommandSet set, int command)
9448 const char **cmds;
9449 int cmds_len = 0;
9451 switch (set) {
9452 case CMD_SET_VM:
9453 cmds = vm_cmds_str;
9454 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9455 break;
9456 case CMD_SET_OBJECT_REF:
9457 cmds = object_cmds_str;
9458 cmds_len = G_N_ELEMENTS (object_cmds_str);
9459 break;
9460 case CMD_SET_STRING_REF:
9461 cmds = string_cmds_str;
9462 cmds_len = G_N_ELEMENTS (string_cmds_str);
9463 break;
9464 case CMD_SET_THREAD:
9465 cmds = thread_cmds_str;
9466 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9467 break;
9468 case CMD_SET_ARRAY_REF:
9469 cmds = array_cmds_str;
9470 cmds_len = G_N_ELEMENTS (array_cmds_str);
9471 break;
9472 case CMD_SET_EVENT_REQUEST:
9473 cmds = event_cmds_str;
9474 cmds_len = G_N_ELEMENTS (event_cmds_str);
9475 break;
9476 case CMD_SET_STACK_FRAME:
9477 cmds = stack_frame_cmds_str;
9478 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9479 break;
9480 case CMD_SET_APPDOMAIN:
9481 cmds = appdomain_cmds_str;
9482 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9483 break;
9484 case CMD_SET_ASSEMBLY:
9485 cmds = assembly_cmds_str;
9486 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9487 break;
9488 case CMD_SET_METHOD:
9489 cmds = method_cmds_str;
9490 cmds_len = G_N_ELEMENTS (method_cmds_str);
9491 break;
9492 case CMD_SET_TYPE:
9493 cmds = type_cmds_str;
9494 cmds_len = G_N_ELEMENTS (type_cmds_str);
9495 break;
9496 case CMD_SET_MODULE:
9497 cmds = module_cmds_str;
9498 cmds_len = G_N_ELEMENTS (module_cmds_str);
9499 break;
9500 case CMD_SET_FIELD:
9501 cmds = field_cmds_str;
9502 cmds_len = G_N_ELEMENTS (field_cmds_str);
9503 break;
9504 case CMD_SET_EVENT:
9505 cmds = event_cmds_str;
9506 cmds_len = G_N_ELEMENTS (event_cmds_str);
9507 break;
9508 case CMD_SET_POINTER:
9509 cmds = pointer_cmds_str;
9510 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
9511 break;
9512 default:
9513 return NULL;
9515 if (command > 0 && command <= cmds_len)
9516 return cmds [command - 1];
9517 else
9518 return NULL;
9521 static gboolean
9522 wait_for_attach (void)
9524 #ifndef DISABLE_SOCKET_TRANSPORT
9525 if (listen_fd == -1) {
9526 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9527 return FALSE;
9530 /* Block and wait for client connection */
9531 conn_fd = socket_transport_accept (listen_fd);
9533 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9534 if (conn_fd == -1) {
9535 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9536 return FALSE;
9538 #else
9539 g_assert_not_reached ();
9540 #endif
9542 /* Handshake */
9543 disconnected = !transport_handshake ();
9544 if (disconnected) {
9545 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9546 return FALSE;
9549 return TRUE;
9553 * debugger_thread:
9555 * This thread handles communication with the debugger client using a JDWP
9556 * like protocol.
9558 static gsize WINAPI
9559 debugger_thread (void *arg)
9561 ERROR_DECL (error);
9562 int res, len, id, flags, command = 0;
9563 CommandSet command_set = (CommandSet)0;
9564 guint8 header [HEADER_LENGTH];
9565 guint8 *data, *p, *end;
9566 Buffer buf;
9567 ErrorCode err;
9568 gboolean no_reply;
9569 gboolean attach_failed = FALSE;
9571 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9573 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
9575 debugger_thread_id = mono_native_thread_id_get ();
9577 MonoInternalThread *internal = mono_thread_internal_current ();
9578 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", error);
9579 mono_error_assert_ok (error);
9580 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
9581 mono_error_assert_ok (error);
9583 internal->state |= ThreadState_Background;
9584 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9586 if (agent_config.defer) {
9587 if (!wait_for_attach ()) {
9588 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9589 attach_failed = TRUE; // Don't abort process when we can't listen
9590 } else {
9591 mono_set_is_debugger_attached (TRUE);
9592 /* Send start event to client */
9593 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9595 } else {
9596 mono_set_is_debugger_attached (TRUE);
9599 while (!attach_failed) {
9600 res = transport_recv (header, HEADER_LENGTH);
9602 /* This will break if the socket is closed during shutdown too */
9603 if (res != HEADER_LENGTH) {
9604 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9605 len = HEADER_LENGTH;
9606 id = 0;
9607 flags = 0;
9608 command_set = CMD_SET_VM;
9609 command = CMD_VM_DISPOSE;
9610 } else {
9611 p = header;
9612 end = header + HEADER_LENGTH;
9614 len = decode_int (p, &p, end);
9615 id = decode_int (p, &p, end);
9616 flags = decode_byte (p, &p, end);
9617 command_set = (CommandSet)decode_byte (p, &p, end);
9618 command = decode_byte (p, &p, end);
9621 g_assert (flags == 0);
9622 const char *cmd_str;
9623 char cmd_num [256];
9625 cmd_str = cmd_to_string (command_set, command);
9626 if (!cmd_str) {
9627 sprintf (cmd_num, "%d", command);
9628 cmd_str = cmd_num;
9631 if (log_level) {
9632 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);
9635 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9636 if (len - HEADER_LENGTH > 0)
9638 res = transport_recv (data, len - HEADER_LENGTH);
9639 if (res != len - HEADER_LENGTH) {
9640 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9641 break;
9645 p = data;
9646 end = data + (len - HEADER_LENGTH);
9648 buffer_init (&buf, 128);
9650 err = ERR_NONE;
9651 no_reply = FALSE;
9653 /* Process the request */
9654 switch (command_set) {
9655 case CMD_SET_VM:
9656 err = vm_commands (command, id, p, end, &buf);
9657 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9658 /* Sent after the invoke is complete */
9659 no_reply = TRUE;
9660 break;
9661 case CMD_SET_EVENT_REQUEST:
9662 err = event_commands (command, p, end, &buf);
9663 break;
9664 case CMD_SET_APPDOMAIN:
9665 err = domain_commands (command, p, end, &buf);
9666 break;
9667 case CMD_SET_ASSEMBLY:
9668 err = assembly_commands (command, p, end, &buf);
9669 break;
9670 case CMD_SET_MODULE:
9671 err = module_commands (command, p, end, &buf);
9672 break;
9673 case CMD_SET_FIELD:
9674 err = field_commands (command, p, end, &buf);
9675 break;
9676 case CMD_SET_TYPE:
9677 err = type_commands (command, p, end, &buf);
9678 break;
9679 case CMD_SET_METHOD:
9680 err = method_commands (command, p, end, &buf);
9681 break;
9682 case CMD_SET_THREAD:
9683 err = thread_commands (command, p, end, &buf);
9684 break;
9685 case CMD_SET_STACK_FRAME:
9686 err = frame_commands (command, p, end, &buf);
9687 break;
9688 case CMD_SET_ARRAY_REF:
9689 err = array_commands (command, p, end, &buf);
9690 break;
9691 case CMD_SET_STRING_REF:
9692 err = string_commands (command, p, end, &buf);
9693 break;
9694 case CMD_SET_POINTER:
9695 err = pointer_commands (command, p, end, &buf);
9696 break;
9697 case CMD_SET_OBJECT_REF:
9698 err = object_commands (command, p, end, &buf);
9699 break;
9700 default:
9701 err = ERR_NOT_IMPLEMENTED;
9704 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9705 buffer_replies = TRUE;
9708 if (!no_reply) {
9709 if (buffer_replies) {
9710 buffer_reply_packet (id, err, &buf);
9711 } else {
9712 send_reply_packet (id, err, &buf);
9713 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9717 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
9719 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9720 send_buffered_reply_packets ();
9721 buffer_replies = FALSE;
9724 g_free (data);
9725 buffer_free (&buf);
9727 if (log_each_step) {
9728 char *debugger_log = mono_debugger_state_str ();
9729 if (debugger_log) {
9730 fprintf (stderr, "Debugger state: %s\n", debugger_log);
9731 g_free (debugger_log);
9735 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9736 break;
9739 mono_set_is_debugger_attached (FALSE);
9741 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
9742 debugger_thread_exited = TRUE;
9743 mono_coop_cond_signal (&debugger_thread_exited_cond);
9744 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
9746 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9748 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9749 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9750 ERROR_DECL (error);
9751 start_debugger_thread (error);
9752 mono_error_cleanup (error);
9755 return 0;
9758 void
9759 mono_debugger_agent_init (void)
9761 MonoDebuggerCallbacks cbs;
9763 memset (&cbs, 0, sizeof (MonoDebuggerCallbacks));
9764 cbs.version = MONO_DBG_CALLBACKS_VERSION;
9765 cbs.parse_options = debugger_agent_parse_options;
9766 cbs.init = debugger_agent_init;
9767 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
9768 cbs.single_step_event = debugger_agent_single_step_event;
9769 cbs.single_step_from_context = debugger_agent_single_step_from_context;
9770 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
9771 cbs.free_domain_info = debugger_agent_free_domain_info;
9772 cbs.unhandled_exception = debugger_agent_unhandled_exception;
9773 cbs.handle_exception = debugger_agent_handle_exception;
9774 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
9775 cbs.end_exception_filter = debugger_agent_end_exception_filter;
9776 cbs.user_break = debugger_agent_user_break;
9777 cbs.debug_log = debugger_agent_debug_log;
9778 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
9779 cbs.send_crash = mono_debugger_agent_send_crash;
9781 mini_install_dbg_callbacks (&cbs);
9784 void
9785 mono_debugger_agent_parse_options (char *options)
9787 sdb_options = options;
9790 #endif /* DISABLE_SDB */