blob: 44547f812a2ae5de7f705fa87c98bd69b6a58c52 [file] [log] [blame]
Robert Sloan4c22c5f2019-03-01 15:53:37 -08001/* 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
15#ifndef OPENSSL_HEADER_ABI_TEST_H
16#define OPENSSL_HEADER_ABI_TEST_H
17
18#include <gtest/gtest.h>
19
20#include <string>
21#include <type_traits>
22#include <vector>
23
24#include <openssl/base.h>
25
26#include "../internal.h"
27
28
29// abi_test provides routines for verifying that functions satisfy platform ABI
30// requirements.
31namespace abi_test {
32
33// Result stores the result of an ABI test.
34struct Result {
35 bool ok() const { return errors.empty(); }
36
37 std::vector<std::string> errors;
38};
39
40namespace internal {
41
42// DeductionGuard wraps |T| in a template, so that template argument deduction
43// does not apply to it. This may be used to force C++ to deduce template
44// arguments from another parameter.
45template <typename T>
46struct DeductionGuard {
47 using Type = T;
48};
49
50// Reg128 contains storage space for a 128-bit register.
51struct alignas(16) Reg128 {
52 bool operator==(const Reg128 &x) const { return x.lo == lo && x.hi == hi; }
53 bool operator!=(const Reg128 &x) const { return !((*this) == x); }
54 uint64_t lo, hi;
55};
56
57// LOOP_CALLER_STATE_REGISTERS is a macro that iterates over all registers the
58// callee is expected to save for the caller, with the exception of the stack
59// pointer. The stack pointer is tested implicitly by the function successfully
60// returning at all.
61#if defined(OPENSSL_X86_64)
62
63// References:
64// SysV64: https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf
65// Win64: https://docs.microsoft.com/en-us/cpp/build/x64-software-conventions?view=vs-2017#register-usage
66#if defined(OPENSSL_WINDOWS)
67#define LOOP_CALLER_STATE_REGISTERS() \
68 CALLER_STATE_REGISTER(uint64_t, rbx) \
69 CALLER_STATE_REGISTER(uint64_t, rbp) \
70 CALLER_STATE_REGISTER(uint64_t, rdi) \
71 CALLER_STATE_REGISTER(uint64_t, rsi) \
72 CALLER_STATE_REGISTER(uint64_t, r12) \
73 CALLER_STATE_REGISTER(uint64_t, r13) \
74 CALLER_STATE_REGISTER(uint64_t, r14) \
75 CALLER_STATE_REGISTER(uint64_t, r15) \
76 CALLER_STATE_REGISTER(Reg128, xmm6) \
77 CALLER_STATE_REGISTER(Reg128, xmm7) \
78 CALLER_STATE_REGISTER(Reg128, xmm8) \
79 CALLER_STATE_REGISTER(Reg128, xmm9) \
80 CALLER_STATE_REGISTER(Reg128, xmm10) \
81 CALLER_STATE_REGISTER(Reg128, xmm11) \
82 CALLER_STATE_REGISTER(Reg128, xmm12) \
83 CALLER_STATE_REGISTER(Reg128, xmm13) \
84 CALLER_STATE_REGISTER(Reg128, xmm14) \
85 CALLER_STATE_REGISTER(Reg128, xmm15)
86#else
87#define LOOP_CALLER_STATE_REGISTERS() \
88 CALLER_STATE_REGISTER(uint64_t, rbx) \
89 CALLER_STATE_REGISTER(uint64_t, rbp) \
90 CALLER_STATE_REGISTER(uint64_t, r12) \
91 CALLER_STATE_REGISTER(uint64_t, r13) \
92 CALLER_STATE_REGISTER(uint64_t, r14) \
93 CALLER_STATE_REGISTER(uint64_t, r15)
94#endif // OPENSSL_WINDOWS
95
96#elif defined(OPENSSL_X86)
97
98// References:
99// SysV32: https://uclibc.org/docs/psABI-i386.pdf and
100// Win32: https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions?view=vs-2017
101#define LOOP_CALLER_STATE_REGISTERS() \
102 CALLER_STATE_REGISTER(uint32_t, esi) \
103 CALLER_STATE_REGISTER(uint32_t, edi) \
104 CALLER_STATE_REGISTER(uint32_t, ebx) \
105 CALLER_STATE_REGISTER(uint32_t, ebp)
106
107#elif defined(OPENSSL_ARM)
108
109// References:
110// AAPCS: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042f/IHI0042F_aapcs.pdf
111// iOS32: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARMv6FunctionCallingConventions.html
112// Linux: http://sourcery.mentor.com/sgpp/lite/arm/portal/kbattach142/arm_gnu_linux_%20abi.pdf
113//
114// ARM specifies a common calling convention, except r9 is left to the platform.
115// Linux treats r9 as callee-saved, while iOS 3+ treats it as caller-saved. Most
116// of our assembly treats it as callee-saved to be uniform, but we match the
117// platform to avoid false positives when testing compiler-generated output.
118#define LOOP_CALLER_STATE_REGISTERS_PRE_R9() \
119 CALLER_STATE_REGISTER(uint64_t, d8) \
120 CALLER_STATE_REGISTER(uint64_t, d9) \
121 CALLER_STATE_REGISTER(uint64_t, d10) \
122 CALLER_STATE_REGISTER(uint64_t, d11) \
123 CALLER_STATE_REGISTER(uint64_t, d12) \
124 CALLER_STATE_REGISTER(uint64_t, d13) \
125 CALLER_STATE_REGISTER(uint64_t, d14) \
126 CALLER_STATE_REGISTER(uint64_t, d15) \
127 CALLER_STATE_REGISTER(uint32_t, r4) \
128 CALLER_STATE_REGISTER(uint32_t, r5) \
129 CALLER_STATE_REGISTER(uint32_t, r6) \
130 CALLER_STATE_REGISTER(uint32_t, r7) \
131 CALLER_STATE_REGISTER(uint32_t, r8)
132#define LOOP_CALLER_STATE_REGISTERS_POST_R9() \
133 CALLER_STATE_REGISTER(uint32_t, r10) \
134 CALLER_STATE_REGISTER(uint32_t, r11)
135#if defined(OPENSSL_APPLE)
136#define LOOP_CALLER_STATE_REGISTERS() \
137 LOOP_CALLER_STATE_REGISTERS_PRE_R9() \
138 LOOP_CALLER_STATE_REGISTERS_POST_R9()
139#else // !OPENSSL_APPLE
140#define LOOP_CALLER_STATE_REGISTERS() \
141 LOOP_CALLER_STATE_REGISTERS_PRE_R9() \
142 CALLER_STATE_REGISTER(uint32_t, r9) \
143 LOOP_CALLER_STATE_REGISTERS_POST_R9()
144#endif // OPENSSL_APPLE
145
146#elif defined(OPENSSL_AARCH64)
147
148// References:
149// AAPCS64: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
150// iOS64: https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARM64FunctionCallingConventions.html
151//
Srinivas Paladugudd42a612019-08-09 19:30:39 +0000152// In aarch64, r19 (x19 in a 64-bit context) is the platform register. iOS says
153// user code may not touch it. We found no clear reference for Linux. The iOS
154// behavior implies portable assembly cannot use it, and aarch64 has many
155// registers. Thus this framework ignores register's existence. We can test r19
156// violations with grep.
Robert Sloan4c22c5f2019-03-01 15:53:37 -0800157#define LOOP_CALLER_STATE_REGISTERS() \
158 /* Per AAPCS64, section 5.1.2, only the bottom 64 bits of v8-v15 */ \
159 /* are preserved. These are accessed as dN. */ \
160 CALLER_STATE_REGISTER(uint64_t, d8) \
161 CALLER_STATE_REGISTER(uint64_t, d9) \
162 CALLER_STATE_REGISTER(uint64_t, d10) \
163 CALLER_STATE_REGISTER(uint64_t, d11) \
164 CALLER_STATE_REGISTER(uint64_t, d12) \
165 CALLER_STATE_REGISTER(uint64_t, d13) \
166 CALLER_STATE_REGISTER(uint64_t, d14) \
167 CALLER_STATE_REGISTER(uint64_t, d15) \
168 /* For consistency with dN, use the 64-bit name xN, rather than */ \
169 /* the generic rN. */ \
170 CALLER_STATE_REGISTER(uint64_t, x19) \
171 CALLER_STATE_REGISTER(uint64_t, x20) \
172 CALLER_STATE_REGISTER(uint64_t, x21) \
173 CALLER_STATE_REGISTER(uint64_t, x22) \
174 CALLER_STATE_REGISTER(uint64_t, x23) \
175 CALLER_STATE_REGISTER(uint64_t, x24) \
176 CALLER_STATE_REGISTER(uint64_t, x25) \
177 CALLER_STATE_REGISTER(uint64_t, x26) \
178 CALLER_STATE_REGISTER(uint64_t, x27) \
179 CALLER_STATE_REGISTER(uint64_t, x28) \
180 CALLER_STATE_REGISTER(uint64_t, x29)
181
182#endif // X86_64 || X86 || ARM || AARCH64
183
184// Enable ABI testing if all of the following are true.
185//
186// - We have CallerState and trampoline support for the architecture.
187//
188// - Assembly is enabled.
189//
190// - This is not a shared library build. Assembly functions are not reachable
191// from tests in shared library builds.
192#if defined(LOOP_CALLER_STATE_REGISTERS) && !defined(OPENSSL_NO_ASM) && \
193 !defined(BORINGSSL_SHARED_LIBRARY)
194#define SUPPORTS_ABI_TEST
195
196// CallerState contains all caller state that the callee is expected to
197// preserve.
198struct CallerState {
199#define CALLER_STATE_REGISTER(type, name) type name;
200 LOOP_CALLER_STATE_REGISTERS()
201#undef CALLER_STATE_REGISTER
202};
203
204// RunTrampoline runs |func| on |argv|, recording ABI errors in |out|. It does
205// not perform any type-checking. If |unwind| is true and unwind tests have been
206// enabled, |func| is single-stepped under an unwind test.
207crypto_word_t RunTrampoline(Result *out, crypto_word_t func,
208 const crypto_word_t *argv, size_t argc,
209 bool unwind);
210
211template <typename T>
212inline crypto_word_t ToWord(T t) {
213#if !defined(OPENSSL_X86) && !defined(OPENSSL_X86_64) && \
214 !defined(OPENSSL_ARM) && !defined(OPENSSL_AARCH64)
215#error "Unknown architecture"
216#endif
217 static_assert(sizeof(T) <= sizeof(crypto_word_t),
218 "T is larger than crypto_word_t");
219 static_assert(sizeof(T) >= 4, "types under four bytes are complicated");
220
221 // ABIs are complex around arguments that are smaller than native words. For
222 // 32-bit architectures, the rules above imply we only have word-sized
223 // arguments. For 64-bit architectures, we still have assembly functions which
224 // take |int|.
225 //
226 // For aarch64, AAPCS64, section 5.4.2, clauses C.7 and C.14 says any
227 // remaining bits are unspecified. iOS64 contradicts this and says the callee
228 // extends arguments up to 32 bits, and only the upper 32 bits are
229 // unspecified. Rejecting parameters smaller than 32 bits avoids the
230 // divergence.
231 //
232 // TODO(davidben): Find authoritative citations for x86_64. For x86_64, I
233 // observed the behavior of Clang, GCC, and MSVC. ABI rules here may be
234 // inferred from two kinds of experiments:
235 //
236 // 1. When passing a value to a small-argument-taking function, does the
237 // compiler ensure unused bits are cleared, sign-extended, etc.? Tests for
238 // register parameters are confounded by x86_64's implicit clearing of
239 // registers' upper halves, but passing some_u64 >> 1 usually clears this.
240 //
241 // 2. When compiling a small-argument-taking function, does the compiler make
242 // assumptions about unused bits of arguments?
243 //
244 // MSVC for x86_64 is straightforward. It appears to tolerate and produce
245 // arbitrary values for unused bits, like AAPCS64.
246 //
247 // GCC and Clang for x86_64 are more complex. They match MSVC for stack
248 // parameters. However, for register parameters, they behave like iOS64 and,
249 // as callers, extend up to 32 bits, leaving the remainder arbitrary. When
250 // compiling a callee, Clang takes advantage of this conversion, but I was
251 // unable to make GCC do so.
252 //
253 // Note that, although the Win64 rules are sufficient to require our assembly
254 // be conservative, we wish for |CHECK_ABI| to support C-compiled functions,
255 // so it must enforce the correct rules for each platform.
256 //
257 // Fortunately, the |static_assert|s above cause all supported architectures
258 // to behave the same.
259 crypto_word_t ret;
260 // Filling extra bits with 0xaa will be vastly out of bounds for code
261 // expecting either sign- or zero-extension. (0xaa is 0b10101010.)
262 OPENSSL_memset(&ret, 0xaa, sizeof(ret));
263 OPENSSL_memcpy(&ret, &t, sizeof(t));
264 return ret;
265}
266
267// CheckImpl runs |func| on |args|, recording ABI errors in |out|. If |unwind|
268// is true and unwind tests have been enabled, |func| is single-stepped under an
269// unwind test.
270//
271// It returns the value as a |crypto_word_t| to work around problems when |R| is
272// void. |args| is wrapped in a |DeductionGuard| so |func| determines the
273// template arguments. Otherwise, |args| may deduce |Args| incorrectly. For
274// instance, if |func| takes const int *, and the caller passes an int *, the
275// compiler will complain the deduced types do not match.
276template <typename R, typename... Args>
277inline crypto_word_t CheckImpl(Result *out, bool unwind, R (*func)(Args...),
278 typename DeductionGuard<Args>::Type... args) {
279 // We only support up to 8 arguments. This ensures all arguments on aarch64
280 // are passed in registers and avoids the iOS descrepancy around packing small
281 // arguments on the stack.
282 //
283 // https://developer.apple.com/library/archive/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARM64FunctionCallingConventions.html
284 static_assert(sizeof...(args) <= 8,
285 "too many arguments for abi_test_trampoline");
286
287 // Allocate one extra entry so MSVC does not complain about zero-size arrays.
288 crypto_word_t argv[sizeof...(args) + 1] = {
289 ToWord(args)...,
290 };
291 return RunTrampoline(out, reinterpret_cast<crypto_word_t>(func), argv,
292 sizeof...(args), unwind);
293}
294#else
295// To simplify callers when ABI testing support is unavoidable, provide a backup
296// CheckImpl implementation. It must be specialized for void returns because we
297// call |func| directly.
298template <typename R, typename... Args>
299inline typename std::enable_if<!std::is_void<R>::value, crypto_word_t>::type
300CheckImpl(Result *out, bool /* unwind */, R (*func)(Args...),
301 typename DeductionGuard<Args>::Type... args) {
302 *out = Result();
303 return func(args...);
304}
305
306template <typename... Args>
307inline crypto_word_t CheckImpl(Result *out, bool /* unwind */,
308 void (*func)(Args...),
309 typename DeductionGuard<Args>::Type... args) {
310 *out = Result();
311 func(args...);
312 return 0;
313}
314#endif // SUPPORTS_ABI_TEST
315
316// FixVAArgsString takes a string like "f, 1, 2" and returns a string like
317// "f(1, 2)".
318//
319// This is needed because the |CHECK_ABI| macro below cannot be defined as
320// CHECK_ABI(func, ...). The C specification requires that variadic macros bind
321// at least one variadic argument. Clang, GCC, and MSVC all ignore this, but
322// there are issues with trailing commas and different behaviors across
323// compilers.
324std::string FixVAArgsString(const char *str);
325
326// CheckGTest behaves like |CheckImpl|, but it returns the correct type and
327// raises GTest assertions on failure. If |unwind| is true and unwind tests are
328// enabled, |func| is single-stepped under an unwind test.
329template <typename R, typename... Args>
330inline R CheckGTest(const char *va_args_str, const char *file, int line,
331 bool unwind, R (*func)(Args...),
332 typename DeductionGuard<Args>::Type... args) {
333 Result result;
334 crypto_word_t ret = CheckImpl(&result, unwind, func, args...);
335 if (!result.ok()) {
336 testing::Message msg;
337 msg << "ABI failures in " << FixVAArgsString(va_args_str) << ":\n";
338 for (const auto &error : result.errors) {
339 msg << " " << error << "\n";
340 }
341 ADD_FAILURE_AT(file, line) << msg;
342 }
343 return (R)ret;
344}
345
346} // namespace internal
347
348// Check runs |func| on |args| and returns the result. If ABI-testing is
349// supported in this build configuration, it writes any ABI failures to |out|.
350// Otherwise, it runs the function transparently.
351template <typename R, typename... Args>
352inline R Check(Result *out, R (*func)(Args...),
353 typename internal::DeductionGuard<Args>::Type... args) {
354 return (R)internal::CheckImpl(out, false, func, args...);
355}
356
357// EnableUnwindTests enables unwind tests, if supported. If not supported, it
358// does nothing.
359void EnableUnwindTests();
360
361// UnwindTestsEnabled returns true if unwind tests are enabled and false
362// otherwise.
363bool UnwindTestsEnabled();
364
365} // namespace abi_test
366
367// CHECK_ABI calls the first argument on the remaining arguments and returns the
368// result. If ABI-testing is supported in this build configuration, it adds a
369// non-fatal GTest failure if the call did not satisfy ABI requirements.
370//
371// |CHECK_ABI| does return the value and thus may replace any function call,
372// provided it takes only simple parameters. However, it is recommended to test
373// ABI separately from functional tests of assembly. Fully instrumenting a
374// function for ABI checking requires single-stepping the function, which is
375// inefficient.
376//
377// Functional testing requires coverage of input values, while ABI testing only
378// requires branch coverage. Most of our assembly is constant-time, so usually
379// only a few instrumented calls are necessary.
380//
381// TODO(https://crbug.com/boringssl/259): Most of Windows assembly currently
382// fails SEH testing. For now, |CHECK_ABI| behaves like |CHECK_ABI_NO_UNWIND|
383// on Windows. Functions which work with unwind testing on Windows should use
384// |CHECK_ABI_SEH|.
385#if defined(OPENSSL_WINDOWS)
386#define CHECK_ABI(...) CHECK_ABI_NO_UNWIND(__VA_ARGS__)
387#else
388#define CHECK_ABI(...) CHECK_ABI_SEH(__VA_ARGS__)
389#endif
390
391// CHECK_ABI_SEH behaves like |CHECK_ABI| but enables unwind testing on Windows.
392#define CHECK_ABI_SEH(...) \
393 abi_test::internal::CheckGTest(#__VA_ARGS__, __FILE__, __LINE__, true, \
394 __VA_ARGS__)
395
396// CHECK_ABI_NO_UNWIND behaves like |CHECK_ABI| but disables unwind testing.
397#define CHECK_ABI_NO_UNWIND(...) \
398 abi_test::internal::CheckGTest(#__VA_ARGS__, __FILE__, __LINE__, false, \
399 __VA_ARGS__)
400
401
402// Internal functions.
403
404#if defined(SUPPORTS_ABI_TEST)
405struct Uncallable {
406 Uncallable() = delete;
407};
408
409extern "C" {
410
411// abi_test_trampoline loads callee-saved registers from |state|, calls |func|
412// with |argv|, then saves the callee-saved registers into |state|. It returns
413// the result of |func|. If |unwind| is non-zero, this function triggers unwind
414// instrumentation.
415//
416// We give |func| type |crypto_word_t| to avoid tripping MSVC's warning 4191.
417crypto_word_t abi_test_trampoline(crypto_word_t func,
418 abi_test::internal::CallerState *state,
419 const crypto_word_t *argv, size_t argc,
420 crypto_word_t unwind);
421
422#if defined(OPENSSL_X86_64)
423// abi_test_unwind_start points at the instruction that starts unwind testing in
424// |abi_test_trampoline|. This is the value of the instruction pointer at the
425// first |SIGTRAP| during unwind testing.
426//
427// This symbol is not a function and should not be called.
428void abi_test_unwind_start(Uncallable);
429
430// abi_test_unwind_return points at the instruction immediately after the call in
431// |abi_test_trampoline|. When unwinding the function under test, this is the
432// expected address in the |abi_test_trampoline| frame. After this address, the
433// unwind tester should ignore |SIGTRAP| until |abi_test_unwind_stop|.
434//
435// This symbol is not a function and should not be called.
436void abi_test_unwind_return(Uncallable);
437
438// abi_test_unwind_stop is the value of the instruction pointer at the final
439// |SIGTRAP| during unwind testing.
440//
441// This symbol is not a function and should not be called.
442void abi_test_unwind_stop(Uncallable);
443
444// abi_test_bad_unwind_wrong_register preserves the ABI, but annotates the wrong
445// register in unwind metadata.
446void abi_test_bad_unwind_wrong_register(void);
447
448// abi_test_bad_unwind_temporary preserves the ABI, but temporarily corrupts the
449// storage space for a saved register, breaking unwind.
450void abi_test_bad_unwind_temporary(void);
451
452#if defined(OPENSSL_WINDOWS)
453// abi_test_bad_unwind_epilog preserves the ABI, and correctly annotates the
454// prolog, but the epilog does not match Win64's rules, breaking unwind during
455// the epilog.
456void abi_test_bad_unwind_epilog(void);
457#endif
458#endif // OPENSSL_X86_64
459
460#if defined(OPENSSL_X86_64) || defined(OPENSSL_X86)
461// abi_test_get_and_clear_direction_flag clears the direction flag. If the flag
462// was previously set, it returns one. Otherwise, it returns zero.
463int abi_test_get_and_clear_direction_flag(void);
464
465// abi_test_set_direction_flag sets the direction flag. This does not conform to
466// ABI requirements and must only be called within a |CHECK_ABI| guard to avoid
467// errors later in the program.
468int abi_test_set_direction_flag(void);
469#endif // OPENSSL_X86_64 || OPENSSL_X86
470
471} // extern "C"
472#endif // SUPPORTS_ABI_TEST
473
474
475#endif // OPENSSL_HEADER_ABI_TEST_H