Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/test/abi_test.cc

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