Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/internal.h

raw
1 // Copyright (C) 1995-1998 Eric Young ([email protected])
2 // Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
4
5 #ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
6 #define OPENSSL_HEADER_CRYPTO_INTERNAL_H
7
8 #include <openssl/crypto.h>
9 #include <openssl/ex_data.h>
10 #include <openssl/service_indicator.h>
11 #include <openssl/stack.h>
12 #include <openssl/thread.h>
13
14 #include <assert.h>
15 #include <string.h>
16
17 #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
18 #include <valgrind/memcheck.h>
19 #endif
20
21 #if defined(BORINGSSL_FIPS_BREAK_TESTS)
22 #include <stdlib.h>
23 #endif
24
25 #if !defined(__cplusplus)
26 #if defined(_MSC_VER)
27 #define alignas(x) __declspec(align(x))
28 #define alignof __alignof
29 #elif !defined(AWS_LC_STDALIGN_AVAILABLE)
30 #define alignas(x) __attribute__ ((aligned (x)))
31 #define alignof(x) __alignof__ (x)
32 #else
33 #include <stdalign.h>
34 #endif
35 #endif
36
37 #if defined(OPENSSL_THREADS) && \
38 (!defined(OPENSSL_WINDOWS) || \
39 (defined(__MINGW32__) && !defined(__clang__)))
40 #include <pthread.h>
41 #define OPENSSL_PTHREADS
42 #endif
43
44 #if defined(OPENSSL_THREADS) && !defined(OPENSSL_PTHREADS) && \
45 defined(OPENSSL_WINDOWS)
46 #define OPENSSL_WINDOWS_THREADS
47 OPENSSL_MSVC_PRAGMA(warning(push, 3))
48 #include <windows.h>
49 OPENSSL_MSVC_PRAGMA(warning(pop))
50 #endif
51
52 #include <stdbool.h>
53
54 #if defined(__cplusplus)
55 extern "C" {
56 #endif
57
58 // On non-MSVC 64-bit targets, we expect __uint128_t support. This includes
59 // clang-cl, which defines both __clang__ and _MSC_VER.
60 #if (!defined(_MSC_VER) || defined(__clang__)) && defined(OPENSSL_64_BIT)
61 #define BORINGSSL_HAS_UINT128
62 typedef __int128_t int128_t;
63 typedef __uint128_t uint128_t;
64
65 // __uint128_t division depends on intrinsics in the compiler runtime. Those
66 // intrinsics are missing in clang-cl (https://crbug.com/787617) and nanolibc.
67 // These may be bugs in the toolchain definition, but just disable it for now.
68 #if !defined(_MSC_VER) && !defined(OPENSSL_NANOLIBC)
69 #define BORINGSSL_CAN_DIVIDE_UINT128
70 #endif
71 #endif
72
73 #define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
74
75 // Have a generic fall-through for different versions of C/C++.
76 #if defined(__cplusplus) && __cplusplus >= 201703L
77 #define OPENSSL_FALLTHROUGH [[fallthrough]]
78 #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__clang__)
79 #define OPENSSL_FALLTHROUGH [[clang::fallthrough]]
80 #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__GNUC__) && \
81 __GNUC__ >= 7
82 #define OPENSSL_FALLTHROUGH [[gnu::fallthrough]]
83 #elif defined(__GNUC__) && __GNUC__ >= 7 // gcc 7
84 #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
85 #elif defined(__clang__)
86 #if __has_attribute(fallthrough) && __clang_major__ >= 5
87 // Clang 3.5, at least, complains about "error: declaration does not declare
88 // anything", possibily because we put a semicolon after this macro in
89 // practice. Thus limit it to >= Clang 5, which does work.
90 #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
91 #else // clang versions that do not support fallthrough.
92 #define OPENSSL_FALLTHROUGH
93 #endif
94 #else // C++11 on gcc 6, and all other cases
95 #define OPENSSL_FALLTHROUGH
96 #endif
97
98 // GCC-like compilers indicate SSE2 with |__SSE2__|. MSVC leaves the caller to
99 // know that x86_64 has SSE2, and uses _M_IX86_FP to indicate SSE2 on x86.
100 // https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-170
101 #if defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || \
102 (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
103 #define OPENSSL_SSE2
104 #endif
105
106 #if defined(OPENSSL_X86) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_SSE2)
107 #error \
108 "x86 assembly requires SSE2. Build with -msse2 (recommended), or disable assembly optimizations with -DOPENSSL_NO_ASM."
109 #endif
110
111 // For convenience in testing the fallback code, we allow disabling SSE2
112 // intrinsics via |OPENSSL_NO_SSE2_FOR_TESTING|. We require SSE2 on x86 and
113 // x86_64, so we would otherwise need to test such code on a non-x86 platform.
114 //
115 // This does not remove the above requirement for SSE2 support with assembly
116 // optimizations. It only disables some intrinsics-based optimizations so that
117 // we can test the fallback code on CI.
118 #if defined(OPENSSL_SSE2) && defined(OPENSSL_NO_SSE2_FOR_TESTING)
119 #undef OPENSSL_SSE2
120 #endif
121
122 #if defined(__GNUC__) || defined(__clang__)
123 #define OPENSSL_ATTR_PURE __attribute__((pure))
124 #else
125 #define OPENSSL_ATTR_PURE
126 #endif
127
128 #if defined(__has_builtin)
129 #define OPENSSL_HAS_BUILTIN(x) __has_builtin(x)
130 #else
131 #define OPENSSL_HAS_BUILTIN(x) 0
132 #endif
133
134
135 // Pointer utility functions.
136
137 // buffers_alias returns one if |a| and |b| alias and zero otherwise.
138 static inline int buffers_alias(const uint8_t *a, size_t a_len,
139 const uint8_t *b, size_t b_len) {
140 // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
141 // objects are undefined whereas pointer to integer conversions are merely
142 // implementation-defined. We assume the implementation defined it in a sane
143 // way.
144 uintptr_t a_u = (uintptr_t)a;
145 uintptr_t b_u = (uintptr_t)b;
146 return a_u + a_len > b_u && b_u + b_len > a_u;
147 }
148
149 typedef uint8_t stack_align_type;
150 OPENSSL_STATIC_ASSERT(sizeof(stack_align_type) == 1,
151 stack_align_type_is_not_8_bits_long)
152
153 // align_pointer returns |ptr|, advanced to |alignment|. |alignment| must be a
154 // power of two, and |ptr| must have at least |alignment - 1| bytes of scratch
155 // space.
156 static inline void *align_pointer(void *ptr, size_t alignment) {
157 // |alignment| must be a power of two.
158 assert(alignment != 0 && (alignment & (alignment - 1)) == 0);
159 // Instead of aligning |ptr| as a |uintptr_t| and casting back, compute the
160 // offset and advance in pointer space. C guarantees that casting from pointer
161 // to |uintptr_t| and back gives the same pointer, but general
162 // integer-to-pointer conversions are implementation-defined. GCC does define
163 // it in the useful way, but this makes fewer assumptions.
164 uintptr_t offset = (0u - (uintptr_t)ptr) & (alignment - 1);
165 ptr = (char *)ptr + offset;
166 assert(((uintptr_t)ptr & (alignment - 1)) == 0);
167 return ptr;
168 }
169
170
171 // Constant-time utility functions.
172 //
173 // The following methods return a bitmask of all ones (0xff...f) for true and 0
174 // for false. This is useful for choosing a value based on the result of a
175 // conditional in constant time. For example,
176 //
177 // if (a < b) {
178 // c = a;
179 // } else {
180 // c = b;
181 // }
182 //
183 // can be written as
184 //
185 // crypto_word_t lt = constant_time_lt_w(a, b);
186 // c = constant_time_select_w(lt, a, b);
187
188 // crypto_word_t is the type that most constant-time functions use. Ideally we
189 // would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit
190 // pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64
191 // bits. Since we want to be able to do constant-time operations on a
192 // |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native
193 // word length.
194 #if defined(OPENSSL_64_BIT)
195 typedef uint64_t crypto_word_t;
196 #elif defined(OPENSSL_32_BIT)
197 typedef uint32_t crypto_word_t;
198 #else
199 #error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
200 #endif
201
202 #define CONSTTIME_TRUE_W ~((crypto_word_t)0)
203 #define CONSTTIME_FALSE_W ((crypto_word_t)0)
204 #define CONSTTIME_TRUE_8 ((uint8_t)0xff)
205 #define CONSTTIME_FALSE_8 ((uint8_t)0)
206
207 // value_barrier_w returns |a|, but prevents GCC and Clang from reasoning about
208 // the returned value. This is used to mitigate compilers undoing constant-time
209 // code, until we can express our requirements directly in the language.
210 //
211 // Note the compiler is aware that |value_barrier_w| has no side effects and
212 // always has the same output for a given input. This allows it to eliminate
213 // dead code, move computations across loops, and vectorize.
214 static inline crypto_word_t value_barrier_w(crypto_word_t a) {
215 #if defined(__GNUC__) || defined(__clang__)
216 __asm__("" : "+r"(a) : /* no inputs */);
217 #endif
218 return a;
219 }
220
221 // value_barrier_u32 behaves like |value_barrier_w| but takes a |uint32_t|.
222 static inline uint32_t value_barrier_u32(uint32_t a) {
223 #if defined(__GNUC__) || defined(__clang__)
224 __asm__("" : "+r"(a) : /* no inputs */);
225 #endif
226 return a;
227 }
228
229 // value_barrier_u64 behaves like |value_barrier_w| but takes a |uint64_t|.
230 static inline uint64_t value_barrier_u64(uint64_t a) {
231 #if defined(__GNUC__) || defined(__clang__)
232 __asm__("" : "+r"(a) : /* no inputs */);
233 #endif
234 return a;
235 }
236
237 // constant_time_msb_w returns the given value with the MSB copied to all the
238 // other bits.
239 static inline crypto_word_t constant_time_msb_w(crypto_word_t a) {
240 return 0u - (a >> (sizeof(a) * 8 - 1));
241 }
242
243 // constant_time_lt_w returns 0xff..f if a < b and 0 otherwise.
244 static inline crypto_word_t constant_time_lt_w(crypto_word_t a,
245 crypto_word_t b) {
246 // Consider the two cases of the problem:
247 // msb(a) == msb(b): a < b iff the MSB of a - b is set.
248 // msb(a) != msb(b): a < b iff the MSB of b is set.
249 //
250 // If msb(a) == msb(b) then the following evaluates as:
251 // msb(a^((a^b)|((a-b)^a))) ==
252 // msb(a^((a-b) ^ a)) == (because msb(a^b) == 0)
253 // msb(a^a^(a-b)) == (rearranging)
254 // msb(a-b) (because ∀x. x^x == 0)
255 //
256 // Else, if msb(a) != msb(b) then the following evaluates as:
257 // msb(a^((a^b)|((a-b)^a))) ==
258 // msb(a^(𝟙 | ((a-b)^a))) == (because msb(a^b) == 1 and 𝟙
259 // represents a value s.t. msb(𝟙) = 1)
260 // msb(a^𝟙) == (because ORing with 1 results in 1)
261 // msb(b)
262 //
263 //
264 // Here is an SMT-LIB verification of this formula:
265 //
266 // (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
267 // (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
268 // )
269 //
270 // (declare-fun a () (_ BitVec 32))
271 // (declare-fun b () (_ BitVec 32))
272 //
273 // (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
274 // (check-sat)
275 // (get-model)
276 return constant_time_msb_w(a^((a^b)|((a-b)^a)));
277 }
278
279 // constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit
280 // mask.
281 static inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) {
282 return (uint8_t)(constant_time_lt_w(a, b));
283 }
284
285 // constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise.
286 static inline crypto_word_t constant_time_ge_w(crypto_word_t a,
287 crypto_word_t b) {
288 return ~constant_time_lt_w(a, b);
289 }
290
291 // constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit
292 // mask.
293 static inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) {
294 return (uint8_t)(constant_time_ge_w(a, b));
295 }
296
297 // constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise.
298 static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) {
299 // Here is an SMT-LIB verification of this formula:
300 //
301 // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
302 // (bvand (bvnot a) (bvsub a #x00000001))
303 // )
304 //
305 // (declare-fun a () (_ BitVec 32))
306 //
307 // (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a #x00000000))))
308 // (check-sat)
309 // (get-model)
310 return constant_time_msb_w(~a & (a - 1));
311 }
312
313 // constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an
314 // 8-bit mask.
315 static inline uint8_t constant_time_is_zero_8(crypto_word_t a) {
316 return (uint8_t)(constant_time_is_zero_w(a));
317 }
318
319 // constant_time_eq_w returns 0xff..f if a == b and 0 otherwise.
320 static inline crypto_word_t constant_time_eq_w(crypto_word_t a,
321 crypto_word_t b) {
322 return constant_time_is_zero_w(a ^ b);
323 }
324
325 // constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit
326 // mask.
327 static inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) {
328 return (uint8_t)(constant_time_eq_w(a, b));
329 }
330
331 // constant_time_eq_int acts like |constant_time_eq_w| but works on int
332 // values.
333 static inline crypto_word_t constant_time_eq_int(int a, int b) {
334 return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b));
335 }
336
337 // constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
338 // mask.
339 static inline uint8_t constant_time_eq_int_8(int a, int b) {
340 return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b));
341 }
342
343 // constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all
344 // 1s or all 0s (as returned by the methods above), the select methods return
345 // either |a| (if |mask| is nonzero) or |b| (if |mask| is zero).
346 static inline crypto_word_t constant_time_select_w(crypto_word_t mask,
347 crypto_word_t a,
348 crypto_word_t b) {
349 // Clang recognizes this pattern as a select. While it usually transforms it
350 // to a cmov, it sometimes further transforms it into a branch, which we do
351 // not want.
352 //
353 // Adding barriers to both |mask| and |~mask| breaks the relationship between
354 // the two, which makes the compiler stick with bitmasks.
355 return (value_barrier_w(mask) & a) | (value_barrier_w(~mask) & b);
356 }
357
358 // constant_time_select_8 acts like |constant_time_select| but operates on
359 // 8-bit values.
360 static inline uint8_t constant_time_select_8(uint8_t mask, uint8_t a,
361 uint8_t b) {
362 return (uint8_t)(constant_time_select_w(mask, a, b));
363 }
364
365 // constant_time_select_int acts like |constant_time_select| but operates on
366 // ints.
367 static inline int constant_time_select_int(crypto_word_t mask, int a, int b) {
368 return (int)(constant_time_select_w(mask, (crypto_word_t)(a),
369 (crypto_word_t)(b)));
370 }
371
372 // constant_time_select_array_w applies |constant_time_select_w| on each
373 // corresponding pair of elements of a and b.
374 static inline void constant_time_select_array_w(
375 crypto_word_t *c, crypto_word_t *a, crypto_word_t *b,
376 crypto_word_t mask, size_t len) {
377 for (size_t i = 0; i < len; i++) {
378 c[i] = constant_time_select_w(mask, a[i], b[i]);
379 }
380 }
381
382 static inline void constant_time_select_array_8(
383 uint8_t *c, uint8_t *a, uint8_t *b, uint8_t mask, size_t len) {
384 for (size_t i = 0; i < len; i++) {
385 c[i] = constant_time_select_8(mask, a[i], b[i]);
386 }
387 }
388
389 // constant_time_select_entry_from_table_w selects the idx-th entry from table.
390 static inline void constant_time_select_entry_from_table_w(
391 crypto_word_t *out, crypto_word_t *table,
392 size_t idx, size_t num_entries, size_t entry_size) {
393 for (size_t i = 0; i < num_entries; i++) {
394 crypto_word_t mask = constant_time_eq_w(i, idx);
395 constant_time_select_array_w(out, &table[i * entry_size], out, mask, entry_size);
396 }
397 }
398
399 static inline void constant_time_select_entry_from_table_8(
400 uint8_t *out, uint8_t *table, size_t idx,
401 size_t num_entries, size_t entry_size) {
402 for (size_t i = 0; i < num_entries; i++) {
403 uint8_t mask = (uint8_t)(constant_time_eq_w(i, idx));
404 constant_time_select_array_8(out, &table[i * entry_size], out, mask, entry_size);
405 }
406 }
407
408 #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
409
410 // CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region
411 // of memory as secret. Secret data is tracked as it flows to registers and
412 // other parts of a memory. If secret data is used as a condition for a branch,
413 // or as a memory index, it will trigger warnings in valgrind.
414 #define CONSTTIME_SECRET(ptr, len) VALGRIND_MAKE_MEM_UNDEFINED(ptr, len)
415
416 // CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that
417 // region of memory as public. Public data is not subject to constant-time
418 // rules.
419 #define CONSTTIME_DECLASSIFY(ptr, len) VALGRIND_MAKE_MEM_DEFINED(ptr, len)
420
421 #else
422
423 #define CONSTTIME_SECRET(ptr, len)
424 #define CONSTTIME_DECLASSIFY(ptr, len)
425
426 #endif // BORINGSSL_CONSTANT_TIME_VALIDATION
427
428 static inline crypto_word_t constant_time_declassify_w(crypto_word_t v) {
429 // Return |v| through a value barrier to be safe. Valgrind-based constant-time
430 // validation is partly to check the compiler has not undone any constant-time
431 // work. Any place |BORINGSSL_CONSTANT_TIME_VALIDATION| influences
432 // optimizations, this validation is inaccurate.
433 //
434 // However, by sending pointers through valgrind, we likely inhibit escape
435 // analysis. On local variables, particularly booleans, we likely
436 // significantly impact optimizations.
437 //
438 // Thus, to be safe, stick a value barrier, in hopes of comparably inhibiting
439 // compiler analysis.
440 CONSTTIME_DECLASSIFY(&v, sizeof(v));
441 return value_barrier_w(v);
442 }
443
444 static inline int constant_time_declassify_int(int v) {
445 OPENSSL_STATIC_ASSERT(sizeof(uint32_t) == sizeof(int),
446 int_is_not_the_same_size_as_uint32_t);
447 // See comment above.
448 CONSTTIME_DECLASSIFY(&v, sizeof(v));
449 return value_barrier_u32(v);
450 }
451
452 // declassify_assert behaves like |assert| but declassifies the result of
453 // evaluating |expr|. This allows the assertion to branch on the (presumably
454 // public) result, but still ensures that values leading up to the computation
455 // were secret.
456 #define declassify_assert(expr) assert(constant_time_declassify_int(expr))
457
458
459 // Thread-safe initialisation.
460
461 #if !defined(OPENSSL_THREADS)
462 typedef uint32_t CRYPTO_once_t;
463 #define CRYPTO_ONCE_INIT 0
464 #elif defined(OPENSSL_WINDOWS_THREADS)
465 typedef INIT_ONCE CRYPTO_once_t;
466 #define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
467 #elif defined(OPENSSL_PTHREADS)
468 typedef pthread_once_t CRYPTO_once_t;
469 #define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
470 #else
471 #error "Unknown threading library"
472 #endif
473
474 // CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
475 // concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
476 // then they will block until |init| completes, but |init| will have only been
477 // called once.
478 //
479 // The |once| argument must be a |CRYPTO_once_t| that has been initialised with
480 // the value |CRYPTO_ONCE_INIT|.
481 OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));
482
483
484 // Reference counting.
485
486 #if !defined(__STDC_NO_ATOMICS__) && defined(__STDC_VERSION__) && \
487 __STDC_VERSION__ >= 201112L
488 #include <stdatomic.h>
489 // CRYPTO_refcount_t is a |uint32_t|
490 #define AWS_LC_ATOMIC_LOCK_FREE ATOMIC_LONG_LOCK_FREE
491 #else
492 #define AWS_LC_ATOMIC_LOCK_FREE 0
493 #endif
494
495 // Automatically enable C11 atomics if implemented and lock free
496 #if !defined(OPENSSL_C11_ATOMIC) && defined(OPENSSL_THREADS) && \
497 AWS_LC_ATOMIC_LOCK_FREE == 2
498 #define OPENSSL_C11_ATOMIC
499 #endif
500
501 // Older MSVC does not support C11 atomics, so we fallback to the Windows APIs.
502 // This can be removed once we can rely on
503 // https://devblogs.microsoft.com/cppblog/c11-atomics-in-visual-studio-2022-version-17-5-preview-2/
504 #if !defined(OPENSSL_C11_ATOMIC) && defined(OPENSSL_THREADS) && \
505 defined(OPENSSL_WINDOWS)
506 #define OPENSSL_WINDOWS_ATOMIC
507 #endif
508
509 // CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates.
510 #define CRYPTO_REFCOUNT_MAX 0xffffffff
511
512 // CRYPTO_refcount_inc atomically increments the value at |*count| unless the
513 // value would overflow. It's safe for multiple threads to concurrently call
514 // this or |CRYPTO_refcount_dec_and_test_zero| on the same
515 // |CRYPTO_refcount_t|.
516 OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
517
518 // CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
519 // if it's zero, it crashes the address space.
520 // if it's the maximum value, it returns zero.
521 // otherwise, it atomically decrements it and returns one iff the resulting
522 // value is zero.
523 //
524 // It's safe for multiple threads to concurrently call this or
525 // |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|.
526 OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
527
528
529 // Locks.
530 //
531 // Two types of locks are defined: |CRYPTO_MUTEX|, which can be used in
532 // structures as normal, and |struct CRYPTO_STATIC_MUTEX|, which can be used as
533 // a global lock. A global lock must be initialised to the value
534 // |CRYPTO_STATIC_MUTEX_INIT|.
535 //
536 // |CRYPTO_MUTEX| can appear in public structures and so is defined in
537 // thread.h as a structure large enough to fit the real type. The global lock is
538 // a different type so it may be initialized with platform initializer macros.
539
540 #if !defined(OPENSSL_THREADS)
541 struct CRYPTO_STATIC_MUTEX {
542 char padding; // Empty structs have different sizes in C and C++.
543 };
544 #define CRYPTO_STATIC_MUTEX_INIT { 0 }
545 #elif defined(OPENSSL_WINDOWS_THREADS)
546 struct CRYPTO_STATIC_MUTEX {
547 SRWLOCK lock;
548 };
549 #define CRYPTO_STATIC_MUTEX_INIT { SRWLOCK_INIT }
550 #elif defined(OPENSSL_PTHREADS)
551 struct CRYPTO_STATIC_MUTEX {
552 pthread_rwlock_t lock;
553 };
554 #define CRYPTO_STATIC_MUTEX_INIT { PTHREAD_RWLOCK_INITIALIZER }
555 #else
556 #error "Unknown threading library"
557 #endif
558
559 // CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
560 // |CRYPTO_STATIC_MUTEX|.
561 OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);
562
563 // CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
564 // read lock, but none may have a write lock.
565 OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);
566
567 // CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
568 // of lock on it.
569 OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);
570
571 // CRYPTO_MUTEX_unlock_read unlocks |lock| for reading.
572 OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);
573
574 // CRYPTO_MUTEX_unlock_write unlocks |lock| for writing.
575 OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);
576
577 // CRYPTO_MUTEX_cleanup releases all resources held by |lock|.
578 OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);
579
580 // CRYPTO_STATIC_MUTEX_lock_read locks |lock| such that other threads may also
581 // have a read lock, but none may have a write lock. The |lock| variable does
582 // not need to be initialised by any function, but must have been statically
583 // initialised with |CRYPTO_STATIC_MUTEX_INIT|.
584 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_read(
585 struct CRYPTO_STATIC_MUTEX *lock);
586
587 // CRYPTO_STATIC_MUTEX_lock_write locks |lock| such that no other thread has
588 // any type of lock on it. The |lock| variable does not need to be initialised
589 // by any function, but must have been statically initialised with
590 // |CRYPTO_STATIC_MUTEX_INIT|.
591 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_write(
592 struct CRYPTO_STATIC_MUTEX *lock);
593
594 // CRYPTO_STATIC_MUTEX_unlock_read unlocks |lock| for reading.
595 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_read(
596 struct CRYPTO_STATIC_MUTEX *lock);
597
598 // CRYPTO_STATIC_MUTEX_unlock_write unlocks |lock| for writing.
599 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_write(
600 struct CRYPTO_STATIC_MUTEX *lock);
601
602 #if !defined(NDEBUG)
603 // CRYPTO_STATIC_MUTEX_is_write_locked checks whether |lock| has an active write
604 // lock. If it does, the function returns 1. If it doesn't, it returns 0. Returns -1
605 // on any other error. Note that due to the concurrent nature of locks, the result
606 // may be stale by the time it is used.
607 OPENSSL_EXPORT int CRYPTO_STATIC_MUTEX_is_write_locked(
608 struct CRYPTO_STATIC_MUTEX *lock);
609 #endif
610
611 #if defined(__cplusplus)
612 extern "C++" {
613
614 BSSL_NAMESPACE_BEGIN
615
616 namespace internal {
617
618 // MutexLockBase is a RAII helper for CRYPTO_MUTEX locking.
619 template <void (*LockFunc)(CRYPTO_MUTEX *), void (*ReleaseFunc)(CRYPTO_MUTEX *)>
620 class MutexLockBase {
621 public:
622 explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
623 assert(mu_ != nullptr);
624 LockFunc(mu_);
625 }
626 ~MutexLockBase() { ReleaseFunc(mu_); }
627 MutexLockBase(const MutexLockBase<LockFunc, ReleaseFunc> &) = delete;
628 MutexLockBase &operator=(const MutexLockBase<LockFunc, ReleaseFunc> &) =
629 delete;
630
631 private:
632 CRYPTO_MUTEX *const mu_;
633 };
634
635 } // namespace internal
636
637 using MutexWriteLock =
638 internal::MutexLockBase<CRYPTO_MUTEX_lock_write, CRYPTO_MUTEX_unlock_write>;
639 using MutexReadLock =
640 internal::MutexLockBase<CRYPTO_MUTEX_lock_read, CRYPTO_MUTEX_unlock_read>;
641
642 BSSL_NAMESPACE_END
643
644 } // extern "C++"
645 #endif // defined(__cplusplus)
646
647
648 // Thread local storage.
649
650 // thread_local_data_t enumerates the types of thread-local data that can be
651 // stored.
652 typedef enum {
653 OPENSSL_THREAD_LOCAL_ERR = 0,
654 OPENSSL_THREAD_LOCAL_RAND,
655 OPENSSL_THREAD_LOCAL_FIPS_COUNTERS,
656 AWSLC_THREAD_LOCAL_FIPS_SERVICE_INDICATOR_STATE,
657 OPENSSL_THREAD_LOCAL_TEST,
658 OPENSSL_THREAD_LOCAL_PRIVATE_RAND,
659 OPENSSL_THREAD_LOCAL_PUBLIC_RAND,
660 OPENSSL_THREAD_LOCAL_UBE,
661 NUM_OPENSSL_THREAD_LOCALS,
662 } thread_local_data_t;
663
664 // thread_local_destructor_t is the type of a destructor function that will be
665 // called when a thread exits and its thread-local storage needs to be freed.
666 typedef void (*thread_local_destructor_t)(void *);
667
668 // CRYPTO_get_thread_local gets the pointer value that is stored for the
669 // current thread for the given index, or NULL if none has been set.
670 OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);
671
672 // CRYPTO_set_thread_local sets a pointer value for the current thread at the
673 // given index. This function should only be called once per thread for a given
674 // |index|: rather than update the pointer value itself, update the data that
675 // is pointed to.
676 //
677 // The destructor function will be called when a thread exits to free this
678 // thread-local data. All calls to |CRYPTO_set_thread_local| with the same
679 // |index| should have the same |destructor| argument. The destructor may be
680 // called with a NULL argument if a thread that never set a thread-local
681 // pointer for |index|, exits. The destructor may be called concurrently with
682 // different arguments.
683 //
684 // This function returns one on success or zero on error. If it returns zero
685 // then |destructor| has been called with |value| already.
686 OPENSSL_EXPORT int CRYPTO_set_thread_local(
687 thread_local_data_t index, void *value,
688 thread_local_destructor_t destructor);
689
690
691 // ex_data
692
693 typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;
694
695 DECLARE_STACK_OF(CRYPTO_EX_DATA_FUNCS)
696
697 // CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
698 // supports ex_data. It should defined as a static global within the module
699 // which defines that type.
700 typedef struct {
701 struct CRYPTO_STATIC_MUTEX lock;
702 STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
703 // num_reserved is one if the ex_data index zero is reserved for legacy
704 // |TYPE_get_app_data| functions.
705 uint8_t num_reserved;
706 } CRYPTO_EX_DATA_CLASS;
707
708 #define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_STATIC_MUTEX_INIT, NULL, 0}
709 #define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
710 {CRYPTO_STATIC_MUTEX_INIT, NULL, 1}
711
712 // CRYPTO_get_ex_new_index allocates a new index for |ex_data_class| and writes
713 // it to |*out_index|. Each class of object should provide a wrapper function
714 // that uses the correct |CRYPTO_EX_DATA_CLASS|. It returns one on success and
715 // zero otherwise.
716 OPENSSL_EXPORT int CRYPTO_get_ex_new_index(CRYPTO_EX_DATA_CLASS *ex_data_class,
717 int *out_index, long argl,
718 void *argp,
719 CRYPTO_EX_free *free_func);
720
721 // CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
722 // of object should provide a wrapper function.
723 OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);
724
725 // CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
726 // if no such index exists. Each class of object should provide a wrapper
727 // function.
728 OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);
729
730 // CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|.
731 OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);
732
733 // CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an
734 // object of the given class.
735 OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
736 void *obj, CRYPTO_EX_DATA *ad);
737
738
739 // Endianness conversions.
740
741 #if defined(AWS_LC_BUILTIN_SWAP_SUPPORTED)
742 static inline uint16_t CRYPTO_bswap2(uint16_t x) {
743 return __builtin_bswap16(x);
744 }
745
746 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
747 return __builtin_bswap32(x);
748 }
749
750 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
751 return __builtin_bswap64(x);
752 }
753 static inline crypto_word_t CRYPTO_bswap_word(crypto_word_t x) {
754 #if defined(OPENSSL_64_BIT)
755 return CRYPTO_bswap8(x);
756 #else
757 return CRYPTO_bswap4(x);
758 #endif
759 }
760
761
762 #elif defined(_MSC_VER)
763 OPENSSL_MSVC_PRAGMA(warning(push, 3))
764 #include <stdlib.h>
765 OPENSSL_MSVC_PRAGMA(warning(pop))
766 #pragma intrinsic(_byteswap_uint64, _byteswap_ulong, _byteswap_ushort)
767 static inline uint16_t CRYPTO_bswap2(uint16_t x) {
768 return _byteswap_ushort(x);
769 }
770
771 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
772 return _byteswap_ulong(x);
773 }
774
775 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
776 return _byteswap_uint64(x);
777 }
778 #else
779 static inline uint16_t CRYPTO_bswap2(uint16_t x) {
780 return (x >> 8) | (x << 8);
781 }
782
783 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
784 x = (x >> 16) | (x << 16);
785 x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
786 return x;
787 }
788
789 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
790 return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32);
791 }
792 #endif
793
794
795 // Language bug workarounds.
796 //
797 // Most C standard library functions are undefined if passed NULL, even when the
798 // corresponding length is zero. This gives them (and, in turn, all functions
799 // which call them) surprising behavior on empty arrays. Some compilers will
800 // miscompile code due to this rule. See also
801 // https://www.imperialviolet.org/2016/06/26/nonnull.html
802 //
803 // These wrapper functions behave the same as the corresponding C standard
804 // functions, but behave as expected when passed NULL if the length is zero.
805 //
806 // Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|.
807
808 // C++ defines |memchr| as a const-correct overload.
809 #if defined(__cplusplus)
810 extern "C++" {
811
812 static inline const void *OPENSSL_memchr(const void *s, int c, size_t n) {
813 if (n == 0) {
814 return NULL;
815 }
816
817 return memchr(s, c, n);
818 }
819
820 static inline void *OPENSSL_memchr(void *s, int c, size_t n) {
821 if (n == 0) {
822 return NULL;
823 }
824
825 return memchr(s, c, n);
826 }
827
828 } // extern "C++"
829 #else // __cplusplus
830
831 static inline void *OPENSSL_memchr(const void *s, int c, size_t n) {
832 if (n == 0) {
833 return NULL;
834 }
835
836 // C23 makes memchr const-correct, returning const void * when the input is
837 // const void *. Some C libraries apply this change even in C11 mode. Cast to
838 // match our return type.
839 return (void *)memchr(s, c, n);
840 }
841
842 #endif // __cplusplus
843
844 static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) {
845 if (n == 0) {
846 return 0;
847 }
848
849 return memcmp(s1, s2, n);
850 }
851
852 static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) {
853 if (n == 0) {
854 return dst;
855 }
856
857 return memcpy(dst, src, n);
858 }
859
860 static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) {
861 if (n == 0) {
862 return dst;
863 }
864
865 return memmove(dst, src, n);
866 }
867
868 static inline void *OPENSSL_memset(void *dst, int c, size_t n) {
869 if (n == 0) {
870 return dst;
871 }
872
873 return memset(dst, c, n);
874 }
875
876
877 // Loads and stores.
878 //
879 // The following functions load and store sized integers with the specified
880 // endianness. They use |memcpy|, and so avoid alignment or strict aliasing
881 // requirements on the input and output pointers.
882
883 static inline uint16_t CRYPTO_load_u16_le(const void *in) {
884 uint16_t v;
885 OPENSSL_memcpy(&v, in, sizeof(v));
886 #if defined(OPENSSL_BIG_ENDIAN)
887 return CRYPTO_bswap2(v);
888 #else
889 return v;
890 #endif
891 }
892
893 static inline void CRYPTO_store_u16_le(void *out, uint16_t v) {
894 #if defined(OPENSSL_BIG_ENDIAN)
895 v = CRYPTO_bswap2(v);
896 #endif
897 OPENSSL_memcpy(out, &v, sizeof(v));
898 }
899
900 static inline uint16_t CRYPTO_load_u16_be(const void *in) {
901 uint16_t v;
902 OPENSSL_memcpy(&v, in, sizeof(v));
903 #if defined(OPENSSL_BIG_ENDIAN)
904 return v;
905 #else
906 return CRYPTO_bswap2(v);
907 #endif
908 }
909
910 static inline void CRYPTO_store_u16_be(void *out, uint16_t v) {
911 #if !defined(OPENSSL_BIG_ENDIAN)
912 v = CRYPTO_bswap2(v);
913 #endif
914 OPENSSL_memcpy(out, &v, sizeof(v));
915 }
916
917 static inline uint32_t CRYPTO_load_u32_le(const void *in) {
918 uint32_t v;
919 OPENSSL_memcpy(&v, in, sizeof(v));
920 #if defined(OPENSSL_BIG_ENDIAN)
921 return CRYPTO_bswap4(v);
922 #else
923 return v;
924 #endif
925 }
926
927 static inline void CRYPTO_store_u32_le(void *out, uint32_t v) {
928 #if defined(OPENSSL_BIG_ENDIAN)
929 v = CRYPTO_bswap4(v);
930 #endif
931 OPENSSL_memcpy(out, &v, sizeof(v));
932
933 }
934
935 static inline uint32_t CRYPTO_load_u32_be(const void *in) {
936 uint32_t v;
937 OPENSSL_memcpy(&v, in, sizeof(v));
938 #if defined(OPENSSL_BIG_ENDIAN)
939 return v;
940 #else
941 return CRYPTO_bswap4(v);
942 #endif
943 }
944
945 static inline void CRYPTO_store_u32_be(void *out, uint32_t v) {
946
947 #if !defined(OPENSSL_BIG_ENDIAN)
948 v = CRYPTO_bswap4(v);
949 #endif
950 OPENSSL_memcpy(out, &v, sizeof(v));
951
952 }
953
954 static inline uint64_t CRYPTO_load_u64_le(const void *in) {
955 uint64_t v;
956 OPENSSL_memcpy(&v, in, sizeof(v));
957 #if defined(OPENSSL_BIG_ENDIAN)
958 return CRYPTO_bswap8(v);
959 #else
960 return v;
961 #endif
962 }
963
964 static inline void CRYPTO_store_u64_le(void *out, uint64_t v) {
965 #if defined(OPENSSL_BIG_ENDIAN)
966 v = CRYPTO_bswap8(v);
967 #endif
968 OPENSSL_memcpy(out, &v, sizeof(v));
969
970 }
971
972 static inline uint64_t CRYPTO_load_u64_be(const void *ptr) {
973 uint64_t ret;
974 OPENSSL_memcpy(&ret, ptr, sizeof(ret));
975 #if defined(OPENSSL_BIG_ENDIAN)
976 return ret;
977 #else
978 return CRYPTO_bswap8(ret);
979 #endif
980 }
981
982 static inline void CRYPTO_store_u64_be(void *out, uint64_t v) {
983 #if defined(OPENSSL_BIG_ENDIAN)
984 #else
985 v = CRYPTO_bswap8(v);
986 #endif
987 OPENSSL_memcpy(out, &v, sizeof(v));
988
989 }
990
991 static inline crypto_word_t CRYPTO_load_word_le(const void *in) {
992
993 crypto_word_t v;
994 OPENSSL_memcpy(&v, in, sizeof(v));
995 #if defined(OPENSSL_BIG_ENDIAN)
996 return CRYPTO_bswap_word(v);
997 #else
998 return v;
999 #endif
1000 }
1001
1002 static inline void CRYPTO_store_word_le(void *out, crypto_word_t v) {
1003
1004
1005 #if defined(OPENSSL_BIG_ENDIAN)
1006 v = CRYPTO_bswap_word(v);
1007 #endif
1008 OPENSSL_memcpy(out, &v, sizeof(v));
1009
1010 }
1011
1012 static inline crypto_word_t CRYPTO_load_word_be(const void *in) {
1013 crypto_word_t v;
1014 OPENSSL_memcpy(&v, in, sizeof(v));
1015 #if defined(OPENSSL_BIG_ENDIAN)
1016 return v;
1017 #else
1018 #if defined(OPENSSL_64_BIT)
1019 assert(sizeof(v) == 8);
1020 return CRYPTO_bswap8(v);
1021 #else
1022 assert(sizeof(v) == 4);
1023 return CRYPTO_bswap4(v);
1024 #endif
1025 #endif
1026 }
1027
1028 // Bit rotation functions.
1029 //
1030 // Note these functions use |(-shift) & 31|, etc., because shifting by the bit
1031 // width is undefined. Both Clang and GCC recognize this pattern as a rotation,
1032 // but MSVC does not. Instead, we call MSVC's built-in functions.
1033
1034 static inline uint32_t CRYPTO_rotl_u32(uint32_t value, int shift) {
1035 #if defined(_MSC_VER)
1036 return _rotl(value, shift);
1037 #else
1038 return (value << shift) | (value >> ((-shift) & 31));
1039 #endif
1040 }
1041
1042 static inline uint32_t CRYPTO_rotr_u32(uint32_t value, int shift) {
1043 #if defined(_MSC_VER)
1044 return _rotr(value, shift);
1045 #else
1046 return (value >> shift) | (value << ((-shift) & 31));
1047 #endif
1048 }
1049
1050 static inline uint64_t CRYPTO_rotl_u64(uint64_t value, int shift) {
1051 #if defined(_MSC_VER)
1052 return _rotl64(value, shift);
1053 #else
1054 return (value << shift) | (value >> ((-shift) & 63));
1055 #endif
1056 }
1057
1058 static inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) {
1059 #if defined(_MSC_VER)
1060 return _rotr64(value, shift);
1061 #else
1062 return (value >> shift) | (value << ((-shift) & 63));
1063 #endif
1064 }
1065
1066
1067 // Arithmetic functions.
1068
1069 // The most efficient versions of these functions on GCC and Clang depend on C11
1070 // |_Generic|. If we ever need to call these from C++, we'll need to add a
1071 // variant that uses C++ overloads instead.
1072 #if !defined(__cplusplus)
1073
1074 // CRYPTO_addc_* returns |x + y + carry|, and sets |*out_carry| to the carry
1075 // bit. |carry| must be zero or one.
1076 #if OPENSSL_HAS_BUILTIN(__builtin_addc)
1077
1078 #define CRYPTO_GENERIC_ADDC(x, y, carry, out_carry) \
1079 (_Generic((x), \
1080 unsigned: __builtin_addc, \
1081 unsigned long: __builtin_addcl, \
1082 unsigned long long: __builtin_addcll))((x), (y), (carry), (out_carry))
1083
1084 static inline uint32_t CRYPTO_addc_u32(uint32_t x, uint32_t y, uint32_t carry,
1085 uint32_t *out_carry) {
1086 declassify_assert(carry <= 1);
1087 return CRYPTO_GENERIC_ADDC(x, y, carry, out_carry);
1088 }
1089
1090 static inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry,
1091 uint64_t *out_carry) {
1092 declassify_assert(carry <= 1);
1093 return CRYPTO_GENERIC_ADDC(x, y, carry, out_carry);
1094 }
1095
1096 #else
1097
1098 static inline uint32_t CRYPTO_addc_u32(uint32_t x, uint32_t y, uint32_t carry,
1099 uint32_t *out_carry) {
1100 declassify_assert(carry <= 1);
1101 uint64_t ret = carry;
1102 ret += (uint64_t)x + y;
1103 *out_carry = (uint32_t)(ret >> 32);
1104 return (uint32_t)ret;
1105 }
1106
1107 static inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry,
1108 uint64_t *out_carry) {
1109 declassify_assert(carry <= 1);
1110 #if defined(BORINGSSL_HAS_UINT128)
1111 uint128_t ret = carry;
1112 ret += (uint128_t)x + y;
1113 *out_carry = (uint64_t)(ret >> 64);
1114 return (uint64_t)ret;
1115 #else
1116 x += carry;
1117 carry = x < carry;
1118 uint64_t ret = x + y;
1119 carry += ret < x;
1120 *out_carry = carry;
1121 return ret;
1122 #endif
1123 }
1124 #endif
1125
1126 // CRYPTO_subc_* returns |x - y - borrow|, and sets |*out_borrow| to the borrow
1127 // bit. |borrow| must be zero or one.
1128 #if OPENSSL_HAS_BUILTIN(__builtin_subc)
1129
1130 #define CRYPTO_GENERIC_SUBC(x, y, borrow, out_borrow) \
1131 (_Generic((x), \
1132 unsigned: __builtin_subc, \
1133 unsigned long: __builtin_subcl, \
1134 unsigned long long: __builtin_subcll))((x), (y), (borrow), (out_borrow))
1135
1136 static inline uint32_t CRYPTO_subc_u32(uint32_t x, uint32_t y, uint32_t borrow,
1137 uint32_t *out_borrow) {
1138 declassify_assert(borrow <= 1);
1139 return CRYPTO_GENERIC_SUBC(x, y, borrow, out_borrow);
1140 }
1141
1142 static inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow,
1143 uint64_t *out_borrow) {
1144 declassify_assert(borrow <= 1);
1145 return CRYPTO_GENERIC_SUBC(x, y, borrow, out_borrow);
1146 }
1147
1148 #else
1149
1150 static inline uint32_t CRYPTO_subc_u32(uint32_t x, uint32_t y, uint32_t borrow,
1151 uint32_t *out_borrow) {
1152 declassify_assert(borrow <= 1);
1153 uint32_t ret = x - y - borrow;
1154 *out_borrow = (x < y) | ((x == y) & borrow);
1155 return ret;
1156 }
1157
1158 static inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow,
1159 uint64_t *out_borrow) {
1160 declassify_assert(borrow <= 1);
1161 uint64_t ret = x - y - borrow;
1162 *out_borrow = (x < y) | ((x == y) & borrow);
1163 return ret;
1164 }
1165 #endif
1166
1167 #if defined(OPENSSL_64_BIT)
1168 #define CRYPTO_addc_w CRYPTO_addc_u64
1169 #define CRYPTO_subc_w CRYPTO_subc_u64
1170 #else
1171 #define CRYPTO_addc_w CRYPTO_addc_u32
1172 #define CRYPTO_subc_w CRYPTO_subc_u32
1173 #endif
1174
1175 #endif // !__cplusplus
1176
1177
1178 // FIPS functions.
1179
1180 #if defined(BORINGSSL_FIPS)
1181
1182 // AWS_LC_FIPS_failure is called when a FIPS power-on or continuous test
1183 // fails. The behavior depends on how AWS-LC is built:
1184 // - When AWS-LC is not in FIPS mode it prints |message| to |stderr|.
1185 // - If AWS-LC is built with FIPS it prints |message| to |stderr| and prevents
1186 // any further cryptographic operations by the current process.
1187 // - If AWS-LC is built with FIPS, AWSLC_FIPS_FAILURE_CALLBACK, and the
1188 // application does not define the AWS_LC_fips_failure_callback function
1189 // the normal behavior FIPS behavior is used.
1190 // - If AWS-LC is built with FIPS, AWSLC_FIPS_FAILURE_CALLBACK, and the
1191 // application defines the AWS_LC_fips_failure_callback function that
1192 // function is called with |message|.
1193 #if defined(AWSLC_FIPS_FAILURE_CALLBACK)
1194 void AWS_LC_FIPS_failure(const char* message);
1195 #else
1196 #if defined(_MSC_VER)
1197 __declspec(noreturn) void AWS_LC_FIPS_failure(const char* message);
1198 #else
1199 void AWS_LC_FIPS_failure(const char* message) __attribute__((noreturn));
1200 #endif
1201 #endif
1202 // boringssl_self_test_startup runs all startup self tests and returns one on
1203 // success or zero on error. Startup self tests do not include lazy tests.
1204 // Call |BORINGSSL_self_test| to run every self test.
1205 int boringssl_self_test_startup(void);
1206
1207 // boringssl_ensure_rsa_self_test checks whether the RSA self-test has been run
1208 // in this address space. If not, it runs it and crashes the address space if
1209 // unsuccessful.
1210 void boringssl_ensure_rsa_self_test(void);
1211
1212 // boringssl_ensure_ecc_self_test checks whether the ECDSA and ECDH self-test
1213 // has been run in this address space. If not, it runs it and crashes the
1214 // address space if unsuccessful.
1215 void boringssl_ensure_ecc_self_test(void);
1216
1217 // boringssl_ensure_ffdh_self_test checks whether the FFDH self-test has been
1218 // run in this address space. If not, it runs it and crashes the address space
1219 // if unsuccessful.
1220 void boringssl_ensure_ffdh_self_test(void);
1221
1222 // boringssl_ensure_ml_kem_self_test checks whether the ML-KEM self-test
1223 // has been run in this address space. If not, it runs it and crashes the
1224 // address space if unsuccessful.
1225 void boringssl_ensure_ml_kem_self_test(void);
1226
1227 // boringssl_ensure_ml_dsa_self_test checks whether the ML-DSA self-test
1228 // has been run in this address space. If not, it runs it and crashes the
1229 // address space if unsuccessful.
1230 void boringssl_ensure_ml_dsa_self_test(void);
1231
1232 // boringssl_ensure_eddsa_self_test checks whether the EdDSA self-test
1233 // has been run in this address space. If not, it runs it and crashes the
1234 // address space if unsuccessful.
1235 void boringssl_ensure_eddsa_self_test(void);
1236
1237 // boringssl_ensure_hasheddsa_self_test checks whether the HashEdDSA self-test
1238 // has been run in this address space. If not, it runs it and crashes the
1239 // address space if unsuccessful.
1240 void boringssl_ensure_hasheddsa_self_test(void);
1241
1242 #else
1243
1244 // Outside of FIPS mode, the lazy tests are no-ops.
1245
1246 OPENSSL_INLINE void boringssl_ensure_rsa_self_test(void) {}
1247 OPENSSL_INLINE void boringssl_ensure_ecc_self_test(void) {}
1248 OPENSSL_INLINE void boringssl_ensure_ffdh_self_test(void) {}
1249 OPENSSL_INLINE void boringssl_ensure_ml_kem_self_test(void) {}
1250 OPENSSL_INLINE void boringssl_ensure_ml_dsa_self_test(void) {}
1251 OPENSSL_INLINE void boringssl_ensure_eddsa_self_test(void) {}
1252 OPENSSL_INLINE void boringssl_ensure_hasheddsa_self_test(void) {}
1253
1254 // Outside of FIPS mode AWS_LC_FIPS_failure simply logs the message to stderr
1255 void AWS_LC_FIPS_failure(const char* message);
1256
1257 #endif // FIPS
1258
1259 // boringssl_self_test_sha256 performs a SHA-256 KAT
1260 int boringssl_self_test_sha256(void);
1261
1262 // boringssl_self_test_hmac_sha256 performs an HMAC-SHA-256 KAT
1263 int boringssl_self_test_hmac_sha256(void);
1264
1265 #if defined(BORINGSSL_FIPS_BREAK_TESTS)
1266 OPENSSL_INLINE int boringssl_fips_break_test(const char *test) {
1267 const char *const value = getenv("BORINGSSL_FIPS_BREAK_TEST");
1268 return value != NULL && strcmp(value, test) == 0;
1269 }
1270 #else
1271 OPENSSL_INLINE int boringssl_fips_break_test(const char *test) {
1272 return 0;
1273 }
1274 #endif // BORINGSSL_FIPS_BREAK_TESTS
1275
1276 #if defined(BORINGSSL_DISPATCH_TEST)
1277 // Runtime CPU dispatch testing support
1278
1279 // BORINGSSL_function_hit is an array of flags. The following functions will
1280 // set these flags if BORINGSSL_DISPATCH_TEST is defined.
1281 // On x86 and x86_64:
1282 // 0: aes_hw_ctr32_encrypt_blocks
1283 // 1: aes_hw_encrypt
1284 // 2: aesni_gcm_encrypt
1285 // 3: aes_hw_set_encrypt_key
1286 // 4: vpaes_encrypt
1287 // 5: vpaes_set_encrypt_key
1288 // 6: sha256_block_data_order_shaext
1289 // 7: aes_gcm_encrypt_avx512
1290 // 8: RSAZ_mod_exp_avx512_x2
1291 // 9: sha3_keccak_f1600
1292 // 10: sha3_keccak4_f1600_alt
1293 // On AARCH64:
1294 // 0: aes_hw_ctr32_encrypt_blocks
1295 // 1: aes_hw_encrypt
1296 // 2: aes_gcm_enc_kernel
1297 // 3: aes_hw_set_encrypt_key
1298 // 4: vpaes_encrypt
1299 // 5: vpaes_set_encrypt_key
1300 // 6: sha256_block_armv8
1301 // 7: aesv8_gcm_8x_enc_128
1302 // 8: sha512_block_armv8
1303 // 9: KeccakF1600_hw
1304 // 10: sha3_keccak_f1600
1305 // 11: sha3_keccak_f1600_alt
1306 // 12: sha3_keccak2_f1600
1307 // 13: sha3_keccak4_f1600_alt
1308 // 14: sha3_keccak4_f1600_alt2
1309 extern uint8_t BORINGSSL_function_hit[15];
1310 #endif // BORINGSSL_DISPATCH_TEST
1311
1312 #if !defined(AWSLC_FIPS) && !defined(BORINGSSL_SHARED_LIBRARY)
1313 // This function is defined in |bcm.c|, see the comment therein for explanation.
1314 void dummy_func_for_constructor(void);
1315 #endif
1316 // OPENSSL_vasprintf_internal is just like |vasprintf(3)|. If |system_malloc| is
1317 // 0, memory will be allocated with |OPENSSL_malloc| and must be freed with
1318 // |OPENSSL_free|. Otherwise the system |malloc| function is used and the memory
1319 // must be freed with the system |free| function.
1320 OPENSSL_EXPORT int OPENSSL_vasprintf_internal(char **str, const char *format,
1321 va_list args, int system_malloc)
1322 OPENSSL_PRINTF_FORMAT_FUNC(2, 0);
1323
1324
1325 // Experimental safety macros inspired by s2n-tls.
1326
1327 // If |cond| is false |action| is invoked, otherwise nothing happens.
1328 #define AWS_LC_ENSURE(cond, action) \
1329 do { \
1330 if (!(cond)) { \
1331 action; \
1332 } \
1333 } while (0)
1334
1335 #define AWS_LC_ERROR 0
1336 #define AWS_LC_SUCCESS 1
1337
1338 // GUARD_PTR checks |ptr|: if it is NULL it adds |ERR_R_PASSED_NULL_PARAMETER|
1339 // to the error queue and returns 0, if it is not NULL nothing happens.
1340 //
1341 // NOTE: this macro should only be used with functions that return 0 (for error)
1342 // and 1 (for success).
1343 #define GUARD_PTR(ptr) AWS_LC_ENSURE((ptr) != NULL, OPENSSL_PUT_ERROR(CRYPTO, ERR_R_PASSED_NULL_PARAMETER); \
1344 return AWS_LC_ERROR)
1345
1346 // GUARD_PTR_ABORT checks |ptr|: if it is NULL it calls abort() and does nothing
1347 // otherwise.
1348 #define GUARD_PTR_ABORT(ptr) AWS_LC_ENSURE((ptr) != NULL, abort())
1349
1350 #if defined(NDEBUG)
1351 #define AWSLC_ASSERT(x) (void) (x)
1352 #else
1353 #define AWSLC_ASSERT(x) AWS_LC_ENSURE(x, abort())
1354 #endif
1355
1356 #define AWSLC_ABORT_IF_NOT_ONE(x) AWS_LC_ENSURE(1 == (x), abort())
1357
1358 // Windows doesn't really support weak symbols as of May 2019, and Clang on
1359 // Windows will emit strong symbols instead. See
1360 // https://bugs.llvm.org/show_bug.cgi?id=37598
1361 #if defined(__ELF__) && defined(__GNUC__)
1362 #define WEAK_SYMBOL_FUNC(rettype, name, args) \
1363 rettype name args __attribute__((weak));
1364 #else
1365 #define WEAK_SYMBOL_FUNC(rettype, name, args) static rettype(*name) args = NULL;
1366 #endif
1367
1368
1369 #if defined(__cplusplus)
1370 } // extern C
1371 #endif
1372
1373 #endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H