PageRenderTime 49ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 2ms

/mono/mini/debugger-agent.c

https://bitbucket.org/danipen/mono
C | 8901 lines | 6533 code | 1402 blank | 966 comment | 1422 complexity | 859c5c1a8bab0fc94f2776ea793ecb01 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  1. /*
  2. * debugger-agent.c: Soft Debugger back-end module
  3. *
  4. * Author:
  5. * Zoltan Varga (vargaz@gmail.com)
  6. *
  7. * Copyright 2009-2010 Novell, Inc.
  8. * Copyright 2011 Xamarin Inc.
  9. */
  10. #include <config.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #ifdef HAVE_SYS_TYPES_H
  15. #include <sys/types.h>
  16. #endif
  17. #ifdef HAVE_SYS_SELECT_H
  18. #include <sys/select.h>
  19. #endif
  20. #ifdef HAVE_SYS_SOCKET_H
  21. #include <sys/socket.h>
  22. #endif
  23. #ifdef HAVE_NETINET_TCP_H
  24. #include <netinet/tcp.h>
  25. #endif
  26. #ifdef HAVE_NETINET_IN_H
  27. #include <netinet/in.h>
  28. #endif
  29. #ifdef HAVE_NETDB_H
  30. #include <netdb.h>
  31. #endif
  32. #ifdef HAVE_UNISTD_H
  33. #include <unistd.h>
  34. #endif
  35. #include <errno.h>
  36. #include <glib.h>
  37. #ifdef HAVE_PTHREAD_H
  38. #include <pthread.h>
  39. #endif
  40. #ifdef HAVE_UCONTEXT_H
  41. #include <ucontext.h>
  42. #endif
  43. #ifdef HOST_WIN32
  44. #ifdef _MSC_VER
  45. #include <winsock2.h>
  46. #endif
  47. #include <ws2tcpip.h>
  48. #ifdef __GNUC__
  49. /* cygwin's headers do not seem to define these */
  50. void WSAAPI freeaddrinfo (struct addrinfo*);
  51. int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
  52. struct addrinfo**);
  53. int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
  54. char*,DWORD,int);
  55. #endif
  56. #endif
  57. #ifdef PLATFORM_ANDROID
  58. #include <linux/in.h>
  59. #include <linux/tcp.h>
  60. #include <sys/endian.h>
  61. #endif
  62. #include <mono/metadata/mono-debug.h>
  63. #include <mono/metadata/mono-debug-debugger.h>
  64. #include <mono/metadata/debug-mono-symfile.h>
  65. #include <mono/metadata/gc-internal.h>
  66. #include <mono/metadata/threads-types.h>
  67. #include <mono/metadata/socket-io.h>
  68. #include <mono/metadata/assembly.h>
  69. #include <mono/utils/mono-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 "debugger-agent.h"
  75. #include "mini.h"
  76. /*
  77. On iOS we can't use System.Environment.Exit () as it will do the wrong
  78. shutdown sequence.
  79. */
  80. #if !defined (TARGET_IOS)
  81. #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
  82. #endif
  83. #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  84. #define DISABLE_DEBUGGER_AGENT 1
  85. #endif
  86. #ifdef DISABLE_SOFT_DEBUG
  87. #define DISABLE_DEBUGGER_AGENT 1
  88. #endif
  89. #ifndef DISABLE_DEBUGGER_AGENT
  90. #include <mono/io-layer/mono-mutex.h>
  91. /* Definitions to make backporting to 2.6 easier */
  92. //#define MonoInternalThread MonoThread
  93. //#define mono_thread_internal_current mono_thread_current
  94. #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
  95. typedef struct {
  96. gboolean enabled;
  97. char *transport;
  98. char *address;
  99. int log_level;
  100. char *log_file;
  101. gboolean suspend;
  102. gboolean server;
  103. gboolean onuncaught;
  104. GSList *onthrow;
  105. int timeout;
  106. char *launch;
  107. gboolean embedding;
  108. gboolean defer;
  109. int keepalive;
  110. } AgentConfig;
  111. typedef struct
  112. {
  113. int id;
  114. guint32 il_offset, native_offset;
  115. MonoDomain *domain;
  116. MonoMethod *method;
  117. /*
  118. * If method is gshared, this is the actual instance, otherwise this is equal to
  119. * method.
  120. */
  121. MonoMethod *actual_method;
  122. /*
  123. * This is the method which is visible to debugger clients. Same as method,
  124. * except for native-to-managed wrappers.
  125. */
  126. MonoMethod *api_method;
  127. MonoContext ctx;
  128. MonoDebugMethodJitInfo *jit;
  129. MonoJitInfo *ji;
  130. int flags;
  131. mgreg_t *reg_locations [MONO_MAX_IREGS];
  132. /*
  133. * Whenever ctx is set. This is FALSE for the last frame of running threads, since
  134. * the frame can become invalid.
  135. */
  136. gboolean has_ctx;
  137. } StackFrame;
  138. typedef struct _InvokeData InvokeData;
  139. struct _InvokeData
  140. {
  141. int id;
  142. int flags;
  143. guint8 *p;
  144. guint8 *endp;
  145. /* This is the context which needs to be restored after the invoke */
  146. MonoContext ctx;
  147. gboolean has_ctx;
  148. /*
  149. * If this is set, invoke this method with the arguments given by ARGS.
  150. */
  151. MonoMethod *method;
  152. gpointer *args;
  153. guint32 suspend_count;
  154. int nmethods;
  155. InvokeData *last_invoke;
  156. };
  157. typedef struct {
  158. MonoThreadUnwindState context;
  159. /* This is computed on demand when it is requested using the wire protocol */
  160. /* It is freed up when the thread is resumed */
  161. int frame_count;
  162. StackFrame **frames;
  163. /*
  164. * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
  165. * re-compute it.
  166. */
  167. gboolean frames_up_to_date;
  168. /*
  169. * Points to data about a pending invoke which needs to be executed after the thread
  170. * resumes.
  171. */
  172. InvokeData *pending_invoke;
  173. /*
  174. * Set to TRUE if this thread is suspended in suspend_current () or it is executing
  175. * native code.
  176. */
  177. gboolean suspended;
  178. /*
  179. * Signals whenever the thread is in the process of suspending, i.e. it will suspend
  180. * within a finite amount of time.
  181. */
  182. gboolean suspending;
  183. /*
  184. * Set to TRUE if this thread is suspended in suspend_current ().
  185. */
  186. gboolean really_suspended;
  187. /* Used to pass the context to the breakpoint/single step handler */
  188. MonoContext handler_ctx;
  189. /* Whenever thread_stop () was called for this thread */
  190. gboolean terminated;
  191. /* Number of thread interruptions not yet processed */
  192. gint32 interrupt_count;
  193. /* Whenever to disable breakpoints (used during invokes) */
  194. gboolean disable_breakpoints;
  195. /*
  196. * Number of times this thread has been resumed using resume_thread ().
  197. */
  198. guint32 resume_count;
  199. MonoInternalThread *thread;
  200. /*
  201. * Information about the frame which transitioned to native code for running
  202. * threads.
  203. */
  204. StackFrameInfo async_last_frame;
  205. /*
  206. * The context where the stack walk can be started for running threads.
  207. */
  208. MonoThreadUnwindState async_state;
  209. /*
  210. * The context used for filter clauses
  211. */
  212. MonoThreadUnwindState filter_state;
  213. /*
  214. * The callee address of the last mono_runtime_invoke call
  215. */
  216. gpointer invoke_addr;
  217. gboolean abort_requested;
  218. /*
  219. * The current mono_runtime_invoke invocation.
  220. */
  221. InvokeData *invoke;
  222. /*
  223. * The context where single stepping should resume while the thread is suspended because
  224. * of an EXCEPTION event.
  225. */
  226. MonoThreadUnwindState catch_state;
  227. /*
  228. * The context which needs to be restored after handling a single step/breakpoint
  229. * event. This is the same as the ctx at step/breakpoint site, but includes changes
  230. * to caller saved registers done by set_var ().
  231. */
  232. MonoContext restore_ctx;
  233. } DebuggerTlsData;
  234. typedef struct {
  235. const char *name;
  236. void (*connect) (const char *address);
  237. void (*close1) (void);
  238. void (*close2) (void);
  239. gboolean (*send) (void *buf, int len);
  240. int (*recv) (void *buf, int len);
  241. } DebuggerTransport;
  242. /*
  243. * Wire Protocol definitions
  244. */
  245. #define HEADER_LENGTH 11
  246. #define MAJOR_VERSION 2
  247. #define MINOR_VERSION 23
  248. typedef enum {
  249. CMD_SET_VM = 1,
  250. CMD_SET_OBJECT_REF = 9,
  251. CMD_SET_STRING_REF = 10,
  252. CMD_SET_THREAD = 11,
  253. CMD_SET_ARRAY_REF = 13,
  254. CMD_SET_EVENT_REQUEST = 15,
  255. CMD_SET_STACK_FRAME = 16,
  256. CMD_SET_APPDOMAIN = 20,
  257. CMD_SET_ASSEMBLY = 21,
  258. CMD_SET_METHOD = 22,
  259. CMD_SET_TYPE = 23,
  260. CMD_SET_MODULE = 24,
  261. CMD_SET_EVENT = 64
  262. } CommandSet;
  263. typedef enum {
  264. EVENT_KIND_VM_START = 0,
  265. EVENT_KIND_VM_DEATH = 1,
  266. EVENT_KIND_THREAD_START = 2,
  267. EVENT_KIND_THREAD_DEATH = 3,
  268. EVENT_KIND_APPDOMAIN_CREATE = 4,
  269. EVENT_KIND_APPDOMAIN_UNLOAD = 5,
  270. EVENT_KIND_METHOD_ENTRY = 6,
  271. EVENT_KIND_METHOD_EXIT = 7,
  272. EVENT_KIND_ASSEMBLY_LOAD = 8,
  273. EVENT_KIND_ASSEMBLY_UNLOAD = 9,
  274. EVENT_KIND_BREAKPOINT = 10,
  275. EVENT_KIND_STEP = 11,
  276. EVENT_KIND_TYPE_LOAD = 12,
  277. EVENT_KIND_EXCEPTION = 13,
  278. EVENT_KIND_KEEPALIVE = 14,
  279. EVENT_KIND_USER_BREAK = 15,
  280. EVENT_KIND_USER_LOG = 16
  281. } EventKind;
  282. typedef enum {
  283. SUSPEND_POLICY_NONE = 0,
  284. SUSPEND_POLICY_EVENT_THREAD = 1,
  285. SUSPEND_POLICY_ALL = 2
  286. } SuspendPolicy;
  287. typedef enum {
  288. ERR_NONE = 0,
  289. ERR_INVALID_OBJECT = 20,
  290. ERR_INVALID_FIELDID = 25,
  291. ERR_INVALID_FRAMEID = 30,
  292. ERR_NOT_IMPLEMENTED = 100,
  293. ERR_NOT_SUSPENDED = 101,
  294. ERR_INVALID_ARGUMENT = 102,
  295. ERR_UNLOADED = 103,
  296. ERR_NO_INVOCATION = 104,
  297. ERR_ABSENT_INFORMATION = 105,
  298. ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
  299. ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
  300. } ErrorCode;
  301. typedef enum {
  302. MOD_KIND_COUNT = 1,
  303. MOD_KIND_THREAD_ONLY = 3,
  304. MOD_KIND_LOCATION_ONLY = 7,
  305. MOD_KIND_EXCEPTION_ONLY = 8,
  306. MOD_KIND_STEP = 10,
  307. MOD_KIND_ASSEMBLY_ONLY = 11,
  308. MOD_KIND_SOURCE_FILE_ONLY = 12,
  309. MOD_KIND_TYPE_NAME_ONLY = 13
  310. } ModifierKind;
  311. typedef enum {
  312. STEP_DEPTH_INTO = 0,
  313. STEP_DEPTH_OVER = 1,
  314. STEP_DEPTH_OUT = 2
  315. } StepDepth;
  316. typedef enum {
  317. STEP_SIZE_MIN = 0,
  318. STEP_SIZE_LINE = 1
  319. } StepSize;
  320. typedef enum {
  321. STEP_FILTER_NONE = 0,
  322. STEP_FILTER_STATIC_CTOR = 1,
  323. STEP_FILTER_DEBUGGER_HIDDEN = 2
  324. } StepFilter;
  325. typedef enum {
  326. TOKEN_TYPE_STRING = 0,
  327. TOKEN_TYPE_TYPE = 1,
  328. TOKEN_TYPE_FIELD = 2,
  329. TOKEN_TYPE_METHOD = 3,
  330. TOKEN_TYPE_UNKNOWN = 4
  331. } DebuggerTokenType;
  332. typedef enum {
  333. VALUE_TYPE_ID_NULL = 0xf0,
  334. VALUE_TYPE_ID_TYPE = 0xf1
  335. } ValueTypeId;
  336. typedef enum {
  337. FRAME_FLAG_DEBUGGER_INVOKE = 1,
  338. FRAME_FLAG_NATIVE_TRANSITION = 2
  339. } StackFrameFlags;
  340. typedef enum {
  341. INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
  342. INVOKE_FLAG_SINGLE_THREADED = 2
  343. } InvokeFlags;
  344. typedef enum {
  345. BINDING_FLAGS_IGNORE_CASE = 0x70000000,
  346. } BindingFlagsExtensions;
  347. typedef enum {
  348. CMD_VM_VERSION = 1,
  349. CMD_VM_ALL_THREADS = 2,
  350. CMD_VM_SUSPEND = 3,
  351. CMD_VM_RESUME = 4,
  352. CMD_VM_EXIT = 5,
  353. CMD_VM_DISPOSE = 6,
  354. CMD_VM_INVOKE_METHOD = 7,
  355. CMD_VM_SET_PROTOCOL_VERSION = 8,
  356. CMD_VM_ABORT_INVOKE = 9,
  357. CMD_VM_SET_KEEPALIVE = 10,
  358. CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
  359. CMD_VM_GET_TYPES = 12,
  360. CMD_VM_INVOKE_METHODS = 13
  361. } CmdVM;
  362. typedef enum {
  363. CMD_THREAD_GET_FRAME_INFO = 1,
  364. CMD_THREAD_GET_NAME = 2,
  365. CMD_THREAD_GET_STATE = 3,
  366. CMD_THREAD_GET_INFO = 4,
  367. CMD_THREAD_GET_ID = 5,
  368. CMD_THREAD_GET_TID = 6
  369. } CmdThread;
  370. typedef enum {
  371. CMD_EVENT_REQUEST_SET = 1,
  372. CMD_EVENT_REQUEST_CLEAR = 2,
  373. CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
  374. } CmdEvent;
  375. typedef enum {
  376. CMD_COMPOSITE = 100
  377. } CmdComposite;
  378. typedef enum {
  379. CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
  380. CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
  381. CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
  382. CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
  383. CMD_APPDOMAIN_CREATE_STRING = 5,
  384. CMD_APPDOMAIN_GET_CORLIB = 6,
  385. CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
  386. } CmdAppDomain;
  387. typedef enum {
  388. CMD_ASSEMBLY_GET_LOCATION = 1,
  389. CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
  390. CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
  391. CMD_ASSEMBLY_GET_OBJECT = 4,
  392. CMD_ASSEMBLY_GET_TYPE = 5,
  393. CMD_ASSEMBLY_GET_NAME = 6
  394. } CmdAssembly;
  395. typedef enum {
  396. CMD_MODULE_GET_INFO = 1,
  397. } CmdModule;
  398. typedef enum {
  399. CMD_METHOD_GET_NAME = 1,
  400. CMD_METHOD_GET_DECLARING_TYPE = 2,
  401. CMD_METHOD_GET_DEBUG_INFO = 3,
  402. CMD_METHOD_GET_PARAM_INFO = 4,
  403. CMD_METHOD_GET_LOCALS_INFO = 5,
  404. CMD_METHOD_GET_INFO = 6,
  405. CMD_METHOD_GET_BODY = 7,
  406. CMD_METHOD_RESOLVE_TOKEN = 8,
  407. CMD_METHOD_GET_CATTRS = 9,
  408. } CmdMethod;
  409. typedef enum {
  410. CMD_TYPE_GET_INFO = 1,
  411. CMD_TYPE_GET_METHODS = 2,
  412. CMD_TYPE_GET_FIELDS = 3,
  413. CMD_TYPE_GET_VALUES = 4,
  414. CMD_TYPE_GET_OBJECT = 5,
  415. CMD_TYPE_GET_SOURCE_FILES = 6,
  416. CMD_TYPE_SET_VALUES = 7,
  417. CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
  418. CMD_TYPE_GET_PROPERTIES = 9,
  419. CMD_TYPE_GET_CATTRS = 10,
  420. CMD_TYPE_GET_FIELD_CATTRS = 11,
  421. CMD_TYPE_GET_PROPERTY_CATTRS = 12,
  422. CMD_TYPE_GET_SOURCE_FILES_2 = 13,
  423. CMD_TYPE_GET_VALUES_2 = 14,
  424. CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
  425. CMD_TYPE_GET_INTERFACES = 16,
  426. CMD_TYPE_GET_INTERFACE_MAP = 17,
  427. CMD_TYPE_IS_INITIALIZED = 18
  428. } CmdType;
  429. typedef enum {
  430. CMD_STACK_FRAME_GET_VALUES = 1,
  431. CMD_STACK_FRAME_GET_THIS = 2,
  432. CMD_STACK_FRAME_SET_VALUES = 3
  433. } CmdStackFrame;
  434. typedef enum {
  435. CMD_ARRAY_REF_GET_LENGTH = 1,
  436. CMD_ARRAY_REF_GET_VALUES = 2,
  437. CMD_ARRAY_REF_SET_VALUES = 3,
  438. } CmdArray;
  439. typedef enum {
  440. CMD_STRING_REF_GET_VALUE = 1,
  441. CMD_STRING_REF_GET_LENGTH = 2,
  442. CMD_STRING_REF_GET_CHARS = 3
  443. } CmdString;
  444. typedef enum {
  445. CMD_OBJECT_REF_GET_TYPE = 1,
  446. CMD_OBJECT_REF_GET_VALUES = 2,
  447. CMD_OBJECT_REF_IS_COLLECTED = 3,
  448. CMD_OBJECT_REF_GET_ADDRESS = 4,
  449. CMD_OBJECT_REF_GET_DOMAIN = 5,
  450. CMD_OBJECT_REF_SET_VALUES = 6,
  451. CMD_OBJECT_REF_GET_INFO = 7,
  452. } CmdObject;
  453. typedef struct {
  454. ModifierKind kind;
  455. union {
  456. int count; /* For kind == MOD_KIND_COUNT */
  457. MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
  458. MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
  459. MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
  460. GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
  461. GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
  462. StepFilter filter; /* For kind == MOD_KIND_STEP */
  463. } data;
  464. gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
  465. } Modifier;
  466. typedef struct{
  467. int id;
  468. int event_kind;
  469. int suspend_policy;
  470. int nmodifiers;
  471. gpointer info;
  472. Modifier modifiers [MONO_ZERO_LEN_ARRAY];
  473. } EventRequest;
  474. /*
  475. * Describes a single step request.
  476. */
  477. typedef struct {
  478. EventRequest *req;
  479. MonoInternalThread *thread;
  480. StepDepth depth;
  481. StepSize size;
  482. StepFilter filter;
  483. gpointer last_sp;
  484. gpointer start_sp;
  485. MonoMethod *last_method;
  486. int last_line;
  487. /* Whenever single stepping is performed using start/stop_single_stepping () */
  488. gboolean global;
  489. /* The list of breakpoints used to implement step-over */
  490. GSList *bps;
  491. } SingleStepReq;
  492. /*
  493. * Contains additional information for an event
  494. */
  495. typedef struct {
  496. /* For EVENT_KIND_EXCEPTION */
  497. MonoObject *exc;
  498. MonoContext catch_ctx;
  499. gboolean caught;
  500. /* For EVENT_KIND_USER_LOG */
  501. int level;
  502. char *category, *message;
  503. /* For EVENT_KIND_TYPE_LOAD */
  504. MonoClass *klass;
  505. } EventInfo;
  506. /* Dummy structure used for the profiler callbacks */
  507. typedef struct {
  508. void* dummy;
  509. } DebuggerProfiler;
  510. #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
  511. #ifdef HOST_WIN32
  512. #define get_last_sock_error() WSAGetLastError()
  513. #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
  514. #define MONO_EINTR WSAEINTR
  515. #else
  516. #define get_last_sock_error() errno
  517. #define MONO_EWOULDBLOCK EWOULDBLOCK
  518. #define MONO_EINTR EINTR
  519. #endif
  520. #define CHECK_PROTOCOL_VERSION(major,minor) \
  521. (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
  522. /*
  523. * Globals
  524. */
  525. static AgentConfig agent_config;
  526. /*
  527. * Whenever the agent is fully initialized.
  528. * When using the onuncaught or onthrow options, only some parts of the agent are
  529. * initialized on startup, and the full initialization which includes connection
  530. * establishment and the startup of the agent thread is only done in response to
  531. * an event.
  532. */
  533. static gint32 inited;
  534. #ifndef DISABLE_SOCKET_TRANSPORT
  535. static int conn_fd;
  536. static int listen_fd;
  537. #endif
  538. static int packet_id = 0;
  539. static int objref_id = 0;
  540. static int event_request_id = 0;
  541. static int frame_id = 0;
  542. static GPtrArray *event_requests;
  543. static MonoNativeTlsKey debugger_tls_id;
  544. static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
  545. /* Maps MonoInternalThread -> DebuggerTlsData */
  546. static MonoGHashTable *thread_to_tls;
  547. /* Maps tid -> MonoInternalThread */
  548. static MonoGHashTable *tid_to_thread;
  549. /* Maps tid -> MonoThread (not MonoInternalThread) */
  550. static MonoGHashTable *tid_to_thread_obj;
  551. static gsize debugger_thread_id;
  552. static HANDLE debugger_thread_handle;
  553. static int log_level;
  554. static gboolean embedding;
  555. static FILE *log_file;
  556. /* Assemblies whose assembly load event has no been sent yet */
  557. static GPtrArray *pending_assembly_loads;
  558. /* Whenever the debugger thread has exited */
  559. static gboolean debugger_thread_exited;
  560. /* Cond variable used to wait for debugger_thread_exited becoming true */
  561. static mono_cond_t debugger_thread_exited_cond;
  562. /* Mutex for the cond var above */
  563. static mono_mutex_t debugger_thread_exited_mutex;
  564. static DebuggerProfiler debugger_profiler;
  565. /* The single step request instance */
  566. static SingleStepReq *ss_req = NULL;
  567. static gpointer ss_invoke_addr = NULL;
  568. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  569. /* Number of single stepping operations in progress */
  570. static int ss_count;
  571. #endif
  572. /* The protocol version of the client */
  573. static int major_version, minor_version;
  574. /* Whenever the variables above are set by the client */
  575. static gboolean protocol_version_set;
  576. /* A hash table containing all active domains */
  577. static GHashTable *domains;
  578. /* The number of times the runtime is suspended */
  579. static gint32 suspend_count;
  580. static void transport_init (void);
  581. static void transport_connect (const char *address);
  582. static gboolean transport_handshake (void);
  583. static void register_transport (DebuggerTransport *trans);
  584. static guint32 WINAPI debugger_thread (void *arg);
  585. static void runtime_initialized (MonoProfiler *prof);
  586. static void runtime_shutdown (MonoProfiler *prof);
  587. static void thread_startup (MonoProfiler *prof, uintptr_t tid);
  588. static void thread_end (MonoProfiler *prof, uintptr_t tid);
  589. static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
  590. static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
  591. static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
  592. static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
  593. static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
  594. static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
  595. static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
  596. static void emit_assembly_load (gpointer assembly, gpointer user_data);
  597. static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
  598. static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
  599. static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
  600. static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
  601. static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
  602. static void start_single_stepping (void);
  603. static void stop_single_stepping (void);
  604. static void suspend_current (void);
  605. static void clear_event_requests_for_assembly (MonoAssembly *assembly);
  606. static void clear_types_for_assembly (MonoAssembly *assembly);
  607. static void clear_breakpoints_for_domain (MonoDomain *domain);
  608. static void process_profiler_event (EventKind event, gpointer arg);
  609. /* Submodule init/cleanup */
  610. static void breakpoints_init (void);
  611. static void breakpoints_cleanup (void);
  612. static void objrefs_init (void);
  613. static void objrefs_cleanup (void);
  614. static void ids_init (void);
  615. static void ids_cleanup (void);
  616. static void suspend_init (void);
  617. static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
  618. static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
  619. static void ss_destroy (SingleStepReq *req);
  620. static void start_debugger_thread (void);
  621. static void stop_debugger_thread (void);
  622. static void finish_agent_init (gboolean on_startup);
  623. static void process_profiler_event (EventKind event, gpointer arg);
  624. static void invalidate_frames (DebuggerTlsData *tls);
  625. #ifndef DISABLE_SOCKET_TRANSPORT
  626. static void
  627. register_socket_transport (void);
  628. #endif
  629. static int
  630. parse_address (char *address, char **host, int *port)
  631. {
  632. char *pos = strchr (address, ':');
  633. if (pos == NULL || pos == address)
  634. return 1;
  635. *host = g_malloc (pos - address + 1);
  636. strncpy (*host, address, pos - address);
  637. (*host) [pos - address] = '\0';
  638. *port = atoi (pos + 1);
  639. return 0;
  640. }
  641. static void
  642. print_usage (void)
  643. {
  644. fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
  645. fprintf (stderr, "Available options:\n");
  646. fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
  647. fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
  648. fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
  649. fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
  650. fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
  651. fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
  652. fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
  653. fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
  654. fprintf (stderr, " help\t\t\t\tPrint this help.\n");
  655. }
  656. static gboolean
  657. parse_flag (const char *option, char *flag)
  658. {
  659. if (!strcmp (flag, "y"))
  660. return TRUE;
  661. else if (!strcmp (flag, "n"))
  662. return FALSE;
  663. else {
  664. fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
  665. exit (1);
  666. return FALSE;
  667. }
  668. }
  669. void
  670. mono_debugger_agent_parse_options (char *options)
  671. {
  672. char **args, **ptr;
  673. char *host;
  674. int port;
  675. char *extra;
  676. #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  677. fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
  678. exit (1);
  679. #endif
  680. extra = getenv ("MONO_SDB_ENV_OPTIONS");
  681. if (extra)
  682. options = g_strdup_printf ("%s,%s", options, extra);
  683. agent_config.enabled = TRUE;
  684. agent_config.suspend = TRUE;
  685. agent_config.server = FALSE;
  686. agent_config.defer = FALSE;
  687. agent_config.address = NULL;
  688. args = g_strsplit (options, ",", -1);
  689. for (ptr = args; ptr && *ptr; ptr ++) {
  690. char *arg = *ptr;
  691. if (strncmp (arg, "transport=", 10) == 0) {
  692. agent_config.transport = g_strdup (arg + 10);
  693. } else if (strncmp (arg, "address=", 8) == 0) {
  694. agent_config.address = g_strdup (arg + 8);
  695. } else if (strncmp (arg, "loglevel=", 9) == 0) {
  696. agent_config.log_level = atoi (arg + 9);
  697. } else if (strncmp (arg, "logfile=", 8) == 0) {
  698. agent_config.log_file = g_strdup (arg + 8);
  699. } else if (strncmp (arg, "suspend=", 8) == 0) {
  700. agent_config.suspend = parse_flag ("suspend", arg + 8);
  701. } else if (strncmp (arg, "server=", 7) == 0) {
  702. agent_config.server = parse_flag ("server", arg + 7);
  703. } else if (strncmp (arg, "onuncaught=", 11) == 0) {
  704. agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
  705. } else if (strncmp (arg, "onthrow=", 8) == 0) {
  706. /* We support multiple onthrow= options */
  707. agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
  708. } else if (strncmp (arg, "onthrow", 7) == 0) {
  709. agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
  710. } else if (strncmp (arg, "help", 4) == 0) {
  711. print_usage ();
  712. exit (0);
  713. } else if (strncmp (arg, "timeout=", 8) == 0) {
  714. agent_config.timeout = atoi (arg + 8);
  715. } else if (strncmp (arg, "launch=", 7) == 0) {
  716. agent_config.launch = g_strdup (arg + 7);
  717. } else if (strncmp (arg, "embedding=", 10) == 0) {
  718. agent_config.embedding = atoi (arg + 10) == 1;
  719. } else if (strncmp (arg, "keepalive=", 10) == 0) {
  720. agent_config.keepalive = atoi (arg + 10);
  721. } else {
  722. print_usage ();
  723. exit (1);
  724. }
  725. }
  726. if (agent_config.server && !agent_config.suspend) {
  727. /* Waiting for deferred attachment */
  728. agent_config.defer = TRUE;
  729. if (agent_config.address == NULL) {
  730. agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
  731. }
  732. }
  733. //agent_config.log_level = 0;
  734. if (agent_config.transport == NULL) {
  735. fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
  736. exit (1);
  737. }
  738. if (agent_config.address == NULL && !agent_config.server) {
  739. fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
  740. exit (1);
  741. }
  742. // FIXME:
  743. if (!strcmp (agent_config.transport, "dt_socket")) {
  744. if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
  745. fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
  746. exit (1);
  747. }
  748. }
  749. }
  750. void
  751. mono_debugger_agent_init (void)
  752. {
  753. if (!agent_config.enabled)
  754. return;
  755. transport_init ();
  756. /* Need to know whenever a thread has acquired the loader mutex */
  757. mono_loader_lock_track_ownership (TRUE);
  758. event_requests = g_ptr_array_new ();
  759. mono_mutex_init (&debugger_thread_exited_mutex, NULL);
  760. mono_cond_init (&debugger_thread_exited_cond, NULL);
  761. mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
  762. mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
  763. mono_profiler_install_runtime_initialized (runtime_initialized);
  764. mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
  765. mono_profiler_install_thread (thread_startup, thread_end);
  766. mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
  767. mono_profiler_install_jit_end (jit_end);
  768. mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
  769. mono_native_tls_alloc (&debugger_tls_id, NULL);
  770. thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
  771. MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
  772. tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
  773. MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
  774. tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
  775. MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
  776. pending_assembly_loads = g_ptr_array_new ();
  777. domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
  778. log_level = agent_config.log_level;
  779. embedding = agent_config.embedding;
  780. disconnected = TRUE;
  781. if (agent_config.log_file) {
  782. log_file = fopen (agent_config.log_file, "w+");
  783. if (!log_file) {
  784. fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
  785. exit (1);
  786. }
  787. } else {
  788. log_file = stdout;
  789. }
  790. ids_init ();
  791. objrefs_init ();
  792. breakpoints_init ();
  793. suspend_init ();
  794. mini_get_debug_options ()->gen_seq_points = TRUE;
  795. /*
  796. * This is needed because currently we don't handle liveness info.
  797. */
  798. mini_get_debug_options ()->mdb_optimizations = TRUE;
  799. #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
  800. /* This is needed because we can't set local variables in registers yet */
  801. mono_disable_optimizations (MONO_OPT_LINEARS);
  802. #endif
  803. /*
  804. * The stack walk done from thread_interrupt () needs to be signal safe, but it
  805. * isn't, since it can call into mono_aot_find_jit_info () which is not signal
  806. * safe (#3411). So load AOT info eagerly when the debugger is running as a
  807. * workaround.
  808. */
  809. mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
  810. if (!agent_config.onuncaught && !agent_config.onthrow)
  811. finish_agent_init (TRUE);
  812. }
  813. /*
  814. * finish_agent_init:
  815. *
  816. * Finish the initialization of the agent. This involves connecting the transport
  817. * and starting the agent thread. This is either done at startup, or
  818. * in response to some event like an unhandled exception.
  819. */
  820. static void
  821. finish_agent_init (gboolean on_startup)
  822. {
  823. int res;
  824. if (InterlockedCompareExchange (&inited, 1, 0) == 1)
  825. return;
  826. if (agent_config.launch) {
  827. char *argv [16];
  828. // FIXME: Generated address
  829. // FIXME: Races with transport_connect ()
  830. argv [0] = agent_config.launch;
  831. argv [1] = agent_config.transport;
  832. argv [2] = agent_config.address;
  833. argv [3] = NULL;
  834. res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
  835. if (!res) {
  836. fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
  837. exit (1);
  838. }
  839. }
  840. transport_connect (agent_config.address);
  841. if (!on_startup) {
  842. /* Do some which is usually done after sending the VMStart () event */
  843. vm_start_event_sent = TRUE;
  844. start_debugger_thread ();
  845. }
  846. }
  847. static void
  848. mono_debugger_agent_cleanup (void)
  849. {
  850. if (!inited)
  851. return;
  852. stop_debugger_thread ();
  853. breakpoints_cleanup ();
  854. objrefs_cleanup ();
  855. ids_cleanup ();
  856. mono_mutex_destroy (&debugger_thread_exited_mutex);
  857. mono_cond_destroy (&debugger_thread_exited_cond);
  858. }
  859. /*
  860. * SOCKET TRANSPORT
  861. */
  862. #ifndef DISABLE_SOCKET_TRANSPORT
  863. /*
  864. * recv_length:
  865. *
  866. * recv() + handle incomplete reads and EINTR
  867. */
  868. static int
  869. socket_transport_recv (void *buf, int len)
  870. {
  871. int res;
  872. int total = 0;
  873. int fd = conn_fd;
  874. int flags = 0;
  875. static gint32 last_keepalive;
  876. gint32 msecs;
  877. do {
  878. again:
  879. res = recv (fd, (char *) buf + total, len - total, flags);
  880. if (res > 0)
  881. total += res;
  882. if (agent_config.keepalive) {
  883. gboolean need_keepalive = FALSE;
  884. if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
  885. need_keepalive = TRUE;
  886. } else if (res == -1) {
  887. /* This could happen if recv () is interrupted repeatedly */
  888. msecs = mono_msec_ticks ();
  889. if (msecs - last_keepalive >= agent_config.keepalive) {
  890. need_keepalive = TRUE;
  891. last_keepalive = msecs;
  892. }
  893. }
  894. if (need_keepalive) {
  895. process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
  896. goto again;
  897. }
  898. }
  899. } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
  900. return total;
  901. }
  902. #ifndef TARGET_PS3
  903. #define HAVE_GETADDRINFO 1
  904. #endif
  905. static void
  906. set_keepalive (void)
  907. {
  908. struct timeval tv;
  909. int result;
  910. if (!agent_config.keepalive || !conn_fd)
  911. return;
  912. tv.tv_sec = agent_config.keepalive / 1000;
  913. tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
  914. result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
  915. g_assert (result >= 0);
  916. }
  917. static int
  918. socket_transport_accept (int socket_fd)
  919. {
  920. conn_fd = accept (socket_fd, NULL, NULL);
  921. if (conn_fd == -1) {
  922. fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
  923. } else {
  924. DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
  925. }
  926. return conn_fd;
  927. }
  928. static gboolean
  929. socket_transport_send (void *data, int len)
  930. {
  931. int res;
  932. do {
  933. res = send (conn_fd, data, len, 0);
  934. } while (res == -1 && get_last_sock_error () == MONO_EINTR);
  935. if (res != len)
  936. return FALSE;
  937. else
  938. return TRUE;
  939. }
  940. /*
  941. * socket_transport_connect:
  942. *
  943. * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
  944. */
  945. static void
  946. socket_transport_connect (const char *address)
  947. {
  948. #ifdef HAVE_GETADDRINFO
  949. struct addrinfo hints;
  950. struct addrinfo *result, *rp;
  951. #else
  952. struct hostent *result;
  953. #endif
  954. int sfd = -1, s, res;
  955. char port_string [128];
  956. char *host;
  957. int port;
  958. if (agent_config.address) {
  959. res = parse_address (agent_config.address, &host, &port);
  960. g_assert (res == 0);
  961. } else {
  962. host = NULL;
  963. port = 0;
  964. }
  965. conn_fd = -1;
  966. listen_fd = -1;
  967. if (host) {
  968. sprintf (port_string, "%d", port);
  969. mono_network_init ();
  970. /* Obtain address(es) matching host/port */
  971. #ifdef HAVE_GETADDRINFO
  972. memset (&hints, 0, sizeof (struct addrinfo));
  973. hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
  974. hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
  975. hints.ai_flags = 0;
  976. hints.ai_protocol = 0; /* Any protocol */
  977. s = getaddrinfo (host, port_string, &hints, &result);
  978. if (s != 0) {
  979. fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
  980. exit (1);
  981. }
  982. #else
  983. /* The PS3 doesn't even have _r or hstrerror () */
  984. result = gethostbyname (host);
  985. if (!result) {
  986. fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
  987. }
  988. #endif
  989. }
  990. if (agent_config.server) {
  991. #ifdef HAVE_GETADDRINFO
  992. /* Wait for a connection */
  993. if (!host) {
  994. struct sockaddr_in addr;
  995. socklen_t addrlen;
  996. /* No address, generate one */
  997. sfd = socket (AF_INET, SOCK_STREAM, 0);
  998. g_assert (sfd);
  999. /* This will bind the socket to a random port */
  1000. res = listen (sfd, 16);
  1001. if (res == -1) {
  1002. fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
  1003. exit (1);
  1004. }
  1005. listen_fd = sfd;
  1006. addrlen = sizeof (addr);
  1007. memset (&addr, 0, sizeof (addr));
  1008. res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
  1009. g_assert (res == 0);
  1010. host = (char*)"127.0.0.1";
  1011. port = ntohs (addr.sin_port);
  1012. /* Emit the address to stdout */
  1013. /* FIXME: Should print another interface, not localhost */
  1014. printf ("%s:%d\n", host, port);
  1015. } else {
  1016. /* Listen on the provided address */
  1017. for (rp = result; rp != NULL; rp = rp->ai_next) {
  1018. int n = 1;
  1019. sfd = socket (rp->ai_family, rp->ai_socktype,
  1020. rp->ai_protocol);
  1021. if (sfd == -1)
  1022. continue;
  1023. if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
  1024. continue;
  1025. res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
  1026. if (res == -1)
  1027. continue;
  1028. res = listen (sfd, 16);
  1029. if (res == -1)
  1030. continue;
  1031. listen_fd = sfd;
  1032. break;
  1033. }
  1034. #ifndef HOST_WIN32
  1035. /*
  1036. * this function is not present on win2000 which we still support, and the
  1037. * workaround described here:
  1038. * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
  1039. * only works with MSVC.
  1040. */
  1041. #ifdef HAVE_GETADDRINFO
  1042. freeaddrinfo (result);
  1043. #endif
  1044. #endif
  1045. }
  1046. if (agent_config.defer)
  1047. return;
  1048. DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
  1049. if (agent_config.timeout) {
  1050. fd_set readfds;
  1051. struct timeval tv;
  1052. tv.tv_sec = 0;
  1053. tv.tv_usec = agent_config.timeout * 1000;
  1054. FD_ZERO (&readfds);
  1055. FD_SET (sfd, &readfds);
  1056. res = select (sfd + 1, &readfds, NULL, NULL, &tv);
  1057. if (res == 0) {
  1058. fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
  1059. exit (1);
  1060. }
  1061. }
  1062. conn_fd = socket_transport_accept (sfd);
  1063. if (conn_fd == -1)
  1064. exit (1);
  1065. DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
  1066. #else
  1067. NOT_IMPLEMENTED;
  1068. #endif /* HAVE_GETADDRINFO */
  1069. } else {
  1070. /* Connect to the specified address */
  1071. #ifdef HAVE_GETADDRINFO
  1072. /* FIXME: Respect the timeout */
  1073. for (rp = result; rp != NULL; rp = rp->ai_next) {
  1074. sfd = socket (rp->ai_family, rp->ai_socktype,
  1075. rp->ai_protocol);
  1076. if (sfd == -1)
  1077. continue;
  1078. if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
  1079. break; /* Success */
  1080. close (sfd);
  1081. }
  1082. if (rp == 0) {
  1083. fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
  1084. exit (1);
  1085. }
  1086. #else
  1087. sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
  1088. if (sfd == -1)
  1089. g_assert_not_reached ();
  1090. res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
  1091. if (res == -1)
  1092. g_assert_not_reached ();
  1093. #endif
  1094. conn_fd = sfd;
  1095. #ifndef HOST_WIN32
  1096. /* See the comment above */
  1097. #ifdef HAVE_GETADDRINFO
  1098. freeaddrinfo (result);
  1099. #endif
  1100. #endif
  1101. }
  1102. if (!transport_handshake ())
  1103. exit (1);
  1104. }
  1105. static void
  1106. socket_transport_close1 (void)
  1107. {
  1108. /* This will interrupt the agent thread */
  1109. /* Close the read part only so it can still send back replies */
  1110. /* Also shut down the connection listener so that we can exit normally */
  1111. #ifdef HOST_WIN32
  1112. /* SD_RECEIVE doesn't break the recv in the debugger thread */
  1113. shutdown (conn_fd, SD_BOTH);
  1114. shutdown (listen_fd, SD_BOTH);
  1115. closesocket (listen_fd);
  1116. #else
  1117. shutdown (conn_fd, SHUT_RD);
  1118. shutdown (listen_fd, SHUT_RDWR);
  1119. close (listen_fd);
  1120. #endif
  1121. }
  1122. static void
  1123. socket_transport_close2 (void)
  1124. {
  1125. #ifdef HOST_WIN32
  1126. shutdown (conn_fd, SD_BOTH);
  1127. #else
  1128. shutdown (conn_fd, SHUT_RDWR);
  1129. #endif
  1130. }
  1131. static void
  1132. register_socket_transport (void)
  1133. {
  1134. DebuggerTransport trans;
  1135. trans.name = "dt_socket";
  1136. trans.connect = socket_transport_connect;
  1137. trans.close1 = socket_transport_close1;
  1138. trans.close2 = socket_transport_close2;
  1139. trans.send = socket_transport_send;
  1140. trans.recv = socket_transport_recv;
  1141. register_transport (&trans);
  1142. }
  1143. #endif /* DISABLE_SOCKET_TRANSPORT */
  1144. /*
  1145. * TRANSPORT CODE
  1146. */
  1147. #define MAX_TRANSPORTS 16
  1148. static DebuggerTransport *transport;
  1149. static DebuggerTransport transports [MAX_TRANSPORTS];
  1150. static int ntransports;
  1151. void
  1152. mono_debugger_agent_register_transport (DebuggerTransport *trans);
  1153. void
  1154. mono_debugger_agent_register_transport (DebuggerTransport *trans)
  1155. {
  1156. register_transport (trans);
  1157. }
  1158. static void
  1159. register_transport (DebuggerTransport *trans)
  1160. {
  1161. g_assert (ntransports < MAX_TRANSPORTS);
  1162. memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
  1163. ntransports ++;
  1164. }
  1165. static void
  1166. transport_init (void)
  1167. {
  1168. int i;
  1169. #ifndef DISABLE_SOCKET_TRANSPORT
  1170. register_socket_transport ();
  1171. #endif
  1172. for (i = 0; i < ntransports; ++i) {
  1173. if (!strcmp (agent_config.transport, transports [i].name))
  1174. break;
  1175. }
  1176. if (i == ntransports) {
  1177. fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
  1178. for (i = 0; i < ntransports; ++i)
  1179. fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
  1180. fprintf (stderr, "\n");
  1181. exit (1);
  1182. }
  1183. transport = &transports [i];
  1184. }
  1185. void
  1186. transport_connect (const char *address)
  1187. {
  1188. transport->connect (address);
  1189. }
  1190. static void
  1191. transport_close1 (void)
  1192. {
  1193. transport->close1 ();
  1194. }
  1195. static void
  1196. transport_close2 (void)
  1197. {
  1198. transport->close2 ();
  1199. }
  1200. static int
  1201. transport_send (void *buf, int len)
  1202. {
  1203. return transport->send (buf, len);
  1204. }
  1205. static int
  1206. transport_recv (void *buf, int len)
  1207. {
  1208. return transport->recv (buf, len);
  1209. }
  1210. gboolean
  1211. mono_debugger_agent_transport_handshake (void)
  1212. {
  1213. return transport_handshake ();
  1214. }
  1215. static gboolean
  1216. transport_handshake (void)
  1217. {
  1218. char handshake_msg [128];
  1219. guint8 buf [128];
  1220. int res;
  1221. disconnected = TRUE;
  1222. /* Write handshake message */
  1223. sprintf (handshake_msg, "DWP-Handshake");
  1224. do {
  1225. res = transport_send (handshake_msg, strlen (handshake_msg));
  1226. } while (res == -1 && get_last_sock_error () == MONO_EINTR);
  1227. g_assert (res != -1);
  1228. /* Read answer */
  1229. res = transport_recv (buf, strlen (handshake_msg));
  1230. if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
  1231. fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
  1232. return FALSE;
  1233. }
  1234. /*
  1235. * To support older clients, the client sends its protocol version after connecting
  1236. * using a command. Until that is received, default to our protocol version.
  1237. */
  1238. major_version = MAJOR_VERSION;
  1239. minor_version = MINOR_VERSION;
  1240. protocol_version_set = FALSE;
  1241. #ifndef DISABLE_SOCKET_TRANSPORT
  1242. // FIXME: Move this somewhere else
  1243. /*
  1244. * Set TCP_NODELAY on the socket so the client receives events/command
  1245. * results immediately.
  1246. */
  1247. if (conn_fd) {
  1248. int flag = 1;
  1249. int result = setsockopt (conn_fd,
  1250. IPPROTO_TCP,
  1251. TCP_NODELAY,
  1252. (char *) &flag,
  1253. sizeof(int));
  1254. g_assert (result >= 0);
  1255. }
  1256. set_keepalive ();
  1257. #endif
  1258. disconnected = FALSE;
  1259. return TRUE;
  1260. }
  1261. static void
  1262. stop_debugger_thread (void)
  1263. {
  1264. if (!inited)
  1265. return;
  1266. transport_close1 ();
  1267. /*
  1268. * Wait for the thread to exit.
  1269. *
  1270. * If we continue with the shutdown without waiting for it, then the client might
  1271. * not receive an answer to its last command like a resume.
  1272. * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
  1273. * use pthreads.
  1274. */
  1275. //WaitForSingleObject (debugger_thread_handle, INFINITE);
  1276. if (GetCurrentThreadId () != debugger_thread_id) {
  1277. do {
  1278. mono_mutex_lock (&debugger_thread_exited_mutex);
  1279. if (!debugger_thread_exited) {
  1280. #ifdef HOST_WIN32
  1281. if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
  1282. mono_mutex_unlock (&debugger_thread_exited_mutex);
  1283. Sleep(1);
  1284. mono_mutex_lock (&debugger_thread_exited_mutex);
  1285. }
  1286. #else
  1287. mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
  1288. #endif
  1289. }
  1290. mono_mutex_unlock (&debugger_thread_exited_mutex);
  1291. } while (!debugger_thread_exited);
  1292. }
  1293. transport_close2 ();
  1294. }
  1295. static void
  1296. start_debugger_thread (void)
  1297. {
  1298. gsize tid;
  1299. debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
  1300. g_assert (debugger_thread_handle);
  1301. }
  1302. /*
  1303. * Functions to decode protocol data
  1304. */
  1305. static inline int
  1306. decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
  1307. {
  1308. *endbuf = buf + 1;
  1309. g_assert (*endbuf <= limit);
  1310. return buf [0];
  1311. }
  1312. static inline int
  1313. decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
  1314. {
  1315. *endbuf = buf + 4;
  1316. g_assert (*endbuf <= limit);
  1317. return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
  1318. }
  1319. static inline gint64
  1320. decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
  1321. {
  1322. guint32 high = decode_int (buf, &buf, limit);
  1323. guint32 low = decode_int (buf, &buf, limit);
  1324. *endbuf = buf;
  1325. return ((((guint64)high) << 32) | ((guint64)low));
  1326. }
  1327. static inline int
  1328. decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
  1329. {
  1330. return decode_int (buf, endbuf, limit);
  1331. }
  1332. static inline char*
  1333. decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
  1334. {
  1335. int len = decode_int (buf, &buf, limit);
  1336. char *s;
  1337. if (len < 0) {
  1338. *endbuf = buf;
  1339. return NULL;
  1340. }
  1341. s = g_malloc (len + 1);
  1342. g_assert (s);
  1343. memcpy (s, buf, len);
  1344. s [len] = '\0';
  1345. buf += len;
  1346. *endbuf = buf;
  1347. return s;
  1348. }
  1349. /*
  1350. * Functions to encode protocol data
  1351. */
  1352. typedef struct {
  1353. guint8 *buf, *p, *end;
  1354. } Buffer;
  1355. static inline void
  1356. buffer_init (Buffer *buf, int size)
  1357. {
  1358. buf->buf = g_malloc (size);
  1359. buf->p = buf->buf;
  1360. buf->end = buf->buf + size;
  1361. }
  1362. static inline void
  1363. buffer_make_room (Buffer *buf, int size)
  1364. {
  1365. if (buf->end - buf->p < size) {
  1366. int new_size = buf->end - buf->buf + size + 32;
  1367. guint8 *p = g_realloc (buf->buf, new_size);
  1368. size = buf->p - buf->buf;
  1369. buf->buf = p;
  1370. buf->p = p + size;
  1371. buf->end = buf->buf + new_size;
  1372. }
  1373. }
  1374. static inline void
  1375. buffer_add_byte (Buffer *buf, guint8 val)
  1376. {
  1377. buffer_make_room (buf, 1);
  1378. buf->p [0] = val;
  1379. buf->p++;
  1380. }
  1381. static inline void
  1382. buffer_add_short (Buffer *buf, guint32 val)
  1383. {
  1384. buffer_make_room (buf, 2);
  1385. buf->p [0] = (val >> 8) & 0xff;
  1386. buf->p [1] = (val >> 0) & 0xff;
  1387. buf->p += 2;
  1388. }
  1389. static inline void
  1390. buffer_add_int (Buffer *buf, guint32 val)
  1391. {
  1392. buffer_make_room (buf, 4);
  1393. buf->p [0] = (val >> 24) & 0xff;
  1394. buf->p [1] = (val >> 16) & 0xff;
  1395. buf->p [2] = (val >> 8) & 0xff;
  1396. buf->p [3] = (val >> 0) & 0xff;
  1397. buf->p += 4;
  1398. }
  1399. static inline void
  1400. buffer_add_long (Buffer *buf, guint64 l)
  1401. {
  1402. buffer_add_int (buf, (l >> 32) & 0xffffffff);
  1403. buffer_add_int (buf, (l >> 0) & 0xffffffff);
  1404. }
  1405. static inline void
  1406. buffer_add_id (Buffer *buf, int id)
  1407. {
  1408. buffer_add_int (buf, (guint64)id);
  1409. }
  1410. static inline void
  1411. buffer_add_data (Buffer *buf, guint8 *data, int len)
  1412. {
  1413. buffer_make_room (buf, len);
  1414. memcpy (buf->p, data, len);
  1415. buf->p += len;
  1416. }
  1417. static inline void
  1418. buffer_add_string (Buffer *buf, const char *str)
  1419. {
  1420. int len;
  1421. if (str == NULL) {
  1422. buffer_add_int (buf, 0);
  1423. } else {
  1424. len = strlen (str);
  1425. buffer_add_int (buf, len);
  1426. buffer_add_data (buf, (guint8*)str, len);
  1427. }
  1428. }
  1429. static inline void
  1430. buffer_free (Buffer *buf)
  1431. {
  1432. g_free (buf->buf);
  1433. }
  1434. static gboolean
  1435. send_packet (int command_set, int command, Buffer *data)
  1436. {
  1437. Buffer buf;
  1438. int len, id;
  1439. gboolean res;
  1440. id = InterlockedIncrement (&packet_id);
  1441. len = data->p - data->buf + 11;
  1442. buffer_init (&buf, len);
  1443. buffer_add_int (&buf, len);
  1444. buffer_add_int (&buf, id);
  1445. buffer_add_byte (&buf, 0); /* flags */
  1446. buffer_add_byte (&buf, command_set);
  1447. buffer_add_byte (&buf, command);
  1448. memcpy (buf.buf + 11, data->buf, data->p - data->buf);
  1449. res = transport_send (buf.buf, len);
  1450. buffer_free (&buf);
  1451. return res;
  1452. }
  1453. static gboolean
  1454. send_reply_packet (int id, int error, Buffer *data)
  1455. {
  1456. Buffer buf;
  1457. int len;
  1458. gboolean res;
  1459. len = data->p - data->buf + 11;
  1460. buffer_init (&buf, len);
  1461. buffer_add_int (&buf, len);
  1462. buffer_add_int (&buf, id);
  1463. buffer_add_byte (&buf, 0x80); /* flags */
  1464. buffer_add_byte (&buf, (error >> 8) & 0xff);
  1465. buffer_add_byte (&buf, error);
  1466. memcpy (buf.buf + 11, data->buf, data->p - data->buf);
  1467. res = transport_send (buf.buf, len);
  1468. buffer_free (&buf);
  1469. return res;
  1470. }
  1471. /*
  1472. * OBJECT IDS
  1473. */
  1474. /*
  1475. * Represents an object accessible by the debugger client.
  1476. */
  1477. typedef struct {
  1478. /* Unique id used in the wire protocol to refer to objects */
  1479. int id;
  1480. /*
  1481. * A weakref gc handle pointing to the object. The gc handle is used to
  1482. * detect if the object was garbage collected.
  1483. */
  1484. guint32 handle;
  1485. } ObjRef;
  1486. /* Maps objid -> ObjRef */
  1487. static GHashTable *objrefs;
  1488. static void
  1489. free_objref (gpointer value)
  1490. {
  1491. ObjRef *o = value;
  1492. mono_gchandle_free (o->handle);
  1493. g_free (o);
  1494. }
  1495. static void
  1496. objrefs_init (void)
  1497. {
  1498. objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
  1499. }
  1500. static void
  1501. objrefs_cleanup (void)
  1502. {
  1503. g_hash_table_destroy (objrefs);
  1504. objrefs = NULL;
  1505. }
  1506. static GHashTable *obj_to_objref;
  1507. static MonoGHashTable *suspended_objs;
  1508. /*
  1509. * Return an ObjRef for OBJ.
  1510. */
  1511. static ObjRef*
  1512. get_objref (MonoObject *obj)
  1513. {
  1514. ObjRef *ref;
  1515. GSList *reflist = NULL, *l;
  1516. int hash = 0;
  1517. if (obj == NULL)
  1518. return 0;
  1519. mono_loader_lock ();
  1520. if (!obj_to_objref) {
  1521. obj_to_objref = g_hash_table_new (NULL, NULL);
  1522. suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
  1523. MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
  1524. }
  1525. if (suspend_count) {
  1526. /*
  1527. * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
  1528. */
  1529. mono_g_hash_table_insert (suspended_objs, obj, NULL);
  1530. }
  1531. /* FIXME: The tables can grow indefinitely */
  1532. if (mono_gc_is_moving ()) {
  1533. /*
  1534. * Objects can move, so use a hash table mapping hash codes to lists of
  1535. * ObjRef structures.
  1536. */
  1537. hash = mono_object_hash (obj);
  1538. reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
  1539. for (l = reflist; l; l = l->next) {
  1540. ref = l->data;
  1541. if (ref && mono_gchandle_get_target (ref->handle) == obj) {
  1542. mono_loader_unlock ();
  1543. return ref;
  1544. }
  1545. }
  1546. } else {
  1547. /* Use a hash table with masked pointers to internalize object references */
  1548. ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
  1549. /* ref might refer to a different object with the same addr which was GCd */
  1550. if (ref && mono_gchandle_get_target (ref->handle) == obj) {
  1551. mono_loader_unlock ();
  1552. return ref;
  1553. }
  1554. }
  1555. ref = g_new0 (ObjRef, 1);
  1556. ref->id = InterlockedIncrement (&objref_id);
  1557. ref->handle = mono_gchandle_new_weakref (obj, FALSE);
  1558. g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
  1559. if (mono_gc_is_moving ()) {
  1560. reflist = g_slist_append (reflist, ref);
  1561. g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
  1562. } else {
  1563. g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
  1564. }
  1565. mono_loader_unlock ();
  1566. return ref;
  1567. }
  1568. static gboolean
  1569. true_pred (gpointer key, gpointer value, gpointer user_data)
  1570. {
  1571. return TRUE;
  1572. }
  1573. static void
  1574. clear_suspended_objs (void)
  1575. {
  1576. mono_loader_lock ();
  1577. mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
  1578. mono_loader_unlock ();
  1579. }
  1580. static inline int
  1581. get_objid (MonoObject *obj)
  1582. {
  1583. return get_objref (obj)->id;
  1584. }
  1585. /*
  1586. * Set OBJ to the object identified by OBJID.
  1587. * Returns 0 or an error code if OBJID is invalid or the object has been garbage
  1588. * collected.
  1589. */
  1590. static ErrorCode
  1591. get_object_allow_null (int objid, MonoObject **obj)
  1592. {
  1593. ObjRef *ref;
  1594. if (objid == 0) {
  1595. *obj = NULL;
  1596. return 0;
  1597. }
  1598. if (!objrefs)
  1599. return ERR_INVALID_OBJECT;
  1600. mono_loader_lock ();
  1601. ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
  1602. if (ref) {
  1603. *obj = mono_gchandle_get_target (ref->handle);
  1604. mono_loader_unlock ();
  1605. if (!(*obj))
  1606. return ERR_INVALID_OBJECT;
  1607. return 0;
  1608. } else {
  1609. mono_loader_unlock ();
  1610. return ERR_INVALID_OBJECT;
  1611. }
  1612. }
  1613. static ErrorCode
  1614. get_object (int objid, MonoObject **obj)
  1615. {
  1616. int err = get_object_allow_null (objid, obj);
  1617. if (err)
  1618. return err;
  1619. if (!(*obj))
  1620. return ERR_INVALID_OBJECT;
  1621. return 0;
  1622. }
  1623. static inline int
  1624. decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
  1625. {
  1626. return decode_id (buf, endbuf, limit);
  1627. }
  1628. static inline void
  1629. buffer_add_objid (Buffer *buf, MonoObject *o)
  1630. {
  1631. buffer_add_id (buf, get_objid (o));
  1632. }
  1633. /*
  1634. * IDS
  1635. */
  1636. typedef enum {
  1637. ID_ASSEMBLY = 0,
  1638. ID_MODULE = 1,
  1639. ID_TYPE = 2,
  1640. ID_METHOD = 3,
  1641. ID_FIELD = 4,
  1642. ID_DOMAIN = 5,
  1643. ID_PROPERTY = 6,
  1644. ID_NUM
  1645. } IdType;
  1646. /*
  1647. * Represents a runtime structure accessible to the debugger client
  1648. */
  1649. typedef struct {
  1650. /* Unique id used in the wire protocol */
  1651. int id;
  1652. /* Domain of the runtime structure, NULL if the domain was unloaded */
  1653. MonoDomain *domain;
  1654. union {
  1655. gpointer val;
  1656. MonoClass *klass;
  1657. MonoMethod *method;
  1658. MonoImage *image;
  1659. MonoAssembly *assembly;
  1660. MonoClassField *field;
  1661. MonoDomain *domain;
  1662. MonoProperty *property;
  1663. } data;
  1664. } Id;
  1665. typedef struct {
  1666. /* Maps runtime structure -> Id */
  1667. GHashTable *val_to_id [ID_NUM];
  1668. /* Classes whose class load event has been sent */
  1669. GHashTable *loaded_classes;
  1670. /* Maps MonoClass->GPtrArray of file names */
  1671. GHashTable *source_files;
  1672. /* Maps source file basename -> GSList of classes */
  1673. GHashTable *source_file_to_class;
  1674. /* Same with ignore-case */
  1675. GHashTable *source_file_to_class_ignorecase;
  1676. } AgentDomainInfo;
  1677. /* Maps id -> Id */
  1678. static GPtrArray *ids [ID_NUM];
  1679. static void
  1680. ids_init (void)
  1681. {
  1682. int i;
  1683. for (i = 0; i < ID_NUM; ++i)
  1684. ids [i] = g_ptr_array_new ();
  1685. }
  1686. static void
  1687. ids_cleanup (void)
  1688. {
  1689. int i, j;
  1690. for (i = 0; i < ID_NUM; ++i) {
  1691. if (ids [i]) {
  1692. for (j = 0; j < ids [i]->len; ++j)
  1693. g_free (g_ptr_array_index (ids [i], j));
  1694. g_ptr_array_free (ids [i], TRUE);
  1695. }
  1696. ids [i] = NULL;
  1697. }
  1698. }
  1699. void
  1700. mono_debugger_agent_free_domain_info (MonoDomain *domain)
  1701. {
  1702. AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
  1703. int i, j;
  1704. GHashTableIter iter;
  1705. GPtrArray *file_names;
  1706. char *basename;
  1707. GSList *l;
  1708. if (info) {
  1709. for (i = 0; i < ID_NUM; ++i)
  1710. if (info->val_to_id [i])
  1711. g_hash_table_destroy (info->val_to_id [i]);
  1712. g_hash_table_destroy (info->loaded_classes);
  1713. g_hash_table_iter_init (&iter, info->source_files);
  1714. while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
  1715. for (i = 0; i < file_names->len; ++i)
  1716. g_free (g_ptr_array_index (file_names, i));
  1717. g_ptr_array_free (file_names, TRUE);
  1718. }
  1719. g_hash_table_iter_init (&iter, info->source_file_to_class);
  1720. while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
  1721. g_free (basename);
  1722. g_slist_free (l);
  1723. }
  1724. g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
  1725. while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
  1726. g_free (basename);
  1727. g_slist_free (l);
  1728. }
  1729. g_free (info);
  1730. }
  1731. domain_jit_info (domain)->agent_info = NULL;
  1732. /* Clear ids referencing structures in the domain */
  1733. for (i = 0; i < ID_NUM; ++i) {
  1734. if (ids [i]) {
  1735. for (j = 0; j < ids [i]->len; ++j) {
  1736. Id *id = g_ptr_array_index (ids [i], j);
  1737. if (id->domain == domain)
  1738. id->domain = NULL;
  1739. }
  1740. }
  1741. }
  1742. mono_loader_lock ();
  1743. g_hash_table_remove (domains, domain);
  1744. mono_loader_unlock ();
  1745. }
  1746. static AgentDomainInfo*
  1747. get_agent_domain_info (MonoDomain *domain)
  1748. {
  1749. AgentDomainInfo *info = NULL;
  1750. mono_domain_lock (domain);
  1751. info = domain_jit_info (domain)->agent_info;
  1752. if (!info) {
  1753. info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
  1754. info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
  1755. info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
  1756. info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
  1757. info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
  1758. }
  1759. mono_domain_unlock (domain);
  1760. return info;
  1761. }
  1762. static int
  1763. get_id (MonoDomain *domain, IdType type, gpointer val)
  1764. {
  1765. Id *id;
  1766. AgentDomainInfo *info;
  1767. if (val == NULL)
  1768. return 0;
  1769. mono_loader_lock ();
  1770. mono_domain_lock (domain);
  1771. info = get_agent_domain_info (domain);
  1772. if (info->val_to_id [type] == NULL)
  1773. info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
  1774. id = g_hash_table_lookup (info->val_to_id [type], val);
  1775. if (id) {
  1776. mono_domain_unlock (domain);
  1777. mono_loader_unlock ();
  1778. return id->id;
  1779. }
  1780. id = g_new0 (Id, 1);
  1781. /* Reserve id 0 */
  1782. id->id = ids [type]->len + 1;
  1783. id->domain = domain;
  1784. id->data.val = val;
  1785. g_hash_table_insert (info->val_to_id [type], val, id);
  1786. mono_domain_unlock (domain);
  1787. g_ptr_array_add (ids [type], id);
  1788. mono_loader_unlock ();
  1789. return id->id;
  1790. }
  1791. static inline gpointer
  1792. decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
  1793. {
  1794. Id *res;
  1795. int id = decode_id (buf, endbuf, limit);
  1796. *err = 0;
  1797. if (domain)
  1798. *domain = NULL;
  1799. if (id == 0)
  1800. return NULL;
  1801. // FIXME: error handling
  1802. mono_loader_lock ();
  1803. g_assert (id > 0 && id <= ids [type]->len);
  1804. res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
  1805. mono_loader_unlock ();
  1806. if (res->domain == NULL) {
  1807. *err = ERR_UNLOADED;
  1808. return NULL;
  1809. }
  1810. if (domain)
  1811. *domain = res->domain;
  1812. return res->data.val;
  1813. }
  1814. static inline void
  1815. buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
  1816. {
  1817. buffer_add_id (buf, get_id (domain, type, val));
  1818. }
  1819. static inline MonoClass*
  1820. decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1821. {
  1822. return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
  1823. }
  1824. static inline MonoAssembly*
  1825. decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1826. {
  1827. return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
  1828. }
  1829. static inline MonoImage*
  1830. decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1831. {
  1832. return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
  1833. }
  1834. static inline MonoMethod*
  1835. decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1836. {
  1837. return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
  1838. }
  1839. static inline MonoClassField*
  1840. decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1841. {
  1842. return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
  1843. }
  1844. static inline MonoDomain*
  1845. decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1846. {
  1847. return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
  1848. }
  1849. static inline MonoProperty*
  1850. decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
  1851. {
  1852. return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
  1853. }
  1854. static inline void
  1855. buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
  1856. {
  1857. buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
  1858. }
  1859. static inline void
  1860. buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
  1861. {
  1862. buffer_add_ptr_id (buf, domain, ID_METHOD, method);
  1863. }
  1864. static inline void
  1865. buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
  1866. {
  1867. buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
  1868. }
  1869. static inline void
  1870. buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
  1871. {
  1872. buffer_add_ptr_id (buf, domain, ID_MODULE, image);
  1873. }
  1874. static inline void
  1875. buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
  1876. {
  1877. buffer_add_ptr_id (buf, domain, ID_FIELD, field);
  1878. }
  1879. static inline void
  1880. buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
  1881. {
  1882. buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
  1883. }
  1884. static inline void
  1885. buffer_add_domainid (Buffer *buf, MonoDomain *domain)
  1886. {
  1887. buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
  1888. }
  1889. static void invoke_method (void);
  1890. /*
  1891. * SUSPEND/RESUME
  1892. */
  1893. /*
  1894. * save_thread_context:
  1895. *
  1896. * Set CTX as the current threads context which is used for computing stack traces.
  1897. * This function is signal-safe.
  1898. */
  1899. static void
  1900. save_thread_context (MonoContext *ctx)
  1901. {
  1902. DebuggerTlsData *tls;
  1903. tls = mono_native_tls_get_value (debugger_tls_id);
  1904. g_assert (tls);
  1905. if (ctx)
  1906. mono_thread_state_init_from_monoctx (&tls->context, ctx);
  1907. else
  1908. mono_thread_state_init_from_current (&tls->context);
  1909. }
  1910. /* Number of threads suspended */
  1911. /*
  1912. * If this is equal to the size of thread_to_tls, the runtime is considered
  1913. * suspended.
  1914. */
  1915. static gint32 threads_suspend_count;
  1916. static mono_mutex_t suspend_mutex;
  1917. /* Cond variable used to wait for suspend_count becoming 0 */
  1918. static mono_cond_t suspend_cond;
  1919. /* Semaphore used to wait for a thread becoming suspended */
  1920. static MonoSemType suspend_sem;
  1921. static void
  1922. suspend_init (void)
  1923. {
  1924. mono_mutex_init (&suspend_mutex, NULL);
  1925. mono_cond_init (&suspend_cond, NULL);
  1926. MONO_SEM_INIT (&suspend_sem, 0);
  1927. }
  1928. typedef struct
  1929. {
  1930. StackFrameInfo last_frame;
  1931. gboolean last_frame_set;
  1932. MonoContext ctx;
  1933. gpointer lmf;
  1934. } GetLastFrameUserData;
  1935. static gboolean
  1936. get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
  1937. {
  1938. GetLastFrameUserData *data = user_data;
  1939. if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
  1940. return FALSE;
  1941. if (!data->last_frame_set) {
  1942. /* Store the last frame */
  1943. memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
  1944. data->last_frame_set = TRUE;
  1945. return FALSE;
  1946. } else {
  1947. /* Store the context/lmf for the frame above the last frame */
  1948. memcpy (&data->ctx, ctx, sizeof (MonoContext));
  1949. data->lmf = info->lmf;
  1950. return TRUE;
  1951. }
  1952. }
  1953. /*
  1954. * thread_interrupt:
  1955. *
  1956. * Process interruption of a thread. If SIGCTX is set, process the current thread. If
  1957. * INFO is set, process the thread described by INFO.
  1958. * This should be signal safe.
  1959. */
  1960. static gboolean
  1961. thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
  1962. {
  1963. gboolean res;
  1964. gpointer ip;
  1965. MonoNativeThreadId tid;
  1966. /*
  1967. * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
  1968. * guarantee the signal handler will be called that many times. Instead of tracking
  1969. * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
  1970. * has been requested that hasn't been handled yet, otherwise we can have threads
  1971. * refuse to die when VM_EXIT is called
  1972. */
  1973. #if defined(__APPLE__)
  1974. if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
  1975. return FALSE;
  1976. #else
  1977. /*
  1978. * We use interrupt_count to determine whenever this interrupt should be processed
  1979. * by us or the normal interrupt processing code in the signal handler.
  1980. * There is no race here with notify_thread (), since the signal is sent after
  1981. * incrementing interrupt_count.
  1982. */
  1983. if (tls->interrupt_count == 0)
  1984. return FALSE;
  1985. InterlockedDecrement (&tls->interrupt_count);
  1986. #endif
  1987. if (sigctx)
  1988. ip = mono_arch_ip_from_context (sigctx);
  1989. else if (info)
  1990. ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
  1991. else
  1992. ip = NULL;
  1993. if (info)
  1994. tid = mono_thread_info_get_tid (info);
  1995. else
  1996. tid = (MonoNativeThreadId)GetCurrentThreadId ();
  1997. // FIXME: Races when the thread leaves managed code before hitting a single step
  1998. // event.
  1999. if (ji) {
  2000. /* Running managed code, will be suspended by the single step code */
  2001. DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
  2002. return TRUE;
  2003. } else {
  2004. /*
  2005. * Running native code, will be suspended when it returns to/enters
  2006. * managed code. Treat it as already suspended.
  2007. * This might interrupt the code in process_single_step_inner (), we use the
  2008. * tls->suspending flag to avoid races when that happens.
  2009. */
  2010. if (!tls->suspended && !tls->suspending) {
  2011. MonoContext ctx;
  2012. GetLastFrameUserData data;
  2013. // FIXME: printf is not signal safe, but this is only used during
  2014. // debugger debugging
  2015. if (ip)
  2016. DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
  2017. //save_thread_context (&ctx);
  2018. if (!tls->thread)
  2019. /* Already terminated */
  2020. return TRUE;
  2021. tls->context.valid = FALSE;
  2022. /*
  2023. * We are in a difficult position: we want to be able to provide stack
  2024. * traces for this thread, but we can't use the current ctx+lmf, since
  2025. * the thread is still running, so it might return to managed code,
  2026. * making these invalid.
  2027. * So we start a stack walk and save the first frame, along with the
  2028. * parent frame's ctx+lmf. This (hopefully) works because the thread will be
  2029. * suspended when it returns to managed code, so the parent's ctx should
  2030. * remain valid.
  2031. */
  2032. data.last_frame_set = FALSE;
  2033. if (sigctx) {
  2034. mono_arch_sigctx_to_monoctx (sigctx, &ctx);
  2035. /*
  2036. * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
  2037. * get_last_frame () doesn't need it, the last frame cannot be a ginst
  2038. * since we are not in a JITted method.
  2039. */
  2040. mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
  2041. } else if (info) {
  2042. mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
  2043. }
  2044. if (data.last_frame_set) {
  2045. memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
  2046. res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
  2047. g_assert (res);
  2048. mono_thread_state_init_from_monoctx (&tls->context, &ctx);
  2049. g_assert (res);
  2050. memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
  2051. tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
  2052. tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
  2053. } else {
  2054. /* No managed frames */
  2055. tls->async_state.valid = FALSE;
  2056. }
  2057. mono_memory_barrier ();
  2058. tls->suspended = TRUE;
  2059. MONO_SEM_POST (&suspend_sem);
  2060. }
  2061. return TRUE;
  2062. }
  2063. }
  2064. /*
  2065. * mono_debugger_agent_thread_interrupt:
  2066. *
  2067. * Called by the abort signal handler.
  2068. * Should be signal safe.
  2069. */
  2070. gboolean
  2071. mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
  2072. {
  2073. DebuggerTlsData *tls;
  2074. if (!inited)
  2075. return FALSE;
  2076. tls = mono_native_tls_get_value (debugger_tls_id);
  2077. if (!tls) {
  2078. DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
  2079. return FALSE;
  2080. }
  2081. return thread_interrupt (tls, NULL, sigctx, ji);
  2082. }
  2083. #ifdef HOST_WIN32
  2084. static void CALLBACK notify_thread_apc (ULONG_PTR param)
  2085. {
  2086. //DebugBreak ();
  2087. mono_debugger_agent_thread_interrupt (NULL, NULL);
  2088. }
  2089. #endif /* HOST_WIN32 */
  2090. /*
  2091. * reset_native_thread_suspend_state:
  2092. *
  2093. * Reset the suspended flag and state on native threads
  2094. */
  2095. static void
  2096. reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
  2097. {
  2098. DebuggerTlsData *tls = value;
  2099. if (!tls->really_suspended && tls->suspended) {
  2100. tls->suspended = FALSE;
  2101. /*
  2102. * The thread might still be running if it was executing native code, so the state won't be invalided by
  2103. * suspend_current ().
  2104. */
  2105. tls->context.valid = FALSE;
  2106. tls->async_state.valid = FALSE;
  2107. invalidate_frames (tls);
  2108. }
  2109. }
  2110. /*
  2111. * notify_thread:
  2112. *
  2113. * Notify a thread that it needs to suspend.
  2114. */
  2115. static void
  2116. notify_thread (gpointer key, gpointer value, gpointer user_data)
  2117. {
  2118. MonoInternalThread *thread = key;
  2119. DebuggerTlsData *tls = value;
  2120. gsize tid = thread->tid;
  2121. int res;
  2122. if (GetCurrentThreadId () == tid || tls->terminated)
  2123. return;
  2124. DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
  2125. /*
  2126. * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
  2127. * guarantee the signal handler will be called that many times. Instead of tracking
  2128. * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
  2129. * has been requested that hasn't been handled yet, otherwise we can have threads
  2130. * refuse to die when VM_EXIT is called
  2131. */
  2132. #if defined(__APPLE__)
  2133. if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
  2134. return;
  2135. #else
  2136. /*
  2137. * Maybe we could use the normal interrupt infrastructure, but that does a lot
  2138. * of things like breaking waits etc. which we don't want.
  2139. */
  2140. InterlockedIncrement (&tls->interrupt_count);
  2141. #endif
  2142. /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
  2143. #ifdef HOST_WIN32
  2144. QueueUserAPC (notify_thread_apc, thread->handle, NULL);
  2145. #else
  2146. if (mono_thread_info_new_interrupt_enabled ()) {
  2147. MonoThreadInfo *info;
  2148. MonoJitInfo *ji;
  2149. info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
  2150. if (!info) {
  2151. DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
  2152. /*
  2153. * Attached thread which died without detaching.
  2154. */
  2155. tls->terminated = TRUE;
  2156. } else {
  2157. ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
  2158. thread_interrupt (tls, info, NULL, ji);
  2159. mono_thread_info_resume (mono_thread_info_get_tid (info));
  2160. }
  2161. } else {
  2162. res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
  2163. if (res) {
  2164. DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
  2165. /*
  2166. * Attached thread which died without detaching.
  2167. */
  2168. tls->terminated = TRUE;
  2169. }
  2170. }
  2171. #endif
  2172. }
  2173. static void
  2174. process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
  2175. {
  2176. guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
  2177. MonoJitInfo *ji;
  2178. if (mono_loader_lock_is_owned_by_self ()) {
  2179. /*
  2180. * Shortcut for the check in suspend_current (). This speeds up processing
  2181. * when executing long running code inside the loader lock, i.e. assembly load
  2182. * hooks.
  2183. */
  2184. return;
  2185. }
  2186. if (debugger_thread_id == GetCurrentThreadId ())
  2187. return;
  2188. /* Prevent races with mono_debugger_agent_thread_interrupt () */
  2189. if (suspend_count - tls->resume_count > 0)
  2190. tls->suspending = TRUE;
  2191. DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
  2192. if (suspend_count - tls->resume_count == 0) {
  2193. /*
  2194. * We are executing a single threaded invoke but the single step for
  2195. * suspending is still active.
  2196. * FIXME: This slows down single threaded invokes.
  2197. */
  2198. DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
  2199. return;
  2200. }
  2201. ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
  2202. /* Can't suspend in these methods */
  2203. if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
  2204. return;
  2205. save_thread_context (ctx);
  2206. suspend_current ();
  2207. }
  2208. /*
  2209. * suspend_vm:
  2210. *
  2211. * Increase the suspend count of the VM. While the suspend count is greater
  2212. * than 0, runtime threads are suspended at certain points during execution.
  2213. */
  2214. static void
  2215. suspend_vm (void)
  2216. {
  2217. mono_loader_lock ();
  2218. mono_mutex_lock (&suspend_mutex);
  2219. suspend_count ++;
  2220. DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
  2221. if (suspend_count == 1) {
  2222. // FIXME: Is it safe to call this inside the lock ?
  2223. start_single_stepping ();
  2224. mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
  2225. }
  2226. mono_mutex_unlock (&suspend_mutex);
  2227. mono_loader_unlock ();
  2228. }
  2229. /*
  2230. * resume_vm:
  2231. *
  2232. * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
  2233. * are resumed.
  2234. */
  2235. static void
  2236. resume_vm (void)
  2237. {
  2238. int err;
  2239. g_assert (debugger_thread_id == GetCurrentThreadId ());
  2240. mono_loader_lock ();
  2241. mono_mutex_lock (&suspend_mutex);
  2242. g_assert (suspend_count > 0);
  2243. suspend_count --;
  2244. DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
  2245. if (suspend_count == 0) {
  2246. // FIXME: Is it safe to call this inside the lock ?
  2247. stop_single_stepping ();
  2248. mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
  2249. }
  2250. /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
  2251. err = mono_cond_broadcast (&suspend_cond);
  2252. g_assert (err == 0);
  2253. mono_mutex_unlock (&suspend_mutex);
  2254. //g_assert (err == 0);
  2255. mono_loader_unlock ();
  2256. }
  2257. /*
  2258. * resume_thread:
  2259. *
  2260. * Resume just one thread.
  2261. */
  2262. static void
  2263. resume_thread (MonoInternalThread *thread)
  2264. {
  2265. int err;
  2266. DebuggerTlsData *tls;
  2267. g_assert (debugger_thread_id == GetCurrentThreadId ());
  2268. mono_loader_lock ();
  2269. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  2270. g_assert (tls);
  2271. mono_mutex_lock (&suspend_mutex);
  2272. g_assert (suspend_count > 0);
  2273. DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
  2274. tls->resume_count += suspend_count;
  2275. /*
  2276. * Signal suspend_count without decreasing suspend_count, the threads will wake up
  2277. * but only the one whose resume_count field is > 0 will be resumed.
  2278. */
  2279. err = mono_cond_broadcast (&suspend_cond);
  2280. g_assert (err == 0);
  2281. mono_mutex_unlock (&suspend_mutex);
  2282. //g_assert (err == 0);
  2283. mono_loader_unlock ();
  2284. }
  2285. static void
  2286. invalidate_frames (DebuggerTlsData *tls)
  2287. {
  2288. int i;
  2289. if (!tls)
  2290. tls = mono_native_tls_get_value (debugger_tls_id);
  2291. g_assert (tls);
  2292. for (i = 0; i < tls->frame_count; ++i) {
  2293. if (tls->frames [i]->jit)
  2294. mono_debug_free_method_jit_info (tls->frames [i]->jit);
  2295. g_free (tls->frames [i]);
  2296. }
  2297. g_free (tls->frames);
  2298. tls->frame_count = 0;
  2299. tls->frames = NULL;
  2300. }
  2301. /*
  2302. * suspend_current:
  2303. *
  2304. * Suspend the current thread until the runtime is resumed. If the thread has a
  2305. * pending invoke, then the invoke is executed before this function returns.
  2306. */
  2307. static void
  2308. suspend_current (void)
  2309. {
  2310. int err;
  2311. DebuggerTlsData *tls;
  2312. g_assert (debugger_thread_id != GetCurrentThreadId ());
  2313. if (mono_loader_lock_is_owned_by_self ()) {
  2314. /*
  2315. * If we own the loader mutex, can't suspend until we release it, since the
  2316. * whole runtime can deadlock otherwise.
  2317. */
  2318. return;
  2319. }
  2320. tls = mono_native_tls_get_value (debugger_tls_id);
  2321. g_assert (tls);
  2322. mono_mutex_lock (&suspend_mutex);
  2323. tls->suspending = FALSE;
  2324. tls->really_suspended = TRUE;
  2325. if (!tls->suspended) {
  2326. tls->suspended = TRUE;
  2327. MONO_SEM_POST (&suspend_sem);
  2328. }
  2329. DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
  2330. while (suspend_count - tls->resume_count > 0) {
  2331. #ifdef HOST_WIN32
  2332. if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
  2333. {
  2334. mono_mutex_unlock (&suspend_mutex);
  2335. Sleep(1);
  2336. mono_mutex_lock (&suspend_mutex);
  2337. }
  2338. else
  2339. {
  2340. }
  2341. #else
  2342. err = mono_cond_wait (&suspend_cond, &suspend_mutex);
  2343. g_assert (err == 0);
  2344. #endif
  2345. }
  2346. tls->suspended = FALSE;
  2347. tls->really_suspended = FALSE;
  2348. threads_suspend_count --;
  2349. mono_mutex_unlock (&suspend_mutex);
  2350. DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
  2351. if (tls->pending_invoke) {
  2352. /* Save the original context */
  2353. tls->pending_invoke->has_ctx = TRUE;
  2354. tls->pending_invoke->ctx = tls->context.ctx;
  2355. invoke_method ();
  2356. }
  2357. /* The frame info becomes invalid after a resume */
  2358. tls->context.valid = FALSE;
  2359. tls->async_state.valid = FALSE;
  2360. invalidate_frames (tls);
  2361. }
  2362. static void
  2363. count_thread (gpointer key, gpointer value, gpointer user_data)
  2364. {
  2365. DebuggerTlsData *tls = value;
  2366. if (!tls->suspended && !tls->terminated)
  2367. *(int*)user_data = *(int*)user_data + 1;
  2368. }
  2369. static int
  2370. count_threads_to_wait_for (void)
  2371. {
  2372. int count = 0;
  2373. mono_loader_lock ();
  2374. mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
  2375. mono_loader_unlock ();
  2376. return count;
  2377. }
  2378. /*
  2379. * wait_for_suspend:
  2380. *
  2381. * Wait until the runtime is completely suspended.
  2382. */
  2383. static void
  2384. wait_for_suspend (void)
  2385. {
  2386. int nthreads, nwait, err;
  2387. gboolean waited = FALSE;
  2388. // FIXME: Threads starting/stopping ?
  2389. mono_loader_lock ();
  2390. nthreads = mono_g_hash_table_size (thread_to_tls);
  2391. mono_loader_unlock ();
  2392. while (TRUE) {
  2393. nwait = count_threads_to_wait_for ();
  2394. if (nwait) {
  2395. DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
  2396. err = MONO_SEM_WAIT (&suspend_sem);
  2397. g_assert (err == 0);
  2398. waited = TRUE;
  2399. } else {
  2400. break;
  2401. }
  2402. }
  2403. if (waited)
  2404. DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
  2405. }
  2406. /*
  2407. * is_suspended:
  2408. *
  2409. * Return whenever the runtime is suspended.
  2410. */
  2411. static gboolean
  2412. is_suspended (void)
  2413. {
  2414. return count_threads_to_wait_for () == 0;
  2415. }
  2416. static MonoSeqPointInfo*
  2417. get_seq_points (MonoDomain *domain, MonoMethod *method)
  2418. {
  2419. MonoSeqPointInfo *seq_points;
  2420. mono_domain_lock (domain);
  2421. seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
  2422. if (!seq_points && method->is_inflated) {
  2423. /* generic sharing + aot */
  2424. seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
  2425. if (!seq_points)
  2426. seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
  2427. }
  2428. mono_domain_unlock (domain);
  2429. return seq_points;
  2430. }
  2431. static MonoSeqPointInfo*
  2432. find_seq_points (MonoDomain *domain, MonoMethod *method)
  2433. {
  2434. MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
  2435. if (!seq_points)
  2436. printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
  2437. g_assert (seq_points);
  2438. return seq_points;
  2439. }
  2440. /*
  2441. * find_next_seq_point_for_native_offset:
  2442. *
  2443. * Find the first sequence point after NATIVE_OFFSET.
  2444. */
  2445. static SeqPoint*
  2446. find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
  2447. {
  2448. MonoSeqPointInfo *seq_points;
  2449. int i;
  2450. seq_points = find_seq_points (domain, method);
  2451. g_assert (seq_points);
  2452. if (info)
  2453. *info = seq_points;
  2454. for (i = 0; i < seq_points->len; ++i) {
  2455. if (seq_points->seq_points [i].native_offset >= native_offset)
  2456. return &seq_points->seq_points [i];
  2457. }
  2458. return NULL;
  2459. }
  2460. /*
  2461. * find_prev_seq_point_for_native_offset:
  2462. *
  2463. * Find the first sequence point before NATIVE_OFFSET.
  2464. */
  2465. static SeqPoint*
  2466. find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
  2467. {
  2468. MonoSeqPointInfo *seq_points;
  2469. int i;
  2470. seq_points = get_seq_points (domain, method);
  2471. if (info)
  2472. *info = seq_points;
  2473. if (!seq_points)
  2474. return NULL;
  2475. for (i = seq_points->len - 1; i >= 0; --i) {
  2476. if (seq_points->seq_points [i].native_offset <= native_offset)
  2477. return &seq_points->seq_points [i];
  2478. }
  2479. return NULL;
  2480. }
  2481. /*
  2482. * find_seq_point:
  2483. *
  2484. * Find the sequence point corresponding to the IL offset IL_OFFSET, which
  2485. * should be the location of a sequence point.
  2486. */
  2487. static G_GNUC_UNUSED SeqPoint*
  2488. find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
  2489. {
  2490. MonoSeqPointInfo *seq_points;
  2491. int i;
  2492. *info = NULL;
  2493. seq_points = get_seq_points (domain, method);
  2494. if (!seq_points)
  2495. return NULL;
  2496. *info = seq_points;
  2497. for (i = 0; i < seq_points->len; ++i) {
  2498. if (seq_points->seq_points [i].il_offset == il_offset)
  2499. return &seq_points->seq_points [i];
  2500. }
  2501. return NULL;
  2502. }
  2503. typedef struct {
  2504. DebuggerTlsData *tls;
  2505. GSList *frames;
  2506. } ComputeFramesUserData;
  2507. static gboolean
  2508. process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
  2509. {
  2510. ComputeFramesUserData *ud = user_data;
  2511. StackFrame *frame;
  2512. MonoMethod *method, *actual_method, *api_method;
  2513. SeqPoint *sp;
  2514. int flags = 0;
  2515. if (info->type != FRAME_TYPE_MANAGED) {
  2516. if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
  2517. /* Mark the last frame as an invoke frame */
  2518. if (ud->frames)
  2519. ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
  2520. }
  2521. return FALSE;
  2522. }
  2523. if (info->ji)
  2524. method = info->ji->method;
  2525. else
  2526. method = info->method;
  2527. actual_method = info->actual_method;
  2528. api_method = method;
  2529. if (!method)
  2530. return FALSE;
  2531. if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
  2532. return FALSE;
  2533. if (info->il_offset == -1) {
  2534. /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
  2535. if (ud->frames == NULL) {
  2536. sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
  2537. if (sp)
  2538. info->il_offset = sp->il_offset;
  2539. }
  2540. if (info->il_offset == -1)
  2541. info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
  2542. }
  2543. DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
  2544. if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
  2545. if (!CHECK_PROTOCOL_VERSION (2, 17))
  2546. /* Older clients can't handle this flag */
  2547. return FALSE;
  2548. api_method = mono_marshal_method_from_wrapper (method);
  2549. if (!api_method)
  2550. return FALSE;
  2551. actual_method = api_method;
  2552. flags |= FRAME_FLAG_NATIVE_TRANSITION;
  2553. }
  2554. frame = g_new0 (StackFrame, 1);
  2555. frame->method = method;
  2556. frame->actual_method = actual_method;
  2557. frame->api_method = api_method;
  2558. frame->il_offset = info->il_offset;
  2559. frame->native_offset = info->native_offset;
  2560. frame->flags = flags;
  2561. frame->ji = info->ji;
  2562. if (info->reg_locations)
  2563. memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
  2564. if (ctx) {
  2565. frame->ctx = *ctx;
  2566. frame->has_ctx = TRUE;
  2567. }
  2568. frame->domain = info->domain;
  2569. ud->frames = g_slist_append (ud->frames, frame);
  2570. return FALSE;
  2571. }
  2572. static gboolean
  2573. process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
  2574. {
  2575. ComputeFramesUserData *ud = user_data;
  2576. /*
  2577. * 'tls->filter_ctx' is the location of the throw site.
  2578. *
  2579. * mono_walk_stack() will never actually hit the throw site, but unwind
  2580. * directly from the filter to the call site; we abort stack unwinding here
  2581. * once this happens and resume from the throw site.
  2582. */
  2583. if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
  2584. return TRUE;
  2585. return process_frame (info, ctx, user_data);
  2586. }
  2587. static void
  2588. compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
  2589. {
  2590. ComputeFramesUserData user_data;
  2591. GSList *tmp;
  2592. int i, findex, new_frame_count;
  2593. StackFrame **new_frames, *f;
  2594. MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
  2595. // FIXME: Locking on tls
  2596. if (tls->frames && tls->frames_up_to_date)
  2597. return;
  2598. DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
  2599. user_data.tls = tls;
  2600. user_data.frames = NULL;
  2601. if (tls->terminated) {
  2602. tls->frame_count = 0;
  2603. return;
  2604. } if (!tls->really_suspended && tls->async_state.valid) {
  2605. /* Have to use the state saved by the signal handler */
  2606. process_frame (&tls->async_last_frame, NULL, &user_data);
  2607. mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
  2608. } else if (tls->filter_state.valid) {
  2609. /*
  2610. * We are inside an exception filter.
  2611. *
  2612. * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
  2613. */
  2614. if (tls->context.valid)
  2615. mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
  2616. /*
  2617. * After that, we resume unwinding from the location where the exception has been thrown.
  2618. */
  2619. mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
  2620. } else if (tls->context.valid) {
  2621. mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
  2622. } else {
  2623. // FIXME:
  2624. tls->frame_count = 0;
  2625. return;
  2626. }
  2627. new_frame_count = g_slist_length (user_data.frames);
  2628. new_frames = g_new0 (StackFrame*, new_frame_count);
  2629. findex = 0;
  2630. for (tmp = user_data.frames; tmp; tmp = tmp->next) {
  2631. f = tmp->data;
  2632. /*
  2633. * Reuse the id for already existing stack frames, so invokes don't invalidate
  2634. * the still valid stack frames.
  2635. */
  2636. for (i = 0; i < tls->frame_count; ++i) {
  2637. if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
  2638. f->id = tls->frames [i]->id;
  2639. break;
  2640. }
  2641. }
  2642. if (i >= tls->frame_count)
  2643. f->id = InterlockedIncrement (&frame_id);
  2644. new_frames [findex ++] = f;
  2645. }
  2646. g_slist_free (user_data.frames);
  2647. invalidate_frames (tls);
  2648. tls->frames = new_frames;
  2649. tls->frame_count = new_frame_count;
  2650. tls->frames_up_to_date = TRUE;
  2651. }
  2652. /*
  2653. * GHFunc to emit an appdomain creation event
  2654. * @param key Don't care
  2655. * @param value A loaded appdomain
  2656. * @param user_data Don't care
  2657. */
  2658. static void
  2659. emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
  2660. {
  2661. process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
  2662. g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
  2663. }
  2664. /*
  2665. * GHFunc to emit a thread start event
  2666. * @param key A thread id
  2667. * @param value A thread object
  2668. * @param user_data Don't care
  2669. */
  2670. static void
  2671. emit_thread_start (gpointer key, gpointer value, gpointer user_data)
  2672. {
  2673. if (GPOINTER_TO_INT (key) != debugger_thread_id)
  2674. process_profiler_event (EVENT_KIND_THREAD_START, value);
  2675. }
  2676. /*
  2677. * GFunc to emit an assembly load event
  2678. * @param value A loaded assembly
  2679. * @param user_data Don't care
  2680. */
  2681. static void
  2682. emit_assembly_load (gpointer value, gpointer user_data)
  2683. {
  2684. process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
  2685. }
  2686. /*
  2687. * GFunc to emit a type load event
  2688. * @param value A loaded type
  2689. * @param user_data Don't care
  2690. */
  2691. static void
  2692. emit_type_load (gpointer key, gpointer value, gpointer user_data)
  2693. {
  2694. process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
  2695. }
  2696. static char*
  2697. strdup_tolower (char *s)
  2698. {
  2699. char *s2, *p;
  2700. s2 = g_strdup (s);
  2701. for (p = s2; *p; ++p)
  2702. *p = tolower (*p);
  2703. return s2;
  2704. }
  2705. /*
  2706. * EVENT HANDLING
  2707. */
  2708. /*
  2709. * create_event_list:
  2710. *
  2711. * Return a list of event request ids matching EVENT, starting from REQS, which
  2712. * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
  2713. * policy.
  2714. * We return request ids, instead of requests, to simplify threading, since
  2715. * requests could be deleted anytime when the loader lock is not held.
  2716. * LOCKING: Assumes the loader lock is held.
  2717. */
  2718. static GSList*
  2719. create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
  2720. {
  2721. int i, j;
  2722. GSList *events = NULL;
  2723. *suspend_policy = SUSPEND_POLICY_NONE;
  2724. if (!reqs)
  2725. reqs = event_requests;
  2726. if (!reqs)
  2727. return NULL;
  2728. for (i = 0; i < reqs->len; ++i) {
  2729. EventRequest *req = g_ptr_array_index (reqs, i);
  2730. if (req->event_kind == event) {
  2731. gboolean filtered = FALSE;
  2732. /* Apply filters */
  2733. for (j = 0; j < req->nmodifiers; ++j) {
  2734. Modifier *mod = &req->modifiers [j];
  2735. if (mod->kind == MOD_KIND_COUNT) {
  2736. filtered = TRUE;
  2737. if (mod->data.count > 0) {
  2738. if (mod->data.count > 0) {
  2739. mod->data.count --;
  2740. if (mod->data.count == 0)
  2741. filtered = FALSE;
  2742. }
  2743. }
  2744. } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
  2745. if (mod->data.thread != mono_thread_internal_current ())
  2746. filtered = TRUE;
  2747. } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
  2748. if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
  2749. filtered = TRUE;
  2750. if (ei->caught && !mod->caught)
  2751. filtered = TRUE;
  2752. if (!ei->caught && !mod->uncaught)
  2753. filtered = TRUE;
  2754. } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
  2755. int k;
  2756. gboolean found = FALSE;
  2757. MonoAssembly **assemblies = mod->data.assemblies;
  2758. if (assemblies) {
  2759. for (k = 0; assemblies [k]; ++k)
  2760. if (assemblies [k] == ji->method->klass->image->assembly)
  2761. found = TRUE;
  2762. }
  2763. if (!found)
  2764. filtered = TRUE;
  2765. } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
  2766. gpointer iter = NULL;
  2767. MonoMethod *method;
  2768. MonoDebugSourceInfo *sinfo;
  2769. char *source_file, *s;
  2770. gboolean found = FALSE;
  2771. int i;
  2772. GPtrArray *source_file_list;
  2773. while ((method = mono_class_get_methods (ei->klass, &iter))) {
  2774. MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
  2775. if (minfo) {
  2776. mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
  2777. for (i = 0; i < source_file_list->len; ++i) {
  2778. sinfo = g_ptr_array_index (source_file_list, i);
  2779. /*
  2780. * Do a case-insesitive match by converting the file name to
  2781. * lowercase.
  2782. */
  2783. s = strdup_tolower (sinfo->source_file);
  2784. if (g_hash_table_lookup (mod->data.source_files, s))
  2785. found = TRUE;
  2786. else {
  2787. char *s2 = g_path_get_basename (sinfo->source_file);
  2788. char *s3 = strdup_tolower (s2);
  2789. if (g_hash_table_lookup (mod->data.source_files, s3))
  2790. found = TRUE;
  2791. g_free (s2);
  2792. g_free (s3);
  2793. }
  2794. g_free (s);
  2795. }
  2796. g_ptr_array_free (source_file_list, TRUE);
  2797. }
  2798. }
  2799. if (!found)
  2800. filtered = TRUE;
  2801. } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
  2802. char *s;
  2803. s = mono_type_full_name (&ei->klass->byval_arg);
  2804. if (!g_hash_table_lookup (mod->data.type_names, s))
  2805. filtered = TRUE;
  2806. g_free (s);
  2807. } else if (mod->kind == MOD_KIND_STEP) {
  2808. if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
  2809. (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
  2810. !strcmp (ji->method->name, ".cctor"))
  2811. filtered = TRUE;
  2812. if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
  2813. MonoCustomAttrInfo *ainfo;
  2814. static MonoClass *klass;
  2815. if (!klass) {
  2816. klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
  2817. g_assert (klass);
  2818. }
  2819. if (!ji->dbg_hidden_inited) {
  2820. ainfo = mono_custom_attrs_from_method (ji->method);
  2821. if (ainfo) {
  2822. if (mono_custom_attrs_has_attr (ainfo, klass))
  2823. ji->dbg_hidden = TRUE;
  2824. mono_custom_attrs_free (ainfo);
  2825. }
  2826. ji->dbg_hidden_inited = TRUE;
  2827. }
  2828. if (ji->dbg_hidden)
  2829. filtered = TRUE;
  2830. }
  2831. }
  2832. }
  2833. if (!filtered) {
  2834. *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
  2835. events = g_slist_append (events, GINT_TO_POINTER (req->id));
  2836. }
  2837. }
  2838. }
  2839. /* Send a VM START/DEATH event by default */
  2840. if (event == EVENT_KIND_VM_START)
  2841. events = g_slist_append (events, GINT_TO_POINTER (0));
  2842. if (event == EVENT_KIND_VM_DEATH)
  2843. events = g_slist_append (events, GINT_TO_POINTER (0));
  2844. return events;
  2845. }
  2846. static G_GNUC_UNUSED const char*
  2847. event_to_string (EventKind event)
  2848. {
  2849. switch (event) {
  2850. case EVENT_KIND_VM_START: return "VM_START";
  2851. case EVENT_KIND_VM_DEATH: return "VM_DEATH";
  2852. case EVENT_KIND_THREAD_START: return "THREAD_START";
  2853. case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
  2854. case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
  2855. case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
  2856. case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
  2857. case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
  2858. case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
  2859. case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
  2860. case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
  2861. case EVENT_KIND_STEP: return "STEP";
  2862. case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
  2863. case EVENT_KIND_EXCEPTION: return "EXCEPTION";
  2864. case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
  2865. case EVENT_KIND_USER_BREAK: return "USER_BREAK";
  2866. case EVENT_KIND_USER_LOG: return "USER_LOG";
  2867. default:
  2868. g_assert_not_reached ();
  2869. }
  2870. }
  2871. /*
  2872. * process_event:
  2873. *
  2874. * Send an event to the client, suspending the vm if needed.
  2875. * LOCKING: Since this can suspend the calling thread, no locks should be held
  2876. * by the caller.
  2877. * The EVENTS list is freed by this function.
  2878. */
  2879. static void
  2880. process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
  2881. {
  2882. Buffer buf;
  2883. GSList *l;
  2884. MonoDomain *domain = mono_domain_get ();
  2885. MonoThread *thread = NULL;
  2886. gboolean send_success = FALSE;
  2887. static int ecount;
  2888. int nevents;
  2889. if (!inited) {
  2890. DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
  2891. return;
  2892. }
  2893. if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
  2894. // FIXME: We miss those events
  2895. DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
  2896. return;
  2897. }
  2898. if (vm_death_event_sent) {
  2899. DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
  2900. return;
  2901. }
  2902. if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
  2903. DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
  2904. return;
  2905. }
  2906. if (disconnected) {
  2907. DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
  2908. return;
  2909. }
  2910. if (event == EVENT_KIND_KEEPALIVE)
  2911. suspend_policy = SUSPEND_POLICY_NONE;
  2912. else {
  2913. if (events == NULL)
  2914. return;
  2915. if (agent_config.defer) {
  2916. /* Make sure the thread id is always set when doing deferred debugging */
  2917. if (debugger_thread_id == GetCurrentThreadId ()) {
  2918. /* Don't suspend on events from the debugger thread */
  2919. suspend_policy = SUSPEND_POLICY_NONE;
  2920. thread = mono_thread_get_main ();
  2921. }
  2922. else thread = mono_thread_current ();
  2923. } else {
  2924. if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
  2925. // FIXME: Send these with a NULL thread, don't suspend the current thread
  2926. return;
  2927. }
  2928. }
  2929. nevents = g_slist_length (events);
  2930. buffer_init (&buf, 128);
  2931. buffer_add_byte (&buf, suspend_policy);
  2932. buffer_add_int (&buf, nevents);
  2933. for (l = events; l; l = l->next) {
  2934. buffer_add_byte (&buf, event); // event kind
  2935. buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
  2936. ecount ++;
  2937. if (!thread)
  2938. thread = mono_thread_current ();
  2939. if (event == EVENT_KIND_VM_START && arg != NULL)
  2940. thread = arg;
  2941. buffer_add_objid (&buf, (MonoObject*)thread); // thread
  2942. switch (event) {
  2943. case EVENT_KIND_THREAD_START:
  2944. case EVENT_KIND_THREAD_DEATH:
  2945. break;
  2946. case EVENT_KIND_APPDOMAIN_CREATE:
  2947. case EVENT_KIND_APPDOMAIN_UNLOAD:
  2948. buffer_add_domainid (&buf, arg);
  2949. break;
  2950. case EVENT_KIND_METHOD_ENTRY:
  2951. case EVENT_KIND_METHOD_EXIT:
  2952. buffer_add_methodid (&buf, domain, arg);
  2953. break;
  2954. case EVENT_KIND_ASSEMBLY_LOAD:
  2955. case EVENT_KIND_ASSEMBLY_UNLOAD:
  2956. buffer_add_assemblyid (&buf, domain, arg);
  2957. break;
  2958. case EVENT_KIND_TYPE_LOAD:
  2959. buffer_add_typeid (&buf, domain, arg);
  2960. break;
  2961. case EVENT_KIND_BREAKPOINT:
  2962. case EVENT_KIND_STEP:
  2963. buffer_add_methodid (&buf, domain, arg);
  2964. buffer_add_long (&buf, il_offset);
  2965. break;
  2966. case EVENT_KIND_VM_START:
  2967. buffer_add_domainid (&buf, mono_get_root_domain ());
  2968. break;
  2969. case EVENT_KIND_VM_DEATH:
  2970. break;
  2971. case EVENT_KIND_EXCEPTION: {
  2972. EventInfo *ei = arg;
  2973. buffer_add_objid (&buf, ei->exc);
  2974. break;
  2975. }
  2976. case EVENT_KIND_USER_BREAK:
  2977. break;
  2978. case EVENT_KIND_USER_LOG: {
  2979. EventInfo *ei = arg;
  2980. buffer_add_int (&buf, ei->level);
  2981. buffer_add_string (&buf, ei->category ? ei->category : "");
  2982. buffer_add_string (&buf, ei->message ? ei->message : "");
  2983. break;
  2984. }
  2985. case EVENT_KIND_KEEPALIVE:
  2986. suspend_policy = SUSPEND_POLICY_NONE;
  2987. break;
  2988. default:
  2989. g_assert_not_reached ();
  2990. }
  2991. }
  2992. if (event == EVENT_KIND_VM_START) {
  2993. suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
  2994. if (!agent_config.defer)
  2995. start_debugger_thread ();
  2996. }
  2997. if (event == EVENT_KIND_VM_DEATH) {
  2998. vm_death_event_sent = TRUE;
  2999. suspend_policy = SUSPEND_POLICY_NONE;
  3000. }
  3001. if (mono_runtime_is_shutting_down ())
  3002. suspend_policy = SUSPEND_POLICY_NONE;
  3003. if (suspend_policy != SUSPEND_POLICY_NONE) {
  3004. /*
  3005. * Save the thread context and start suspending before sending the packet,
  3006. * since we could be receiving the resume request before send_packet ()
  3007. * returns.
  3008. */
  3009. save_thread_context (ctx);
  3010. suspend_vm ();
  3011. }
  3012. send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
  3013. buffer_free (&buf);
  3014. g_slist_free (events);
  3015. events = NULL;
  3016. if (!send_success) {
  3017. DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
  3018. return;
  3019. }
  3020. if (event == EVENT_KIND_VM_START) {
  3021. vm_start_event_sent = TRUE;
  3022. }
  3023. DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
  3024. switch (suspend_policy) {
  3025. case SUSPEND_POLICY_NONE:
  3026. break;
  3027. case SUSPEND_POLICY_ALL:
  3028. suspend_current ();
  3029. break;
  3030. case SUSPEND_POLICY_EVENT_THREAD:
  3031. NOT_IMPLEMENTED;
  3032. break;
  3033. default:
  3034. g_assert_not_reached ();
  3035. }
  3036. }
  3037. static void
  3038. process_profiler_event (EventKind event, gpointer arg)
  3039. {
  3040. int suspend_policy;
  3041. GSList *events;
  3042. EventInfo ei, *ei_arg = NULL;
  3043. if (event == EVENT_KIND_TYPE_LOAD) {
  3044. ei.klass = arg;
  3045. ei_arg = &ei;
  3046. }
  3047. mono_loader_lock ();
  3048. events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
  3049. mono_loader_unlock ();
  3050. process_event (event, arg, 0, NULL, events, suspend_policy);
  3051. }
  3052. static void
  3053. runtime_initialized (MonoProfiler *prof)
  3054. {
  3055. process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
  3056. if (agent_config.defer)
  3057. start_debugger_thread ();
  3058. }
  3059. static void
  3060. runtime_shutdown (MonoProfiler *prof)
  3061. {
  3062. process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
  3063. mono_debugger_agent_cleanup ();
  3064. }
  3065. static void
  3066. thread_startup (MonoProfiler *prof, uintptr_t tid)
  3067. {
  3068. MonoInternalThread *thread = mono_thread_internal_current ();
  3069. MonoInternalThread *old_thread;
  3070. DebuggerTlsData *tls;
  3071. if (tid == debugger_thread_id)
  3072. return;
  3073. g_assert (thread->tid == tid);
  3074. mono_loader_lock ();
  3075. old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
  3076. mono_loader_unlock ();
  3077. if (old_thread) {
  3078. if (thread == old_thread) {
  3079. /*
  3080. * For some reason, thread_startup () might be called for the same thread
  3081. * multiple times (attach ?).
  3082. */
  3083. DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
  3084. return;
  3085. } else {
  3086. /*
  3087. * thread_end () might not be called for some threads, and the tid could
  3088. * get reused.
  3089. */
  3090. DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
  3091. mono_loader_lock ();
  3092. mono_g_hash_table_remove (thread_to_tls, old_thread);
  3093. mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
  3094. mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
  3095. mono_loader_unlock ();
  3096. }
  3097. }
  3098. tls = mono_native_tls_get_value (debugger_tls_id);
  3099. g_assert (!tls);
  3100. // FIXME: Free this somewhere
  3101. tls = g_new0 (DebuggerTlsData, 1);
  3102. MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
  3103. tls->thread = thread;
  3104. mono_native_tls_set_value (debugger_tls_id, tls);
  3105. DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
  3106. mono_loader_lock ();
  3107. mono_g_hash_table_insert (thread_to_tls, thread, tls);
  3108. mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
  3109. mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
  3110. mono_loader_unlock ();
  3111. process_profiler_event (EVENT_KIND_THREAD_START, thread);
  3112. /*
  3113. * suspend_vm () could have missed this thread, so wait for a resume.
  3114. */
  3115. suspend_current ();
  3116. }
  3117. static void
  3118. thread_end (MonoProfiler *prof, uintptr_t tid)
  3119. {
  3120. MonoInternalThread *thread;
  3121. DebuggerTlsData *tls = NULL;
  3122. mono_loader_lock ();
  3123. thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
  3124. if (thread) {
  3125. mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
  3126. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  3127. if (tls) {
  3128. /* FIXME: Maybe we need to free this instead, but some code can't handle that */
  3129. tls->terminated = TRUE;
  3130. /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
  3131. MONO_GC_UNREGISTER_ROOT (tls->thread);
  3132. tls->thread = NULL;
  3133. }
  3134. }
  3135. mono_loader_unlock ();
  3136. /* We might be called for threads started before we registered the start callback */
  3137. if (thread) {
  3138. DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
  3139. process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
  3140. }
  3141. }
  3142. static void
  3143. appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
  3144. {
  3145. mono_loader_lock ();
  3146. g_hash_table_insert (domains, domain, domain);
  3147. mono_loader_unlock ();
  3148. process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
  3149. }
  3150. static void
  3151. appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
  3152. {
  3153. clear_breakpoints_for_domain (domain);
  3154. mono_loader_lock ();
  3155. /* Invalidate each thread's frame stack */
  3156. mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
  3157. mono_loader_unlock ();
  3158. process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
  3159. }
  3160. /*
  3161. * invalidate_each_thread:
  3162. *
  3163. * A GHFunc to invalidate frames.
  3164. * value must be a DebuggerTlsData*
  3165. */
  3166. static void
  3167. invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
  3168. {
  3169. invalidate_frames (value);
  3170. }
  3171. static void
  3172. assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
  3173. {
  3174. /* Sent later in jit_end () */
  3175. mono_loader_lock ();
  3176. g_ptr_array_add (pending_assembly_loads, assembly);
  3177. mono_loader_unlock ();
  3178. }
  3179. static void
  3180. assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
  3181. {
  3182. process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
  3183. clear_event_requests_for_assembly (assembly);
  3184. clear_types_for_assembly (assembly);
  3185. }
  3186. static void
  3187. start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
  3188. {
  3189. #if defined(HOST_WIN32) && !defined(__GNUC__)
  3190. gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
  3191. #else
  3192. gpointer stackptr = __builtin_frame_address (1);
  3193. #endif
  3194. MonoInternalThread *thread = mono_thread_internal_current ();
  3195. DebuggerTlsData *tls;
  3196. mono_loader_lock ();
  3197. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  3198. /* Could be the debugger thread with assembly/type load hooks */
  3199. if (tls)
  3200. tls->invoke_addr = stackptr;
  3201. mono_loader_unlock ();
  3202. }
  3203. static void
  3204. end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
  3205. {
  3206. int i;
  3207. #if defined(HOST_WIN32) && !defined(__GNUC__)
  3208. gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
  3209. #else
  3210. gpointer stackptr = __builtin_frame_address (1);
  3211. #endif
  3212. if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
  3213. return;
  3214. /*
  3215. * We need to stop single stepping when exiting a runtime invoke, since if it is
  3216. * a step out, it may return to native code, and thus never end.
  3217. */
  3218. mono_loader_lock ();
  3219. ss_invoke_addr = NULL;
  3220. for (i = 0; i < event_requests->len; ++i) {
  3221. EventRequest *req = g_ptr_array_index (event_requests, i);
  3222. if (req->event_kind == EVENT_KIND_STEP) {
  3223. ss_destroy (req->info);
  3224. g_ptr_array_remove_index_fast (event_requests, i);
  3225. g_free (req);
  3226. break;
  3227. }
  3228. }
  3229. mono_loader_unlock ();
  3230. }
  3231. static void
  3232. send_type_load (MonoClass *klass)
  3233. {
  3234. gboolean type_load = FALSE;
  3235. MonoDomain *domain = mono_domain_get ();
  3236. AgentDomainInfo *info = NULL;
  3237. mono_loader_lock ();
  3238. mono_domain_lock (domain);
  3239. info = get_agent_domain_info (domain);
  3240. if (!g_hash_table_lookup (info->loaded_classes, klass)) {
  3241. type_load = TRUE;
  3242. g_hash_table_insert (info->loaded_classes, klass, klass);
  3243. }
  3244. mono_domain_unlock (domain);
  3245. mono_loader_unlock ();
  3246. if (type_load)
  3247. emit_type_load (klass, klass, NULL);
  3248. }
  3249. /*
  3250. * Emit load events for all types currently loaded in the domain.
  3251. * Takes the loader and domain locks.
  3252. * user_data is unused.
  3253. */
  3254. static void
  3255. send_types_for_domain (MonoDomain *domain, void *user_data)
  3256. {
  3257. AgentDomainInfo *info = NULL;
  3258. mono_loader_lock ();
  3259. mono_domain_lock (domain);
  3260. info = get_agent_domain_info (domain);
  3261. g_assert (info);
  3262. g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
  3263. mono_domain_unlock (domain);
  3264. mono_loader_unlock ();
  3265. }
  3266. static void
  3267. jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
  3268. {
  3269. /*
  3270. * We emit type load events when the first method of the type is JITted,
  3271. * since the class load profiler callbacks might be called with the
  3272. * loader lock held. They could also occur in the debugger thread.
  3273. * Same for assembly load events.
  3274. */
  3275. while (TRUE) {
  3276. MonoAssembly *assembly = NULL;
  3277. // FIXME: Maybe store this in TLS so the thread of the event is correct ?
  3278. mono_loader_lock ();
  3279. if (pending_assembly_loads->len > 0) {
  3280. assembly = g_ptr_array_index (pending_assembly_loads, 0);
  3281. g_ptr_array_remove_index (pending_assembly_loads, 0);
  3282. }
  3283. mono_loader_unlock ();
  3284. if (assembly) {
  3285. process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
  3286. } else {
  3287. break;
  3288. }
  3289. }
  3290. send_type_load (method->klass);
  3291. if (!result)
  3292. add_pending_breakpoints (method, jinfo);
  3293. }
  3294. /*
  3295. * BREAKPOINTS/SINGLE STEPPING
  3296. */
  3297. /*
  3298. * Contains information about an inserted breakpoint.
  3299. */
  3300. typedef struct {
  3301. long il_offset, native_offset;
  3302. guint8 *ip;
  3303. MonoJitInfo *ji;
  3304. MonoDomain *domain;
  3305. SeqPoint *sp;
  3306. } BreakpointInstance;
  3307. /*
  3308. * Contains generic information about a breakpoint.
  3309. */
  3310. typedef struct {
  3311. /*
  3312. * The method where the breakpoint is placed. Can be NULL in which case it
  3313. * is inserted into every method. This is used to implement method entry/
  3314. * exit events. Can be a generic method definition, in which case the
  3315. * breakpoint is inserted into every instance.
  3316. */
  3317. MonoMethod *method;
  3318. long il_offset;
  3319. EventRequest *req;
  3320. /*
  3321. * A list of BreakpointInstance structures describing where the breakpoint
  3322. * was inserted. There could be more than one because of
  3323. * generics/appdomains/method entry/exit.
  3324. */
  3325. GPtrArray *children;
  3326. } MonoBreakpoint;
  3327. /* List of breakpoints */
  3328. static GPtrArray *breakpoints;
  3329. /* Maps breakpoint locations to the number of breakpoints at that location */
  3330. static GHashTable *bp_locs;
  3331. static void
  3332. breakpoints_init (void)
  3333. {
  3334. breakpoints = g_ptr_array_new ();
  3335. bp_locs = g_hash_table_new (NULL, NULL);
  3336. }
  3337. /*
  3338. * insert_breakpoint:
  3339. *
  3340. * Insert the breakpoint described by BP into the method described by
  3341. * JI.
  3342. */
  3343. static void
  3344. insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
  3345. {
  3346. int i, count;
  3347. BreakpointInstance *inst;
  3348. SeqPoint *sp = NULL;
  3349. if (error)
  3350. mono_error_init (error);
  3351. for (i = 0; i < seq_points->len; ++i) {
  3352. sp = &seq_points->seq_points [i];
  3353. if (sp->il_offset == bp->il_offset)
  3354. break;
  3355. }
  3356. if (i == seq_points->len) {
  3357. /*
  3358. * The set of IL offsets with seq points doesn't completely match the
  3359. * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
  3360. */
  3361. for (i = 0; i < seq_points->len; ++i) {
  3362. sp = &seq_points->seq_points [i];
  3363. if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
  3364. break;
  3365. }
  3366. }
  3367. if (i == seq_points->len) {
  3368. char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
  3369. for (i = 0; i < seq_points->len; ++i)
  3370. DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
  3371. if (error) {
  3372. mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
  3373. g_free (s);
  3374. return;
  3375. } else {
  3376. g_error ("%s", s);
  3377. g_free (s);
  3378. }
  3379. }
  3380. inst = g_new0 (BreakpointInstance, 1);
  3381. inst->sp = sp;
  3382. inst->native_offset = sp->native_offset;
  3383. inst->ip = (guint8*)ji->code_start + sp->native_offset;
  3384. inst->ji = ji;
  3385. inst->domain = domain;
  3386. mono_loader_lock ();
  3387. g_ptr_array_add (bp->children, inst);
  3388. count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
  3389. g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
  3390. mono_loader_unlock ();
  3391. if (count == 0) {
  3392. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  3393. mono_arch_set_breakpoint (ji, inst->ip);
  3394. #else
  3395. NOT_IMPLEMENTED;
  3396. #endif
  3397. }
  3398. DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
  3399. }
  3400. static void
  3401. remove_breakpoint (BreakpointInstance *inst)
  3402. {
  3403. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  3404. int count;
  3405. MonoJitInfo *ji = inst->ji;
  3406. guint8 *ip = inst->ip;
  3407. mono_loader_lock ();
  3408. count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
  3409. g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
  3410. mono_loader_unlock ();
  3411. g_assert (count > 0);
  3412. if (count == 1) {
  3413. mono_arch_clear_breakpoint (ji, ip);
  3414. }
  3415. #else
  3416. NOT_IMPLEMENTED;
  3417. #endif
  3418. }
  3419. static inline gboolean
  3420. bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
  3421. {
  3422. int i;
  3423. if (!bp->method)
  3424. return TRUE;
  3425. if (method == bp->method)
  3426. return TRUE;
  3427. if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
  3428. return TRUE;
  3429. if (bp->method->is_inflated && method->is_inflated) {
  3430. MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
  3431. MonoMethodInflated *imethod = (MonoMethodInflated*)method;
  3432. /* Open generic methods should match closed generic methods of the same class */
  3433. if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
  3434. for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
  3435. MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
  3436. /* FIXME: Handle !mvar */
  3437. if (t1->type != MONO_TYPE_MVAR)
  3438. return FALSE;
  3439. }
  3440. return TRUE;
  3441. }
  3442. }
  3443. return FALSE;
  3444. }
  3445. /*
  3446. * add_pending_breakpoints:
  3447. *
  3448. * Insert pending breakpoints into the newly JITted method METHOD.
  3449. */
  3450. static void
  3451. add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
  3452. {
  3453. int i, j;
  3454. MonoSeqPointInfo *seq_points;
  3455. MonoDomain *domain;
  3456. if (!breakpoints)
  3457. return;
  3458. domain = mono_domain_get ();
  3459. mono_loader_lock ();
  3460. for (i = 0; i < breakpoints->len; ++i) {
  3461. MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
  3462. gboolean found = FALSE;
  3463. if (!bp_matches_method (bp, method))
  3464. continue;
  3465. for (j = 0; j < bp->children->len; ++j) {
  3466. BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
  3467. if (inst->ji == ji)
  3468. found = TRUE;
  3469. }
  3470. if (!found) {
  3471. mono_domain_lock (domain);
  3472. seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
  3473. if (!seq_points && ji->method->is_inflated)
  3474. seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
  3475. mono_domain_unlock (domain);
  3476. if (!seq_points)
  3477. /* Could be AOT code */
  3478. continue;
  3479. g_assert (seq_points);
  3480. insert_breakpoint (seq_points, domain, ji, bp, NULL);
  3481. }
  3482. }
  3483. mono_loader_unlock ();
  3484. }
  3485. static void
  3486. set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
  3487. {
  3488. gpointer code;
  3489. MonoJitInfo *ji;
  3490. if (error)
  3491. mono_error_init (error);
  3492. code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
  3493. if (!code) {
  3494. /* Might be AOTed code */
  3495. code = mono_aot_get_method (domain, method);
  3496. g_assert (code);
  3497. ji = mono_jit_info_table_find (domain, code);
  3498. g_assert (ji);
  3499. }
  3500. g_assert (code);
  3501. insert_breakpoint (seq_points, domain, ji, bp, error);
  3502. }
  3503. static void
  3504. clear_breakpoint (MonoBreakpoint *bp);
  3505. /*
  3506. * set_breakpoint:
  3507. *
  3508. * Set a breakpoint at IL_OFFSET in METHOD.
  3509. * METHOD can be NULL, in which case a breakpoint is placed in all methods.
  3510. * METHOD can also be a generic method definition, in which case a breakpoint
  3511. * is placed in all instances of the method.
  3512. * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
  3513. * inserted.
  3514. */
  3515. static MonoBreakpoint*
  3516. set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
  3517. {
  3518. MonoBreakpoint *bp;
  3519. GHashTableIter iter, iter2;
  3520. MonoDomain *domain;
  3521. MonoMethod *m;
  3522. MonoSeqPointInfo *seq_points;
  3523. if (error)
  3524. mono_error_init (error);
  3525. // FIXME:
  3526. // - suspend/resume the vm to prevent code patching problems
  3527. // - multiple breakpoints on the same location
  3528. // - dynamic methods
  3529. // - races
  3530. bp = g_new0 (MonoBreakpoint, 1);
  3531. bp->method = method;
  3532. bp->il_offset = il_offset;
  3533. bp->req = req;
  3534. bp->children = g_ptr_array_new ();
  3535. DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
  3536. mono_loader_lock ();
  3537. g_hash_table_iter_init (&iter, domains);
  3538. while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
  3539. mono_domain_lock (domain);
  3540. g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
  3541. while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
  3542. if (bp_matches_method (bp, m))
  3543. set_bp_in_method (domain, m, seq_points, bp, error);
  3544. }
  3545. mono_domain_unlock (domain);
  3546. }
  3547. mono_loader_unlock ();
  3548. mono_loader_lock ();
  3549. g_ptr_array_add (breakpoints, bp);
  3550. mono_loader_unlock ();
  3551. if (error && !mono_error_ok (error)) {
  3552. clear_breakpoint (bp);
  3553. return NULL;
  3554. }
  3555. return bp;
  3556. }
  3557. static void
  3558. clear_breakpoint (MonoBreakpoint *bp)
  3559. {
  3560. int i;
  3561. // FIXME: locking, races
  3562. for (i = 0; i < bp->children->len; ++i) {
  3563. BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
  3564. remove_breakpoint (inst);
  3565. g_free (inst);
  3566. }
  3567. mono_loader_lock ();
  3568. g_ptr_array_remove (breakpoints, bp);
  3569. mono_loader_unlock ();
  3570. g_ptr_array_free (bp->children, TRUE);
  3571. g_free (bp);
  3572. }
  3573. static void
  3574. breakpoints_cleanup (void)
  3575. {
  3576. int i;
  3577. mono_loader_lock ();
  3578. i = 0;
  3579. while (i < event_requests->len) {
  3580. EventRequest *req = g_ptr_array_index (event_requests, i);
  3581. if (req->event_kind == EVENT_KIND_BREAKPOINT) {
  3582. clear_breakpoint (req->info);
  3583. g_ptr_array_remove_index_fast (event_requests, i);
  3584. g_free (req);
  3585. } else {
  3586. i ++;
  3587. }
  3588. }
  3589. for (i = 0; i < breakpoints->len; ++i)
  3590. g_free (g_ptr_array_index (breakpoints, i));
  3591. g_ptr_array_free (breakpoints, TRUE);
  3592. g_hash_table_destroy (bp_locs);
  3593. breakpoints = NULL;
  3594. bp_locs = NULL;
  3595. mono_loader_unlock ();
  3596. }
  3597. /*
  3598. * clear_breakpoints_for_domain:
  3599. *
  3600. * Clear breakpoint instances which reference DOMAIN.
  3601. */
  3602. static void
  3603. clear_breakpoints_for_domain (MonoDomain *domain)
  3604. {
  3605. int i, j;
  3606. /* This could be called after shutdown */
  3607. if (!breakpoints)
  3608. return;
  3609. mono_loader_lock ();
  3610. for (i = 0; i < breakpoints->len; ++i) {
  3611. MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
  3612. j = 0;
  3613. while (j < bp->children->len) {
  3614. BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
  3615. if (inst->domain == domain) {
  3616. remove_breakpoint (inst);
  3617. g_free (inst);
  3618. g_ptr_array_remove_index_fast (bp->children, j);
  3619. } else {
  3620. j ++;
  3621. }
  3622. }
  3623. }
  3624. mono_loader_unlock ();
  3625. }
  3626. static gboolean
  3627. breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
  3628. {
  3629. return bp->method && bp->method->klass->image->assembly == assembly;
  3630. }
  3631. static void
  3632. process_breakpoint_inner (DebuggerTlsData *tls)
  3633. {
  3634. MonoJitInfo *ji;
  3635. guint8 *ip;
  3636. int i, j, suspend_policy;
  3637. guint32 native_offset;
  3638. MonoBreakpoint *bp;
  3639. BreakpointInstance *inst;
  3640. GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
  3641. GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
  3642. EventKind kind = EVENT_KIND_BREAKPOINT;
  3643. MonoContext *ctx = &tls->restore_ctx;
  3644. MonoSeqPointInfo *info;
  3645. SeqPoint *sp;
  3646. // FIXME: Speed this up
  3647. ip = MONO_CONTEXT_GET_IP (ctx);
  3648. ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
  3649. g_assert (ji);
  3650. g_assert (ji->method);
  3651. /* Compute the native offset of the breakpoint from the ip */
  3652. native_offset = ip - (guint8*)ji->code_start;
  3653. /*
  3654. * Skip the instruction causing the breakpoint signal.
  3655. */
  3656. mono_arch_skip_breakpoint (ctx, ji);
  3657. if (ji->method->wrapper_type || tls->disable_breakpoints)
  3658. return;
  3659. bp_reqs = g_ptr_array_new ();
  3660. ss_reqs = g_ptr_array_new ();
  3661. ss_reqs_orig = g_ptr_array_new ();
  3662. mono_loader_lock ();
  3663. /*
  3664. * The ip points to the instruction causing the breakpoint event, which is after
  3665. * the offset recorded in the seq point map, so find the prev seq point before ip.
  3666. */
  3667. sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
  3668. g_assert (sp);
  3669. DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, ip, native_offset, sp ? sp->il_offset : -1));
  3670. bp = NULL;
  3671. for (i = 0; i < breakpoints->len; ++i) {
  3672. bp = g_ptr_array_index (breakpoints, i);
  3673. if (!bp->method)
  3674. continue;
  3675. for (j = 0; j < bp->children->len; ++j) {
  3676. inst = g_ptr_array_index (bp->children, j);
  3677. if (inst->ji == ji && inst->sp == sp) {
  3678. if (bp->req->event_kind == EVENT_KIND_STEP) {
  3679. g_ptr_array_add (ss_reqs_orig, bp->req);
  3680. } else {
  3681. g_ptr_array_add (bp_reqs, bp->req);
  3682. }
  3683. }
  3684. }
  3685. }
  3686. if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
  3687. /* Maybe a method entry/exit event */
  3688. if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
  3689. kind = EVENT_KIND_METHOD_ENTRY;
  3690. else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
  3691. kind = EVENT_KIND_METHOD_EXIT;
  3692. }
  3693. /* Process single step requests */
  3694. for (i = 0; i < ss_reqs_orig->len; ++i) {
  3695. EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
  3696. SingleStepReq *ss_req = req->info;
  3697. gboolean hit = TRUE;
  3698. if (ss_req->size == STEP_SIZE_LINE) {
  3699. /* Have to check whenever a different source line was reached */
  3700. MonoDebugMethodInfo *minfo;
  3701. MonoDebugSourceLocation *loc = NULL;
  3702. minfo = mono_debug_lookup_method (ji->method);
  3703. if (minfo)
  3704. loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
  3705. if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
  3706. /* Have to continue single stepping */
  3707. DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
  3708. hit = FALSE;
  3709. }
  3710. if (loc) {
  3711. ss_req->last_method = ji->method;
  3712. ss_req->last_line = loc->row;
  3713. mono_debug_free_source_location (loc);
  3714. }
  3715. }
  3716. if (hit)
  3717. g_ptr_array_add (ss_reqs, req);
  3718. /* Start single stepping again from the current sequence point */
  3719. ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
  3720. }
  3721. if (ss_reqs->len > 0)
  3722. ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
  3723. if (bp_reqs->len > 0)
  3724. bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
  3725. if (kind != EVENT_KIND_BREAKPOINT)
  3726. enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
  3727. mono_loader_unlock ();
  3728. g_ptr_array_free (bp_reqs, TRUE);
  3729. g_ptr_array_free (ss_reqs, TRUE);
  3730. /*
  3731. * FIXME: The first event will suspend, so the second will only be sent after the
  3732. * resume.
  3733. */
  3734. if (ss_events)
  3735. process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
  3736. if (bp_events)
  3737. process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
  3738. if (enter_leave_events)
  3739. process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
  3740. }
  3741. /* Process a breakpoint/single step event after resuming from a signal handler */
  3742. static void
  3743. process_signal_event (void (*func) (DebuggerTlsData*))
  3744. {
  3745. DebuggerTlsData *tls;
  3746. MonoContext orig_restore_ctx, ctx;
  3747. static void (*restore_context) (void *);
  3748. if (!restore_context)
  3749. restore_context = mono_get_restore_context ();
  3750. tls = mono_native_tls_get_value (debugger_tls_id);
  3751. /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
  3752. memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
  3753. memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
  3754. func (tls);
  3755. /* This is called when resuming from a signal handler, so it shouldn't return */
  3756. memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
  3757. memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
  3758. restore_context (&ctx);
  3759. g_assert_not_reached ();
  3760. }
  3761. static void
  3762. process_breakpoint (void)
  3763. {
  3764. process_signal_event (process_breakpoint_inner);
  3765. }
  3766. static void
  3767. resume_from_signal_handler (void *sigctx, void *func)
  3768. {
  3769. DebuggerTlsData *tls;
  3770. MonoContext ctx;
  3771. /* Save the original context in TLS */
  3772. // FIXME: This might not work on an altstack ?
  3773. tls = mono_native_tls_get_value (debugger_tls_id);
  3774. if (!tls)
  3775. fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
  3776. g_assert (tls);
  3777. // FIXME: MonoContext usually doesn't include the fp registers, so these are
  3778. // clobbered by a single step/breakpoint event. If this turns out to be a problem,
  3779. // clob:c could be added to op_seq_point.
  3780. mono_arch_sigctx_to_monoctx (sigctx, &ctx);
  3781. memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
  3782. #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
  3783. mono_arch_setup_resume_sighandler_ctx (&ctx, func);
  3784. #else
  3785. MONO_CONTEXT_SET_IP (&ctx, func);
  3786. #endif
  3787. mono_arch_monoctx_to_sigctx (&ctx, sigctx);
  3788. #ifdef PPC_USES_FUNCTION_DESCRIPTOR
  3789. mono_ppc_set_func_into_sigctx (sigctx, func);
  3790. #endif
  3791. }
  3792. void
  3793. mono_debugger_agent_breakpoint_hit (void *sigctx)
  3794. {
  3795. /*
  3796. * We are called from a signal handler, and running code there causes all kinds of
  3797. * problems, like the original signal is disabled, libgc can't handle altstack, etc.
  3798. * So set up the signal context to return to the real breakpoint handler function.
  3799. */
  3800. resume_from_signal_handler (sigctx, process_breakpoint);
  3801. }
  3802. static gboolean
  3803. user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
  3804. {
  3805. if (frame->managed) {
  3806. *(MonoContext*)data = *ctx;
  3807. return TRUE;
  3808. } else {
  3809. return FALSE;
  3810. }
  3811. }
  3812. /*
  3813. * Called by System.Diagnostics.Debugger:Break ().
  3814. */
  3815. void
  3816. mono_debugger_agent_user_break (void)
  3817. {
  3818. if (agent_config.enabled) {
  3819. MonoContext ctx;
  3820. int suspend_policy;
  3821. GSList *events;
  3822. /* Obtain a context */
  3823. MONO_CONTEXT_SET_IP (&ctx, NULL);
  3824. mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
  3825. g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
  3826. mono_loader_lock ();
  3827. events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
  3828. mono_loader_unlock ();
  3829. process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
  3830. } else {
  3831. G_BREAKPOINT ();
  3832. }
  3833. }
  3834. static const char*
  3835. ss_depth_to_string (StepDepth depth)
  3836. {
  3837. switch (depth) {
  3838. case STEP_DEPTH_OVER:
  3839. return "over";
  3840. case STEP_DEPTH_OUT:
  3841. return "out";
  3842. case STEP_DEPTH_INTO:
  3843. return "into";
  3844. default:
  3845. g_assert_not_reached ();
  3846. return NULL;
  3847. }
  3848. }
  3849. static void
  3850. process_single_step_inner (DebuggerTlsData *tls)
  3851. {
  3852. MonoJitInfo *ji;
  3853. guint8 *ip;
  3854. GPtrArray *reqs;
  3855. int il_offset, suspend_policy;
  3856. MonoDomain *domain;
  3857. GSList *events;
  3858. MonoContext *ctx = &tls->restore_ctx;
  3859. SeqPoint *sp;
  3860. MonoSeqPointInfo *info;
  3861. ip = MONO_CONTEXT_GET_IP (ctx);
  3862. /* Skip the instruction causing the single step */
  3863. mono_arch_skip_single_step (ctx);
  3864. if (suspend_count > 0) {
  3865. process_suspend (tls, ctx);
  3866. return;
  3867. }
  3868. if (!ss_req)
  3869. // FIXME: A suspend race
  3870. return;
  3871. if (mono_thread_internal_current () != ss_req->thread)
  3872. return;
  3873. if (log_level > 0) {
  3874. ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
  3875. DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
  3876. }
  3877. ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
  3878. g_assert (ji);
  3879. g_assert (ji->method);
  3880. if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
  3881. return;
  3882. /*
  3883. * FIXME:
  3884. * Stopping in memset makes half-initialized vtypes visible.
  3885. * Stopping in memcpy makes half-copied vtypes visible.
  3886. */
  3887. if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
  3888. return;
  3889. /*
  3890. * The ip points to the instruction causing the single step event, which is before
  3891. * the offset recorded in the seq point map, so find the next seq point after ip.
  3892. */
  3893. sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
  3894. if (!sp)
  3895. return;
  3896. il_offset = sp->il_offset;
  3897. // FIXME: No tests fail if this is disabled
  3898. #if 0
  3899. if (ss_req->size == STEP_SIZE_LINE) {
  3900. // FIXME:
  3901. NOT_IMPLEMENTED;
  3902. /* Step until a different source line is reached */
  3903. MonoDebugMethodInfo *minfo;
  3904. minfo = mono_debug_lookup_method (ji->method);
  3905. if (minfo) {
  3906. MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
  3907. if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
  3908. mono_debug_free_source_location (loc);
  3909. return;
  3910. }
  3911. if (!loc)
  3912. /*
  3913. * Step until we reach a location with line number info,
  3914. * otherwise the client can't show a location.
  3915. * This can happen for example with statics initialized inline
  3916. * outside of a cctor.
  3917. */
  3918. return;
  3919. if (loc) {
  3920. ss_req->last_method = ji->method;
  3921. ss_req->last_line = loc->row;
  3922. mono_debug_free_source_location (loc);
  3923. }
  3924. }
  3925. }
  3926. #endif
  3927. /* Start single stepping again from the current sequence point */
  3928. ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
  3929. if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
  3930. (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
  3931. !strcmp (ji->method->name, ".cctor"))
  3932. return;
  3933. // FIXME: Has to lock earlier
  3934. reqs = g_ptr_array_new ();
  3935. mono_loader_lock ();
  3936. g_ptr_array_add (reqs, ss_req->req);
  3937. events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
  3938. g_ptr_array_free (reqs, TRUE);
  3939. mono_loader_unlock ();
  3940. process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
  3941. }
  3942. static void
  3943. process_single_step (void)
  3944. {
  3945. process_signal_event (process_single_step_inner);
  3946. }
  3947. /*
  3948. * mono_debugger_agent_single_step_event:
  3949. *
  3950. * Called from a signal handler to handle a single step event.
  3951. */
  3952. void
  3953. mono_debugger_agent_single_step_event (void *sigctx)
  3954. {
  3955. /* Resume to process_single_step through the signal context */
  3956. // FIXME: Since step out/over is implemented using step in, the step in case should
  3957. // be as fast as possible. Move the relevant code from process_single_step_inner ()
  3958. // here
  3959. if (GetCurrentThreadId () == debugger_thread_id) {
  3960. /*
  3961. * This could happen despite our best effors when the runtime calls
  3962. * assembly/type resolve hooks.
  3963. * FIXME: Breakpoints too.
  3964. */
  3965. MonoContext ctx;
  3966. mono_arch_sigctx_to_monoctx (sigctx, &ctx);
  3967. mono_arch_skip_single_step (&ctx);
  3968. mono_arch_monoctx_to_sigctx (&ctx, sigctx);
  3969. return;
  3970. }
  3971. resume_from_signal_handler (sigctx, process_single_step);
  3972. }
  3973. void
  3974. debugger_agent_single_step_from_context (MonoContext *ctx)
  3975. {
  3976. DebuggerTlsData *tls;
  3977. MonoContext orig_restore_ctx;
  3978. tls = mono_native_tls_get_value (debugger_tls_id);
  3979. g_assert (tls);
  3980. /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
  3981. memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
  3982. memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
  3983. process_single_step_inner (tls);
  3984. memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
  3985. memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
  3986. }
  3987. void
  3988. debugger_agent_breakpoint_from_context (MonoContext *ctx)
  3989. {
  3990. DebuggerTlsData *tls;
  3991. MonoContext orig_restore_ctx;
  3992. tls = mono_native_tls_get_value (debugger_tls_id);
  3993. g_assert (tls);
  3994. memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
  3995. memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
  3996. process_breakpoint_inner (tls);
  3997. memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
  3998. memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
  3999. }
  4000. /*
  4001. * start_single_stepping:
  4002. *
  4003. * Turn on single stepping. Can be called multiple times, for example,
  4004. * by a single step event request + a suspend.
  4005. */
  4006. static void
  4007. start_single_stepping (void)
  4008. {
  4009. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  4010. int val = InterlockedIncrement (&ss_count);
  4011. if (val == 1)
  4012. mono_arch_start_single_stepping ();
  4013. if (ss_req != NULL && ss_invoke_addr == NULL) {
  4014. DebuggerTlsData *tls;
  4015. mono_loader_lock ();
  4016. tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
  4017. ss_invoke_addr = tls->invoke_addr;
  4018. mono_loader_unlock ();
  4019. }
  4020. #else
  4021. g_assert_not_reached ();
  4022. #endif
  4023. }
  4024. static void
  4025. stop_single_stepping (void)
  4026. {
  4027. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  4028. int val = InterlockedDecrement (&ss_count);
  4029. if (val == 0)
  4030. mono_arch_stop_single_stepping ();
  4031. #else
  4032. g_assert_not_reached ();
  4033. #endif
  4034. }
  4035. /*
  4036. * ss_stop:
  4037. *
  4038. * Stop the single stepping operation given by SS_REQ.
  4039. */
  4040. static void
  4041. ss_stop (SingleStepReq *ss_req)
  4042. {
  4043. if (ss_req->bps) {
  4044. GSList *l;
  4045. for (l = ss_req->bps; l; l = l->next) {
  4046. clear_breakpoint (l->data);
  4047. }
  4048. g_slist_free (ss_req->bps);
  4049. ss_req->bps = NULL;
  4050. }
  4051. if (ss_req->global) {
  4052. stop_single_stepping ();
  4053. ss_req->global = FALSE;
  4054. }
  4055. }
  4056. /*
  4057. * ss_start:
  4058. *
  4059. * Start the single stepping operation given by SS_REQ from the sequence point SP.
  4060. * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
  4061. * belong to the same thread as CTX.
  4062. */
  4063. static void
  4064. ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
  4065. {
  4066. int i, j, frame_index;
  4067. SeqPoint *next_sp;
  4068. MonoBreakpoint *bp;
  4069. gboolean enable_global = FALSE;
  4070. /* Stop the previous operation */
  4071. ss_stop (ss_req);
  4072. /*
  4073. * Implement single stepping using breakpoints if possible.
  4074. */
  4075. if (step_to_catch) {
  4076. bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
  4077. ss_req->bps = g_slist_append (ss_req->bps, bp);
  4078. } else {
  4079. frame_index = 1;
  4080. if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
  4081. /* Need parent frames */
  4082. if (!tls->context.valid)
  4083. mono_thread_state_init_from_monoctx (&tls->context, ctx);
  4084. compute_frame_info (tls->thread, tls);
  4085. }
  4086. /*
  4087. * Find the first sequence point in the current or in a previous frame which
  4088. * is not the last in its method.
  4089. */
  4090. if (ss_req->depth == STEP_DEPTH_OUT) {
  4091. /* Ignore seq points in current method */
  4092. while (frame_index < tls->frame_count) {
  4093. StackFrame *frame = tls->frames [frame_index];
  4094. method = frame->method;
  4095. sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
  4096. frame_index ++;
  4097. if (sp && sp->next_len != 0)
  4098. break;
  4099. }
  4100. // There could be method calls before the next seq point in the caller when using nested calls
  4101. //enable_global = TRUE;
  4102. } else {
  4103. while (sp && sp->next_len == 0) {
  4104. sp = NULL;
  4105. if (frame_index < tls->frame_count) {
  4106. StackFrame *frame = tls->frames [frame_index];
  4107. method = frame->method;
  4108. sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
  4109. frame_index ++;
  4110. }
  4111. }
  4112. }
  4113. if (sp && sp->next_len > 0) {
  4114. for (i = 0; i < sp->next_len; ++i) {
  4115. next_sp = &info->seq_points [sp->next [i]];
  4116. bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
  4117. ss_req->bps = g_slist_append (ss_req->bps, bp);
  4118. }
  4119. }
  4120. if (ss_req->depth == STEP_DEPTH_OVER) {
  4121. /* Need to stop in catch clauses as well */
  4122. for (i = 0; i < tls->frame_count; ++i) {
  4123. StackFrame *frame = tls->frames [i];
  4124. if (frame->ji) {
  4125. MonoJitInfo *jinfo = frame->ji;
  4126. for (j = 0; j < jinfo->num_clauses; ++j) {
  4127. MonoJitExceptionInfo *ei = &jinfo->clauses [j];
  4128. sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
  4129. if (sp) {
  4130. bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
  4131. ss_req->bps = g_slist_append (ss_req->bps, bp);
  4132. }
  4133. }
  4134. }
  4135. }
  4136. }
  4137. if (ss_req->depth == STEP_DEPTH_INTO) {
  4138. /* Enable global stepping so we stop at method entry too */
  4139. enable_global = TRUE;
  4140. }
  4141. /*
  4142. * The ctx/frame info computed above will become invalid when we continue.
  4143. */
  4144. tls->context.valid = FALSE;
  4145. tls->async_state.valid = FALSE;
  4146. invalidate_frames (tls);
  4147. }
  4148. if (enable_global) {
  4149. DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
  4150. ss_req->global = TRUE;
  4151. start_single_stepping ();
  4152. } else if (!ss_req->bps) {
  4153. DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
  4154. ss_req->global = TRUE;
  4155. start_single_stepping ();
  4156. } else {
  4157. ss_req->global = FALSE;
  4158. }
  4159. }
  4160. /*
  4161. * Start single stepping of thread THREAD
  4162. */
  4163. static ErrorCode
  4164. ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
  4165. {
  4166. DebuggerTlsData *tls;
  4167. MonoSeqPointInfo *info = NULL;
  4168. SeqPoint *sp = NULL;
  4169. MonoMethod *method = NULL;
  4170. MonoDebugMethodInfo *minfo;
  4171. gboolean step_to_catch = FALSE;
  4172. if (suspend_count == 0)
  4173. return ERR_NOT_SUSPENDED;
  4174. wait_for_suspend ();
  4175. // FIXME: Multiple requests
  4176. if (ss_req) {
  4177. DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
  4178. return ERR_NOT_IMPLEMENTED;
  4179. }
  4180. DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
  4181. ss_req = g_new0 (SingleStepReq, 1);
  4182. ss_req->req = req;
  4183. ss_req->thread = thread;
  4184. ss_req->size = size;
  4185. ss_req->depth = depth;
  4186. req->info = ss_req;
  4187. mono_loader_lock ();
  4188. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  4189. mono_loader_unlock ();
  4190. g_assert (tls);
  4191. g_assert (tls->context.valid);
  4192. ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
  4193. if (tls->catch_state.valid) {
  4194. gboolean res;
  4195. StackFrameInfo frame;
  4196. MonoContext new_ctx;
  4197. MonoLMF *lmf = NULL;
  4198. /*
  4199. * We are stopped at a throw site. Stepping should go to the catch site.
  4200. */
  4201. /* Find the the jit info for the catch context */
  4202. res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
  4203. g_assert (res);
  4204. g_assert (frame.type == FRAME_TYPE_MANAGED);
  4205. /*
  4206. * Find the seq point corresponding to the landing site ip, which is the first seq
  4207. * point after ip.
  4208. */
  4209. sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
  4210. g_assert (sp);
  4211. method = frame.method;
  4212. step_to_catch = TRUE;
  4213. /* This make sure the seq point is not skipped by process_single_step () */
  4214. ss_req->last_sp = NULL;
  4215. }
  4216. if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
  4217. StackFrame *frame;
  4218. /* Compute the initial line info */
  4219. compute_frame_info (thread, tls);
  4220. if (tls->frame_count) {
  4221. frame = tls->frames [0];
  4222. ss_req->last_method = frame->method;
  4223. ss_req->last_line = -1;
  4224. minfo = mono_debug_lookup_method (frame->method);
  4225. if (minfo && frame->il_offset != -1) {
  4226. MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
  4227. if (loc) {
  4228. ss_req->last_line = loc->row;
  4229. g_free (loc);
  4230. }
  4231. }
  4232. }
  4233. }
  4234. if (!step_to_catch) {
  4235. StackFrame *frame;
  4236. compute_frame_info (thread, tls);
  4237. if (tls->frame_count) {
  4238. frame = tls->frames [0];
  4239. if (!method && frame->il_offset != -1) {
  4240. /* FIXME: Sort the table and use a binary search */
  4241. sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
  4242. g_assert (sp);
  4243. method = frame->method;
  4244. }
  4245. }
  4246. }
  4247. ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
  4248. return 0;
  4249. }
  4250. static void
  4251. ss_destroy (SingleStepReq *req)
  4252. {
  4253. // FIXME: Locking
  4254. g_assert (ss_req == req);
  4255. ss_stop (ss_req);
  4256. g_free (ss_req);
  4257. ss_req = NULL;
  4258. }
  4259. /*
  4260. * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
  4261. */
  4262. void
  4263. mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
  4264. {
  4265. int suspend_policy;
  4266. GSList *events;
  4267. EventInfo ei;
  4268. if (!agent_config.enabled)
  4269. return;
  4270. mono_loader_lock ();
  4271. events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
  4272. mono_loader_unlock ();
  4273. ei.level = level;
  4274. ei.category = category ? mono_string_to_utf8 (category) : NULL;
  4275. ei.message = message ? mono_string_to_utf8 (message) : NULL;
  4276. process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
  4277. g_free (ei.category);
  4278. g_free (ei.message);
  4279. }
  4280. gboolean
  4281. mono_debugger_agent_debug_log_is_enabled (void)
  4282. {
  4283. /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
  4284. return agent_config.enabled;
  4285. }
  4286. #ifdef PLATFORM_ANDROID
  4287. void
  4288. mono_debugger_agent_unhandled_exception (MonoException *exc)
  4289. {
  4290. int suspend_policy;
  4291. GSList *events;
  4292. EventInfo ei;
  4293. if (!inited)
  4294. return;
  4295. memset (&ei, 0, sizeof (EventInfo));
  4296. ei.exc = (MonoObject*)exc;
  4297. mono_loader_lock ();
  4298. events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
  4299. mono_loader_unlock ();
  4300. process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
  4301. }
  4302. #endif
  4303. void
  4304. mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
  4305. MonoContext *catch_ctx)
  4306. {
  4307. int i, j, suspend_policy;
  4308. GSList *events;
  4309. MonoJitInfo *ji, *catch_ji;
  4310. EventInfo ei;
  4311. DebuggerTlsData *tls = NULL;
  4312. if (thread_to_tls != NULL) {
  4313. MonoInternalThread *thread = mono_thread_internal_current ();
  4314. mono_loader_lock ();
  4315. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  4316. mono_loader_unlock ();
  4317. if (tls && tls->abort_requested)
  4318. return;
  4319. if (tls && tls->disable_breakpoints)
  4320. return;
  4321. }
  4322. memset (&ei, 0, sizeof (EventInfo));
  4323. /* Just-In-Time debugging */
  4324. if (!catch_ctx) {
  4325. if (agent_config.onuncaught && !inited) {
  4326. finish_agent_init (FALSE);
  4327. /*
  4328. * Send an unsolicited EXCEPTION event with a dummy request id.
  4329. */
  4330. events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
  4331. ei.exc = (MonoObject*)exc;
  4332. process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
  4333. return;
  4334. }
  4335. } else if (agent_config.onthrow && !inited) {
  4336. GSList *l;
  4337. gboolean found = FALSE;
  4338. for (l = agent_config.onthrow; l; l = l->next) {
  4339. char *ex_type = l->data;
  4340. char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
  4341. if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
  4342. found = TRUE;
  4343. g_free (f);
  4344. }
  4345. if (found) {
  4346. finish_agent_init (FALSE);
  4347. /*
  4348. * Send an unsolicited EXCEPTION event with a dummy request id.
  4349. */
  4350. events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
  4351. ei.exc = (MonoObject*)exc;
  4352. process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
  4353. return;
  4354. }
  4355. }
  4356. if (!inited)
  4357. return;
  4358. ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
  4359. if (catch_ctx)
  4360. catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
  4361. else
  4362. catch_ji = NULL;
  4363. ei.exc = (MonoObject*)exc;
  4364. ei.caught = catch_ctx != NULL;
  4365. mono_loader_lock ();
  4366. /* Treat exceptions which are caught in non-user code as unhandled */
  4367. for (i = 0; i < event_requests->len; ++i) {
  4368. EventRequest *req = g_ptr_array_index (event_requests, i);
  4369. if (req->event_kind != EVENT_KIND_EXCEPTION)
  4370. continue;
  4371. for (j = 0; j < req->nmodifiers; ++j) {
  4372. Modifier *mod = &req->modifiers [j];
  4373. if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
  4374. int k;
  4375. gboolean found = FALSE;
  4376. MonoAssembly **assemblies = mod->data.assemblies;
  4377. if (assemblies) {
  4378. for (k = 0; assemblies [k]; ++k)
  4379. if (assemblies [k] == catch_ji->method->klass->image->assembly)
  4380. found = TRUE;
  4381. }
  4382. if (!found)
  4383. ei.caught = FALSE;
  4384. }
  4385. }
  4386. }
  4387. events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
  4388. mono_loader_unlock ();
  4389. if (tls && ei.caught && catch_ctx) {
  4390. memset (&tls->catch_state, 0, sizeof (tls->catch_state));
  4391. tls->catch_state.ctx = *catch_ctx;
  4392. tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
  4393. tls->catch_state.valid = TRUE;
  4394. }
  4395. process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
  4396. if (tls)
  4397. tls->catch_state.valid = FALSE;
  4398. }
  4399. void
  4400. mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
  4401. {
  4402. DebuggerTlsData *tls;
  4403. if (!inited)
  4404. return;
  4405. tls = mono_native_tls_get_value (debugger_tls_id);
  4406. if (!tls)
  4407. return;
  4408. /*
  4409. * We're about to invoke an exception filter during the first pass of exception handling.
  4410. *
  4411. * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
  4412. * 'orig_ctx' is the context where the exception has been thrown.
  4413. *
  4414. *
  4415. * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
  4416. *
  4417. * If we're stopped in Filter(), normal stack unwinding would first unwind to
  4418. * the call site (line 37) and then continue to Main(), but it would never
  4419. * include the throw site (line 32).
  4420. *
  4421. * Since exception filters are invoked during the first pass of exception handling,
  4422. * the stack frames of the throw site are still intact, so we should include them
  4423. * in a stack trace.
  4424. *
  4425. * We do this here by saving the context of the throw site in 'tls->filter_state'.
  4426. *
  4427. * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
  4428. * but report the location of the 'throw' to the user.
  4429. *
  4430. */
  4431. g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
  4432. }
  4433. void
  4434. mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
  4435. {
  4436. DebuggerTlsData *tls;
  4437. if (!inited)
  4438. return;
  4439. tls = mono_native_tls_get_value (debugger_tls_id);
  4440. if (!tls)
  4441. return;
  4442. tls->filter_state.valid = FALSE;
  4443. }
  4444. /*
  4445. * buffer_add_value_full:
  4446. *
  4447. * Add the encoding of the value at ADDR described by T to the buffer.
  4448. * AS_VTYPE determines whenever to treat primitive types as primitive types or
  4449. * vtypes.
  4450. */
  4451. static void
  4452. buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
  4453. gboolean as_vtype)
  4454. {
  4455. MonoObject *obj;
  4456. if (t->byref) {
  4457. if (!(*(void**)addr))
  4458. printf ("%s\n", mono_type_full_name (t));
  4459. g_assert (*(void**)addr);
  4460. addr = *(void**)addr;
  4461. }
  4462. if (as_vtype) {
  4463. switch (t->type) {
  4464. case MONO_TYPE_BOOLEAN:
  4465. case MONO_TYPE_I1:
  4466. case MONO_TYPE_U1:
  4467. case MONO_TYPE_CHAR:
  4468. case MONO_TYPE_I2:
  4469. case MONO_TYPE_U2:
  4470. case MONO_TYPE_I4:
  4471. case MONO_TYPE_U4:
  4472. case MONO_TYPE_R4:
  4473. case MONO_TYPE_I8:
  4474. case MONO_TYPE_U8:
  4475. case MONO_TYPE_R8:
  4476. case MONO_TYPE_I:
  4477. case MONO_TYPE_U:
  4478. case MONO_TYPE_PTR:
  4479. goto handle_vtype;
  4480. break;
  4481. default:
  4482. break;
  4483. }
  4484. }
  4485. switch (t->type) {
  4486. case MONO_TYPE_VOID:
  4487. buffer_add_byte (buf, t->type);
  4488. break;
  4489. case MONO_TYPE_BOOLEAN:
  4490. case MONO_TYPE_I1:
  4491. case MONO_TYPE_U1:
  4492. buffer_add_byte (buf, t->type);
  4493. buffer_add_int (buf, *(gint8*)addr);
  4494. break;
  4495. case MONO_TYPE_CHAR:
  4496. case MONO_TYPE_I2:
  4497. case MONO_TYPE_U2:
  4498. buffer_add_byte (buf, t->type);
  4499. buffer_add_int (buf, *(gint16*)addr);
  4500. break;
  4501. case MONO_TYPE_I4:
  4502. case MONO_TYPE_U4:
  4503. case MONO_TYPE_R4:
  4504. buffer_add_byte (buf, t->type);
  4505. buffer_add_int (buf, *(gint32*)addr);
  4506. break;
  4507. case MONO_TYPE_I8:
  4508. case MONO_TYPE_U8:
  4509. case MONO_TYPE_R8:
  4510. buffer_add_byte (buf, t->type);
  4511. buffer_add_long (buf, *(gint64*)addr);
  4512. break;
  4513. case MONO_TYPE_I:
  4514. case MONO_TYPE_U:
  4515. /* Treat it as a vtype */
  4516. goto handle_vtype;
  4517. case MONO_TYPE_PTR: {
  4518. gssize val = *(gssize*)addr;
  4519. buffer_add_byte (buf, t->type);
  4520. buffer_add_long (buf, val);
  4521. break;
  4522. }
  4523. handle_ref:
  4524. case MONO_TYPE_STRING:
  4525. case MONO_TYPE_SZARRAY:
  4526. case MONO_TYPE_OBJECT:
  4527. case MONO_TYPE_CLASS:
  4528. case MONO_TYPE_ARRAY:
  4529. obj = *(MonoObject**)addr;
  4530. if (!obj) {
  4531. buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
  4532. } else {
  4533. if (obj->vtable->klass->valuetype) {
  4534. t = &obj->vtable->klass->byval_arg;
  4535. addr = mono_object_unbox (obj);
  4536. goto handle_vtype;
  4537. } else if (obj->vtable->klass->rank) {
  4538. buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
  4539. } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
  4540. buffer_add_byte (buf, MONO_TYPE_CLASS);
  4541. } else {
  4542. buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
  4543. }
  4544. buffer_add_objid (buf, obj);
  4545. }
  4546. break;
  4547. handle_vtype:
  4548. case MONO_TYPE_VALUETYPE: {
  4549. int nfields;
  4550. gpointer iter;
  4551. MonoClassField *f;
  4552. MonoClass *klass = mono_class_from_mono_type (t);
  4553. buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
  4554. buffer_add_byte (buf, klass->enumtype);
  4555. buffer_add_typeid (buf, domain, klass);
  4556. nfields = 0;
  4557. iter = NULL;
  4558. while ((f = mono_class_get_fields (klass, &iter))) {
  4559. if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
  4560. continue;
  4561. if (mono_field_is_deleted (f))
  4562. continue;
  4563. nfields ++;
  4564. }
  4565. buffer_add_int (buf, nfields);
  4566. iter = NULL;
  4567. while ((f = mono_class_get_fields (klass, &iter))) {
  4568. if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
  4569. continue;
  4570. if (mono_field_is_deleted (f))
  4571. continue;
  4572. buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
  4573. }
  4574. break;
  4575. }
  4576. case MONO_TYPE_GENERICINST:
  4577. if (mono_type_generic_inst_is_valuetype (t)) {
  4578. goto handle_vtype;
  4579. } else {
  4580. goto handle_ref;
  4581. }
  4582. break;
  4583. default:
  4584. NOT_IMPLEMENTED;
  4585. }
  4586. }
  4587. static void
  4588. buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
  4589. {
  4590. buffer_add_value_full (buf, t, addr, domain, FALSE);
  4591. }
  4592. static gboolean
  4593. obj_is_of_type (MonoObject *obj, MonoType *t)
  4594. {
  4595. MonoClass *klass = obj->vtable->klass;
  4596. if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
  4597. if (mono_class_is_transparent_proxy (klass)) {
  4598. klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
  4599. if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
  4600. return TRUE;
  4601. }
  4602. }
  4603. return FALSE;
  4604. }
  4605. return TRUE;
  4606. }
  4607. static ErrorCode
  4608. decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
  4609. static ErrorCode
  4610. decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
  4611. {
  4612. int err;
  4613. if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
  4614. !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
  4615. !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
  4616. !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
  4617. !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
  4618. char *name = mono_type_full_name (t);
  4619. DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
  4620. g_free (name);
  4621. return ERR_INVALID_ARGUMENT;
  4622. }
  4623. switch (t->type) {
  4624. case MONO_TYPE_BOOLEAN:
  4625. *(guint8*)addr = decode_int (buf, &buf, limit);
  4626. break;
  4627. case MONO_TYPE_CHAR:
  4628. *(gunichar2*)addr = decode_int (buf, &buf, limit);
  4629. break;
  4630. case MONO_TYPE_I1:
  4631. *(gint8*)addr = decode_int (buf, &buf, limit);
  4632. break;
  4633. case MONO_TYPE_U1:
  4634. *(guint8*)addr = decode_int (buf, &buf, limit);
  4635. break;
  4636. case MONO_TYPE_I2:
  4637. *(gint16*)addr = decode_int (buf, &buf, limit);
  4638. break;
  4639. case MONO_TYPE_U2:
  4640. *(guint16*)addr = decode_int (buf, &buf, limit);
  4641. break;
  4642. case MONO_TYPE_I4:
  4643. *(gint32*)addr = decode_int (buf, &buf, limit);
  4644. break;
  4645. case MONO_TYPE_U4:
  4646. *(guint32*)addr = decode_int (buf, &buf, limit);
  4647. break;
  4648. case MONO_TYPE_I8:
  4649. *(gint64*)addr = decode_long (buf, &buf, limit);
  4650. break;
  4651. case MONO_TYPE_U8:
  4652. *(guint64*)addr = decode_long (buf, &buf, limit);
  4653. break;
  4654. case MONO_TYPE_R4:
  4655. *(guint32*)addr = decode_int (buf, &buf, limit);
  4656. break;
  4657. case MONO_TYPE_R8:
  4658. *(guint64*)addr = decode_long (buf, &buf, limit);
  4659. break;
  4660. case MONO_TYPE_PTR:
  4661. /* We send these as I8, so we get them back as such */
  4662. g_assert (type == MONO_TYPE_I8);
  4663. *(gssize*)addr = decode_long (buf, &buf, limit);
  4664. break;
  4665. case MONO_TYPE_GENERICINST:
  4666. if (MONO_TYPE_ISSTRUCT (t)) {
  4667. /* The client sends these as a valuetype */
  4668. goto handle_vtype;
  4669. } else {
  4670. goto handle_ref;
  4671. }
  4672. break;
  4673. case MONO_TYPE_I:
  4674. case MONO_TYPE_U:
  4675. /* We send these as vtypes, so we get them back as such */
  4676. g_assert (type == MONO_TYPE_VALUETYPE);
  4677. /* Fall through */
  4678. handle_vtype:
  4679. case MONO_TYPE_VALUETYPE: {
  4680. gboolean is_enum = decode_byte (buf, &buf, limit);
  4681. MonoClass *klass;
  4682. MonoClassField *f;
  4683. int nfields;
  4684. gpointer iter = NULL;
  4685. MonoDomain *d;
  4686. /* Enums are sent as a normal vtype */
  4687. if (is_enum)
  4688. return ERR_NOT_IMPLEMENTED;
  4689. klass = decode_typeid (buf, &buf, limit, &d, &err);
  4690. if (err)
  4691. return err;
  4692. if (klass != mono_class_from_mono_type (t))
  4693. return ERR_INVALID_ARGUMENT;
  4694. nfields = decode_int (buf, &buf, limit);
  4695. while ((f = mono_class_get_fields (klass, &iter))) {
  4696. if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
  4697. continue;
  4698. if (mono_field_is_deleted (f))
  4699. continue;
  4700. err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
  4701. if (err)
  4702. return err;
  4703. nfields --;
  4704. }
  4705. g_assert (nfields == 0);
  4706. break;
  4707. }
  4708. handle_ref:
  4709. default:
  4710. if (MONO_TYPE_IS_REFERENCE (t)) {
  4711. if (type == MONO_TYPE_OBJECT) {
  4712. int objid = decode_objid (buf, &buf, limit);
  4713. int err;
  4714. MonoObject *obj;
  4715. err = get_object (objid, (MonoObject**)&obj);
  4716. if (err)
  4717. return err;
  4718. if (obj) {
  4719. if (!obj_is_of_type (obj, t)) {
  4720. DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
  4721. return ERR_INVALID_ARGUMENT;
  4722. }
  4723. }
  4724. if (obj && obj->vtable->domain != domain)
  4725. return ERR_INVALID_ARGUMENT;
  4726. mono_gc_wbarrier_generic_store (addr, obj);
  4727. } else if (type == VALUE_TYPE_ID_NULL) {
  4728. *(MonoObject**)addr = NULL;
  4729. } else {
  4730. return ERR_INVALID_ARGUMENT;
  4731. }
  4732. } else {
  4733. NOT_IMPLEMENTED;
  4734. }
  4735. break;
  4736. }
  4737. *endbuf = buf;
  4738. return 0;
  4739. }
  4740. static ErrorCode
  4741. decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
  4742. {
  4743. int err;
  4744. int type = decode_byte (buf, &buf, limit);
  4745. if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
  4746. MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
  4747. guint8 *nullable_buf;
  4748. /*
  4749. * First try decoding it as a Nullable`1
  4750. */
  4751. err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
  4752. if (!err)
  4753. return err;
  4754. /*
  4755. * Then try decoding as a primitive value or null.
  4756. */
  4757. if (targ->type == type) {
  4758. nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
  4759. err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
  4760. if (err) {
  4761. g_free (nullable_buf);
  4762. return err;
  4763. }
  4764. mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
  4765. g_free (nullable_buf);
  4766. *endbuf = buf;
  4767. return ERR_NONE;
  4768. } else if (type == VALUE_TYPE_ID_NULL) {
  4769. mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
  4770. *endbuf = buf;
  4771. return ERR_NONE;
  4772. }
  4773. }
  4774. return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
  4775. }
  4776. static void
  4777. add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
  4778. {
  4779. guint32 flags;
  4780. int reg;
  4781. guint8 *addr;
  4782. mgreg_t reg_val;
  4783. flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
  4784. reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
  4785. switch (flags) {
  4786. case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
  4787. reg_val = mono_arch_context_get_int_reg (ctx, reg);
  4788. buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
  4789. break;
  4790. case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
  4791. addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
  4792. addr += (gint32)var->offset;
  4793. //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
  4794. buffer_add_value_full (buf, t, addr, domain, as_vtype);
  4795. break;
  4796. case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
  4797. NOT_IMPLEMENTED;
  4798. break;
  4799. default:
  4800. g_assert_not_reached ();
  4801. }
  4802. }
  4803. static void
  4804. set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
  4805. {
  4806. guint32 flags;
  4807. int reg, size;
  4808. guint8 *addr;
  4809. flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
  4810. reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
  4811. if (MONO_TYPE_IS_REFERENCE (t))
  4812. size = sizeof (gpointer);
  4813. else
  4814. size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
  4815. switch (flags) {
  4816. case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
  4817. #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
  4818. mgreg_t v;
  4819. gboolean is_signed = FALSE;
  4820. if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
  4821. is_signed = TRUE;
  4822. switch (size) {
  4823. case 1:
  4824. v = is_signed ? *(gint8*)val : *(guint8*)val;
  4825. break;
  4826. case 2:
  4827. v = is_signed ? *(gint16*)val : *(guint16*)val;
  4828. break;
  4829. case 4:
  4830. v = is_signed ? *(gint32*)val : *(guint32*)val;
  4831. break;
  4832. case 8:
  4833. v = is_signed ? *(gint64*)val : *(guint64*)val;
  4834. break;
  4835. default:
  4836. g_assert_not_reached ();
  4837. }
  4838. if (t->byref)
  4839. NOT_IMPLEMENTED;
  4840. /* Set value on the stack or in the return ctx */
  4841. if (reg_locations [reg]) {
  4842. /* Saved on the stack */
  4843. DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
  4844. *(reg_locations [reg]) = v;
  4845. } else {
  4846. /* Not saved yet */
  4847. DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
  4848. mono_arch_context_set_int_reg (restore_ctx, reg, v);
  4849. }
  4850. // FIXME: Move these to mono-context.h/c.
  4851. mono_arch_context_set_int_reg (ctx, reg, v);
  4852. #else
  4853. // FIXME: Can't set registers, so we disable linears
  4854. NOT_IMPLEMENTED;
  4855. #endif
  4856. break;
  4857. }
  4858. case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
  4859. addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
  4860. addr += (gint32)var->offset;
  4861. //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
  4862. if (t->byref) {
  4863. addr = *(guint8**)addr;
  4864. if (!addr)
  4865. break;
  4866. }
  4867. // FIXME: Write barriers
  4868. mono_gc_memmove (addr, val, size);
  4869. break;
  4870. case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
  4871. NOT_IMPLEMENTED;
  4872. break;
  4873. default:
  4874. g_assert_not_reached ();
  4875. }
  4876. }
  4877. static void
  4878. clear_event_request (int req_id, int etype)
  4879. {
  4880. int i;
  4881. mono_loader_lock ();
  4882. for (i = 0; i < event_requests->len; ++i) {
  4883. EventRequest *req = g_ptr_array_index (event_requests, i);
  4884. if (req->id == req_id && req->event_kind == etype) {
  4885. if (req->event_kind == EVENT_KIND_BREAKPOINT)
  4886. clear_breakpoint (req->info);
  4887. if (req->event_kind == EVENT_KIND_STEP)
  4888. ss_destroy (req->info);
  4889. if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
  4890. clear_breakpoint (req->info);
  4891. if (req->event_kind == EVENT_KIND_METHOD_EXIT)
  4892. clear_breakpoint (req->info);
  4893. g_ptr_array_remove_index_fast (event_requests, i);
  4894. g_free (req);
  4895. break;
  4896. }
  4897. }
  4898. mono_loader_unlock ();
  4899. }
  4900. static gboolean
  4901. event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
  4902. {
  4903. if (req->event_kind == EVENT_KIND_BREAKPOINT)
  4904. return breakpoint_matches_assembly (req->info, assembly);
  4905. else {
  4906. int i, j;
  4907. for (i = 0; i < req->nmodifiers; ++i) {
  4908. Modifier *m = &req->modifiers [i];
  4909. if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
  4910. return TRUE;
  4911. if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
  4912. for (j = 0; m->data.assemblies [j]; ++j)
  4913. if (m->data.assemblies [j] == assembly)
  4914. return TRUE;
  4915. }
  4916. }
  4917. }
  4918. return FALSE;
  4919. }
  4920. /*
  4921. * clear_event_requests_for_assembly:
  4922. *
  4923. * Clear all events requests which reference ASSEMBLY.
  4924. */
  4925. static void
  4926. clear_event_requests_for_assembly (MonoAssembly *assembly)
  4927. {
  4928. int i;
  4929. gboolean found;
  4930. mono_loader_lock ();
  4931. found = TRUE;
  4932. while (found) {
  4933. found = FALSE;
  4934. for (i = 0; i < event_requests->len; ++i) {
  4935. EventRequest *req = g_ptr_array_index (event_requests, i);
  4936. if (event_req_matches_assembly (req, assembly)) {
  4937. clear_event_request (req->id, req->event_kind);
  4938. found = TRUE;
  4939. break;
  4940. }
  4941. }
  4942. }
  4943. mono_loader_unlock ();
  4944. }
  4945. /*
  4946. * type_comes_from_assembly:
  4947. *
  4948. * GHRFunc that returns TRUE if klass comes from assembly
  4949. */
  4950. static gboolean
  4951. type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
  4952. {
  4953. return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
  4954. }
  4955. /*
  4956. * clear_types_for_assembly:
  4957. *
  4958. * Clears types from loaded_classes for a given assembly
  4959. */
  4960. static void
  4961. clear_types_for_assembly (MonoAssembly *assembly)
  4962. {
  4963. MonoDomain *domain = mono_domain_get ();
  4964. AgentDomainInfo *info = NULL;
  4965. mono_loader_lock ();
  4966. info = get_agent_domain_info (domain);
  4967. g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
  4968. mono_loader_unlock ();
  4969. }
  4970. static void
  4971. add_thread (gpointer key, gpointer value, gpointer user_data)
  4972. {
  4973. MonoInternalThread *thread = value;
  4974. Buffer *buf = user_data;
  4975. buffer_add_objid (buf, (MonoObject*)thread);
  4976. }
  4977. static ErrorCode
  4978. do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
  4979. {
  4980. guint8 *end = invoke->endp;
  4981. MonoMethod *m;
  4982. int i, err, nargs;
  4983. MonoMethodSignature *sig;
  4984. guint8 **arg_buf;
  4985. void **args;
  4986. MonoObject *this, *res, *exc;
  4987. MonoDomain *domain;
  4988. guint8 *this_buf;
  4989. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  4990. MonoLMFExt ext;
  4991. #endif
  4992. MonoStopwatch watch;
  4993. if (invoke->method) {
  4994. /*
  4995. * Invoke this method directly, currently only Environment.Exit () is supported.
  4996. */
  4997. this = NULL;
  4998. DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
  4999. mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
  5000. g_assert_not_reached ();
  5001. }
  5002. m = decode_methodid (p, &p, end, &domain, &err);
  5003. if (err)
  5004. return err;
  5005. sig = mono_method_signature (m);
  5006. if (m->klass->valuetype)
  5007. this_buf = g_alloca (mono_class_instance_size (m->klass));
  5008. else
  5009. this_buf = g_alloca (sizeof (MonoObject*));
  5010. if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
  5011. /* Should be null */
  5012. int type = decode_byte (p, &p, end);
  5013. if (type != VALUE_TYPE_ID_NULL)
  5014. return ERR_INVALID_ARGUMENT;
  5015. memset (this_buf, 0, mono_class_instance_size (m->klass));
  5016. } else {
  5017. err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
  5018. if (err)
  5019. return err;
  5020. }
  5021. if (!m->klass->valuetype)
  5022. this = *(MonoObject**)this_buf;
  5023. else
  5024. this = NULL;
  5025. DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
  5026. if (this && this->vtable->domain != domain)
  5027. NOT_IMPLEMENTED;
  5028. if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
  5029. if (!strcmp (m->name, ".ctor")) {
  5030. if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
  5031. return ERR_INVALID_ARGUMENT;
  5032. else
  5033. this = mono_object_new (domain, m->klass);
  5034. } else {
  5035. return ERR_INVALID_ARGUMENT;
  5036. }
  5037. }
  5038. if (this && !obj_is_of_type (this, &m->klass->byval_arg))
  5039. return ERR_INVALID_ARGUMENT;
  5040. nargs = decode_int (p, &p, end);
  5041. if (nargs != sig->param_count)
  5042. return ERR_INVALID_ARGUMENT;
  5043. /* Use alloca to get gc tracking */
  5044. arg_buf = g_alloca (nargs * sizeof (gpointer));
  5045. memset (arg_buf, 0, nargs * sizeof (gpointer));
  5046. args = g_alloca (nargs * sizeof (gpointer));
  5047. for (i = 0; i < nargs; ++i) {
  5048. if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
  5049. err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
  5050. if (err)
  5051. break;
  5052. if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
  5053. NOT_IMPLEMENTED;
  5054. } else {
  5055. arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
  5056. err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
  5057. if (err)
  5058. break;
  5059. args [i] = arg_buf [i];
  5060. }
  5061. }
  5062. if (i < nargs)
  5063. return err;
  5064. if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
  5065. tls->disable_breakpoints = TRUE;
  5066. else
  5067. tls->disable_breakpoints = FALSE;
  5068. /*
  5069. * Add an LMF frame to link the stack frames on the invoke method with our caller.
  5070. */
  5071. /* FIXME: Move this to arch specific code */
  5072. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  5073. if (invoke->has_ctx) {
  5074. MonoLMF **lmf_addr;
  5075. lmf_addr = mono_get_lmf_addr ();
  5076. /* Setup our lmf */
  5077. memset (&ext, 0, sizeof (ext));
  5078. #ifdef TARGET_AMD64
  5079. ext.lmf.previous_lmf = *(lmf_addr);
  5080. /* Mark that this is a MonoLMFExt */
  5081. ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
  5082. ext.lmf.rsp = (gssize)&ext;
  5083. #elif defined(TARGET_X86)
  5084. ext.lmf.previous_lmf = (gsize)*(lmf_addr);
  5085. /* Mark that this is a MonoLMFExt */
  5086. ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
  5087. ext.lmf.ebp = (gssize)&ext;
  5088. #elif defined(TARGET_ARM)
  5089. ext.lmf.previous_lmf = *(lmf_addr);
  5090. /* Mark that this is a MonoLMFExt */
  5091. ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
  5092. ext.lmf.sp = (gssize)&ext;
  5093. #elif defined(TARGET_POWERPC)
  5094. ext.lmf.previous_lmf = *(lmf_addr);
  5095. /* Mark that this is a MonoLMFExt */
  5096. ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
  5097. ext.lmf.ebp = (gssize)&ext;
  5098. #elif defined(TARGET_S390X)
  5099. ext.lmf.previous_lmf = *(lmf_addr);
  5100. /* Mark that this is a MonoLMFExt */
  5101. ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
  5102. ext.lmf.ebp = (gssize)&ext;
  5103. #elif defined(TARGET_MIPS)
  5104. ext.lmf.previous_lmf = *(lmf_addr);
  5105. /* Mark that this is a MonoLMFExt */
  5106. ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
  5107. ext.lmf.iregs [mips_sp] = (gssize)&ext;
  5108. #else
  5109. g_assert_not_reached ();
  5110. #endif
  5111. ext.debugger_invoke = TRUE;
  5112. memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
  5113. mono_set_lmf ((MonoLMF*)&ext);
  5114. }
  5115. #endif
  5116. mono_stopwatch_start (&watch);
  5117. if (m->klass->valuetype)
  5118. res = mono_runtime_invoke (m, this_buf, args, &exc);
  5119. else
  5120. res = mono_runtime_invoke (m, this, args, &exc);
  5121. mono_stopwatch_stop (&watch);
  5122. DEBUG (1, fprintf (log_file, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch)));
  5123. if (exc) {
  5124. buffer_add_byte (buf, 0);
  5125. buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
  5126. } else {
  5127. buffer_add_byte (buf, 1);
  5128. if (sig->ret->type == MONO_TYPE_VOID) {
  5129. if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
  5130. buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
  5131. }
  5132. else
  5133. buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
  5134. } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
  5135. buffer_add_value (buf, sig->ret, &res, domain);
  5136. } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
  5137. if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
  5138. MonoClass *k = mono_class_from_mono_type (sig->ret);
  5139. guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
  5140. g_assert (nullable_buf);
  5141. mono_nullable_init (nullable_buf, res, k);
  5142. buffer_add_value (buf, sig->ret, nullable_buf, domain);
  5143. } else {
  5144. g_assert (res);
  5145. buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
  5146. }
  5147. } else {
  5148. NOT_IMPLEMENTED;
  5149. }
  5150. }
  5151. tls->disable_breakpoints = FALSE;
  5152. #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
  5153. if (invoke->has_ctx)
  5154. mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
  5155. #endif
  5156. *endp = p;
  5157. // FIXME: byref arguments
  5158. // FIXME: varargs
  5159. return ERR_NONE;
  5160. }
  5161. /*
  5162. * invoke_method:
  5163. *
  5164. * Invoke the method given by tls->pending_invoke in the current thread.
  5165. */
  5166. static void
  5167. invoke_method (void)
  5168. {
  5169. DebuggerTlsData *tls;
  5170. InvokeData *invoke;
  5171. int id;
  5172. int i, err, mindex;
  5173. Buffer buf;
  5174. static void (*restore_context) (void *);
  5175. MonoContext restore_ctx;
  5176. guint8 *p;
  5177. if (!restore_context)
  5178. restore_context = mono_get_restore_context ();
  5179. tls = mono_native_tls_get_value (debugger_tls_id);
  5180. g_assert (tls);
  5181. /*
  5182. * Store the `InvokeData *' in `tls->invoke' until we're done with
  5183. * the invocation, so CMD_VM_ABORT_INVOKE can check it.
  5184. */
  5185. mono_loader_lock ();
  5186. invoke = tls->pending_invoke;
  5187. g_assert (invoke);
  5188. tls->pending_invoke = NULL;
  5189. invoke->last_invoke = tls->invoke;
  5190. tls->invoke = invoke;
  5191. mono_loader_unlock ();
  5192. tls->frames_up_to_date = FALSE;
  5193. id = invoke->id;
  5194. p = invoke->p;
  5195. err = 0;
  5196. for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
  5197. buffer_init (&buf, 128);
  5198. if (err) {
  5199. /* Fail the other invokes as well */
  5200. } else {
  5201. err = do_invoke_method (tls, &buf, invoke, p, &p);
  5202. }
  5203. /* Start suspending before sending the reply */
  5204. if (mindex == invoke->nmethods - 1) {
  5205. if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
  5206. for (i = 0; i < invoke->suspend_count; ++i)
  5207. suspend_vm ();
  5208. }
  5209. }
  5210. send_reply_packet (id, err, &buf);
  5211. buffer_free (&buf);
  5212. }
  5213. memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
  5214. if (invoke->has_ctx)
  5215. save_thread_context (&restore_ctx);
  5216. if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
  5217. g_assert (tls->resume_count);
  5218. tls->resume_count -= invoke->suspend_count;
  5219. }
  5220. DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
  5221. /*
  5222. * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
  5223. *
  5224. * It is possible that ves_icall_System_Threading_Thread_Abort () was called
  5225. * after the mono_runtime_invoke() already returned, but it doesn't matter
  5226. * because we reset the abort here.
  5227. */
  5228. mono_loader_lock ();
  5229. if (tls->abort_requested)
  5230. mono_thread_internal_reset_abort (tls->thread);
  5231. tls->invoke = tls->invoke->last_invoke;
  5232. tls->abort_requested = FALSE;
  5233. mono_loader_unlock ();
  5234. g_free (invoke->p);
  5235. g_free (invoke);
  5236. suspend_current ();
  5237. }
  5238. static gboolean
  5239. is_really_suspended (gpointer key, gpointer value, gpointer user_data)
  5240. {
  5241. MonoThread *thread = value;
  5242. DebuggerTlsData *tls;
  5243. gboolean res;
  5244. mono_loader_lock ();
  5245. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  5246. g_assert (tls);
  5247. res = tls->really_suspended;
  5248. mono_loader_unlock ();
  5249. return res;
  5250. }
  5251. static GPtrArray*
  5252. get_source_files_for_type (MonoClass *klass)
  5253. {
  5254. gpointer iter = NULL;
  5255. MonoMethod *method;
  5256. MonoDebugSourceInfo *sinfo;
  5257. GPtrArray *files;
  5258. int i, j;
  5259. files = g_ptr_array_new ();
  5260. while ((method = mono_class_get_methods (klass, &iter))) {
  5261. MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
  5262. GPtrArray *source_file_list;
  5263. if (minfo) {
  5264. mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
  5265. for (j = 0; j < source_file_list->len; ++j) {
  5266. sinfo = g_ptr_array_index (source_file_list, j);
  5267. for (i = 0; i < files->len; ++i)
  5268. if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
  5269. break;
  5270. if (i == files->len)
  5271. g_ptr_array_add (files, g_strdup (sinfo->source_file));
  5272. }
  5273. g_ptr_array_free (source_file_list, TRUE);
  5274. }
  5275. }
  5276. return files;
  5277. }
  5278. static ErrorCode
  5279. vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
  5280. {
  5281. switch (command) {
  5282. case CMD_VM_VERSION: {
  5283. char *build_info, *version;
  5284. build_info = mono_get_runtime_build_info ();
  5285. version = g_strdup_printf ("mono %s", build_info);
  5286. buffer_add_string (buf, version); /* vm version */
  5287. buffer_add_int (buf, MAJOR_VERSION);
  5288. buffer_add_int (buf, MINOR_VERSION);
  5289. g_free (build_info);
  5290. g_free (version);
  5291. break;
  5292. }
  5293. case CMD_VM_SET_PROTOCOL_VERSION: {
  5294. major_version = decode_int (p, &p, end);
  5295. minor_version = decode_int (p, &p, end);
  5296. protocol_version_set = TRUE;
  5297. DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
  5298. break;
  5299. }
  5300. case CMD_VM_ALL_THREADS: {
  5301. // FIXME: Domains
  5302. mono_loader_lock ();
  5303. buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
  5304. mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
  5305. mono_loader_unlock ();
  5306. break;
  5307. }
  5308. case CMD_VM_SUSPEND:
  5309. suspend_vm ();
  5310. wait_for_suspend ();
  5311. break;
  5312. case CMD_VM_RESUME:
  5313. if (suspend_count == 0)
  5314. return ERR_NOT_SUSPENDED;
  5315. resume_vm ();
  5316. clear_suspended_objs ();
  5317. break;
  5318. case CMD_VM_DISPOSE:
  5319. /* Clear all event requests */
  5320. mono_loader_lock ();
  5321. while (event_requests->len > 0) {
  5322. EventRequest *req = g_ptr_array_index (event_requests, 0);
  5323. clear_event_request (req->id, req->event_kind);
  5324. }
  5325. mono_loader_unlock ();
  5326. while (suspend_count > 0)
  5327. resume_vm ();
  5328. disconnected = TRUE;
  5329. vm_start_event_sent = FALSE;
  5330. break;
  5331. case CMD_VM_EXIT: {
  5332. MonoInternalThread *thread;
  5333. DebuggerTlsData *tls;
  5334. MonoClass *env_class;
  5335. MonoMethod *exit_method = NULL;
  5336. gpointer *args;
  5337. int exit_code;
  5338. exit_code = decode_int (p, &p, end);
  5339. // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
  5340. /* Have to send a reply before exiting */
  5341. send_reply_packet (id, 0, buf);
  5342. /* Clear all event requests */
  5343. mono_loader_lock ();
  5344. while (event_requests->len > 0) {
  5345. EventRequest *req = g_ptr_array_index (event_requests, 0);
  5346. clear_event_request (req->id, req->event_kind);
  5347. }
  5348. mono_loader_unlock ();
  5349. /*
  5350. * The JDWP documentation says that the shutdown is not orderly. It doesn't
  5351. * specify whenever a VM_DEATH event is sent. We currently do an orderly
  5352. * shutdown by hijacking a thread to execute Environment.Exit (). This is
  5353. * better than doing the shutdown ourselves, since it avoids various races.
  5354. */
  5355. suspend_vm ();
  5356. wait_for_suspend ();
  5357. #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
  5358. env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
  5359. if (env_class)
  5360. exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
  5361. #endif
  5362. mono_loader_lock ();
  5363. thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
  5364. mono_loader_unlock ();
  5365. if (thread && exit_method) {
  5366. mono_loader_lock ();
  5367. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  5368. mono_loader_unlock ();
  5369. args = g_new0 (gpointer, 1);
  5370. args [0] = g_malloc (sizeof (int));
  5371. *(int*)(args [0]) = exit_code;
  5372. tls->pending_invoke = g_new0 (InvokeData, 1);
  5373. tls->pending_invoke->method = exit_method;
  5374. tls->pending_invoke->args = args;
  5375. tls->pending_invoke->nmethods = 1;
  5376. while (suspend_count > 0)
  5377. resume_vm ();
  5378. } else {
  5379. /*
  5380. * No thread found, do it ourselves.
  5381. * FIXME: This can race with normal shutdown etc.
  5382. */
  5383. while (suspend_count > 0)
  5384. resume_vm ();
  5385. mono_runtime_set_shutting_down ();
  5386. mono_threads_set_shutting_down ();
  5387. /* Suspend all managed threads since the runtime is going away */
  5388. DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
  5389. mono_thread_suspend_all_other_threads ();
  5390. DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
  5391. mono_runtime_quit ();
  5392. transport_close2 ();
  5393. DEBUG(1, fprintf (log_file, "Exiting...\n"));
  5394. exit (exit_code);
  5395. }
  5396. break;
  5397. }
  5398. case CMD_VM_INVOKE_METHOD:
  5399. case CMD_VM_INVOKE_METHODS: {
  5400. int objid = decode_objid (p, &p, end);
  5401. MonoThread *thread;
  5402. DebuggerTlsData *tls;
  5403. int i, count, err, flags, nmethods;
  5404. err = get_object (objid, (MonoObject**)&thread);
  5405. if (err)
  5406. return err;
  5407. flags = decode_int (p, &p, end);
  5408. if (command == CMD_VM_INVOKE_METHODS)
  5409. nmethods = decode_int (p, &p, end);
  5410. else
  5411. nmethods = 1;
  5412. // Wait for suspending if it already started
  5413. if (suspend_count)
  5414. wait_for_suspend ();
  5415. if (!is_suspended ())
  5416. return ERR_NOT_SUSPENDED;
  5417. mono_loader_lock ();
  5418. tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
  5419. mono_loader_unlock ();
  5420. g_assert (tls);
  5421. if (!tls->really_suspended)
  5422. /* The thread is still running native code, can't do invokes */
  5423. return ERR_NOT_SUSPENDED;
  5424. /*
  5425. * Store the invoke data into tls, the thread will execute it after it is
  5426. * resumed.
  5427. */
  5428. if (tls->pending_invoke)
  5429. return ERR_NOT_SUSPENDED;
  5430. tls->pending_invoke = g_new0 (InvokeData, 1);
  5431. tls->pending_invoke->id = id;
  5432. tls->pending_invoke->flags = flags;
  5433. tls->pending_invoke->p = g_malloc (end - p);
  5434. memcpy (tls->pending_invoke->p, p, end - p);
  5435. tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
  5436. tls->pending_invoke->suspend_count = suspend_count;
  5437. tls->pending_invoke->nmethods = nmethods;
  5438. if (flags & INVOKE_FLAG_SINGLE_THREADED) {
  5439. resume_thread (THREAD_TO_INTERNAL (thread));
  5440. }
  5441. else {
  5442. count = suspend_count;
  5443. for (i = 0; i < count; ++i)
  5444. resume_vm ();
  5445. }
  5446. break;
  5447. }
  5448. case CMD_VM_ABORT_INVOKE: {
  5449. int objid = decode_objid (p, &p, end);
  5450. MonoThread *thread;
  5451. DebuggerTlsData *tls;
  5452. int invoke_id, err;
  5453. err = get_object (objid, (MonoObject**)&thread);
  5454. if (err)
  5455. return err;
  5456. invoke_id = decode_int (p, &p, end);
  5457. mono_loader_lock ();
  5458. tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
  5459. g_assert (tls);
  5460. if (tls->abort_requested) {
  5461. mono_loader_unlock ();
  5462. break;
  5463. }
  5464. /*
  5465. * Check whether we're still inside the mono_runtime_invoke() and that it's
  5466. * actually the correct invocation.
  5467. *
  5468. * Careful, we do not stop the thread that's doing the invocation, so we can't
  5469. * inspect its stack. However, invoke_method() also acquires the loader lock
  5470. * when it's done, so we're safe here.
  5471. *
  5472. */
  5473. if (!tls->invoke || (tls->invoke->id != invoke_id)) {
  5474. mono_loader_unlock ();
  5475. return ERR_NO_INVOCATION;
  5476. }
  5477. tls->abort_requested = TRUE;
  5478. ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
  5479. mono_loader_unlock ();
  5480. break;
  5481. }
  5482. case CMD_VM_SET_KEEPALIVE: {
  5483. int timeout = decode_int (p, &p, end);
  5484. agent_config.keepalive = timeout;
  5485. // FIXME:
  5486. #ifndef DISABLE_SOCKET_TRANSPORT
  5487. set_keepalive ();
  5488. #else
  5489. NOT_IMPLEMENTED;
  5490. #endif
  5491. break;
  5492. }
  5493. case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
  5494. GHashTableIter iter, kiter;
  5495. MonoDomain *domain;
  5496. MonoClass *klass;
  5497. GPtrArray *files;
  5498. int i;
  5499. char *fname, *basename;
  5500. gboolean ignore_case;
  5501. GSList *class_list, *l;
  5502. GPtrArray *res_classes, *res_domains;
  5503. fname = decode_string (p, &p, end);
  5504. ignore_case = decode_byte (p, &p, end);
  5505. basename = g_path_get_basename (fname);
  5506. res_classes = g_ptr_array_new ();
  5507. res_domains = g_ptr_array_new ();
  5508. mono_loader_lock ();
  5509. g_hash_table_iter_init (&iter, domains);
  5510. while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
  5511. AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
  5512. /* Update 'source_file_to_class' cache */
  5513. g_hash_table_iter_init (&kiter, info->loaded_classes);
  5514. while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
  5515. if (!g_hash_table_lookup (info->source_files, klass)) {
  5516. files = get_source_files_for_type (klass);
  5517. g_hash_table_insert (info->source_files, klass, files);
  5518. for (i = 0; i < files->len; ++i) {
  5519. char *s = g_ptr_array_index (files, i);
  5520. char *s2 = g_path_get_basename (s);
  5521. char *s3;
  5522. class_list = g_hash_table_lookup (info->source_file_to_class, s2);
  5523. if (!class_list) {
  5524. class_list = g_slist_prepend (class_list, klass);
  5525. g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
  5526. } else {
  5527. class_list = g_slist_prepend (class_list, klass);
  5528. g_hash_table_insert (info->source_file_to_class, s2, class_list);
  5529. }
  5530. /* The _ignorecase hash contains the lowercase path */
  5531. s3 = strdup_tolower (s2);
  5532. class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
  5533. if (!class_list) {
  5534. class_list = g_slist_prepend (class_list, klass);
  5535. g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
  5536. } else {
  5537. class_list = g_slist_prepend (class_list, klass);
  5538. g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
  5539. }
  5540. g_free (s2);
  5541. g_free (s3);
  5542. }
  5543. }
  5544. }
  5545. if (ignore_case) {
  5546. char *s;
  5547. s = strdup_tolower (basename);
  5548. class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
  5549. g_free (s);
  5550. } else {
  5551. class_list = g_hash_table_lookup (info->source_file_to_class, basename);
  5552. }
  5553. for (l = class_list; l; l = l->next) {
  5554. klass = l->data;
  5555. g_ptr_array_add (res_classes, klass);
  5556. g_ptr_array_add (res_domains, domain);
  5557. }
  5558. }
  5559. mono_loader_unlock ();
  5560. g_free (fname);
  5561. g_free (basename);
  5562. buffer_add_int (buf, res_classes->len);
  5563. for (i = 0; i < res_classes->len; ++i)
  5564. buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
  5565. g_ptr_array_free (res_classes, TRUE);
  5566. g_ptr_array_free (res_domains, TRUE);
  5567. break;
  5568. }
  5569. case CMD_VM_GET_TYPES: {
  5570. GHashTableIter iter;
  5571. MonoDomain *domain;
  5572. int i;
  5573. char *name;
  5574. gboolean ignore_case;
  5575. GPtrArray *res_classes, *res_domains;
  5576. MonoTypeNameParse info;
  5577. name = decode_string (p, &p, end);
  5578. ignore_case = decode_byte (p, &p, end);
  5579. if (!mono_reflection_parse_type (name, &info)) {
  5580. g_free (name);
  5581. mono_reflection_free_type_info (&info);
  5582. return ERR_INVALID_ARGUMENT;
  5583. }
  5584. res_classes = g_ptr_array_new ();
  5585. res_domains = g_ptr_array_new ();
  5586. mono_loader_lock ();
  5587. g_hash_table_iter_init (&iter, domains);
  5588. while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
  5589. MonoAssembly *ass;
  5590. gboolean type_resolve;
  5591. MonoType *t;
  5592. GSList *tmp;
  5593. mono_domain_assemblies_lock (domain);
  5594. for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
  5595. ass = tmp->data;
  5596. if (ass->image) {
  5597. type_resolve = TRUE;
  5598. t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
  5599. if (t) {
  5600. g_ptr_array_add (res_classes, mono_type_get_class (t));
  5601. g_ptr_array_add (res_domains, domain);
  5602. }
  5603. }
  5604. }
  5605. mono_domain_assemblies_unlock (domain);
  5606. }
  5607. mono_loader_unlock ();
  5608. g_free (name);
  5609. mono_reflection_free_type_info (&info);
  5610. buffer_add_int (buf, res_classes->len);
  5611. for (i = 0; i < res_classes->len; ++i)
  5612. buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
  5613. g_ptr_array_free (res_classes, TRUE);
  5614. g_ptr_array_free (res_domains, TRUE);
  5615. break;
  5616. }
  5617. default:
  5618. return ERR_NOT_IMPLEMENTED;
  5619. }
  5620. return ERR_NONE;
  5621. }
  5622. static ErrorCode
  5623. event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  5624. {
  5625. int err;
  5626. MonoError error;
  5627. switch (command) {
  5628. case CMD_EVENT_REQUEST_SET: {
  5629. EventRequest *req;
  5630. int i, event_kind, suspend_policy, nmodifiers, mod;
  5631. MonoMethod *method;
  5632. long location = 0;
  5633. MonoThread *step_thread;
  5634. int size = 0, depth = 0, filter = 0, step_thread_id = 0;
  5635. MonoDomain *domain;
  5636. Modifier *modifier;
  5637. event_kind = decode_byte (p, &p, end);
  5638. suspend_policy = decode_byte (p, &p, end);
  5639. nmodifiers = decode_byte (p, &p, end);
  5640. req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
  5641. req->id = InterlockedIncrement (&event_request_id);
  5642. req->event_kind = event_kind;
  5643. req->suspend_policy = suspend_policy;
  5644. req->nmodifiers = nmodifiers;
  5645. method = NULL;
  5646. for (i = 0; i < nmodifiers; ++i) {
  5647. mod = decode_byte (p, &p, end);
  5648. req->modifiers [i].kind = mod;
  5649. if (mod == MOD_KIND_COUNT) {
  5650. req->modifiers [i].data.count = decode_int (p, &p, end);
  5651. } else if (mod == MOD_KIND_LOCATION_ONLY) {
  5652. method = decode_methodid (p, &p, end, &domain, &err);
  5653. if (err)
  5654. return err;
  5655. location = decode_long (p, &p, end);
  5656. } else if (mod == MOD_KIND_STEP) {
  5657. step_thread_id = decode_id (p, &p, end);
  5658. size = decode_int (p, &p, end);
  5659. depth = decode_int (p, &p, end);
  5660. if (CHECK_PROTOCOL_VERSION (2, 16))
  5661. filter = decode_int (p, &p, end);
  5662. req->modifiers [i].data.filter = filter;
  5663. } else if (mod == MOD_KIND_THREAD_ONLY) {
  5664. int id = decode_id (p, &p, end);
  5665. err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
  5666. if (err) {
  5667. g_free (req);
  5668. return err;
  5669. }
  5670. } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
  5671. MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
  5672. if (err)
  5673. return err;
  5674. req->modifiers [i].caught = decode_byte (p, &p, end);
  5675. req->modifiers [i].uncaught = decode_byte (p, &p, end);
  5676. DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
  5677. if (exc_class) {
  5678. req->modifiers [i].data.exc_class = exc_class;
  5679. if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
  5680. g_free (req);
  5681. return ERR_INVALID_ARGUMENT;
  5682. }
  5683. }
  5684. } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
  5685. int n = decode_int (p, &p, end);
  5686. int j;
  5687. req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
  5688. for (j = 0; j < n; ++j) {
  5689. req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
  5690. if (err) {
  5691. g_free (req->modifiers [i].data.assemblies);
  5692. return err;
  5693. }
  5694. }
  5695. } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
  5696. int n = decode_int (p, &p, end);
  5697. int j;
  5698. modifier = &req->modifiers [i];
  5699. modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
  5700. for (j = 0; j < n; ++j) {
  5701. char *s = decode_string (p, &p, end);
  5702. char *s2;
  5703. if (s) {
  5704. s2 = strdup_tolower (s);
  5705. g_hash_table_insert (modifier->data.source_files, s2, s2);
  5706. g_free (s);
  5707. }
  5708. }
  5709. } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
  5710. int n = decode_int (p, &p, end);
  5711. int j;
  5712. modifier = &req->modifiers [i];
  5713. modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
  5714. for (j = 0; j < n; ++j) {
  5715. char *s = decode_string (p, &p, end);
  5716. if (s)
  5717. g_hash_table_insert (modifier->data.type_names, s, s);
  5718. }
  5719. } else {
  5720. g_free (req);
  5721. return ERR_NOT_IMPLEMENTED;
  5722. }
  5723. }
  5724. if (req->event_kind == EVENT_KIND_BREAKPOINT) {
  5725. g_assert (method);
  5726. req->info = set_breakpoint (method, location, req, &error);
  5727. if (!mono_error_ok (&error)) {
  5728. g_free (req);
  5729. DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
  5730. mono_error_cleanup (&error);
  5731. return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
  5732. }
  5733. } else if (req->event_kind == EVENT_KIND_STEP) {
  5734. g_assert (step_thread_id);
  5735. err = get_object (step_thread_id, (MonoObject**)&step_thread);
  5736. if (err) {
  5737. g_free (req);
  5738. return err;
  5739. }
  5740. err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
  5741. if (err) {
  5742. g_free (req);
  5743. return err;
  5744. }
  5745. } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
  5746. req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
  5747. } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
  5748. req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
  5749. } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
  5750. } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
  5751. } else {
  5752. if (req->nmodifiers) {
  5753. g_free (req);
  5754. return ERR_NOT_IMPLEMENTED;
  5755. }
  5756. }
  5757. mono_loader_lock ();
  5758. g_ptr_array_add (event_requests, req);
  5759. if (agent_config.defer) {
  5760. /* Transmit cached data to the client on receipt of the event request */
  5761. switch (req->event_kind) {
  5762. case EVENT_KIND_APPDOMAIN_CREATE:
  5763. /* Emit load events for currently loaded domains */
  5764. g_hash_table_foreach (domains, emit_appdomain_load, NULL);
  5765. break;
  5766. case EVENT_KIND_ASSEMBLY_LOAD:
  5767. /* Emit load events for currently loaded assemblies */
  5768. mono_assembly_foreach (emit_assembly_load, NULL);
  5769. break;
  5770. case EVENT_KIND_THREAD_START:
  5771. /* Emit start events for currently started threads */
  5772. mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
  5773. break;
  5774. case EVENT_KIND_TYPE_LOAD:
  5775. /* Emit type load events for currently loaded types */
  5776. mono_domain_foreach (send_types_for_domain, NULL);
  5777. break;
  5778. default:
  5779. break;
  5780. }
  5781. }
  5782. mono_loader_unlock ();
  5783. buffer_add_int (buf, req->id);
  5784. break;
  5785. }
  5786. case CMD_EVENT_REQUEST_CLEAR: {
  5787. int etype = decode_byte (p, &p, end);
  5788. int req_id = decode_int (p, &p, end);
  5789. // FIXME: Make a faster mapping from req_id to request
  5790. mono_loader_lock ();
  5791. clear_event_request (req_id, etype);
  5792. mono_loader_unlock ();
  5793. break;
  5794. }
  5795. case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
  5796. int i;
  5797. mono_loader_lock ();
  5798. i = 0;
  5799. while (i < event_requests->len) {
  5800. EventRequest *req = g_ptr_array_index (event_requests, i);
  5801. if (req->event_kind == EVENT_KIND_BREAKPOINT) {
  5802. clear_breakpoint (req->info);
  5803. g_ptr_array_remove_index_fast (event_requests, i);
  5804. g_free (req);
  5805. } else {
  5806. i ++;
  5807. }
  5808. }
  5809. mono_loader_unlock ();
  5810. break;
  5811. }
  5812. default:
  5813. return ERR_NOT_IMPLEMENTED;
  5814. }
  5815. return ERR_NONE;
  5816. }
  5817. static ErrorCode
  5818. domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  5819. {
  5820. int err;
  5821. MonoDomain *domain;
  5822. switch (command) {
  5823. case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
  5824. buffer_add_domainid (buf, mono_get_root_domain ());
  5825. break;
  5826. }
  5827. case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
  5828. domain = decode_domainid (p, &p, end, NULL, &err);
  5829. if (err)
  5830. return err;
  5831. buffer_add_string (buf, domain->friendly_name);
  5832. break;
  5833. }
  5834. case CMD_APPDOMAIN_GET_ASSEMBLIES: {
  5835. GSList *tmp;
  5836. MonoAssembly *ass;
  5837. int count;
  5838. domain = decode_domainid (p, &p, end, NULL, &err);
  5839. if (err)
  5840. return err;
  5841. mono_loader_lock ();
  5842. count = 0;
  5843. for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
  5844. count ++;
  5845. }
  5846. buffer_add_int (buf, count);
  5847. for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
  5848. ass = tmp->data;
  5849. buffer_add_assemblyid (buf, domain, ass);
  5850. }
  5851. mono_loader_unlock ();
  5852. break;
  5853. }
  5854. case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
  5855. domain = decode_domainid (p, &p, end, NULL, &err);
  5856. if (err)
  5857. return err;
  5858. buffer_add_assemblyid (buf, domain, domain->entry_assembly);
  5859. break;
  5860. }
  5861. case CMD_APPDOMAIN_GET_CORLIB: {
  5862. domain = decode_domainid (p, &p, end, NULL, &err);
  5863. if (err)
  5864. return err;
  5865. buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
  5866. break;
  5867. }
  5868. case CMD_APPDOMAIN_CREATE_STRING: {
  5869. char *s;
  5870. MonoString *o;
  5871. domain = decode_domainid (p, &p, end, NULL, &err);
  5872. if (err)
  5873. return err;
  5874. s = decode_string (p, &p, end);
  5875. o = mono_string_new (domain, s);
  5876. buffer_add_objid (buf, (MonoObject*)o);
  5877. break;
  5878. }
  5879. case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
  5880. MonoClass *klass;
  5881. MonoDomain *domain2;
  5882. MonoObject *o;
  5883. domain = decode_domainid (p, &p, end, NULL, &err);
  5884. if (err)
  5885. return err;
  5886. klass = decode_typeid (p, &p, end, &domain2, &err);
  5887. if (err)
  5888. return err;
  5889. // FIXME:
  5890. g_assert (domain == domain2);
  5891. o = mono_object_new (domain, klass);
  5892. err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
  5893. if (err)
  5894. return err;
  5895. buffer_add_objid (buf, o);
  5896. break;
  5897. }
  5898. default:
  5899. return ERR_NOT_IMPLEMENTED;
  5900. }
  5901. return ERR_NONE;
  5902. }
  5903. static ErrorCode
  5904. assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  5905. {
  5906. int err;
  5907. MonoAssembly *ass;
  5908. MonoDomain *domain;
  5909. ass = decode_assemblyid (p, &p, end, &domain, &err);
  5910. if (err)
  5911. return err;
  5912. switch (command) {
  5913. case CMD_ASSEMBLY_GET_LOCATION: {
  5914. buffer_add_string (buf, mono_image_get_filename (ass->image));
  5915. break;
  5916. }
  5917. case CMD_ASSEMBLY_GET_ENTRY_POINT: {
  5918. guint32 token;
  5919. MonoMethod *m;
  5920. if (ass->image->dynamic) {
  5921. buffer_add_id (buf, 0);
  5922. } else {
  5923. token = mono_image_get_entry_point (ass->image);
  5924. if (token == 0) {
  5925. buffer_add_id (buf, 0);
  5926. } else {
  5927. m = mono_get_method (ass->image, token, NULL);
  5928. buffer_add_methodid (buf, domain, m);
  5929. }
  5930. }
  5931. break;
  5932. }
  5933. case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
  5934. buffer_add_moduleid (buf, domain, ass->image);
  5935. break;
  5936. }
  5937. case CMD_ASSEMBLY_GET_OBJECT: {
  5938. MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
  5939. buffer_add_objid (buf, o);
  5940. break;
  5941. }
  5942. case CMD_ASSEMBLY_GET_TYPE: {
  5943. char *s = decode_string (p, &p, end);
  5944. gboolean ignorecase = decode_byte (p, &p, end);
  5945. MonoTypeNameParse info;
  5946. MonoType *t;
  5947. gboolean type_resolve, res;
  5948. MonoDomain *d = mono_domain_get ();
  5949. /* This is needed to be able to find referenced assemblies */
  5950. res = mono_domain_set (domain, FALSE);
  5951. g_assert (res);
  5952. if (!mono_reflection_parse_type (s, &info)) {
  5953. t = NULL;
  5954. } else {
  5955. if (info.assembly.name)
  5956. NOT_IMPLEMENTED;
  5957. t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
  5958. }
  5959. buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
  5960. mono_reflection_free_type_info (&info);
  5961. g_free (s);
  5962. mono_domain_set (d, TRUE);
  5963. break;
  5964. }
  5965. case CMD_ASSEMBLY_GET_NAME: {
  5966. gchar *name;
  5967. MonoAssembly *mass = ass;
  5968. name = g_strdup_printf (
  5969. "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
  5970. mass->aname.name,
  5971. mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
  5972. mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
  5973. mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
  5974. (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
  5975. buffer_add_string (buf, name);
  5976. g_free (name);
  5977. break;
  5978. }
  5979. default:
  5980. return ERR_NOT_IMPLEMENTED;
  5981. }
  5982. return ERR_NONE;
  5983. }
  5984. static ErrorCode
  5985. module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  5986. {
  5987. int err;
  5988. MonoDomain *domain;
  5989. switch (command) {
  5990. case CMD_MODULE_GET_INFO: {
  5991. MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
  5992. char *basename;
  5993. basename = g_path_get_basename (image->name);
  5994. buffer_add_string (buf, basename); // name
  5995. buffer_add_string (buf, image->module_name); // scopename
  5996. buffer_add_string (buf, image->name); // fqname
  5997. buffer_add_string (buf, mono_image_get_guid (image)); // guid
  5998. buffer_add_assemblyid (buf, domain, image->assembly); // assembly
  5999. g_free (basename);
  6000. break;
  6001. }
  6002. default:
  6003. return ERR_NOT_IMPLEMENTED;
  6004. }
  6005. return ERR_NONE;
  6006. }
  6007. static void
  6008. buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
  6009. {
  6010. if (val && val->vtable->klass == mono_defaults.monotype_class) {
  6011. /* Special case these so the client doesn't have to handle Type objects */
  6012. buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
  6013. buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
  6014. } else if (MONO_TYPE_IS_REFERENCE (t))
  6015. buffer_add_value (buf, t, &val, domain);
  6016. else
  6017. buffer_add_value (buf, t, mono_object_unbox (val), domain);
  6018. }
  6019. static void
  6020. buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
  6021. {
  6022. int i, j;
  6023. int nattrs = 0;
  6024. if (!cinfo) {
  6025. buffer_add_int (buf, 0);
  6026. return;
  6027. }
  6028. for (i = 0; i < cinfo->num_attrs; ++i) {
  6029. if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
  6030. nattrs ++;
  6031. }
  6032. buffer_add_int (buf, nattrs);
  6033. for (i = 0; i < cinfo->num_attrs; ++i) {
  6034. MonoCustomAttrEntry *attr = &cinfo->attrs [i];
  6035. if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
  6036. MonoArray *typed_args, *named_args;
  6037. MonoType *t;
  6038. CattrNamedArg *arginfo;
  6039. mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
  6040. buffer_add_methodid (buf, domain, attr->ctor);
  6041. /* Ctor args */
  6042. if (typed_args) {
  6043. buffer_add_int (buf, mono_array_length (typed_args));
  6044. for (j = 0; j < mono_array_length (typed_args); ++j) {
  6045. MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
  6046. t = mono_method_signature (attr->ctor)->params [j];
  6047. buffer_add_cattr_arg (buf, t, domain, val);
  6048. }
  6049. } else {
  6050. buffer_add_int (buf, 0);
  6051. }
  6052. /* Named args */
  6053. if (named_args) {
  6054. buffer_add_int (buf, mono_array_length (named_args));
  6055. for (j = 0; j < mono_array_length (named_args); ++j) {
  6056. MonoObject *val = mono_array_get (named_args, MonoObject*, j);
  6057. if (arginfo [j].prop) {
  6058. buffer_add_byte (buf, 0x54);
  6059. buffer_add_propertyid (buf, domain, arginfo [j].prop);
  6060. } else if (arginfo [j].field) {
  6061. buffer_add_byte (buf, 0x53);
  6062. buffer_add_fieldid (buf, domain, arginfo [j].field);
  6063. } else {
  6064. g_assert_not_reached ();
  6065. }
  6066. buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
  6067. }
  6068. } else {
  6069. buffer_add_int (buf, 0);
  6070. }
  6071. }
  6072. }
  6073. }
  6074. /* FIXME: Code duplication with icall.c */
  6075. static void
  6076. collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
  6077. {
  6078. int i;
  6079. MonoClass *ic;
  6080. mono_class_setup_interfaces (klass, error);
  6081. if (!mono_error_ok (error))
  6082. return;
  6083. for (i = 0; i < klass->interface_count; i++) {
  6084. ic = klass->interfaces [i];
  6085. g_hash_table_insert (ifaces, ic, ic);
  6086. collect_interfaces (ic, ifaces, error);
  6087. if (!mono_error_ok (error))
  6088. return;
  6089. }
  6090. }
  6091. static ErrorCode
  6092. type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
  6093. {
  6094. MonoClass *nested;
  6095. MonoType *type;
  6096. gpointer iter;
  6097. guint8 b;
  6098. int err, nnested;
  6099. char *name;
  6100. switch (command) {
  6101. case CMD_TYPE_GET_INFO: {
  6102. buffer_add_string (buf, klass->name_space);
  6103. buffer_add_string (buf, klass->name);
  6104. // FIXME: byref
  6105. name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
  6106. buffer_add_string (buf, name);
  6107. g_free (name);
  6108. buffer_add_assemblyid (buf, domain, klass->image->assembly);
  6109. buffer_add_moduleid (buf, domain, klass->image);
  6110. buffer_add_typeid (buf, domain, klass->parent);
  6111. if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
  6112. buffer_add_typeid (buf, domain, klass->element_class);
  6113. else
  6114. buffer_add_id (buf, 0);
  6115. buffer_add_int (buf, klass->type_token);
  6116. buffer_add_byte (buf, klass->rank);
  6117. buffer_add_int (buf, klass->flags);
  6118. b = 0;
  6119. type = &klass->byval_arg;
  6120. // FIXME: Can't decide whenever a class represents a byref type
  6121. if (FALSE)
  6122. b |= (1 << 0);
  6123. if (type->type == MONO_TYPE_PTR)
  6124. b |= (1 << 1);
  6125. if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
  6126. b |= (1 << 2);
  6127. if (type->type == MONO_TYPE_VALUETYPE)
  6128. b |= (1 << 3);
  6129. if (klass->enumtype)
  6130. b |= (1 << 4);
  6131. if (klass->generic_container)
  6132. b |= (1 << 5);
  6133. if (klass->generic_container || klass->generic_class)
  6134. b |= (1 << 6);
  6135. buffer_add_byte (buf, b);
  6136. nnested = 0;
  6137. iter = NULL;
  6138. while ((nested = mono_class_get_nested_types (klass, &iter)))
  6139. nnested ++;
  6140. buffer_add_int (buf, nnested);
  6141. iter = NULL;
  6142. while ((nested = mono_class_get_nested_types (klass, &iter)))
  6143. buffer_add_typeid (buf, domain, nested);
  6144. if (CHECK_PROTOCOL_VERSION (2, 12)) {
  6145. if (klass->generic_container)
  6146. buffer_add_typeid (buf, domain, klass);
  6147. else if (klass->generic_class)
  6148. buffer_add_typeid (buf, domain, klass->generic_class->container_class);
  6149. else
  6150. buffer_add_id (buf, 0);
  6151. }
  6152. if (CHECK_PROTOCOL_VERSION (2, 15)) {
  6153. int count, i;
  6154. if (klass->generic_class) {
  6155. MonoGenericInst *inst = klass->generic_class->context.class_inst;
  6156. count = inst->type_argc;
  6157. buffer_add_int (buf, count);
  6158. for (i = 0; i < count; i++)
  6159. buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
  6160. } else if (klass->generic_container) {
  6161. MonoGenericContainer *container = klass->generic_container;
  6162. MonoClass *pklass;
  6163. count = container->type_argc;
  6164. buffer_add_int (buf, count);
  6165. for (i = 0; i < count; i++) {
  6166. pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
  6167. buffer_add_typeid (buf, domain, pklass);
  6168. }
  6169. } else {
  6170. buffer_add_int (buf, 0);
  6171. }
  6172. }
  6173. break;
  6174. }
  6175. case CMD_TYPE_GET_METHODS: {
  6176. int nmethods;
  6177. int i = 0;
  6178. gpointer iter = NULL;
  6179. MonoMethod *m;
  6180. mono_class_setup_methods (klass);
  6181. nmethods = mono_class_num_methods (klass);
  6182. buffer_add_int (buf, nmethods);
  6183. while ((m = mono_class_get_methods (klass, &iter))) {
  6184. buffer_add_methodid (buf, domain, m);
  6185. i ++;
  6186. }
  6187. g_assert (i == nmethods);
  6188. break;
  6189. }
  6190. case CMD_TYPE_GET_FIELDS: {
  6191. int nfields;
  6192. int i = 0;
  6193. gpointer iter = NULL;
  6194. MonoClassField *f;
  6195. nfields = mono_class_num_fields (klass);
  6196. buffer_add_int (buf, nfields);
  6197. while ((f = mono_class_get_fields (klass, &iter))) {
  6198. buffer_add_fieldid (buf, domain, f);
  6199. buffer_add_string (buf, f->name);
  6200. buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
  6201. buffer_add_int (buf, f->type->attrs);
  6202. i ++;
  6203. }
  6204. g_assert (i == nfields);
  6205. break;
  6206. }
  6207. case CMD_TYPE_GET_PROPERTIES: {
  6208. int nprops;
  6209. int i = 0;
  6210. gpointer iter = NULL;
  6211. MonoProperty *p;
  6212. nprops = mono_class_num_properties (klass);
  6213. buffer_add_int (buf, nprops);
  6214. while ((p = mono_class_get_properties (klass, &iter))) {
  6215. buffer_add_propertyid (buf, domain, p);
  6216. buffer_add_string (buf, p->name);
  6217. buffer_add_methodid (buf, domain, p->get);
  6218. buffer_add_methodid (buf, domain, p->set);
  6219. buffer_add_int (buf, p->attrs);
  6220. i ++;
  6221. }
  6222. g_assert (i == nprops);
  6223. break;
  6224. }
  6225. case CMD_TYPE_GET_CATTRS: {
  6226. MonoClass *attr_klass;
  6227. MonoCustomAttrInfo *cinfo;
  6228. attr_klass = decode_typeid (p, &p, end, NULL, &err);
  6229. /* attr_klass can be NULL */
  6230. if (err)
  6231. return err;
  6232. cinfo = mono_custom_attrs_from_class (klass);
  6233. buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
  6234. break;
  6235. }
  6236. case CMD_TYPE_GET_FIELD_CATTRS: {
  6237. MonoClass *attr_klass;
  6238. MonoCustomAttrInfo *cinfo;
  6239. MonoClassField *field;
  6240. field = decode_fieldid (p, &p, end, NULL, &err);
  6241. if (err)
  6242. return err;
  6243. attr_klass = decode_typeid (p, &p, end, NULL, &err);
  6244. if (err)
  6245. return err;
  6246. cinfo = mono_custom_attrs_from_field (klass, field);
  6247. buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
  6248. break;
  6249. }
  6250. case CMD_TYPE_GET_PROPERTY_CATTRS: {
  6251. MonoClass *attr_klass;
  6252. MonoCustomAttrInfo *cinfo;
  6253. MonoProperty *prop;
  6254. prop = decode_propertyid (p, &p, end, NULL, &err);
  6255. if (err)
  6256. return err;
  6257. attr_klass = decode_typeid (p, &p, end, NULL, &err);
  6258. if (err)
  6259. return err;
  6260. cinfo = mono_custom_attrs_from_property (klass, prop);
  6261. buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
  6262. break;
  6263. }
  6264. case CMD_TYPE_GET_VALUES:
  6265. case CMD_TYPE_GET_VALUES_2: {
  6266. guint8 *val;
  6267. MonoClassField *f;
  6268. MonoVTable *vtable;
  6269. MonoClass *k;
  6270. int len, i;
  6271. gboolean found;
  6272. MonoThread *thread_obj;
  6273. MonoInternalThread *thread = NULL;
  6274. guint32 special_static_type;
  6275. if (command == CMD_TYPE_GET_VALUES_2) {
  6276. int objid = decode_objid (p, &p, end);
  6277. int err;
  6278. err = get_object (objid, (MonoObject**)&thread_obj);
  6279. if (err)
  6280. return err;
  6281. thread = THREAD_TO_INTERNAL (thread_obj);
  6282. }
  6283. len = decode_int (p, &p, end);
  6284. for (i = 0; i < len; ++i) {
  6285. f = decode_fieldid (p, &p, end, NULL, &err);
  6286. if (err)
  6287. return err;
  6288. if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
  6289. return ERR_INVALID_FIELDID;
  6290. special_static_type = mono_class_field_get_special_static_type (f);
  6291. if (special_static_type != SPECIAL_STATIC_NONE) {
  6292. if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
  6293. return ERR_INVALID_FIELDID;
  6294. }
  6295. /* Check that the field belongs to the object */
  6296. found = FALSE;
  6297. for (k = klass; k; k = k->parent) {
  6298. if (k == f->parent) {
  6299. found = TRUE;
  6300. break;
  6301. }
  6302. }
  6303. if (!found)
  6304. return ERR_INVALID_FIELDID;
  6305. vtable = mono_class_vtable (domain, f->parent);
  6306. val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
  6307. mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
  6308. buffer_add_value (buf, f->type, val, domain);
  6309. g_free (val);
  6310. }
  6311. break;
  6312. }
  6313. case CMD_TYPE_SET_VALUES: {
  6314. guint8 *val;
  6315. MonoClassField *f;
  6316. MonoVTable *vtable;
  6317. MonoClass *k;
  6318. int len, i;
  6319. gboolean found;
  6320. len = decode_int (p, &p, end);
  6321. for (i = 0; i < len; ++i) {
  6322. f = decode_fieldid (p, &p, end, NULL, &err);
  6323. if (err)
  6324. return err;
  6325. if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
  6326. return ERR_INVALID_FIELDID;
  6327. if (mono_class_field_is_special_static (f))
  6328. return ERR_INVALID_FIELDID;
  6329. /* Check that the field belongs to the object */
  6330. found = FALSE;
  6331. for (k = klass; k; k = k->parent) {
  6332. if (k == f->parent) {
  6333. found = TRUE;
  6334. break;
  6335. }
  6336. }
  6337. if (!found)
  6338. return ERR_INVALID_FIELDID;
  6339. // FIXME: Check for literal/const
  6340. vtable = mono_class_vtable (domain, f->parent);
  6341. val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
  6342. err = decode_value (f->type, domain, val, p, &p, end);
  6343. if (err) {
  6344. g_free (val);
  6345. return err;
  6346. }
  6347. if (MONO_TYPE_IS_REFERENCE (f->type))
  6348. mono_field_static_set_value (vtable, f, *(gpointer*)val);
  6349. else
  6350. mono_field_static_set_value (vtable, f, val);
  6351. g_free (val);
  6352. }
  6353. break;
  6354. }
  6355. case CMD_TYPE_GET_OBJECT: {
  6356. MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
  6357. buffer_add_objid (buf, o);
  6358. break;
  6359. }
  6360. case CMD_TYPE_GET_SOURCE_FILES:
  6361. case CMD_TYPE_GET_SOURCE_FILES_2: {
  6362. char *source_file, *base;
  6363. GPtrArray *files;
  6364. int i;
  6365. files = get_source_files_for_type (klass);
  6366. buffer_add_int (buf, files->len);
  6367. for (i = 0; i < files->len; ++i) {
  6368. source_file = g_ptr_array_index (files, i);
  6369. if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
  6370. buffer_add_string (buf, source_file);
  6371. } else {
  6372. base = g_path_get_basename (source_file);
  6373. buffer_add_string (buf, base);
  6374. g_free (base);
  6375. }
  6376. g_free (source_file);
  6377. }
  6378. g_ptr_array_free (files, TRUE);
  6379. break;
  6380. }
  6381. case CMD_TYPE_IS_ASSIGNABLE_FROM: {
  6382. MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
  6383. if (err)
  6384. return err;
  6385. if (mono_class_is_assignable_from (klass, oklass))
  6386. buffer_add_byte (buf, 1);
  6387. else
  6388. buffer_add_byte (buf, 0);
  6389. break;
  6390. }
  6391. case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
  6392. char *name = decode_string (p, &p, end);
  6393. int i, flags = decode_int (p, &p, end);
  6394. MonoException *ex = NULL;
  6395. GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
  6396. if (!array)
  6397. return ERR_LOADER_ERROR;
  6398. buffer_add_int (buf, array->len);
  6399. for (i = 0; i < array->len; ++i) {
  6400. MonoMethod *method = g_ptr_array_index (array, i);
  6401. buffer_add_methodid (buf, domain, method);
  6402. }
  6403. g_ptr_array_free (array, TRUE);
  6404. g_free (name);
  6405. break;
  6406. }
  6407. case CMD_TYPE_GET_INTERFACES: {
  6408. MonoClass *parent;
  6409. GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
  6410. MonoError error;
  6411. MonoClass *tclass, *iface;
  6412. GHashTableIter iter;
  6413. tclass = klass;
  6414. for (parent = tclass; parent; parent = parent->parent) {
  6415. mono_class_setup_interfaces (parent, &error);
  6416. if (!mono_error_ok (&error))
  6417. return ERR_LOADER_ERROR;
  6418. collect_interfaces (parent, iface_hash, &error);
  6419. if (!mono_error_ok (&error))
  6420. return ERR_LOADER_ERROR;
  6421. }
  6422. buffer_add_int (buf, g_hash_table_size (iface_hash));
  6423. g_hash_table_iter_init (&iter, iface_hash);
  6424. while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
  6425. buffer_add_typeid (buf, domain, iface);
  6426. g_hash_table_destroy (iface_hash);
  6427. break;
  6428. }
  6429. case CMD_TYPE_GET_INTERFACE_MAP: {
  6430. int tindex, ioffset;
  6431. gboolean variance_used;
  6432. MonoClass *iclass;
  6433. int len, nmethods, i;
  6434. gpointer iter;
  6435. MonoMethod *method;
  6436. len = decode_int (p, &p, end);
  6437. mono_class_setup_vtable (klass);
  6438. for (tindex = 0; tindex < len; ++tindex) {
  6439. iclass = decode_typeid (p, &p, end, NULL, &err);
  6440. if (err)
  6441. return err;
  6442. ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
  6443. if (ioffset == -1)
  6444. return ERR_INVALID_ARGUMENT;
  6445. nmethods = mono_class_num_methods (iclass);
  6446. buffer_add_int (buf, nmethods);
  6447. iter = NULL;
  6448. while ((method = mono_class_get_methods (iclass, &iter))) {
  6449. buffer_add_methodid (buf, domain, method);
  6450. }
  6451. for (i = 0; i < nmethods; ++i)
  6452. buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
  6453. }
  6454. break;
  6455. }
  6456. case CMD_TYPE_IS_INITIALIZED: {
  6457. MonoVTable *vtable = mono_class_vtable (domain, klass);
  6458. if (vtable)
  6459. buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
  6460. else
  6461. buffer_add_int (buf, 0);
  6462. break;
  6463. }
  6464. default:
  6465. return ERR_NOT_IMPLEMENTED;
  6466. }
  6467. return ERR_NONE;
  6468. }
  6469. static ErrorCode
  6470. type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  6471. {
  6472. MonoClass *klass;
  6473. MonoDomain *old_domain;
  6474. MonoDomain *domain;
  6475. int err;
  6476. klass = decode_typeid (p, &p, end, &domain, &err);
  6477. if (err)
  6478. return err;
  6479. old_domain = mono_domain_get ();
  6480. mono_domain_set (domain, TRUE);
  6481. err = type_commands_internal (command, klass, domain, p, end, buf);
  6482. mono_domain_set (old_domain, TRUE);
  6483. return err;
  6484. }
  6485. static ErrorCode
  6486. method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
  6487. {
  6488. MonoMethodHeader *header;
  6489. int err;
  6490. switch (command) {
  6491. case CMD_METHOD_GET_NAME: {
  6492. buffer_add_string (buf, method->name);
  6493. break;
  6494. }
  6495. case CMD_METHOD_GET_DECLARING_TYPE: {
  6496. buffer_add_typeid (buf, domain, method->klass);
  6497. break;
  6498. }
  6499. case CMD_METHOD_GET_DEBUG_INFO: {
  6500. MonoDebugMethodInfo *minfo;
  6501. char *source_file;
  6502. int i, j, n_il_offsets;
  6503. int *il_offsets;
  6504. int *line_numbers;
  6505. int *column_numbers;
  6506. int *source_files;
  6507. GPtrArray *source_file_list;
  6508. header = mono_method_get_header (method);
  6509. if (!header) {
  6510. buffer_add_int (buf, 0);
  6511. buffer_add_string (buf, "");
  6512. buffer_add_int (buf, 0);
  6513. break;
  6514. }
  6515. minfo = mono_debug_lookup_method (method);
  6516. if (!minfo) {
  6517. buffer_add_int (buf, header->code_size);
  6518. buffer_add_string (buf, "");
  6519. buffer_add_int (buf, 0);
  6520. mono_metadata_free_mh (header);
  6521. break;
  6522. }
  6523. mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
  6524. buffer_add_int (buf, header->code_size);
  6525. if (CHECK_PROTOCOL_VERSION (2, 13)) {
  6526. buffer_add_int (buf, source_file_list->len);
  6527. for (i = 0; i < source_file_list->len; ++i) {
  6528. MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
  6529. buffer_add_string (buf, sinfo->source_file);
  6530. if (CHECK_PROTOCOL_VERSION (2, 14)) {
  6531. for (j = 0; j < 16; ++j)
  6532. buffer_add_byte (buf, sinfo->hash [j]);
  6533. }
  6534. }
  6535. } else {
  6536. buffer_add_string (buf, source_file);
  6537. }
  6538. buffer_add_int (buf, n_il_offsets);
  6539. DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
  6540. for (i = 0; i < n_il_offsets; ++i) {
  6541. const char *srcfile = "";
  6542. if (source_files [i] != -1) {
  6543. MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
  6544. srcfile = sinfo->source_file;
  6545. }
  6546. DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
  6547. buffer_add_int (buf, il_offsets [i]);
  6548. buffer_add_int (buf, line_numbers [i]);
  6549. if (CHECK_PROTOCOL_VERSION (2, 13))
  6550. buffer_add_int (buf, source_files [i]);
  6551. if (CHECK_PROTOCOL_VERSION (2, 19))
  6552. buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
  6553. }
  6554. g_free (source_file);
  6555. g_free (il_offsets);
  6556. g_free (line_numbers);
  6557. g_free (source_files);
  6558. g_ptr_array_free (source_file_list, TRUE);
  6559. mono_metadata_free_mh (header);
  6560. break;
  6561. }
  6562. case CMD_METHOD_GET_PARAM_INFO: {
  6563. MonoMethodSignature *sig = mono_method_signature (method);
  6564. guint32 i;
  6565. char **names;
  6566. /* FIXME: mono_class_from_mono_type () and byrefs */
  6567. /* FIXME: Use a smaller encoding */
  6568. buffer_add_int (buf, sig->call_convention);
  6569. buffer_add_int (buf, sig->param_count);
  6570. buffer_add_int (buf, sig->generic_param_count);
  6571. buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
  6572. for (i = 0; i < sig->param_count; ++i) {
  6573. /* FIXME: vararg */
  6574. buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
  6575. }
  6576. /* Emit parameter names */
  6577. names = g_new (char *, sig->param_count);
  6578. mono_method_get_param_names (method, (const char **) names);
  6579. for (i = 0; i < sig->param_count; ++i)
  6580. buffer_add_string (buf, names [i]);
  6581. g_free (names);
  6582. break;
  6583. }
  6584. case CMD_METHOD_GET_LOCALS_INFO: {
  6585. int i, j, num_locals;
  6586. MonoDebugLocalsInfo *locals;
  6587. header = mono_method_get_header (method);
  6588. if (!header)
  6589. return ERR_INVALID_ARGUMENT;
  6590. buffer_add_int (buf, header->num_locals);
  6591. /* Types */
  6592. for (i = 0; i < header->num_locals; ++i)
  6593. buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
  6594. /* Names */
  6595. locals = mono_debug_lookup_locals (method);
  6596. if (locals)
  6597. num_locals = locals->num_locals;
  6598. else
  6599. num_locals = 0;
  6600. for (i = 0; i < header->num_locals; ++i) {
  6601. for (j = 0; j < num_locals; ++j)
  6602. if (locals->locals [j].index == i)
  6603. break;
  6604. if (j < num_locals)
  6605. buffer_add_string (buf, locals->locals [j].name);
  6606. else
  6607. buffer_add_string (buf, "");
  6608. }
  6609. /* Scopes */
  6610. for (i = 0; i < header->num_locals; ++i) {
  6611. for (j = 0; j < num_locals; ++j)
  6612. if (locals->locals [j].index == i)
  6613. break;
  6614. if (j < num_locals && locals->locals [j].block) {
  6615. buffer_add_int (buf, locals->locals [j].block->start_offset);
  6616. buffer_add_int (buf, locals->locals [j].block->end_offset);
  6617. } else {
  6618. buffer_add_int (buf, 0);
  6619. buffer_add_int (buf, header->code_size);
  6620. }
  6621. }
  6622. mono_metadata_free_mh (header);
  6623. if (locals)
  6624. mono_debug_symfile_free_locals (locals);
  6625. break;
  6626. }
  6627. case CMD_METHOD_GET_INFO:
  6628. buffer_add_int (buf, method->flags);
  6629. buffer_add_int (buf, method->iflags);
  6630. buffer_add_int (buf, method->token);
  6631. if (CHECK_PROTOCOL_VERSION (2, 12)) {
  6632. guint8 attrs = 0;
  6633. if (method->is_generic)
  6634. attrs |= (1 << 0);
  6635. if (mono_method_signature (method)->generic_param_count)
  6636. attrs |= (1 << 1);
  6637. buffer_add_byte (buf, attrs);
  6638. if (method->is_generic || method->is_inflated) {
  6639. MonoMethod *result;
  6640. if (method->is_generic) {
  6641. result = method;
  6642. } else {
  6643. MonoMethodInflated *imethod = (MonoMethodInflated *)method;
  6644. result = imethod->declaring;
  6645. if (imethod->context.class_inst) {
  6646. MonoClass *klass = ((MonoMethod *) imethod)->klass;
  6647. /*Generic methods gets the context of the GTD.*/
  6648. if (mono_class_get_context (klass))
  6649. result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
  6650. }
  6651. }
  6652. buffer_add_methodid (buf, domain, result);
  6653. } else {
  6654. buffer_add_id (buf, 0);
  6655. }
  6656. if (CHECK_PROTOCOL_VERSION (2, 15)) {
  6657. if (mono_method_signature (method)->generic_param_count) {
  6658. int count, i;
  6659. if (method->is_inflated) {
  6660. MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
  6661. if (inst) {
  6662. count = inst->type_argc;
  6663. buffer_add_int (buf, count);
  6664. for (i = 0; i < count; i++)
  6665. buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
  6666. } else {
  6667. buffer_add_int (buf, 0);
  6668. }
  6669. } else if (method->is_generic) {
  6670. MonoGenericContainer *container = mono_method_get_generic_container (method);
  6671. count = mono_method_signature (method)->generic_param_count;
  6672. buffer_add_int (buf, count);
  6673. for (i = 0; i < count; i++) {
  6674. MonoGenericParam *param = mono_generic_container_get_param (container, i);
  6675. MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
  6676. buffer_add_typeid (buf, domain, pklass);
  6677. }
  6678. } else {
  6679. buffer_add_int (buf, 0);
  6680. }
  6681. } else {
  6682. buffer_add_int (buf, 0);
  6683. }
  6684. }
  6685. }
  6686. break;
  6687. case CMD_METHOD_GET_BODY: {
  6688. int i;
  6689. header = mono_method_get_header (method);
  6690. if (!header) {
  6691. buffer_add_int (buf, 0);
  6692. if (CHECK_PROTOCOL_VERSION (2, 18))
  6693. buffer_add_int (buf, 0);
  6694. } else {
  6695. buffer_add_int (buf, header->code_size);
  6696. for (i = 0; i < header->code_size; ++i)
  6697. buffer_add_byte (buf, header->code [i]);
  6698. if (CHECK_PROTOCOL_VERSION (2, 18)) {
  6699. buffer_add_int (buf, header->num_clauses);
  6700. for (i = 0; i < header->num_clauses; ++i) {
  6701. MonoExceptionClause *clause = &header->clauses [i];
  6702. buffer_add_int (buf, clause->flags);
  6703. buffer_add_int (buf, clause->try_offset);
  6704. buffer_add_int (buf, clause->try_len);
  6705. buffer_add_int (buf, clause->handler_offset);
  6706. buffer_add_int (buf, clause->handler_len);
  6707. if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
  6708. buffer_add_typeid (buf, domain, clause->data.catch_class);
  6709. else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
  6710. buffer_add_int (buf, clause->data.filter_offset);
  6711. }
  6712. }
  6713. mono_metadata_free_mh (header);
  6714. }
  6715. break;
  6716. }
  6717. case CMD_METHOD_RESOLVE_TOKEN: {
  6718. guint32 token = decode_int (p, &p, end);
  6719. // FIXME: Generics
  6720. switch (mono_metadata_token_code (token)) {
  6721. case MONO_TOKEN_STRING: {
  6722. MonoString *s;
  6723. char *s2;
  6724. s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
  6725. g_assert (s);
  6726. s2 = mono_string_to_utf8 (s);
  6727. buffer_add_byte (buf, TOKEN_TYPE_STRING);
  6728. buffer_add_string (buf, s2);
  6729. g_free (s2);
  6730. break;
  6731. }
  6732. default: {
  6733. gpointer val;
  6734. MonoClass *handle_class;
  6735. if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
  6736. val = mono_method_get_wrapper_data (method, token);
  6737. handle_class = mono_method_get_wrapper_data (method, token + 1);
  6738. if (handle_class == NULL) {
  6739. // Can't figure out the token type
  6740. buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
  6741. break;
  6742. }
  6743. } else {
  6744. val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
  6745. g_assert (val);
  6746. }
  6747. if (handle_class == mono_defaults.typehandle_class) {
  6748. buffer_add_byte (buf, TOKEN_TYPE_TYPE);
  6749. if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
  6750. buffer_add_typeid (buf, domain, (MonoClass *) val);
  6751. else
  6752. buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
  6753. } else if (handle_class == mono_defaults.fieldhandle_class) {
  6754. buffer_add_byte (buf, TOKEN_TYPE_FIELD);
  6755. buffer_add_fieldid (buf, domain, val);
  6756. } else if (handle_class == mono_defaults.methodhandle_class) {
  6757. buffer_add_byte (buf, TOKEN_TYPE_METHOD);
  6758. buffer_add_methodid (buf, domain, val);
  6759. } else if (handle_class == mono_defaults.string_class) {
  6760. char *s;
  6761. s = mono_string_to_utf8 (val);
  6762. buffer_add_byte (buf, TOKEN_TYPE_STRING);
  6763. buffer_add_string (buf, s);
  6764. g_free (s);
  6765. } else {
  6766. g_assert_not_reached ();
  6767. }
  6768. break;
  6769. }
  6770. }
  6771. break;
  6772. }
  6773. case CMD_METHOD_GET_CATTRS: {
  6774. MonoClass *attr_klass;
  6775. MonoCustomAttrInfo *cinfo;
  6776. attr_klass = decode_typeid (p, &p, end, NULL, &err);
  6777. /* attr_klass can be NULL */
  6778. if (err)
  6779. return err;
  6780. cinfo = mono_custom_attrs_from_method (method);
  6781. buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
  6782. break;
  6783. }
  6784. default:
  6785. return ERR_NOT_IMPLEMENTED;
  6786. }
  6787. return ERR_NONE;
  6788. }
  6789. static ErrorCode
  6790. method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  6791. {
  6792. int err;
  6793. MonoDomain *old_domain;
  6794. MonoDomain *domain;
  6795. MonoMethod *method;
  6796. method = decode_methodid (p, &p, end, &domain, &err);
  6797. if (err)
  6798. return err;
  6799. old_domain = mono_domain_get ();
  6800. mono_domain_set (domain, TRUE);
  6801. err = method_commands_internal (command, method, domain, p, end, buf);
  6802. mono_domain_set (old_domain, TRUE);
  6803. return err;
  6804. }
  6805. static ErrorCode
  6806. thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  6807. {
  6808. int objid = decode_objid (p, &p, end);
  6809. int err;
  6810. MonoThread *thread_obj;
  6811. MonoInternalThread *thread;
  6812. err = get_object (objid, (MonoObject**)&thread_obj);
  6813. if (err)
  6814. return err;
  6815. thread = THREAD_TO_INTERNAL (thread_obj);
  6816. switch (command) {
  6817. case CMD_THREAD_GET_NAME: {
  6818. guint32 name_len;
  6819. gunichar2 *s = mono_thread_get_name (thread, &name_len);
  6820. if (!s) {
  6821. buffer_add_int (buf, 0);
  6822. } else {
  6823. char *name;
  6824. glong len;
  6825. name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
  6826. g_assert (name);
  6827. buffer_add_int (buf, len);
  6828. buffer_add_data (buf, (guint8*)name, len);
  6829. g_free (s);
  6830. }
  6831. break;
  6832. }
  6833. case CMD_THREAD_GET_FRAME_INFO: {
  6834. DebuggerTlsData *tls;
  6835. int i, start_frame, length;
  6836. // Wait for suspending if it already started
  6837. // FIXME: Races with suspend_count
  6838. while (!is_suspended ()) {
  6839. if (suspend_count)
  6840. wait_for_suspend ();
  6841. }
  6842. /*
  6843. if (suspend_count)
  6844. wait_for_suspend ();
  6845. if (!is_suspended ())
  6846. return ERR_NOT_SUSPENDED;
  6847. */
  6848. start_frame = decode_int (p, &p, end);
  6849. length = decode_int (p, &p, end);
  6850. if (start_frame != 0 || length != -1)
  6851. return ERR_NOT_IMPLEMENTED;
  6852. mono_loader_lock ();
  6853. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  6854. mono_loader_unlock ();
  6855. g_assert (tls);
  6856. compute_frame_info (thread, tls);
  6857. buffer_add_int (buf, tls->frame_count);
  6858. for (i = 0; i < tls->frame_count; ++i) {
  6859. buffer_add_int (buf, tls->frames [i]->id);
  6860. buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
  6861. buffer_add_int (buf, tls->frames [i]->il_offset);
  6862. /*
  6863. * Instead of passing the frame type directly to the client, we associate
  6864. * it with the previous frame using a set of flags. This avoids lots of
  6865. * conditional code in the client, since a frame whose type isn't
  6866. * FRAME_TYPE_MANAGED has no method, location, etc.
  6867. */
  6868. buffer_add_byte (buf, tls->frames [i]->flags);
  6869. }
  6870. break;
  6871. }
  6872. case CMD_THREAD_GET_STATE:
  6873. buffer_add_int (buf, thread->state);
  6874. break;
  6875. case CMD_THREAD_GET_INFO:
  6876. buffer_add_byte (buf, thread->threadpool_thread);
  6877. break;
  6878. case CMD_THREAD_GET_ID:
  6879. buffer_add_long (buf, (guint64)(gsize)thread);
  6880. break;
  6881. case CMD_THREAD_GET_TID:
  6882. buffer_add_long (buf, (guint64)thread->tid);
  6883. break;
  6884. default:
  6885. return ERR_NOT_IMPLEMENTED;
  6886. }
  6887. return ERR_NONE;
  6888. }
  6889. static ErrorCode
  6890. frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  6891. {
  6892. int objid;
  6893. int err;
  6894. MonoThread *thread_obj;
  6895. MonoInternalThread *thread;
  6896. int pos, i, len, frame_idx;
  6897. DebuggerTlsData *tls;
  6898. StackFrame *frame;
  6899. MonoDebugMethodJitInfo *jit;
  6900. MonoDebugVarInfo *var;
  6901. MonoMethodSignature *sig;
  6902. gssize id;
  6903. MonoMethodHeader *header;
  6904. objid = decode_objid (p, &p, end);
  6905. err = get_object (objid, (MonoObject**)&thread_obj);
  6906. if (err)
  6907. return err;
  6908. thread = THREAD_TO_INTERNAL (thread_obj);
  6909. id = decode_id (p, &p, end);
  6910. mono_loader_lock ();
  6911. tls = mono_g_hash_table_lookup (thread_to_tls, thread);
  6912. mono_loader_unlock ();
  6913. g_assert (tls);
  6914. for (i = 0; i < tls->frame_count; ++i) {
  6915. if (tls->frames [i]->id == id)
  6916. break;
  6917. }
  6918. if (i == tls->frame_count)
  6919. return ERR_INVALID_FRAMEID;
  6920. frame_idx = i;
  6921. frame = tls->frames [frame_idx];
  6922. if (!frame->has_ctx)
  6923. // FIXME:
  6924. return ERR_INVALID_FRAMEID;
  6925. if (!frame->jit) {
  6926. frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
  6927. if (!frame->jit && frame->api_method->is_inflated)
  6928. frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
  6929. if (!frame->jit) {
  6930. char *s;
  6931. /* This could happen for aot images with no jit debug info */
  6932. s = mono_method_full_name (frame->api_method, TRUE);
  6933. DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
  6934. g_free (s);
  6935. return ERR_ABSENT_INFORMATION;
  6936. }
  6937. }
  6938. jit = frame->jit;
  6939. sig = mono_method_signature (frame->actual_method);
  6940. if (!get_seq_points (frame->domain, frame->actual_method))
  6941. /*
  6942. * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
  6943. */
  6944. return ERR_ABSENT_INFORMATION;
  6945. switch (command) {
  6946. case CMD_STACK_FRAME_GET_VALUES: {
  6947. len = decode_int (p, &p, end);
  6948. header = mono_method_get_header (frame->actual_method);
  6949. for (i = 0; i < len; ++i) {
  6950. pos = decode_int (p, &p, end);
  6951. if (pos < 0) {
  6952. pos = - pos - 1;
  6953. g_assert (pos >= 0 && pos < jit->num_params);
  6954. var = &jit->params [pos];
  6955. add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
  6956. } else {
  6957. g_assert (pos >= 0 && pos < jit->num_locals);
  6958. var = &jit->locals [pos];
  6959. add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
  6960. }
  6961. }
  6962. mono_metadata_free_mh (header);
  6963. break;
  6964. }
  6965. case CMD_STACK_FRAME_GET_THIS: {
  6966. if (frame->api_method->klass->valuetype) {
  6967. if (!sig->hasthis) {
  6968. MonoObject *p = NULL;
  6969. buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
  6970. } else {
  6971. add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
  6972. }
  6973. } else {
  6974. if (!sig->hasthis) {
  6975. MonoObject *p = NULL;
  6976. buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
  6977. } else {
  6978. add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
  6979. }
  6980. }
  6981. break;
  6982. }
  6983. case CMD_STACK_FRAME_SET_VALUES: {
  6984. guint8 *val_buf;
  6985. MonoType *t;
  6986. MonoDebugVarInfo *var;
  6987. len = decode_int (p, &p, end);
  6988. header = mono_method_get_header (frame->actual_method);
  6989. for (i = 0; i < len; ++i) {
  6990. pos = decode_int (p, &p, end);
  6991. if (pos < 0) {
  6992. pos = - pos - 1;
  6993. g_assert (pos >= 0 && pos < jit->num_params);
  6994. t = sig->params [pos];
  6995. var = &jit->params [pos];
  6996. } else {
  6997. g_assert (pos >= 0 && pos < jit->num_locals);
  6998. t = header->locals [pos];
  6999. var = &jit->locals [pos];
  7000. }
  7001. if (MONO_TYPE_IS_REFERENCE (t))
  7002. val_buf = g_alloca (sizeof (MonoObject*));
  7003. else
  7004. val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
  7005. err = decode_value (t, frame->domain, val_buf, p, &p, end);
  7006. if (err)
  7007. return err;
  7008. set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
  7009. }
  7010. mono_metadata_free_mh (header);
  7011. break;
  7012. }
  7013. default:
  7014. return ERR_NOT_IMPLEMENTED;
  7015. }
  7016. return ERR_NONE;
  7017. }
  7018. static ErrorCode
  7019. array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  7020. {
  7021. MonoArray *arr;
  7022. int objid, err, index, len, i, esize;
  7023. gpointer elem;
  7024. objid = decode_objid (p, &p, end);
  7025. err = get_object (objid, (MonoObject**)&arr);
  7026. if (err)
  7027. return err;
  7028. switch (command) {
  7029. case CMD_ARRAY_REF_GET_LENGTH:
  7030. buffer_add_int (buf, arr->obj.vtable->klass->rank);
  7031. if (!arr->bounds) {
  7032. buffer_add_int (buf, arr->max_length);
  7033. buffer_add_int (buf, 0);
  7034. } else {
  7035. for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
  7036. buffer_add_int (buf, arr->bounds [i].length);
  7037. buffer_add_int (buf, arr->bounds [i].lower_bound);
  7038. }
  7039. }
  7040. break;
  7041. case CMD_ARRAY_REF_GET_VALUES:
  7042. index = decode_int (p, &p, end);
  7043. len = decode_int (p, &p, end);
  7044. g_assert (index >= 0 && len >= 0);
  7045. // Reordered to avoid integer overflow
  7046. g_assert (!(index > arr->max_length - len));
  7047. esize = mono_array_element_size (arr->obj.vtable->klass);
  7048. for (i = index; i < index + len; ++i) {
  7049. elem = (gpointer*)((char*)arr->vector + (i * esize));
  7050. buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
  7051. }
  7052. break;
  7053. case CMD_ARRAY_REF_SET_VALUES:
  7054. index = decode_int (p, &p, end);
  7055. len = decode_int (p, &p, end);
  7056. g_assert (index >= 0 && len >= 0);
  7057. // Reordered to avoid integer overflow
  7058. g_assert (!(index > arr->max_length - len));
  7059. esize = mono_array_element_size (arr->obj.vtable->klass);
  7060. for (i = index; i < index + len; ++i) {
  7061. elem = (gpointer*)((char*)arr->vector + (i * esize));
  7062. decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
  7063. }
  7064. break;
  7065. default:
  7066. return ERR_NOT_IMPLEMENTED;
  7067. }
  7068. return ERR_NONE;
  7069. }
  7070. static ErrorCode
  7071. string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  7072. {
  7073. int objid, err;
  7074. MonoString *str;
  7075. char *s;
  7076. int i, index, length;
  7077. gunichar2 *c;
  7078. objid = decode_objid (p, &p, end);
  7079. err = get_object (objid, (MonoObject**)&str);
  7080. if (err)
  7081. return err;
  7082. switch (command) {
  7083. case CMD_STRING_REF_GET_VALUE:
  7084. s = mono_string_to_utf8 (str);
  7085. buffer_add_string (buf, s);
  7086. g_free (s);
  7087. break;
  7088. case CMD_STRING_REF_GET_LENGTH:
  7089. buffer_add_long (buf, mono_string_length (str));
  7090. break;
  7091. case CMD_STRING_REF_GET_CHARS:
  7092. index = decode_long (p, &p, end);
  7093. length = decode_long (p, &p, end);
  7094. if (index > mono_string_length (str) - length)
  7095. return ERR_INVALID_ARGUMENT;
  7096. c = mono_string_chars (str) + index;
  7097. for (i = 0; i < length; ++i)
  7098. buffer_add_short (buf, c [i]);
  7099. break;
  7100. default:
  7101. return ERR_NOT_IMPLEMENTED;
  7102. }
  7103. return ERR_NONE;
  7104. }
  7105. static ErrorCode
  7106. object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  7107. {
  7108. int objid, err;
  7109. MonoObject *obj;
  7110. int len, i;
  7111. MonoClassField *f;
  7112. MonoClass *k;
  7113. gboolean found;
  7114. if (command == CMD_OBJECT_REF_IS_COLLECTED) {
  7115. objid = decode_objid (p, &p, end);
  7116. err = get_object (objid, &obj);
  7117. if (err)
  7118. buffer_add_int (buf, 1);
  7119. else
  7120. buffer_add_int (buf, 0);
  7121. return 0;
  7122. }
  7123. objid = decode_objid (p, &p, end);
  7124. err = get_object (objid, &obj);
  7125. if (err)
  7126. return err;
  7127. switch (command) {
  7128. case CMD_OBJECT_REF_GET_TYPE:
  7129. /* This handles transparent proxies too */
  7130. buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
  7131. break;
  7132. case CMD_OBJECT_REF_GET_VALUES:
  7133. len = decode_int (p, &p, end);
  7134. for (i = 0; i < len; ++i) {
  7135. MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
  7136. if (err)
  7137. return err;
  7138. /* Check that the field belongs to the object */
  7139. found = FALSE;
  7140. for (k = obj->vtable->klass; k; k = k->parent) {
  7141. if (k == f->parent) {
  7142. found = TRUE;
  7143. break;
  7144. }
  7145. }
  7146. if (!found)
  7147. return ERR_INVALID_FIELDID;
  7148. if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
  7149. guint8 *val;
  7150. MonoVTable *vtable;
  7151. if (mono_class_field_is_special_static (f))
  7152. return ERR_INVALID_FIELDID;
  7153. g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
  7154. vtable = mono_class_vtable (obj->vtable->domain, f->parent);
  7155. val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
  7156. mono_field_static_get_value (vtable, f, val);
  7157. buffer_add_value (buf, f->type, val, obj->vtable->domain);
  7158. g_free (val);
  7159. } else {
  7160. buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
  7161. }
  7162. }
  7163. break;
  7164. case CMD_OBJECT_REF_SET_VALUES:
  7165. len = decode_int (p, &p, end);
  7166. for (i = 0; i < len; ++i) {
  7167. f = decode_fieldid (p, &p, end, NULL, &err);
  7168. if (err)
  7169. return err;
  7170. /* Check that the field belongs to the object */
  7171. found = FALSE;
  7172. for (k = obj->vtable->klass; k; k = k->parent) {
  7173. if (k == f->parent) {
  7174. found = TRUE;
  7175. break;
  7176. }
  7177. }
  7178. if (!found)
  7179. return ERR_INVALID_FIELDID;
  7180. if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
  7181. guint8 *val;
  7182. MonoVTable *vtable;
  7183. if (mono_class_field_is_special_static (f))
  7184. return ERR_INVALID_FIELDID;
  7185. g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
  7186. vtable = mono_class_vtable (obj->vtable->domain, f->parent);
  7187. val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
  7188. err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
  7189. if (err) {
  7190. g_free (val);
  7191. return err;
  7192. }
  7193. mono_field_static_set_value (vtable, f, val);
  7194. g_free (val);
  7195. } else {
  7196. err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
  7197. if (err)
  7198. return err;
  7199. }
  7200. }
  7201. break;
  7202. case CMD_OBJECT_REF_GET_ADDRESS:
  7203. buffer_add_long (buf, (gssize)obj);
  7204. break;
  7205. case CMD_OBJECT_REF_GET_DOMAIN:
  7206. buffer_add_domainid (buf, obj->vtable->domain);
  7207. break;
  7208. case CMD_OBJECT_REF_GET_INFO:
  7209. buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
  7210. buffer_add_domainid (buf, obj->vtable->domain);
  7211. break;
  7212. default:
  7213. return ERR_NOT_IMPLEMENTED;
  7214. }
  7215. return ERR_NONE;
  7216. }
  7217. static const char*
  7218. command_set_to_string (CommandSet command_set)
  7219. {
  7220. switch (command_set) {
  7221. case CMD_SET_VM:
  7222. return "VM";
  7223. case CMD_SET_OBJECT_REF:
  7224. return "OBJECT_REF";
  7225. case CMD_SET_STRING_REF:
  7226. return "STRING_REF";
  7227. case CMD_SET_THREAD:
  7228. return "THREAD";
  7229. case CMD_SET_ARRAY_REF:
  7230. return "ARRAY_REF";
  7231. case CMD_SET_EVENT_REQUEST:
  7232. return "EVENT_REQUEST";
  7233. case CMD_SET_STACK_FRAME:
  7234. return "STACK_FRAME";
  7235. case CMD_SET_APPDOMAIN:
  7236. return "APPDOMAIN";
  7237. case CMD_SET_ASSEMBLY:
  7238. return "ASSEMBLY";
  7239. case CMD_SET_METHOD:
  7240. return "METHOD";
  7241. case CMD_SET_TYPE:
  7242. return "TYPE";
  7243. case CMD_SET_MODULE:
  7244. return "MODULE";
  7245. case CMD_SET_EVENT:
  7246. return "EVENT";
  7247. default:
  7248. return "";
  7249. }
  7250. }
  7251. static const char*
  7252. cmd_to_string (CommandSet set, int command)
  7253. {
  7254. switch (set) {
  7255. case CMD_SET_VM: {
  7256. switch (command) {
  7257. case CMD_VM_VERSION:
  7258. return "VERSION";
  7259. case CMD_VM_ALL_THREADS:
  7260. return "ALL_THREADS";
  7261. case CMD_VM_SUSPEND:
  7262. return "SUSPEND";
  7263. case CMD_VM_RESUME:
  7264. return "RESUME";
  7265. case CMD_VM_EXIT:
  7266. return "EXIT";
  7267. case CMD_VM_DISPOSE:
  7268. return "DISPOSE";
  7269. case CMD_VM_INVOKE_METHOD:
  7270. return "INVOKE_METHOD";
  7271. case CMD_VM_SET_PROTOCOL_VERSION:
  7272. return "SET_PROTOCOL_VERSION";
  7273. case CMD_VM_ABORT_INVOKE:
  7274. return "ABORT_INVOKE";
  7275. case CMD_VM_SET_KEEPALIVE:
  7276. return "SET_KEEPALIVE";
  7277. default:
  7278. break;
  7279. }
  7280. break;
  7281. }
  7282. default:
  7283. break;
  7284. }
  7285. return NULL;
  7286. }
  7287. static gboolean
  7288. wait_for_attach (void)
  7289. {
  7290. #ifndef DISABLE_SOCKET_TRANSPORT
  7291. if (listen_fd == -1) {
  7292. DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
  7293. return FALSE;
  7294. }
  7295. /* Block and wait for client connection */
  7296. conn_fd = socket_transport_accept (listen_fd);
  7297. DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
  7298. if (conn_fd == -1) {
  7299. DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
  7300. return FALSE;
  7301. }
  7302. #else
  7303. g_assert_not_reached ();
  7304. #endif
  7305. /* Handshake */
  7306. disconnected = !transport_handshake ();
  7307. if (disconnected) {
  7308. DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
  7309. return FALSE;
  7310. }
  7311. return TRUE;
  7312. }
  7313. /*
  7314. * debugger_thread:
  7315. *
  7316. * This thread handles communication with the debugger client using a JDWP
  7317. * like protocol.
  7318. */
  7319. static guint32 WINAPI
  7320. debugger_thread (void *arg)
  7321. {
  7322. int res, len, id, flags, command_set = 0, command = 0;
  7323. guint8 header [HEADER_LENGTH];
  7324. guint8 *data, *p, *end;
  7325. Buffer buf;
  7326. ErrorCode err;
  7327. gboolean no_reply;
  7328. gboolean attach_failed = FALSE;
  7329. DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
  7330. debugger_thread_id = GetCurrentThreadId ();
  7331. mono_jit_thread_attach (mono_get_root_domain ());
  7332. mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
  7333. mono_set_is_debugger_attached (TRUE);
  7334. if (agent_config.defer) {
  7335. if (!wait_for_attach ()) {
  7336. DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
  7337. attach_failed = TRUE; // Don't abort process when we can't listen
  7338. } else {
  7339. /* Send start event to client */
  7340. process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
  7341. }
  7342. }
  7343. while (!attach_failed) {
  7344. res = transport_recv (header, HEADER_LENGTH);
  7345. /* This will break if the socket is closed during shutdown too */
  7346. if (res != HEADER_LENGTH) {
  7347. DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
  7348. break;
  7349. }
  7350. p = header;
  7351. end = header + HEADER_LENGTH;
  7352. len = decode_int (p, &p, end);
  7353. id = decode_int (p, &p, end);
  7354. flags = decode_byte (p, &p, end);
  7355. command_set = decode_byte (p, &p, end);
  7356. command = decode_byte (p, &p, end);
  7357. g_assert (flags == 0);
  7358. if (log_level) {
  7359. const char *cmd_str;
  7360. char cmd_num [256];
  7361. cmd_str = cmd_to_string (command_set, command);
  7362. if (!cmd_str) {
  7363. sprintf (cmd_num, "%d", command);
  7364. cmd_str = cmd_num;
  7365. }
  7366. DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
  7367. }
  7368. data = g_malloc (len - HEADER_LENGTH);
  7369. if (len - HEADER_LENGTH > 0)
  7370. {
  7371. res = transport_recv (data, len - HEADER_LENGTH);
  7372. if (res != len - HEADER_LENGTH) {
  7373. DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
  7374. break;
  7375. }
  7376. }
  7377. p = data;
  7378. end = data + (len - HEADER_LENGTH);
  7379. buffer_init (&buf, 128);
  7380. err = ERR_NONE;
  7381. no_reply = FALSE;
  7382. /* Process the request */
  7383. switch (command_set) {
  7384. case CMD_SET_VM:
  7385. err = vm_commands (command, id, p, end, &buf);
  7386. if (!err && command == CMD_VM_INVOKE_METHOD)
  7387. /* Sent after the invoke is complete */
  7388. no_reply = TRUE;
  7389. break;
  7390. case CMD_SET_EVENT_REQUEST:
  7391. err = event_commands (command, p, end, &buf);
  7392. break;
  7393. case CMD_SET_APPDOMAIN:
  7394. err = domain_commands (command, p, end, &buf);
  7395. break;
  7396. case CMD_SET_ASSEMBLY:
  7397. err = assembly_commands (command, p, end, &buf);
  7398. break;
  7399. case CMD_SET_MODULE:
  7400. err = module_commands (command, p, end, &buf);
  7401. break;
  7402. case CMD_SET_TYPE:
  7403. err = type_commands (command, p, end, &buf);
  7404. break;
  7405. case CMD_SET_METHOD:
  7406. err = method_commands (command, p, end, &buf);
  7407. break;
  7408. case CMD_SET_THREAD:
  7409. err = thread_commands (command, p, end, &buf);
  7410. break;
  7411. case CMD_SET_STACK_FRAME:
  7412. err = frame_commands (command, p, end, &buf);
  7413. break;
  7414. case CMD_SET_ARRAY_REF:
  7415. err = array_commands (command, p, end, &buf);
  7416. break;
  7417. case CMD_SET_STRING_REF:
  7418. err = string_commands (command, p, end, &buf);
  7419. break;
  7420. case CMD_SET_OBJECT_REF:
  7421. err = object_commands (command, p, end, &buf);
  7422. break;
  7423. default:
  7424. err = ERR_NOT_IMPLEMENTED;
  7425. }
  7426. if (!no_reply)
  7427. send_reply_packet (id, err, &buf);
  7428. g_free (data);
  7429. buffer_free (&buf);
  7430. if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
  7431. break;
  7432. }
  7433. mono_set_is_debugger_attached (FALSE);
  7434. mono_mutex_lock (&debugger_thread_exited_mutex);
  7435. debugger_thread_exited = TRUE;
  7436. mono_cond_signal (&debugger_thread_exited_cond);
  7437. mono_mutex_unlock (&debugger_thread_exited_mutex);
  7438. DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
  7439. if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
  7440. DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
  7441. start_debugger_thread ();
  7442. }
  7443. return 0;
  7444. }
  7445. #else /* DISABLE_DEBUGGER_AGENT */
  7446. void
  7447. mono_debugger_agent_parse_options (char *options)
  7448. {
  7449. g_error ("This runtime is configured with the debugger agent disabled.");
  7450. }
  7451. void
  7452. mono_debugger_agent_init (void)
  7453. {
  7454. }
  7455. void
  7456. mono_debugger_agent_breakpoint_hit (void *sigctx)
  7457. {
  7458. }
  7459. void
  7460. mono_debugger_agent_single_step_event (void *sigctx)
  7461. {
  7462. }
  7463. void
  7464. mono_debugger_agent_free_domain_info (MonoDomain *domain)
  7465. {
  7466. }
  7467. gboolean
  7468. mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
  7469. {
  7470. return FALSE;
  7471. }
  7472. void
  7473. mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
  7474. MonoContext *catch_ctx)
  7475. {
  7476. }
  7477. void
  7478. mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
  7479. {
  7480. }
  7481. void
  7482. mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
  7483. {
  7484. }
  7485. void
  7486. mono_debugger_agent_user_break (void)
  7487. {
  7488. G_BREAKPOINT ();
  7489. }
  7490. void
  7491. mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
  7492. {
  7493. }
  7494. gboolean
  7495. mono_debugger_agent_debug_log_is_enabled (void)
  7496. {
  7497. return FALSE;
  7498. }
  7499. #endif