You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

787 line
24 KiB

  1. /* Copyright (c) 2018, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include "abi_test.h"
  15. #include <stdarg.h>
  16. #include <stdio.h>
  17. #include <algorithm>
  18. #include <array>
  19. #include <openssl/buf.h>
  20. #include <openssl/mem.h>
  21. #include <openssl/rand.h>
  22. #include <openssl/span.h>
  23. #if defined(OPENSSL_X86_64) && defined(SUPPORTS_ABI_TEST)
  24. #if defined(OPENSSL_LINUX) && defined(BORINGSSL_HAVE_LIBUNWIND)
  25. #define SUPPORTS_UNWIND_TEST
  26. #define UNW_LOCAL_ONLY
  27. #include <errno.h>
  28. #include <fcntl.h>
  29. #include <libunwind.h>
  30. #include <pthread.h>
  31. #include <signal.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <sys/stat.h>
  35. #include <sys/types.h>
  36. #include <unistd.h>
  37. #elif defined(OPENSSL_WINDOWS)
  38. #define SUPPORTS_UNWIND_TEST
  39. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  40. #include <windows.h>
  41. #include <dbghelp.h>
  42. OPENSSL_MSVC_PRAGMA(warning(pop))
  43. #endif
  44. #endif // X86_64 && SUPPORTS_ABI_TEST
  45. namespace abi_test {
  46. namespace internal {
  47. static bool g_unwind_tests_enabled = false;
  48. std::string FixVAArgsString(const char *str) {
  49. std::string ret = str;
  50. size_t idx = ret.find(',');
  51. if (idx == std::string::npos) {
  52. return ret + "()";
  53. }
  54. size_t idx2 = idx + 1;
  55. while (idx2 < ret.size() && ret[idx2] == ' ') {
  56. idx2++;
  57. }
  58. while (idx > 0 && ret[idx - 1] == ' ') {
  59. idx--;
  60. }
  61. return ret.substr(0, idx) + "(" + ret.substr(idx2) + ")";
  62. }
  63. #if defined(SUPPORTS_ABI_TEST)
  64. // ForEachMismatch calls |func| for each register where |a| and |b| differ.
  65. template <typename Func>
  66. static void ForEachMismatch(const CallerState &a, const CallerState &b,
  67. const Func &func) {
  68. #define CALLER_STATE_REGISTER(type, name) \
  69. if (a.name != b.name) { \
  70. func(#name); \
  71. }
  72. LOOP_CALLER_STATE_REGISTERS()
  73. #undef CALLER_STATE_REGISTER
  74. }
  75. // ReadUnwindResult adds the results of the most recent unwind test to |out|.
  76. static void ReadUnwindResult(Result *out);
  77. crypto_word_t RunTrampoline(Result *out, crypto_word_t func,
  78. const crypto_word_t *argv, size_t argc,
  79. bool unwind) {
  80. CallerState state;
  81. RAND_bytes(reinterpret_cast<uint8_t *>(&state), sizeof(state));
  82. unwind &= g_unwind_tests_enabled;
  83. CallerState state2 = state;
  84. crypto_word_t ret = abi_test_trampoline(func, &state2, argv, argc, unwind);
  85. #if defined(OPENSSL_X86_64) || defined(OPENSSL_X86)
  86. // Query and clear the direction flag early, so negative tests do not
  87. // interfere with |malloc|.
  88. bool direction_flag = abi_test_get_and_clear_direction_flag();
  89. #endif // OPENSSL_X86_64 || OPENSSL_X86
  90. *out = Result();
  91. ForEachMismatch(state, state2, [&](const char *reg) {
  92. out->errors.push_back(std::string(reg) + " was not restored after return");
  93. });
  94. #if defined(OPENSSL_X86_64) || defined(OPENSSL_X86)
  95. // Linux and Windows ABIs for x86 require the direction flag be cleared on
  96. // return. (Some OpenSSL assembly preserves it, which is stronger, but we only
  97. // require what is specified by the ABI so |CHECK_ABI| works with C compiler
  98. // output.)
  99. if (direction_flag) {
  100. out->errors.emplace_back("Direction flag set after return");
  101. }
  102. #endif // OPENSSL_X86_64 || OPENSSL_X86
  103. if (unwind) {
  104. ReadUnwindResult(out);
  105. }
  106. return ret;
  107. }
  108. #endif // SUPPORTS_ABI_TEST
  109. #if defined(SUPPORTS_UNWIND_TEST)
  110. // We test unwind metadata by running the function under test with the trap flag
  111. // set. This results in |SIGTRAP| and |EXCEPTION_SINGLE_STEP| on Linux and
  112. // Windows, respectively. We hande these and verify libunwind or the Windows
  113. // unwind APIs unwind successfully.
  114. // IsAncestorStackFrame returns true if |a_sp| is an ancestor stack frame of
  115. // |b_sp|.
  116. static bool IsAncestorStackFrame(crypto_word_t a_sp, crypto_word_t b_sp) {
  117. #if defined(OPENSSL_X86_64)
  118. // The stack grows down, so ancestor stack frames have higher addresses.
  119. return a_sp > b_sp;
  120. #else
  121. #error "unknown architecture"
  122. #endif
  123. }
  124. // Implement some string formatting utilties. Ideally we would use |snprintf|,
  125. // but this is called in a signal handler and |snprintf| is not async-signal-
  126. // safe.
  127. #if !defined(OPENSSL_WINDOWS)
  128. static std::array<char, DECIMAL_SIZE(crypto_word_t) + 1> WordToDecimal(
  129. crypto_word_t v) {
  130. std::array<char, DECIMAL_SIZE(crypto_word_t) + 1> ret;
  131. size_t len = 0;
  132. do {
  133. ret[len++] = '0' + v % 10;
  134. v /= 10;
  135. } while (v != 0);
  136. for (size_t i = 0; i < len / 2; i++) {
  137. std::swap(ret[i], ret[len - 1 - i]);
  138. }
  139. ret[len] = '\0';
  140. return ret;
  141. }
  142. #endif // !OPENSSL_WINDOWS
  143. static std::array<char, sizeof(crypto_word_t) * 2 + 1> WordToHex(
  144. crypto_word_t v) {
  145. static const char kHex[] = "0123456789abcdef";
  146. std::array<char, sizeof(crypto_word_t) * 2 + 1> ret;
  147. for (size_t i = sizeof(crypto_word_t) - 1; i < sizeof(crypto_word_t); i--) {
  148. uint8_t b = v & 0xff;
  149. v >>= 8;
  150. ret[i * 2] = kHex[b >> 4];
  151. ret[i * 2 + 1] = kHex[b & 0xf];
  152. }
  153. ret[sizeof(crypto_word_t) * 2] = '\0';
  154. return ret;
  155. }
  156. static void StrCatSignalSafeImpl(bssl::Span<char> out) {}
  157. template <typename... Args>
  158. static void StrCatSignalSafeImpl(bssl::Span<char> out, const char *str,
  159. Args... args) {
  160. BUF_strlcat(out.data(), str, out.size());
  161. StrCatSignalSafeImpl(out, args...);
  162. }
  163. template <typename... Args>
  164. static void StrCatSignalSafe(bssl::Span<char> out, Args... args) {
  165. if (out.empty()) {
  166. return;
  167. }
  168. out[0] = '\0';
  169. StrCatSignalSafeImpl(out, args...);
  170. }
  171. template <typename... Args>
  172. [[noreturn]] static void FatalError(Args... args) {
  173. // We cannot use |snprintf| here because it is not async-signal-safe.
  174. char buf[512];
  175. StrCatSignalSafe(buf, args..., "\n");
  176. #if defined(OPENSSL_WINDOWS)
  177. HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
  178. if (stderr_handle != INVALID_HANDLE_VALUE) {
  179. DWORD unused;
  180. WriteFile(stderr_handle, buf, strlen(buf), &unused, nullptr);
  181. }
  182. #else
  183. write(STDERR_FILENO, buf, strlen(buf));
  184. #endif
  185. abort();
  186. }
  187. class UnwindStatus {
  188. public:
  189. UnwindStatus() : err_(nullptr) {}
  190. explicit UnwindStatus(const char *err) : err_(err) {}
  191. bool ok() const { return err_ == nullptr; }
  192. const char *Error() const { return err_; }
  193. private:
  194. const char *err_;
  195. };
  196. template<typename T>
  197. class UnwindStatusOr {
  198. public:
  199. UnwindStatusOr(UnwindStatus status) : status_(status) {
  200. assert(!status_.ok());
  201. }
  202. UnwindStatusOr(const T &value) : status_(UnwindStatus()), value_(value) {}
  203. bool ok() const { return status_.ok(); }
  204. const char *Error() const { return status_.Error(); }
  205. const T &ValueOrDie(const char *msg = "Unexpected error") const {
  206. if (!ok()) {
  207. FatalError(msg, ": ", Error());
  208. }
  209. return value_;
  210. }
  211. private:
  212. UnwindStatus status_;
  213. T value_;
  214. };
  215. // UnwindCursor abstracts between libunwind and Windows unwind APIs. It is
  216. // async-signal-safe.
  217. #if defined(OPENSSL_WINDOWS)
  218. class UnwindCursor {
  219. public:
  220. explicit UnwindCursor(const CONTEXT &ctx) : ctx_(ctx) {
  221. starting_ip_ = ctx_.Rip;
  222. }
  223. crypto_word_t starting_ip() const { return starting_ip_; }
  224. // Step unwinds the cursor by one frame. On success, it returns whether there
  225. // were more frames to unwind.
  226. UnwindStatusOr<bool> Step() {
  227. bool is_top = is_top_;
  228. is_top_ = false;
  229. DWORD64 image_base;
  230. RUNTIME_FUNCTION *entry =
  231. RtlLookupFunctionEntry(ctx_.Rip, &image_base, nullptr);
  232. if (entry == nullptr) {
  233. // This is a leaf function. Leaf functions do not touch stack or
  234. // callee-saved registers, so they may be unwound by simulating a ret.
  235. if (!is_top) {
  236. return UnwindStatus("leaf function found below the top frame");
  237. }
  238. memcpy(&ctx_.Rip, reinterpret_cast<const void *>(ctx_.Rsp),
  239. sizeof(ctx_.Rip));
  240. ctx_.Rsp += 8;
  241. return true;
  242. }
  243. // This is a frame function. Call into the Windows unwinder.
  244. void *handler_data;
  245. DWORD64 establisher_frame;
  246. RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, ctx_.Rip, entry, &ctx_,
  247. &handler_data, &establisher_frame, nullptr);
  248. return ctx_.Rip != 0;
  249. }
  250. // GetIP returns the instruction pointer at the current frame.
  251. UnwindStatusOr<crypto_word_t> GetIP() { return ctx_.Rip; }
  252. // GetSP returns the stack pointer at the current frame.
  253. UnwindStatusOr<crypto_word_t> GetSP() { return ctx_.Rsp; }
  254. // GetCallerState returns the callee-saved registers at the current frame.
  255. UnwindStatusOr<CallerState> GetCallerState() {
  256. CallerState state;
  257. state.rbx = ctx_.Rbx;
  258. state.rbp = ctx_.Rbp;
  259. state.rdi = ctx_.Rdi;
  260. state.rsi = ctx_.Rsi;
  261. state.r12 = ctx_.R12;
  262. state.r13 = ctx_.R13;
  263. state.r14 = ctx_.R14;
  264. state.r15 = ctx_.R15;
  265. memcpy(&state.xmm6, &ctx_.Xmm6, sizeof(Reg128));
  266. memcpy(&state.xmm7, &ctx_.Xmm7, sizeof(Reg128));
  267. memcpy(&state.xmm8, &ctx_.Xmm8, sizeof(Reg128));
  268. memcpy(&state.xmm9, &ctx_.Xmm9, sizeof(Reg128));
  269. memcpy(&state.xmm10, &ctx_.Xmm10, sizeof(Reg128));
  270. memcpy(&state.xmm11, &ctx_.Xmm11, sizeof(Reg128));
  271. memcpy(&state.xmm12, &ctx_.Xmm12, sizeof(Reg128));
  272. memcpy(&state.xmm13, &ctx_.Xmm13, sizeof(Reg128));
  273. memcpy(&state.xmm14, &ctx_.Xmm14, sizeof(Reg128));
  274. memcpy(&state.xmm15, &ctx_.Xmm15, sizeof(Reg128));
  275. return state;
  276. }
  277. // ToString returns a human-readable representation of the address the cursor
  278. // started at.
  279. const char *ToString() {
  280. StrCatSignalSafe(starting_ip_buf_, "0x", WordToHex(starting_ip_).data());
  281. return starting_ip_buf_;
  282. }
  283. private:
  284. CONTEXT ctx_;
  285. crypto_word_t starting_ip_;
  286. char starting_ip_buf_[64];
  287. bool is_top_ = true;
  288. };
  289. #else // !OPENSSL_WINDOWS
  290. class UnwindCursor {
  291. public:
  292. explicit UnwindCursor(unw_context_t *ctx) : ctx_(ctx) {
  293. int ret = InitAtSignalFrame(&cursor_);
  294. if (ret < 0) {
  295. FatalError("Error getting unwind context: ", unw_strerror(ret));
  296. }
  297. starting_ip_ = GetIP().ValueOrDie("Error getting instruction pointer");
  298. }
  299. // Step unwinds the cursor by one frame. On success, it returns whether there
  300. // were more frames to unwind.
  301. UnwindStatusOr<bool> Step() {
  302. int ret = unw_step(&cursor_);
  303. if (ret < 0) {
  304. return UNWError(ret);
  305. }
  306. return ret != 0;
  307. }
  308. // GetIP returns the instruction pointer at the current frame.
  309. UnwindStatusOr<crypto_word_t> GetIP() {
  310. crypto_word_t ip;
  311. int ret = GetReg(&ip, UNW_REG_IP);
  312. if (ret < 0) {
  313. return UNWError(ret);
  314. }
  315. return ip;
  316. }
  317. // GetSP returns the stack pointer at the current frame.
  318. UnwindStatusOr<crypto_word_t> GetSP() {
  319. crypto_word_t sp;
  320. int ret = GetReg(&sp, UNW_REG_SP);
  321. if (ret < 0) {
  322. return UNWError(ret);
  323. }
  324. return sp;
  325. }
  326. // GetCallerState returns the callee-saved registers at the current frame.
  327. UnwindStatusOr<CallerState> GetCallerState() {
  328. CallerState state;
  329. int ret = 0;
  330. #if defined(OPENSSL_X86_64)
  331. ret = ret < 0 ? ret : GetReg(&state.rbx, UNW_X86_64_RBX);
  332. ret = ret < 0 ? ret : GetReg(&state.rbp, UNW_X86_64_RBP);
  333. ret = ret < 0 ? ret : GetReg(&state.r12, UNW_X86_64_R12);
  334. ret = ret < 0 ? ret : GetReg(&state.r13, UNW_X86_64_R13);
  335. ret = ret < 0 ? ret : GetReg(&state.r14, UNW_X86_64_R14);
  336. ret = ret < 0 ? ret : GetReg(&state.r15, UNW_X86_64_R15);
  337. #else
  338. #error "unknown architecture"
  339. #endif
  340. if (ret < 0) {
  341. return UNWError(ret);
  342. }
  343. return state;
  344. }
  345. // ToString returns a human-readable representation of the address the cursor
  346. // started at, using debug information if available.
  347. const char *ToString() {
  348. // Use a new cursor. |cursor_| has already been unwound, and
  349. // |unw_get_proc_name| is slow so we do not sample it unconditionally in the
  350. // constructor.
  351. unw_cursor_t cursor;
  352. unw_word_t off;
  353. if (InitAtSignalFrame(&cursor) != 0 ||
  354. unw_get_proc_name(&cursor, starting_ip_buf_, sizeof(starting_ip_buf_),
  355. &off) != 0) {
  356. StrCatSignalSafe(starting_ip_buf_, "0x", WordToHex(starting_ip_).data());
  357. return starting_ip_buf_;
  358. }
  359. size_t len = strlen(starting_ip_buf_);
  360. // Print the offset in decimal, to match gdb's disassembly output and ease
  361. // debugging.
  362. StrCatSignalSafe(bssl::Span<char>(starting_ip_buf_).subspan(len), "+",
  363. WordToDecimal(off).data(), " (0x",
  364. WordToHex(starting_ip_).data(), ")");
  365. return starting_ip_buf_;
  366. }
  367. private:
  368. static UnwindStatus UNWError(int ret) {
  369. assert(ret < 0);
  370. const char *msg = unw_strerror(ret);
  371. return UnwindStatus(msg == nullptr ? "unknown error" : msg);
  372. }
  373. int InitAtSignalFrame(unw_cursor_t *cursor) {
  374. // Work around a bug in libunwind which breaks rax and rdx recovery. This
  375. // breaks functions which temporarily use rax as the CFA register. See
  376. // https://git.savannah.gnu.org/gitweb/?p=libunwind.git;a=commit;h=819bf51bbd2da462c2ec3401e8ac9153b6e725e3
  377. OPENSSL_memset(cursor, 0, sizeof(*cursor));
  378. int ret = unw_init_local(cursor, ctx_);
  379. if (ret < 0) {
  380. return ret;
  381. }
  382. for (;;) {
  383. ret = unw_is_signal_frame(cursor);
  384. if (ret < 0) {
  385. return ret;
  386. }
  387. if (ret != 0) {
  388. return 0; // Found the signal frame.
  389. }
  390. ret = unw_step(cursor);
  391. if (ret < 0) {
  392. return ret;
  393. }
  394. }
  395. }
  396. int GetReg(crypto_word_t *out, unw_regnum_t reg) {
  397. unw_word_t val;
  398. int ret = unw_get_reg(&cursor_, reg, &val);
  399. if (ret == 0) {
  400. static_assert(sizeof(crypto_word_t) == sizeof(unw_word_t),
  401. "crypto_word_t and unw_word_t are inconsistent");
  402. *out = val;
  403. }
  404. return ret;
  405. }
  406. unw_context_t *ctx_;
  407. unw_cursor_t cursor_;
  408. crypto_word_t starting_ip_;
  409. char starting_ip_buf_[64];
  410. };
  411. #endif // OPENSSL_WINDOWS
  412. // g_in_trampoline is true if we are in an instrumented |abi_test_trampoline|
  413. // call, in the region that triggers |SIGTRAP|.
  414. static bool g_in_trampoline = false;
  415. // g_unwind_function_done, if |g_in_trampoline| is true, is whether the function
  416. // under test has returned. It is undefined otherwise.
  417. static bool g_unwind_function_done;
  418. // g_trampoline_state, if |g_in_trampoline| is true, is the state the function
  419. // under test must preserve. It is undefined otherwise.
  420. static CallerState g_trampoline_state;
  421. // g_trampoline_sp, if |g_in_trampoline| is true, is the stack pointer of the
  422. // trampoline frame. It is undefined otherwise.
  423. static crypto_word_t g_trampoline_sp;
  424. // kMaxUnwindErrors is the maximum number of unwind errors reported per
  425. // function. If a function's unwind tables are wrong, we are otherwise likely to
  426. // repeat the same error at multiple addresses.
  427. static constexpr size_t kMaxUnwindErrors = 10;
  428. // Errors are saved in a signal handler. We use a static buffer to avoid
  429. // allocation.
  430. static size_t g_num_unwind_errors = 0;
  431. struct UnwindError {
  432. #if defined(OPENSSL_WINDOWS)
  433. crypto_word_t ip;
  434. #endif
  435. char str[512];
  436. };
  437. static UnwindError g_unwind_errors[kMaxUnwindErrors];
  438. template <typename... Args>
  439. static void AddUnwindError(UnwindCursor *cursor, Args... args) {
  440. if (g_num_unwind_errors >= kMaxUnwindErrors) {
  441. return;
  442. }
  443. #if defined(OPENSSL_WINDOWS)
  444. // Windows symbol functions should not be called when handling an
  445. // exception. Stash the instruction pointer, to be symbolized later.
  446. g_unwind_errors[g_num_unwind_errors].ip = cursor->starting_ip();
  447. StrCatSignalSafe(g_unwind_errors[g_num_unwind_errors].str, args...);
  448. #else
  449. StrCatSignalSafe(g_unwind_errors[g_num_unwind_errors].str,
  450. "unwinding at ", cursor->ToString(), ": ", args...);
  451. #endif
  452. g_num_unwind_errors++;
  453. }
  454. static void CheckUnwind(UnwindCursor *cursor) {
  455. const crypto_word_t kStartAddress =
  456. reinterpret_cast<crypto_word_t>(&abi_test_unwind_start);
  457. const crypto_word_t kReturnAddress =
  458. reinterpret_cast<crypto_word_t>(&abi_test_unwind_return);
  459. const crypto_word_t kStopAddress =
  460. reinterpret_cast<crypto_word_t>(&abi_test_unwind_stop);
  461. crypto_word_t sp = cursor->GetSP().ValueOrDie("Error getting stack pointer");
  462. crypto_word_t ip =
  463. cursor->GetIP().ValueOrDie("Error getting instruction pointer");
  464. if (!g_in_trampoline) {
  465. if (ip != kStartAddress) {
  466. FatalError("Unexpected SIGTRAP at ", cursor->ToString());
  467. }
  468. // Save the current state and begin.
  469. g_in_trampoline = true;
  470. g_unwind_function_done = false;
  471. g_trampoline_sp = sp;
  472. g_trampoline_state = cursor->GetCallerState().ValueOrDie(
  473. "Error getting initial caller state");
  474. } else {
  475. if (sp == g_trampoline_sp || g_unwind_function_done) {
  476. // |g_unwind_function_done| should imply |sp| is |g_trampoline_sp|, but
  477. // clearing the trap flag in x86 briefly displaces the stack pointer.
  478. //
  479. // Also note we check both |ip| and |sp| below, in case the function under
  480. // test is also |abi_test_trampoline|.
  481. if (ip == kReturnAddress && sp == g_trampoline_sp) {
  482. g_unwind_function_done = true;
  483. }
  484. if (ip == kStopAddress && sp == g_trampoline_sp) {
  485. // |SIGTRAP| is fatal again.
  486. g_in_trampoline = false;
  487. }
  488. } else if (IsAncestorStackFrame(sp, g_trampoline_sp)) {
  489. // This should never happen. We went past |g_trampoline_sp| without
  490. // stopping at |kStopAddress|.
  491. AddUnwindError(cursor, "stack frame is before caller");
  492. g_in_trampoline = false;
  493. } else if (g_num_unwind_errors < kMaxUnwindErrors) {
  494. for (;;) {
  495. UnwindStatusOr<bool> step_ret = cursor->Step();
  496. if (!step_ret.ok()) {
  497. AddUnwindError(cursor, "error unwinding: ", step_ret.Error());
  498. break;
  499. }
  500. // |Step| returns whether there was a frame to unwind.
  501. if (!step_ret.ValueOrDie()) {
  502. AddUnwindError(cursor, "could not unwind to starting frame");
  503. break;
  504. }
  505. UnwindStatusOr<crypto_word_t> cur_sp = cursor->GetSP();
  506. if (!cur_sp.ok()) {
  507. AddUnwindError(cursor,
  508. "error recovering stack pointer: ", cur_sp.Error());
  509. break;
  510. }
  511. if (IsAncestorStackFrame(cur_sp.ValueOrDie(), g_trampoline_sp)) {
  512. AddUnwindError(cursor, "unwound past starting frame");
  513. break;
  514. }
  515. if (cur_sp.ValueOrDie() == g_trampoline_sp) {
  516. // We found the parent frame. Check the return address.
  517. UnwindStatusOr<crypto_word_t> cur_ip = cursor->GetIP();
  518. if (!cur_ip.ok()) {
  519. AddUnwindError(cursor,
  520. "error recovering return address: ", cur_ip.Error());
  521. } else if (cur_ip.ValueOrDie() != kReturnAddress) {
  522. AddUnwindError(cursor, "wrong return address");
  523. }
  524. // Check the remaining registers.
  525. UnwindStatusOr<CallerState> state = cursor->GetCallerState();
  526. if (!state.ok()) {
  527. AddUnwindError(cursor,
  528. "error recovering registers: ", state.Error());
  529. } else {
  530. ForEachMismatch(state.ValueOrDie(), g_trampoline_state,
  531. [&](const char *reg) {
  532. AddUnwindError(cursor, reg, " was not recovered");
  533. });
  534. }
  535. break;
  536. }
  537. }
  538. }
  539. }
  540. }
  541. static void ReadUnwindResult(Result *out) {
  542. for (size_t i = 0; i < g_num_unwind_errors; i++) {
  543. #if defined(OPENSSL_WINDOWS)
  544. const crypto_word_t ip = g_unwind_errors[i].ip;
  545. char buf[256];
  546. DWORD64 displacement;
  547. struct {
  548. SYMBOL_INFO info;
  549. char name_buf[128];
  550. } symbol;
  551. memset(&symbol, 0, sizeof(symbol));
  552. symbol.info.SizeOfStruct = sizeof(symbol.info);
  553. symbol.info.MaxNameLen = sizeof(symbol.name_buf);
  554. if (SymFromAddr(GetCurrentProcess(), ip, &displacement, &symbol.info)) {
  555. snprintf(buf, sizeof(buf), "unwinding at %s+%llu (0x%s): %s",
  556. symbol.info.Name, displacement, WordToHex(ip).data(),
  557. g_unwind_errors[i].str);
  558. } else {
  559. snprintf(buf, sizeof(buf), "unwinding at 0x%s: %s",
  560. WordToHex(ip).data(), g_unwind_errors[i].str);
  561. }
  562. out->errors.emplace_back(buf);
  563. #else
  564. out->errors.emplace_back(g_unwind_errors[i].str);
  565. #endif
  566. }
  567. if (g_num_unwind_errors == kMaxUnwindErrors) {
  568. out->errors.emplace_back("(additional errors omitted)");
  569. }
  570. g_num_unwind_errors = 0;
  571. }
  572. #if defined(OPENSSL_WINDOWS)
  573. static DWORD g_main_thread;
  574. static long ExceptionHandler(EXCEPTION_POINTERS *info) {
  575. if (info->ExceptionRecord->ExceptionCode != EXCEPTION_SINGLE_STEP ||
  576. GetCurrentThreadId() != g_main_thread) {
  577. return EXCEPTION_CONTINUE_SEARCH;
  578. }
  579. UnwindCursor cursor(*info->ContextRecord);
  580. CheckUnwind(&cursor);
  581. if (g_in_trampoline) {
  582. // Windows clears the trap flag, so we must restore it.
  583. info->ContextRecord->EFlags |= 0x100;
  584. }
  585. return EXCEPTION_CONTINUE_EXECUTION;
  586. }
  587. static void EnableUnwindTestsImpl() {
  588. if (IsDebuggerPresent()) {
  589. // Unwind tests drive logic via |EXCEPTION_SINGLE_STEP|, which conflicts with
  590. // debuggers.
  591. fprintf(stderr, "Debugger detected. Disabling unwind tests.\n");
  592. return;
  593. }
  594. g_main_thread = GetCurrentThreadId();
  595. SymSetOptions(SYMOPT_DEFERRED_LOADS);
  596. if (!SymInitialize(GetCurrentProcess(), nullptr, TRUE)) {
  597. fprintf(stderr, "Could not initialize symbols.\n");
  598. }
  599. if (AddVectoredExceptionHandler(0, ExceptionHandler) == nullptr) {
  600. fprintf(stderr, "Error installing exception handler.\n");
  601. abort();
  602. }
  603. g_unwind_tests_enabled = true;
  604. }
  605. #else // !OPENSSL_WINDOWS
  606. // HandleEINTR runs |func| and returns the result, retrying the operation on
  607. // |EINTR|.
  608. template <typename Func>
  609. static auto HandleEINTR(const Func &func) -> decltype(func()) {
  610. decltype(func()) ret;
  611. do {
  612. ret = func();
  613. } while (ret < 0 && errno == EINTR);
  614. return ret;
  615. }
  616. static bool ReadFileToString(std::string *out, const char *path) {
  617. out->clear();
  618. int fd = HandleEINTR([&] { return open(path, O_RDONLY); });
  619. if (fd < 0) {
  620. return false;
  621. }
  622. for (;;) {
  623. char buf[1024];
  624. ssize_t ret = HandleEINTR([&] { return read(fd, buf, sizeof(buf)); });
  625. if (ret < 0) {
  626. close(fd);
  627. return false;
  628. }
  629. if (ret == 0) {
  630. close(fd);
  631. return true;
  632. }
  633. out->append(buf, static_cast<size_t>(ret));
  634. }
  635. }
  636. static bool IsBeingDebugged() {
  637. std::string status;
  638. if (!ReadFileToString(&status, "/proc/self/status")) {
  639. perror("error reading /proc/self/status");
  640. return false;
  641. }
  642. std::string key = "\nTracerPid:\t";
  643. size_t idx = status.find(key);
  644. if (idx == std::string::npos) {
  645. return false;
  646. }
  647. idx += key.size();
  648. return idx < status.size() && status[idx] != '0';
  649. }
  650. static pthread_t g_main_thread;
  651. static void TrapHandler(int sig) {
  652. // Note this is a signal handler, so only async-signal-safe functions may be
  653. // used here. See signal-safety(7). libunwind promises local unwind is
  654. // async-signal-safe.
  655. // |pthread_equal| is not listed as async-signal-safe, but this is clearly an
  656. // oversight.
  657. if (!pthread_equal(g_main_thread, pthread_self())) {
  658. FatalError("SIGTRAP on background thread");
  659. }
  660. unw_context_t ctx;
  661. int ret = unw_getcontext(&ctx);
  662. if (ret < 0) {
  663. FatalError("Error getting unwind context: ", unw_strerror(ret));
  664. }
  665. UnwindCursor cursor(&ctx);
  666. CheckUnwind(&cursor);
  667. }
  668. static void EnableUnwindTestsImpl() {
  669. if (IsBeingDebugged()) {
  670. // Unwind tests drive logic via |SIGTRAP|, which conflicts with debuggers.
  671. fprintf(stderr, "Debugger detected. Disabling unwind tests.\n");
  672. return;
  673. }
  674. g_main_thread = pthread_self();
  675. struct sigaction trap_action;
  676. OPENSSL_memset(&trap_action, 0, sizeof(trap_action));
  677. sigemptyset(&trap_action.sa_mask);
  678. trap_action.sa_handler = TrapHandler;
  679. if (sigaction(SIGTRAP, &trap_action, NULL) != 0) {
  680. perror("sigaction");
  681. abort();
  682. }
  683. g_unwind_tests_enabled = true;
  684. }
  685. #endif // OPENSSL_WINDOWS
  686. #else // !SUPPORTS_UNWIND_TEST
  687. #if defined(SUPPORTS_ABI_TEST)
  688. static void ReadUnwindResult(Result *) {}
  689. #endif
  690. static void EnableUnwindTestsImpl() {}
  691. #endif // SUPPORTS_UNWIND_TEST
  692. } // namespace internal
  693. void EnableUnwindTests() { internal::EnableUnwindTestsImpl(); }
  694. bool UnwindTestsEnabled() { return internal::g_unwind_tests_enabled; }
  695. } // namespace abi_test