Coverage Report

Created: 2026-02-16 07:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/internal.h
Line
Count
Source
1
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
16
#define OPENSSL_HEADER_CRYPTO_INTERNAL_H
17
18
#include <openssl/base.h>
19
#include <openssl/crypto.h>
20
#include <openssl/ex_data.h>
21
#include <openssl/stack.h>
22
23
#include <assert.h>
24
#include <stdlib.h>
25
#include <string.h>
26
27
#include <type_traits>
28
29
#if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
30
#include <valgrind/memcheck.h>
31
#endif
32
33
#if defined(BORINGSSL_FIPS_BREAK_TESTS)
34
#include <stdlib.h>
35
#endif
36
37
#if defined(OPENSSL_THREADS) && \
38
    (!defined(OPENSSL_WINDOWS) || defined(__MINGW32__))
39
#include <pthread.h>
40
#define OPENSSL_PTHREADS
41
#endif
42
43
#if defined(OPENSSL_THREADS) && !defined(OPENSSL_PTHREADS) && \
44
    defined(OPENSSL_WINDOWS)
45
#define OPENSSL_WINDOWS_THREADS
46
#endif
47
48
#if defined(OPENSSL_THREADS)
49
#include <atomic>
50
#else
51
#include <utility>
52
#endif
53
54
#if defined(OPENSSL_WINDOWS_THREADS)
55
#include <windows.h>
56
#endif
57
58
#if defined(_M_X64) || defined(_M_IX86)
59
#include "intrin.h"
60
#endif
61
62
#if defined(BORINGSSL_PREFIX)
63
#include <openssl/prefix_symbols_internal_c.h>
64
#endif
65
66
67
BSSL_NAMESPACE_BEGIN
68
69
#if !defined(OPENSSL_NO_ASM) &&                         \
70
    (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \
71
     (!defined(OPENSSL_STATIC_ARMCAP) &&                \
72
      (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))))
73
// x86, x86_64, and the ARMs need to record the result of a cpuid/getauxval call
74
// for the asm to work correctly, unless compiled without asm code.
75
#define NEED_CPUID
76
77
// OPENSSL_cpuid_setup initializes the platform-specific feature cache. This
78
// function should not be called directly. Call |OPENSSL_init_cpuid| instead.
79
void OPENSSL_cpuid_setup();
80
81
// OPENSSL_init_cpuid initializes the platform-specific feature cache, if
82
// needed. This function is idempotent and may be called concurrently.
83
void OPENSSL_init_cpuid();
84
#else
85
inline void OPENSSL_init_cpuid() {}
86
#endif
87
88
#if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \
89
    !defined(OPENSSL_STATIC_ARMCAP)
90
// OPENSSL_get_armcap_pointer_for_test returns a pointer to
91
// |OPENSSL_armcap_P| for unit tests. Any modifications to the value must be
92
// made before any other function call in BoringSSL.
93
OPENSSL_EXPORT uint32_t *OPENSSL_get_armcap_pointer_for_test();
94
#endif
95
96
97
// On non-MSVC 64-bit targets, we expect __uint128_t support. This includes
98
// clang-cl, which defines both __clang__ and _MSC_VER.
99
#if (!defined(_MSC_VER) || defined(__clang__)) && defined(OPENSSL_64_BIT)
100
#define BORINGSSL_HAS_UINT128
101
typedef __int128_t int128_t;
102
typedef __uint128_t uint128_t;
103
104
// __uint128_t division depends on intrinsics in the compiler runtime. Those
105
// intrinsics are missing in clang-cl (https://crbug.com/787617) and nanolibc.
106
// These may be bugs in the toolchain definition, but just disable it for now.
107
// EDK2's toolchain is missing __udivti3 (b/339380897) so cannot support
108
// 128-bit division currently.
109
#if !defined(_MSC_VER) && !defined(OPENSSL_NANOLIBC) && \
110
    !defined(__EDK2_BORINGSSL__)
111
#define BORINGSSL_CAN_DIVIDE_UINT128
112
#endif
113
#endif
114
115
// GCC-like compilers indicate SSE2 with |__SSE2__|. MSVC leaves the caller to
116
// know that x86_64 has SSE2, and uses _M_IX86_FP to indicate SSE2 on x86.
117
// https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-170
118
#if defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || \
119
    (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
120
#define OPENSSL_SSE2
121
#endif
122
123
#if defined(OPENSSL_X86) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_SSE2)
124
#error \
125
    "x86 assembly requires SSE2. Build with -msse2 (recommended), or disable assembly optimizations with -DOPENSSL_NO_ASM."
126
#endif
127
128
// For convenience in testing the fallback code, we allow disabling SSE2
129
// intrinsics via |OPENSSL_NO_SSE2_FOR_TESTING|. We require SSE2 on x86 and
130
// x86_64, so we would otherwise need to test such code on a non-x86 platform.
131
//
132
// This does not remove the above requirement for SSE2 support with assembly
133
// optimizations. It only disables some intrinsics-based optimizations so that
134
// we can test the fallback code on CI.
135
#if defined(OPENSSL_SSE2) && defined(OPENSSL_NO_SSE2_FOR_TESTING)
136
#undef OPENSSL_SSE2
137
#endif
138
139
#if defined(__GNUC__) || defined(__clang__)
140
#define OPENSSL_ATTR_CONST __attribute__((const))
141
#else
142
#define OPENSSL_ATTR_CONST
143
#endif
144
145
#if defined(BORINGSSL_MALLOC_FAILURE_TESTING)
146
// OPENSSL_reset_malloc_counter_for_testing, when malloc testing is enabled,
147
// resets the internal malloc counter, to simulate further malloc failures. This
148
// should be called in between independent tests, at a point where failure from
149
// a previous test will not impact subsequent ones.
150
OPENSSL_EXPORT void OPENSSL_reset_malloc_counter_for_testing();
151
152
// OPENSSL_disable_malloc_failures_for_testing, when malloc testing is enabled,
153
// disables simulated malloc failures. Calls to |OPENSSL_malloc| will not
154
// increment the malloc counter or synthesize failures. This may be used to skip
155
// simulating malloc failures in some region of code.
156
OPENSSL_EXPORT void OPENSSL_disable_malloc_failures_for_testing();
157
158
// OPENSSL_enable_malloc_failures_for_testing, when malloc testing is enabled,
159
// re-enables simulated malloc failures.
160
OPENSSL_EXPORT void OPENSSL_enable_malloc_failures_for_testing();
161
#else
162
0
inline void OPENSSL_reset_malloc_counter_for_testing() {}
163
0
inline void OPENSSL_disable_malloc_failures_for_testing() {}
164
0
inline void OPENSSL_enable_malloc_failures_for_testing() {}
165
#endif
166
167
#if defined(__has_builtin)
168
#define OPENSSL_HAS_BUILTIN(x) __has_builtin(x)
169
#else
170
#define OPENSSL_HAS_BUILTIN(x) 0
171
#endif
172
173
174
// Pointer utility functions.
175
176
// buffers_alias returns one if |a| and |b| alias and zero otherwise.
177
inline int buffers_alias(const void *a, size_t a_bytes, const void *b,
178
90.8M
                         size_t b_bytes) {
179
  // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
180
  // objects are undefined whereas pointer to integer conversions are merely
181
  // implementation-defined. We assume the implementation defined it in a sane
182
  // way.
183
90.8M
  uintptr_t a_u = (uintptr_t)a;
184
90.8M
  uintptr_t b_u = (uintptr_t)b;
185
90.8M
  return a_u + a_bytes > b_u && b_u + b_bytes > a_u;
186
90.8M
}
187
188
// align_pointer returns |ptr|, advanced to |alignment|. |alignment| must be a
189
// power of two, and |ptr| must have at least |alignment - 1| bytes of scratch
190
// space.
191
60
inline void *align_pointer(void *ptr, size_t alignment) {
192
  // |alignment| must be a power of two.
193
60
  assert(alignment != 0 && (alignment & (alignment - 1)) == 0);
194
  // Instead of aligning |ptr| as a |uintptr_t| and casting back, compute the
195
  // offset and advance in pointer space. C guarantees that casting from pointer
196
  // to |uintptr_t| and back gives the same pointer, but general
197
  // integer-to-pointer conversions are implementation-defined. GCC does define
198
  // it in the useful way, but this makes fewer assumptions.
199
60
  uintptr_t offset = (0u - (uintptr_t)ptr) & (alignment - 1);
200
60
  ptr = (char *)ptr + offset;
201
60
  assert(((uintptr_t)ptr & (alignment - 1)) == 0);
202
60
  return ptr;
203
60
}
204
205
206
// Constant-time utility functions.
207
//
208
// The following methods return a bitmask of all ones (0xff...f) for true and 0
209
// for false. This is useful for choosing a value based on the result of a
210
// conditional in constant time. For example,
211
//
212
// if (a < b) {
213
//   c = a;
214
// } else {
215
//   c = b;
216
// }
217
//
218
// can be written as
219
//
220
// crypto_word_t lt = constant_time_lt_w(a, b);
221
// c = constant_time_select_w(lt, a, b);
222
223
// crypto_word_t is the type that most constant-time functions use. Ideally we
224
// would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit
225
// pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64
226
// bits. Since we want to be able to do constant-time operations on a
227
// |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native
228
// word length.
229
#if defined(OPENSSL_64_BIT)
230
typedef uint64_t crypto_word_t;
231
#elif defined(OPENSSL_32_BIT)
232
typedef uint32_t crypto_word_t;
233
#else
234
#error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
235
#endif
236
237
0
#define CONSTTIME_TRUE_W ~((crypto_word_t)0)
238
0
#define CONSTTIME_FALSE_W ((crypto_word_t)0)
239
#define CONSTTIME_TRUE_8 ((uint8_t)0xff)
240
#define CONSTTIME_FALSE_8 ((uint8_t)0)
241
242
// value_barrier_w returns |a|, but prevents GCC and Clang from reasoning about
243
// the returned value. This is used to mitigate compilers undoing constant-time
244
// code, until we can express our requirements directly in the language.
245
//
246
// Note the compiler is aware that |value_barrier_w| has no side effects and
247
// always has the same output for a given input. This allows it to eliminate
248
// dead code, move computations across loops, and vectorize.
249
9.72G
inline crypto_word_t value_barrier_w(crypto_word_t a) {
250
9.72G
#if defined(__GNUC__) || defined(__clang__)
251
9.72G
  __asm__("" : "+r"(a) : /* no inputs */);
252
9.72G
#endif
253
9.72G
  return a;
254
9.72G
}
255
256
// value_barrier_u32 behaves like |value_barrier_w| but takes a |uint32_t|.
257
1.91G
inline uint32_t value_barrier_u32(uint32_t a) {
258
1.91G
#if defined(__GNUC__) || defined(__clang__)
259
1.91G
  __asm__("" : "+r"(a) : /* no inputs */);
260
1.91G
#endif
261
1.91G
  return a;
262
1.91G
}
263
264
// value_barrier_u64 behaves like |value_barrier_w| but takes a |uint64_t|.
265
0
inline uint64_t value_barrier_u64(uint64_t a) {
266
0
#if defined(__GNUC__) || defined(__clang__)
267
0
  __asm__("" : "+r"(a) : /* no inputs */);
268
0
#endif
269
0
  return a;
270
0
}
271
272
// |value_barrier_u8| could be defined as above, but compilers other than
273
// clang seem to still materialize 0x00..00MM instead of reusing 0x??..??MM.
274
275
// constant_time_msb_w returns the given value with the MSB copied to all the
276
// other bits.
277
198M
inline crypto_word_t constant_time_msb_w(crypto_word_t a) {
278
198M
  return 0u - (a >> (sizeof(a) * 8 - 1));
279
198M
}
280
281
// constant_time_lt_w returns 0xff..f if a < b and 0 otherwise.
282
8.20M
inline crypto_word_t constant_time_lt_w(crypto_word_t a, crypto_word_t b) {
283
  // Consider the two cases of the problem:
284
  //   msb(a) == msb(b): a < b iff the MSB of a - b is set.
285
  //   msb(a) != msb(b): a < b iff the MSB of b is set.
286
  //
287
  // If msb(a) == msb(b) then the following evaluates as:
288
  //   msb(a^((a^b)|((a-b)^a))) ==
289
  //   msb(a^((a-b) ^ a))       ==   (because msb(a^b) == 0)
290
  //   msb(a^a^(a-b))           ==   (rearranging)
291
  //   msb(a-b)                      (because ∀x. x^x == 0)
292
  //
293
  // Else, if msb(a) != msb(b) then the following evaluates as:
294
  //   msb(a^((a^b)|((a-b)^a))) ==
295
  //   msb(a^(𝟙 | ((a-b)^a)))   ==   (because msb(a^b) == 1 and 𝟙
296
  //                                  represents a value s.t. msb(𝟙) = 1)
297
  //   msb(a^𝟙)                 ==   (because ORing with 1 results in 1)
298
  //   msb(b)
299
  //
300
  //
301
  // Here is an SMT-LIB verification of this formula:
302
  //
303
  // (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
304
  //   (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
305
  // )
306
  //
307
  // (declare-fun a () (_ BitVec 32))
308
  // (declare-fun b () (_ BitVec 32))
309
  //
310
  // (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
311
  // (check-sat)
312
  // (get-model)
313
8.20M
  return constant_time_msb_w(a ^ ((a ^ b) | ((a - b) ^ a)));
314
8.20M
}
315
316
// constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit
317
// mask.
318
228k
inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) {
319
228k
  return (uint8_t)(constant_time_lt_w(a, b));
320
228k
}
321
322
// constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise.
323
309k
inline crypto_word_t constant_time_ge_w(crypto_word_t a, crypto_word_t b) {
324
309k
  return ~constant_time_lt_w(a, b);
325
309k
}
326
327
// constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit
328
// mask.
329
305k
inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) {
330
305k
  return (uint8_t)(constant_time_ge_w(a, b));
331
305k
}
332
333
// constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise.
334
177M
inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) {
335
  // Here is an SMT-LIB verification of this formula:
336
  //
337
  // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
338
  //   (bvand (bvnot a) (bvsub a #x00000001))
339
  // )
340
  //
341
  // (declare-fun a () (_ BitVec 32))
342
  //
343
  // (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a
344
  // #x00000000)))) (check-sat) (get-model)
345
177M
  return constant_time_msb_w(~a & (a - 1));
346
177M
}
347
348
// constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an
349
// 8-bit mask.
350
17.7k
inline uint8_t constant_time_is_zero_8(crypto_word_t a) {
351
17.7k
  return (uint8_t)(constant_time_is_zero_w(a));
352
17.7k
}
353
354
// constant_time_eq_w returns 0xff..f if a == b and 0 otherwise.
355
149M
inline crypto_word_t constant_time_eq_w(crypto_word_t a, crypto_word_t b) {
356
149M
  return constant_time_is_zero_w(a ^ b);
357
149M
}
358
359
// constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit
360
// mask.
361
5.38M
inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) {
362
5.38M
  return (uint8_t)(constant_time_eq_w(a, b));
363
5.38M
}
364
365
// constant_time_eq_int acts like |constant_time_eq_w| but works on int
366
// values.
367
920k
inline crypto_word_t constant_time_eq_int(int a, int b) {
368
920k
  return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b));
369
920k
}
370
371
// constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
372
// mask.
373
192
inline uint8_t constant_time_eq_int_8(int a, int b) {
374
192
  return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b));
375
192
}
376
377
// constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all
378
// 1s or all 0s (as returned by the methods above), the select methods return
379
// either |a| (if |mask| is nonzero) or |b| (if |mask| is zero).
380
inline crypto_word_t constant_time_select_w(crypto_word_t mask, crypto_word_t a,
381
2.70G
                                            crypto_word_t b) {
382
  // Clang recognizes this pattern as a select. While it usually transforms it
383
  // to a cmov, it sometimes further transforms it into a branch, which we do
384
  // not want.
385
  //
386
  // Hiding the value of the mask from the compiler evades this transformation.
387
2.70G
  mask = value_barrier_w(mask);
388
2.70G
  return (mask & a) | (~mask & b);
389
2.70G
}
390
391
// constant_time_select_8 acts like |constant_time_select| but operates on
392
// 8-bit values.
393
inline uint8_t constant_time_select_8(crypto_word_t mask, uint8_t a,
394
780M
                                      uint8_t b) {
395
  // |mask| is a word instead of |uint8_t| to avoid materializing 0x000..0MM
396
  // Making both |mask| and its value barrier |uint8_t| would allow the compiler
397
  // to materialize 0x????..?MM instead, but only clang is that clever.
398
  // However, vectorization of bitwise operations seems to work better on
399
  // |uint8_t| than a mix of |uint64_t| and |uint8_t|, so |m| is cast to
400
  // |uint8_t| after the value barrier but before the bitwise operations.
401
780M
  uint8_t m = value_barrier_w(mask);
402
780M
  return (m & a) | (~m & b);
403
780M
}
404
405
// constant_time_select_int acts like |constant_time_select| but operates on
406
// ints.
407
14.2M
inline int constant_time_select_int(crypto_word_t mask, int a, int b) {
408
14.2M
  return static_cast<int>(constant_time_select_w(
409
14.2M
      mask, static_cast<crypto_word_t>(a), static_cast<crypto_word_t>(b)));
410
14.2M
}
411
412
// constant_time_select_32 acts like |constant_time_select| but operates on
413
// 32-bit values.
414
inline uint32_t constant_time_select_32(crypto_word_t mask, uint32_t a,
415
0
                                        uint32_t b) {
416
0
  return static_cast<uint32_t>(
417
0
      constant_time_select_w(mask, crypto_word_t{a}, crypto_word_t{b}));
418
0
}
419
420
// constant_time_conditional_memcpy copies |n| bytes from |src| to |dst| if
421
// |mask| is 0xff..ff and does nothing if |mask| is 0. The |n|-byte memory
422
// ranges at |dst| and |src| must not overlap, as when calling |memcpy|.
423
inline void constant_time_conditional_memcpy(void *dst, const void *src,
424
                                             const size_t n,
425
24.3M
                                             const crypto_word_t mask) {
426
24.3M
  assert(!buffers_alias(dst, n, src, n));
427
24.3M
  uint8_t *out = (uint8_t *)dst;
428
24.3M
  const uint8_t *in = (const uint8_t *)src;
429
803M
  for (size_t i = 0; i < n; i++) {
430
779M
    out[i] = constant_time_select_8(mask, in[i], out[i]);
431
779M
  }
432
24.3M
}
433
434
// constant_time_conditional_memxor xors |n| bytes from |src| to |dst| if
435
// |mask| is 0xff..ff and does nothing if |mask| is 0. The |n|-byte memory
436
// ranges at |dst| and |src| must not overlap, as when calling |memcpy|.
437
inline void constant_time_conditional_memxor(void *dst, const void *src,
438
                                             size_t n,
439
64.9M
                                             const crypto_word_t mask) {
440
64.9M
  assert(!buffers_alias(dst, n, src, n));
441
64.9M
  uint8_t *out = (uint8_t *)dst;
442
64.9M
  const uint8_t *in = (const uint8_t *)src;
443
#if defined(__GNUC__) && !defined(__clang__)
444
  // gcc 13.2.0 doesn't automatically vectorize this loop regardless of barrier
445
  typedef uint8_t v32u8 __attribute__((vector_size(32), aligned(1), may_alias));
446
  size_t n_vec = n & ~(size_t)31;
447
  v32u8 masks = ((uint8_t)mask - (v32u8){});  // broadcast
448
  for (size_t i = 0; i < n_vec; i += 32) {
449
    *(v32u8 *)&out[i] ^= masks & *(v32u8 *)&in[i];
450
  }
451
  in += n_vec;
452
  out += n_vec;
453
  n -= n_vec;
454
#endif
455
6.30G
  for (size_t i = 0; i < n; i++) {
456
6.23G
    out[i] ^= value_barrier_w(mask) & in[i];
457
6.23G
  }
458
64.9M
}
459
460
#if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
461
462
// CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region
463
// of memory as secret. Secret data is tracked as it flows to registers and
464
// other parts of a memory. If secret data is used as a condition for a branch,
465
// or as a memory index, it will trigger warnings in valgrind.
466
#define CONSTTIME_SECRET(ptr, len) VALGRIND_MAKE_MEM_UNDEFINED(ptr, len)
467
468
// CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that
469
// region of memory as public. Public data is not subject to constant-time
470
// rules.
471
#define CONSTTIME_DECLASSIFY(ptr, len) VALGRIND_MAKE_MEM_DEFINED(ptr, len)
472
473
#else
474
475
// Just disable unused warnings for those.
476
#define CONSTTIME_SECRET(ptr, len) \
477
50.1k
  do {                             \
478
50.1k
    (void)(ptr);                   \
479
50.1k
    (void)(len);                   \
480
50.1k
  } while (false)
481
#define CONSTTIME_DECLASSIFY(ptr, len) \
482
1.91G
  do {                                 \
483
1.91G
    (void)(ptr);                       \
484
1.91G
    (void)(len);                       \
485
1.91G
  } while (false)
486
487
#endif  // BORINGSSL_CONSTANT_TIME_VALIDATION
488
489
2.84M
inline crypto_word_t constant_time_declassify_w(crypto_word_t v) {
490
  // Return |v| through a value barrier to be safe. Valgrind-based constant-time
491
  // validation is partly to check the compiler has not undone any constant-time
492
  // work. Any place |BORINGSSL_CONSTANT_TIME_VALIDATION| influences
493
  // optimizations, this validation is inaccurate.
494
  //
495
  // However, by sending pointers through valgrind, we likely inhibit escape
496
  // analysis. On local variables, particularly booleans, we likely
497
  // significantly impact optimizations.
498
  //
499
  // Thus, to be safe, stick a value barrier, in hopes of comparably inhibiting
500
  // compiler analysis.
501
2.84M
  CONSTTIME_DECLASSIFY(&v, sizeof(v));
502
2.84M
  return value_barrier_w(v);
503
2.84M
}
504
505
1.91G
inline int constant_time_declassify_int(int v) {
506
1.91G
  static_assert(sizeof(uint32_t) == sizeof(int),
507
1.91G
                "int is not the same size as uint32_t");
508
  // See comment above.
509
1.91G
  CONSTTIME_DECLASSIFY(&v, sizeof(v));
510
1.91G
  return value_barrier_u32(v);
511
1.91G
}
512
513
// declassify_assert behaves like |assert| but declassifies the result of
514
// evaluating |expr|. This allows the assertion to branch on the (presumably
515
// public) result, but still ensures that values leading up to the computation
516
// were secret.
517
1.91G
#define declassify_assert(expr) assert(constant_time_declassify_int(expr))
518
519
520
// Thread-safe initialisation.
521
522
#if !defined(OPENSSL_THREADS)
523
typedef uint32_t CRYPTO_once_t;
524
#define CRYPTO_ONCE_INIT 0
525
#elif defined(OPENSSL_WINDOWS_THREADS)
526
typedef INIT_ONCE CRYPTO_once_t;
527
#define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
528
#elif defined(OPENSSL_PTHREADS)
529
typedef pthread_once_t CRYPTO_once_t;
530
#define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
531
#else
532
#error "Unknown threading library"
533
#endif
534
535
// CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
536
// concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
537
// then they will block until |init| completes, but |init| will have only been
538
// called once.
539
//
540
// The |once| argument must be a |CRYPTO_once_t| that has been initialised with
541
// the value |CRYPTO_ONCE_INIT|.
542
OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)());
543
544
545
// Atomics.
546
//
547
// This is a thin wrapper over std::atomic because some embedded platforms do
548
// not support threads and don't provide a trivial std::atomic implementation.
549
// For now, this does not wrap std::memory_order. If we ever use non-default
550
// std::memory_order, we will need to wrap these too, or fix the embedded
551
// platforms to provide a no-op std::atomic. See https://crbug.com/442112336.
552
553
#if defined(OPENSSL_THREADS)
554
template <typename T>
555
using Atomic = std::atomic<T>;
556
#else
557
template <typename T>
558
class Atomic {
559
 public:
560
  static_assert(std::is_integral_v<T> || std::is_pointer_v<T>);
561
562
  Atomic() = default;
563
  constexpr Atomic(T value) : value_(value) {}
564
  Atomic(const Atomic &) = delete;
565
  Atomic &operator=(const Atomic &) = delete;
566
  T operator=(T value) {
567
    value_ = value;
568
    return value_;
569
  }
570
571
  T load() const { return value_; }
572
  void store(T desired) { value_ = desired; }
573
574
  bool compare_exchange_strong(T &expected, T desired) {
575
    if (value_ != expected) {
576
      expected = value_;
577
      return false;
578
    }
579
    value_ = desired;
580
    return true;
581
  }
582
  bool compare_exchange_weak(T &expected, T desired) {
583
    return compare_exchange_strong(expected, desired);
584
  }
585
586
  T exchange(T desired) { return std::exchange(value_, desired); }
587
588
 private:
589
  T value_;
590
};
591
#endif
592
593
594
// Reference counting.
595
596
// CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates.
597
4.53M
#define CRYPTO_REFCOUNT_MAX 0xffffffff
598
599
using CRYPTO_refcount_t = Atomic<uint32_t>;
600
601
// CRYPTO_refcount_inc atomically increments the value at |*count| unless the
602
// value would overflow. It's safe for multiple threads to concurrently call
603
// this or |CRYPTO_refcount_dec_and_test_zero| on the same
604
// |CRYPTO_refcount_t|.
605
OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
606
607
// CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
608
//   if it's zero, it crashes the address space.
609
//   if it's the maximum value, it returns zero.
610
//   otherwise, it atomically decrements it and returns one iff the resulting
611
//       value is zero.
612
//
613
// It's safe for multiple threads to concurrently call this or
614
// |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|.
615
OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
616
617
618
// Locks.
619
620
#if !defined(OPENSSL_THREADS)
621
typedef struct crypto_mutex_st {
622
  char padding;  // Empty structs have different sizes in C and C++.
623
} CRYPTO_MUTEX;
624
#define CRYPTO_MUTEX_INIT {0}
625
#elif defined(OPENSSL_WINDOWS_THREADS)
626
typedef SRWLOCK CRYPTO_MUTEX;
627
#define CRYPTO_MUTEX_INIT SRWLOCK_INIT
628
#elif defined(OPENSSL_PTHREADS)
629
typedef pthread_rwlock_t CRYPTO_MUTEX;
630
#define CRYPTO_MUTEX_INIT PTHREAD_RWLOCK_INITIALIZER
631
#else
632
#error "Unknown threading library"
633
#endif
634
635
// CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
636
// |CRYPTO_MUTEX_INIT|.
637
OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);
638
639
// CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
640
// read lock, but none may have a write lock.
641
OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);
642
643
// CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
644
// of lock on it.
645
OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);
646
647
// CRYPTO_MUTEX_unlock_read unlocks |lock| for reading.
648
OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);
649
650
// CRYPTO_MUTEX_unlock_write unlocks |lock| for writing.
651
OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);
652
653
// CRYPTO_MUTEX_cleanup releases all resources held by |lock|.
654
OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);
655
656
namespace internal {
657
658
// MutexLockBase is a RAII helper for CRYPTO_MUTEX locking.
659
template <void (*LockFunc)(CRYPTO_MUTEX *), void (*ReleaseFunc)(CRYPTO_MUTEX *)>
660
class MutexLockBase {
661
 public:
662
138k
  explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
663
138k
    assert(mu_ != nullptr);
664
138k
    LockFunc(mu_);
665
138k
  }
bssl::internal::MutexLockBase<&bssl::CRYPTO_MUTEX_lock_write, &bssl::CRYPTO_MUTEX_unlock_write>::MutexLockBase(pthread_rwlock_t*)
Line
Count
Source
662
133k
  explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
663
133k
    assert(mu_ != nullptr);
664
133k
    LockFunc(mu_);
665
133k
  }
bssl::internal::MutexLockBase<&bssl::CRYPTO_MUTEX_lock_read, &bssl::CRYPTO_MUTEX_unlock_read>::MutexLockBase(pthread_rwlock_t*)
Line
Count
Source
662
4.87k
  explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
663
4.87k
    assert(mu_ != nullptr);
664
4.87k
    LockFunc(mu_);
665
4.87k
  }
666
138k
  ~MutexLockBase() { ReleaseFunc(mu_); }
bssl::internal::MutexLockBase<&bssl::CRYPTO_MUTEX_lock_write, &bssl::CRYPTO_MUTEX_unlock_write>::~MutexLockBase()
Line
Count
Source
666
133k
  ~MutexLockBase() { ReleaseFunc(mu_); }
bssl::internal::MutexLockBase<&bssl::CRYPTO_MUTEX_lock_read, &bssl::CRYPTO_MUTEX_unlock_read>::~MutexLockBase()
Line
Count
Source
666
4.87k
  ~MutexLockBase() { ReleaseFunc(mu_); }
667
  MutexLockBase(const MutexLockBase<LockFunc, ReleaseFunc> &) = delete;
668
  MutexLockBase &operator=(const MutexLockBase<LockFunc, ReleaseFunc> &) =
669
      delete;
670
671
 private:
672
  CRYPTO_MUTEX *const mu_;
673
};
674
675
}  // namespace internal
676
677
using MutexWriteLock =
678
    internal::MutexLockBase<CRYPTO_MUTEX_lock_write, CRYPTO_MUTEX_unlock_write>;
679
using MutexReadLock =
680
    internal::MutexLockBase<CRYPTO_MUTEX_lock_read, CRYPTO_MUTEX_unlock_read>;
681
682
683
// Thread local storage.
684
685
// thread_local_data_t enumerates the types of thread-local data that can be
686
// stored.
687
typedef enum {
688
  OPENSSL_THREAD_LOCAL_ERR = 0,
689
  OPENSSL_THREAD_LOCAL_RAND,
690
  OPENSSL_THREAD_LOCAL_FIPS_COUNTERS,
691
  OPENSSL_THREAD_LOCAL_FIPS_SERVICE_INDICATOR_STATE,
692
  OPENSSL_THREAD_LOCAL_TEST,
693
  NUM_OPENSSL_THREAD_LOCALS,
694
} thread_local_data_t;
695
696
// thread_local_destructor_t is the type of a destructor function that will be
697
// called when a thread exits and its thread-local storage needs to be freed.
698
typedef void (*thread_local_destructor_t)(void *);
699
700
// CRYPTO_get_thread_local gets the pointer value that is stored for the
701
// current thread for the given index, or NULL if none has been set.
702
OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);
703
704
// CRYPTO_set_thread_local sets a pointer value for the current thread at the
705
// given index. This function should only be called once per thread for a given
706
// |index|: rather than update the pointer value itself, update the data that
707
// is pointed to.
708
//
709
// The destructor function will be called when a thread exits to free this
710
// thread-local data. All calls to |CRYPTO_set_thread_local| with the same
711
// |index| should have the same |destructor| argument. The destructor may be
712
// called with a NULL argument if a thread that never set a thread-local
713
// pointer for |index|, exits. The destructor may be called concurrently with
714
// different arguments.
715
//
716
// This function returns one on success or zero on error. If it returns zero
717
// then |destructor| has been called with |value| already.
718
OPENSSL_EXPORT int CRYPTO_set_thread_local(
719
    thread_local_data_t index, void *value,
720
    thread_local_destructor_t destructor);
721
722
723
// ex_data
724
725
BSSL_NAMESPACE_END
726
727
struct crypto_ex_data_st {
728
  STACK_OF(void) *sk;
729
} /* CRYPTO_EX_DATA */;
730
731
BSSL_NAMESPACE_BEGIN
732
733
typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;
734
735
// CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
736
// supports ex_data. It should defined as a static global within the module
737
// which defines that type.
738
typedef struct {
739
  CRYPTO_MUTEX lock;
740
  // funcs is a linked list of |CRYPTO_EX_DATA_FUNCS| structures. It may be
741
  // traversed without serialization only up to |num_funcs|. last points to the
742
  // final entry of |funcs|, or NULL if empty.
743
  CRYPTO_EX_DATA_FUNCS *funcs, *last;
744
  // num_funcs is the number of entries in |funcs|.
745
  Atomic<uint32_t> num_funcs;
746
  // num_reserved is one if the ex_data index zero is reserved for legacy
747
  // |TYPE_get_app_data| functions.
748
  uint8_t num_reserved;
749
} CRYPTO_EX_DATA_CLASS;
750
751
#define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_MUTEX_INIT, nullptr, nullptr, {}, 0}
752
#define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
753
  {CRYPTO_MUTEX_INIT, nullptr, nullptr, {}, 1}
754
755
// CRYPTO_get_ex_new_index_ex allocates a new index for |ex_data_class|. Each
756
// class of object should provide a wrapper function that uses the correct
757
// |CRYPTO_EX_DATA_CLASS|. It returns the new index on success and -1 on error.
758
OPENSSL_EXPORT int CRYPTO_get_ex_new_index_ex(
759
    CRYPTO_EX_DATA_CLASS *ex_data_class, long argl, void *argp,
760
    CRYPTO_EX_free *free_func);
761
762
// CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
763
// of object should provide a wrapper function.
764
OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);
765
766
// CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
767
// if no such index exists. Each class of object should provide a wrapper
768
// function.
769
OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);
770
771
// CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|.
772
OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);
773
774
// CRYPTO_free_ex_data frees |ad|, which is an object of the given class.
775
OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
776
                                        CRYPTO_EX_DATA *ad);
777
778
779
// Endianness conversions.
780
781
#if defined(__GNUC__) && __GNUC__ >= 2
782
76.5k
inline uint16_t CRYPTO_bswap2(uint16_t x) { return __builtin_bswap16(x); }
783
784
24.0M
inline uint32_t CRYPTO_bswap4(uint32_t x) { return __builtin_bswap32(x); }
785
786
11.9M
inline uint64_t CRYPTO_bswap8(uint64_t x) { return __builtin_bswap64(x); }
787
#elif defined(_MSC_VER)
788
#pragma intrinsic(_byteswap_uint64, _byteswap_ulong, _byteswap_ushort)
789
inline uint16_t CRYPTO_bswap2(uint16_t x) { return _byteswap_ushort(x); }
790
791
inline uint32_t CRYPTO_bswap4(uint32_t x) { return _byteswap_ulong(x); }
792
793
inline uint64_t CRYPTO_bswap8(uint64_t x) { return _byteswap_uint64(x); }
794
#else
795
inline uint16_t CRYPTO_bswap2(uint16_t x) { return (x >> 8) | (x << 8); }
796
797
inline uint32_t CRYPTO_bswap4(uint32_t x) {
798
  x = (x >> 16) | (x << 16);
799
  x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
800
  return x;
801
}
802
803
inline uint64_t CRYPTO_bswap8(uint64_t x) {
804
  return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32);
805
}
806
#endif
807
808
809
// Language bug workarounds.
810
//
811
// Most C standard library functions are undefined if passed NULL, even when the
812
// corresponding length is zero. This gives them (and, in turn, all functions
813
// which call them) surprising behavior on empty arrays. Some compilers will
814
// miscompile code due to this rule. See also
815
// https://www.imperialviolet.org/2016/06/26/nonnull.html
816
//
817
// These wrapper functions behave the same as the corresponding C standard
818
// functions, but behave as expected when passed NULL if the length is zero.
819
//
820
// Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|.
821
822
// C++ defines |memchr| as a const-correct overload.
823
255k
inline const void *OPENSSL_memchr(const void *s, int c, size_t n) {
824
255k
  if (n == 0) {
825
3.81k
    return nullptr;
826
3.81k
  }
827
828
251k
  return memchr(s, c, n);
829
255k
}
830
831
333k
inline void *OPENSSL_memchr(void *s, int c, size_t n) {
832
333k
  if (n == 0) {
833
23.0k
    return nullptr;
834
23.0k
  }
835
836
310k
  return memchr(s, c, n);
837
333k
}
838
839
4.36M
inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) {
840
4.36M
  if (n == 0) {
841
33
    return 0;
842
33
  }
843
844
4.36M
  return memcmp(s1, s2, n);
845
4.36M
}
846
847
125M
inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) {
848
125M
  if (n == 0) {
849
1.40M
    return dst;
850
1.40M
  }
851
852
123M
  return memcpy(dst, src, n);
853
125M
}
854
855
3.16M
inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) {
856
3.16M
  if (n == 0) {
857
1.23M
    return dst;
858
1.23M
  }
859
860
1.92M
  return memmove(dst, src, n);
861
3.16M
}
862
863
112M
inline void *OPENSSL_memset(void *dst, int c, size_t n) {
864
112M
  if (n == 0) {
865
19.6M
    return dst;
866
19.6M
  }
867
868
92.9M
  return memset(dst, c, n);
869
112M
}
870
871
872
// Loads and stores.
873
//
874
// The following functions load and store sized integers with the specified
875
// endianness. They use |memcpy|, and so avoid alignment or strict aliasing
876
// requirements on the input and output pointers.
877
878
0
inline uint16_t CRYPTO_load_u16_le(const void *in) {
879
0
  uint16_t v;
880
0
  OPENSSL_memcpy(&v, in, sizeof(v));
881
0
  return v;
882
0
}
883
884
0
inline void CRYPTO_store_u16_le(void *out, uint16_t v) {
885
0
  OPENSSL_memcpy(out, &v, sizeof(v));
886
0
}
887
888
0
inline uint16_t CRYPTO_load_u16_be(const void *in) {
889
0
  uint16_t v;
890
0
  OPENSSL_memcpy(&v, in, sizeof(v));
891
0
  return CRYPTO_bswap2(v);
892
0
}
893
894
76.5k
inline void CRYPTO_store_u16_be(void *out, uint16_t v) {
895
76.5k
  v = CRYPTO_bswap2(v);
896
76.5k
  OPENSSL_memcpy(out, &v, sizeof(v));
897
76.5k
}
898
899
1.33M
inline uint32_t CRYPTO_load_u32_le(const void *in) {
900
1.33M
  uint32_t v;
901
1.33M
  OPENSSL_memcpy(&v, in, sizeof(v));
902
1.33M
  return v;
903
1.33M
}
904
905
1.09M
inline void CRYPTO_store_u32_le(void *out, uint32_t v) {
906
1.09M
  OPENSSL_memcpy(out, &v, sizeof(v));
907
1.09M
}
908
909
3.43M
inline uint32_t CRYPTO_load_u32_be(const void *in) {
910
3.43M
  uint32_t v;
911
3.43M
  OPENSSL_memcpy(&v, in, sizeof(v));
912
3.43M
  return CRYPTO_bswap4(v);
913
3.43M
}
914
915
20.5M
inline void CRYPTO_store_u32_be(void *out, uint32_t v) {
916
20.5M
  v = CRYPTO_bswap4(v);
917
20.5M
  OPENSSL_memcpy(out, &v, sizeof(v));
918
20.5M
}
919
920
6.20M
inline uint64_t CRYPTO_load_u64_le(const void *in) {
921
6.20M
  uint64_t v;
922
6.20M
  OPENSSL_memcpy(&v, in, sizeof(v));
923
6.20M
  return v;
924
6.20M
}
925
926
0
inline void CRYPTO_store_u64_le(void *out, uint64_t v) {
927
0
  OPENSSL_memcpy(out, &v, sizeof(v));
928
0
}
929
930
140k
inline uint64_t CRYPTO_load_u64_be(const void *ptr) {
931
140k
  uint64_t ret;
932
140k
  OPENSSL_memcpy(&ret, ptr, sizeof(ret));
933
140k
  return CRYPTO_bswap8(ret);
934
140k
}
935
936
3.11M
inline void CRYPTO_store_u64_be(void *out, uint64_t v) {
937
3.11M
  v = CRYPTO_bswap8(v);
938
3.11M
  OPENSSL_memcpy(out, &v, sizeof(v));
939
3.11M
}
940
941
21.4M
inline crypto_word_t CRYPTO_load_word_le(const void *in) {
942
21.4M
  crypto_word_t v;
943
21.4M
  OPENSSL_memcpy(&v, in, sizeof(v));
944
21.4M
  return v;
945
21.4M
}
946
947
10.7M
inline void CRYPTO_store_word_le(void *out, crypto_word_t v) {
948
10.7M
  OPENSSL_memcpy(out, &v, sizeof(v));
949
10.7M
}
950
951
8.66M
inline crypto_word_t CRYPTO_load_word_be(const void *in) {
952
8.66M
  crypto_word_t v;
953
8.66M
  OPENSSL_memcpy(&v, in, sizeof(v));
954
8.66M
#if defined(OPENSSL_64_BIT)
955
8.66M
  static_assert(sizeof(v) == 8, "crypto_word_t has unexpected size");
956
8.66M
  return CRYPTO_bswap8(v);
957
#else
958
  static_assert(sizeof(v) == 4, "crypto_word_t has unexpected size");
959
  return CRYPTO_bswap4(v);
960
#endif
961
8.66M
}
962
963
964
// Bit rotation functions.
965
//
966
// Note these functions use |(-shift) & 31|, etc., because shifting by the bit
967
// width is undefined. Both Clang and GCC recognize this pattern as a rotation,
968
// but MSVC does not. Instead, we call MSVC's built-in functions.
969
970
4.00M
inline uint32_t CRYPTO_rotl_u32(uint32_t value, int shift) {
971
#if defined(_MSC_VER)
972
  return _rotl(value, shift);
973
#else
974
4.00M
  return (value << shift) | (value >> ((-shift) & 31));
975
4.00M
#endif
976
4.00M
}
977
978
1.96M
inline uint32_t CRYPTO_rotr_u32(uint32_t value, int shift) {
979
#if defined(_MSC_VER)
980
  return _rotr(value, shift);
981
#else
982
1.96M
  return (value >> shift) | (value << ((-shift) & 31));
983
1.96M
#endif
984
1.96M
}
985
986
1.36G
inline uint64_t CRYPTO_rotl_u64(uint64_t value, int shift) {
987
#if defined(_MSC_VER)
988
  return _rotl64(value, shift);
989
#else
990
1.36G
  return (value << shift) | (value >> ((-shift) & 63));
991
1.36G
#endif
992
1.36G
}
993
994
0
inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) {
995
#if defined(_MSC_VER)
996
  return _rotr64(value, shift);
997
#else
998
0
  return (value >> shift) | (value << ((-shift) & 63));
999
0
#endif
1000
0
}
1001
1002
1003
// FIPS functions.
1004
1005
#if defined(BORINGSSL_FIPS)
1006
1007
// BORINGSSL_FIPS_abort is called when a FIPS power-on or continuous test
1008
// fails. It prevents any further cryptographic operations by the current
1009
// process.
1010
void BORINGSSL_FIPS_abort() __attribute__((noreturn));
1011
1012
// boringssl_self_test_startup runs all startup self tests and returns one on
1013
// success or zero on error. Startup self tests do not include lazy tests.
1014
// Call |BORINGSSL_self_test| to run every self test.
1015
int boringssl_self_test_startup();
1016
1017
// boringssl_ensure_rsa_self_test checks whether the RSA self-test has been run
1018
// in this address space. If not, it runs it and crashes the address space if
1019
// unsuccessful.
1020
void boringssl_ensure_rsa_self_test();
1021
1022
// boringssl_ensure_ecc_self_test checks whether the ECDSA and ECDH self-test
1023
// has been run in this address space. If not, it runs it and crashes the
1024
// address space if unsuccessful.
1025
void boringssl_ensure_ecc_self_test();
1026
1027
// boringssl_ensure_ffdh_self_test checks whether the FFDH self-test has been
1028
// run in this address space. If not, it runs it and crashes the address space
1029
// if unsuccessful.
1030
void boringssl_ensure_ffdh_self_test();
1031
1032
#else
1033
1034
// Outside of FIPS mode, the lazy tests are no-ops.
1035
1036
44.4k
inline void boringssl_ensure_rsa_self_test() {}
1037
39.5k
inline void boringssl_ensure_ecc_self_test() {}
1038
0
inline void boringssl_ensure_ffdh_self_test() {}
1039
1040
#endif  // FIPS
1041
1042
// BORINGSSL_check_test memcmp's two values of equal length. It returns 1 on
1043
// success and, on failure, it prints an error message that includes the
1044
// hexdumps the two values and returns 0.
1045
int BORINGSSL_check_test(const void *expected, const void *actual,
1046
                         size_t expected_len, const char *name);
1047
1048
// boringssl_self_test_sha256 performs a SHA-256 KAT.
1049
int boringssl_self_test_sha256();
1050
1051
// boringssl_self_test_sha512 performs a SHA-512 KAT.
1052
int boringssl_self_test_sha512();
1053
1054
// boringssl_self_test_hmac_sha256 performs an HMAC-SHA-256 KAT.
1055
int boringssl_self_test_hmac_sha256();
1056
1057
// boringssl_self_test_mlkem performs the ML-KEM KATs.
1058
OPENSSL_EXPORT int boringssl_self_test_mlkem();
1059
1060
// boringssl_self_test_mldsa performs the ML-DSA KATs.
1061
OPENSSL_EXPORT int boringssl_self_test_mldsa();
1062
1063
// boringssl_self_test_slhdsa performs the SLH-DSA KATs.
1064
OPENSSL_EXPORT int boringssl_self_test_slhdsa();
1065
1066
#if defined(BORINGSSL_FIPS_COUNTERS)
1067
void boringssl_fips_inc_counter(enum fips_counter_t counter);
1068
#else
1069
69.2k
inline void boringssl_fips_inc_counter(enum fips_counter_t counter) {}
1070
#endif
1071
1072
#if defined(BORINGSSL_FIPS_BREAK_TESTS)
1073
inline int boringssl_fips_break_test(const char *test) {
1074
  const char *const value = getenv("BORINGSSL_FIPS_BREAK_TEST");
1075
  return value != nullptr && strcmp(value, test) == 0;
1076
}
1077
#else
1078
0
inline int boringssl_fips_break_test(const char *test) { return 0; }
1079
#endif  // BORINGSSL_FIPS_BREAK_TESTS
1080
1081
1082
// Runtime CPU feature support
1083
1084
#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64)
1085
// OPENSSL_ia32cap_P contains the Intel CPUID bits when running on an x86 or
1086
// x86-64 system.
1087
//
1088
//   Index 0:
1089
//     EDX for CPUID where EAX = 1
1090
//     Bit 30 is used to indicate an Intel CPU
1091
//   Index 1:
1092
//     ECX for CPUID where EAX = 1
1093
//   Index 2:
1094
//     EBX for CPUID where EAX = 7, ECX = 0
1095
//     Bit 14 (for removed feature MPX) is used to indicate a preference for ymm
1096
//       registers over zmm even when zmm registers are supported
1097
//   Index 3:
1098
//     ECX for CPUID where EAX = 7, ECX = 0
1099
//
1100
// Note: the CPUID bits are pre-adjusted for the OSXSAVE bit and the XMM, YMM,
1101
// and AVX512 bits in XCR0, so it is not necessary to check those. (WARNING: See
1102
// caveats in cpu_intel.c.)
1103
//
1104
// This symbol should only be accessed with |OPENSSL_get_ia32cap|.
1105
extern uint32_t OPENSSL_ia32cap_P[4];
1106
1107
// OPENSSL_get_ia32cap initializes the library if needed and returns the |idx|th
1108
// entry of |OPENSSL_ia32cap_P|. It is marked as a const function so duplicate
1109
// calls can be merged by the compiler, at least when indices match.
1110
OPENSSL_ATTR_CONST uint32_t OPENSSL_get_ia32cap(int idx);
1111
1112
// OPENSSL_adjust_ia32cap adjusts |cap|, which should contain
1113
// |OPENSSL_ia32cap_P|, based on the environment variable value in |env|. This
1114
// function is exposed for unit tests.
1115
void OPENSSL_adjust_ia32cap(uint32_t cap[4], const char *env);
1116
1117
// See Intel manual, volume 2A, table 3-11.
1118
1119
1.09M
inline int CRYPTO_is_intel_cpu() {
1120
  // The reserved bit 30 is used to indicate an Intel CPU.
1121
1.09M
  return (OPENSSL_get_ia32cap(0) & (1u << 30)) != 0;
1122
1.09M
}
1123
1124
// See Intel manual, volume 2A, table 3-10.
1125
1126
149k
inline int CRYPTO_is_PCLMUL_capable() {
1127
#if defined(__PCLMUL__)
1128
  return 1;
1129
#else
1130
149k
  return (OPENSSL_get_ia32cap(1) & (1u << 1)) != 0;
1131
149k
#endif
1132
149k
}
1133
1134
3.16M
inline int CRYPTO_is_SSSE3_capable() {
1135
#if defined(__SSSE3__)
1136
  return 1;
1137
#else
1138
3.16M
  return (OPENSSL_get_ia32cap(1) & (1u << 9)) != 0;
1139
3.16M
#endif
1140
3.16M
}
1141
1142
1.66k
inline int CRYPTO_is_SSE4_1_capable() {
1143
#if defined(__SSE4_1__)
1144
  return 1;
1145
#else
1146
1.66k
  return (OPENSSL_get_ia32cap(1) & (1u << 19)) != 0;
1147
1.66k
#endif
1148
1.66k
}
1149
1150
69.2k
inline int CRYPTO_is_MOVBE_capable() {
1151
#if defined(__MOVBE__)
1152
  return 1;
1153
#else
1154
69.2k
  return (OPENSSL_get_ia32cap(1) & (1u << 22)) != 0;
1155
69.2k
#endif
1156
69.2k
}
1157
1158
10.5M
inline int CRYPTO_is_AESNI_capable() {
1159
#if defined(__AES__)
1160
  return 1;
1161
#else
1162
10.5M
  return (OPENSSL_get_ia32cap(1) & (1u << 25)) != 0;
1163
10.5M
#endif
1164
10.5M
}
1165
1166
// We intentionally avoid defining a |CRYPTO_is_XSAVE_capable| function. See
1167
// |CRYPTO_cpu_perf_is_like_silvermont|.
1168
1169
2.60M
inline int CRYPTO_is_AVX_capable() {
1170
#if defined(__AVX__)
1171
  return 1;
1172
#else
1173
2.60M
  return (OPENSSL_get_ia32cap(1) & (1u << 28)) != 0;
1174
2.60M
#endif
1175
2.60M
}
1176
1177
446k
inline int CRYPTO_is_RDRAND_capable() {
1178
  // We intentionally do not check |__RDRND__| here. On some AMD processors, we
1179
  // will act as if the hardware is RDRAND-incapable, even it actually supports
1180
  // it. See cpu_intel.c.
1181
446k
  return (OPENSSL_get_ia32cap(1) & (1u << 30)) != 0;
1182
446k
}
1183
1184
// See Intel manual, volume 2A, table 3-8.
1185
1186
9.59M
inline int CRYPTO_is_BMI1_capable() {
1187
#if defined(__BMI__)
1188
  return 1;
1189
#else
1190
9.59M
  return (OPENSSL_get_ia32cap(2) & (1u << 3)) != 0;
1191
9.59M
#endif
1192
9.59M
}
1193
1194
549k
inline int CRYPTO_is_AVX2_capable() {
1195
#if defined(__AVX2__)
1196
  return 1;
1197
#else
1198
549k
  return (OPENSSL_get_ia32cap(2) & (1u << 5)) != 0;
1199
549k
#endif
1200
549k
}
1201
1202
15.9M
inline int CRYPTO_is_BMI2_capable() {
1203
#if defined(__BMI2__)
1204
  return 1;
1205
#else
1206
15.9M
  return (OPENSSL_get_ia32cap(2) & (1u << 8)) != 0;
1207
15.9M
#endif
1208
15.9M
}
1209
1210
15.9M
inline int CRYPTO_is_ADX_capable() {
1211
#if defined(__ADX__)
1212
  return 1;
1213
#else
1214
15.9M
  return (OPENSSL_get_ia32cap(2) & (1u << 19)) != 0;
1215
15.9M
#endif
1216
15.9M
}
1217
1218
// SHA-1 and SHA-256 are defined as a single extension.
1219
3.01M
inline int CRYPTO_is_x86_SHA_capable() {
1220
#if defined(__SHA__)
1221
  return 1;
1222
#else
1223
3.01M
  return (OPENSSL_get_ia32cap(2) & (1u << 29)) != 0;
1224
3.01M
#endif
1225
3.01M
}
1226
1227
// CRYPTO_cpu_perf_is_like_silvermont returns one if, based on a heuristic, the
1228
// CPU has Silvermont-like performance characteristics. It is often faster to
1229
// run different codepaths on these CPUs than the available instructions would
1230
// otherwise select. See chacha-x86_64.pl.
1231
//
1232
// Bonnell, Silvermont's predecessor in the Atom lineup, will also be matched by
1233
// this. Goldmont (Silvermont's successor in the Atom lineup) added XSAVE so it
1234
// isn't matched by this. Various sources indicate AMD first implemented MOVBE
1235
// and XSAVE at the same time in Jaguar, so it seems like AMD chips will not be
1236
// matched by this. That seems to be the case for other x86(-64) CPUs.
1237
408
inline int CRYPTO_cpu_perf_is_like_silvermont() {
1238
  // WARNING: This MUST NOT be used to guard the execution of the XSAVE
1239
  // instruction. This is the "hardware supports XSAVE" bit, not the OSXSAVE bit
1240
  // that indicates whether we can safely execute XSAVE. This bit may be set
1241
  // even when XSAVE is disabled (by the operating system). See how the users of
1242
  // this bit use it.
1243
  //
1244
  // Historically, the XSAVE bit was artificially cleared on Knights Landing
1245
  // and Knights Mill chips, but as Intel has removed all support from GCC,
1246
  // LLVM, and SDE, we assume they are no longer worth special-casing.
1247
408
  int hardware_supports_xsave = (OPENSSL_get_ia32cap(1) & (1u << 26)) != 0;
1248
408
  return !hardware_supports_xsave && CRYPTO_is_MOVBE_capable();
1249
408
}
1250
1251
0
inline int CRYPTO_is_AVX512BW_capable() {
1252
#if defined(__AVX512BW__)
1253
  return 1;
1254
#else
1255
0
  return (OPENSSL_get_ia32cap(2) & (1u << 30)) != 0;
1256
0
#endif
1257
0
}
1258
1259
0
inline int CRYPTO_is_AVX512VL_capable() {
1260
#if defined(__AVX512VL__)
1261
  return 1;
1262
#else
1263
0
  return (OPENSSL_get_ia32cap(2) & (1u << 31)) != 0;
1264
0
#endif
1265
0
}
1266
1267
// CRYPTO_cpu_avoid_zmm_registers returns 1 if zmm registers (512-bit vectors)
1268
// should not be used even if the CPU supports them.
1269
//
1270
// Note that this reuses the bit for the removed MPX feature.
1271
0
inline int CRYPTO_cpu_avoid_zmm_registers() {
1272
0
  return (OPENSSL_get_ia32cap(2) & (1u << 14)) != 0;
1273
0
}
1274
1275
0
inline int CRYPTO_is_VAES_capable() {
1276
#if defined(__VAES__)
1277
  return 1;
1278
#else
1279
0
  return (OPENSSL_get_ia32cap(3) & (1u << 9)) != 0;
1280
0
#endif
1281
0
}
1282
1283
69.2k
inline int CRYPTO_is_VPCLMULQDQ_capable() {
1284
#if defined(__VPCLMULQDQ__)
1285
  return 1;
1286
#else
1287
69.2k
  return (OPENSSL_get_ia32cap(3) & (1u << 10)) != 0;
1288
69.2k
#endif
1289
69.2k
}
1290
1291
#endif  // OPENSSL_X86 || OPENSSL_X86_64
1292
1293
#if defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)
1294
1295
// ARMV7_NEON indicates support for NEON.
1296
#define ARMV7_NEON (1 << 0)
1297
1298
// ARMV8_AES indicates support for hardware AES instructions.
1299
#define ARMV8_AES (1 << 2)
1300
1301
// ARMV8_SHA1 indicates support for hardware SHA-1 instructions.
1302
#define ARMV8_SHA1 (1 << 3)
1303
1304
// ARMV8_SHA256 indicates support for hardware SHA-256 instructions.
1305
#define ARMV8_SHA256 (1 << 4)
1306
1307
// ARMV8_PMULL indicates support for carryless multiplication.
1308
#define ARMV8_PMULL (1 << 5)
1309
1310
// ARMV8_SHA512 indicates support for hardware SHA-512 instructions.
1311
#define ARMV8_SHA512 (1 << 6)
1312
1313
// ARMV8_SHA3 indicates support for eor3 instructions.
1314
#define ARMV8_SHA3 (1 << 7)
1315
1316
#if defined(OPENSSL_STATIC_ARMCAP)
1317
// We assume |CRYPTO_is_*_capable| already checked static capabilities.
1318
inline uint32_t OPENSSL_get_armcap() { return 0; }
1319
#else
1320
// OPENSSL_armcap_P contains ARM CPU capabilities as a bitmask of the above
1321
// constants. This should only be accessed with |OPENSSL_get_armcap|.
1322
extern uint32_t OPENSSL_armcap_P;
1323
1324
// OPENSSL_get_armcap initializes the library if needed and returns ARM CPU
1325
// capabilities. It is marked as a const function so duplicate calls can be
1326
// merged by the compiler.
1327
OPENSSL_ATTR_CONST uint32_t OPENSSL_get_armcap();
1328
#endif  // OPENSSL_STATIC_ARMCAP
1329
1330
// Normalize some older feature flags to their modern ACLE values.
1331
// https://developer.arm.com/architectures/system-architectures/software-standards/acle
1332
#if defined(__ARM_NEON__) && !defined(__ARM_NEON)
1333
#define __ARM_NEON 1
1334
#endif
1335
#if defined(__ARM_FEATURE_CRYPTO)
1336
#if !defined(__ARM_FEATURE_AES)
1337
#define __ARM_FEATURE_AES 1
1338
#endif
1339
#if !defined(__ARM_FEATURE_SHA2)
1340
#define __ARM_FEATURE_SHA2 1
1341
#endif
1342
#endif
1343
1344
// CRYPTO_is_NEON_capable returns true if the current CPU has a NEON unit. If
1345
// this is known statically, it is a constant inline function.
1346
inline int CRYPTO_is_NEON_capable() {
1347
#if (defined(OPENSSL_STATIC_ARMCAP_NEON) || defined(__ARM_NEON)) && \
1348
    !defined(OPENSSL_NO_STATIC_NEON_FOR_TESTING)
1349
  return 1;
1350
#else
1351
  return (OPENSSL_get_armcap() & ARMV7_NEON) != 0;
1352
#endif
1353
}
1354
1355
inline int CRYPTO_is_ARMv8_AES_capable() {
1356
#if defined(OPENSSL_STATIC_ARMCAP_AES) || defined(__ARM_FEATURE_AES)
1357
  return 1;
1358
#else
1359
  return (OPENSSL_get_armcap() & ARMV8_AES) != 0;
1360
#endif
1361
}
1362
1363
inline int CRYPTO_is_ARMv8_PMULL_capable() {
1364
#if defined(OPENSSL_STATIC_ARMCAP_PMULL) || defined(__ARM_FEATURE_AES)
1365
  return 1;
1366
#else
1367
  return (OPENSSL_get_armcap() & ARMV8_PMULL) != 0;
1368
#endif
1369
}
1370
1371
inline int CRYPTO_is_ARMv8_SHA1_capable() {
1372
  // SHA-1 and SHA-2 (only) share |__ARM_FEATURE_SHA2| but otherwise
1373
  // are dealt with independently.
1374
#if defined(OPENSSL_STATIC_ARMCAP_SHA1) || defined(__ARM_FEATURE_SHA2)
1375
  return 1;
1376
#else
1377
  return (OPENSSL_get_armcap() & ARMV8_SHA1) != 0;
1378
#endif
1379
}
1380
1381
inline int CRYPTO_is_ARMv8_SHA256_capable() {
1382
  // SHA-1 and SHA-2 (only) share |__ARM_FEATURE_SHA2| but otherwise
1383
  // are dealt with independently.
1384
#if defined(OPENSSL_STATIC_ARMCAP_SHA256) || defined(__ARM_FEATURE_SHA2)
1385
  return 1;
1386
#else
1387
  return (OPENSSL_get_armcap() & ARMV8_SHA256) != 0;
1388
#endif
1389
}
1390
1391
inline int CRYPTO_is_ARMv8_SHA512_capable() {
1392
  // There is no |OPENSSL_STATIC_ARMCAP_SHA512|.
1393
#if defined(__ARM_FEATURE_SHA512)
1394
  return 1;
1395
#else
1396
  return (OPENSSL_get_armcap() & ARMV8_SHA512) != 0;
1397
#endif
1398
}
1399
1400
inline int CRYPTO_is_ARMv8_SHA3_capable() {
1401
  // There is no |OPENSSL_STATIC_ARMCAP_SHA3|.
1402
#if defined(__ARM_FEATURE_SHA3)
1403
  return 1;
1404
#else
1405
  return (OPENSSL_get_armcap() & ARMV8_SHA3) != 0;
1406
#endif
1407
}
1408
1409
#endif  // OPENSSL_ARM || OPENSSL_AARCH64
1410
1411
1412
#if defined(BORINGSSL_DISPATCH_TEST)
1413
// Runtime CPU dispatch testing support
1414
1415
// BORINGSSL_function_hit is an array of flags. The following functions will
1416
// set these flags if BORINGSSL_DISPATCH_TEST is defined.
1417
//   0: aes_hw_ctr32_encrypt_blocks
1418
//   1: aes_hw_encrypt
1419
//   2: aesni_gcm_encrypt
1420
//   3: aes_hw_set_encrypt_key
1421
//   4: vpaes_encrypt
1422
//   5: vpaes_set_encrypt_key
1423
//   6: aes_gcm_enc_update_vaes_avx2
1424
//   7: aes_gcm_enc_update_vaes_avx512
1425
extern "C" uint8_t BORINGSSL_function_hit[8];
1426
#endif  // BORINGSSL_DISPATCH_TEST
1427
1428
1429
// OPENSSL_vasprintf_internal is just like |vasprintf(3)|. If |system_malloc| is
1430
// 0, memory will be allocated with |OPENSSL_malloc| and must be freed with
1431
// |OPENSSL_free|. Otherwise the system |malloc| function is used and the memory
1432
// must be freed with the system |free| function.
1433
OPENSSL_EXPORT int OPENSSL_vasprintf_internal(char **str, const char *format,
1434
                                              va_list args, int system_malloc)
1435
    OPENSSL_PRINTF_FORMAT_FUNC(2, 0);
1436
1437
1438
// Fuzzer mode.
1439
1440
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
1441
// CRYPTO_fuzzer_mode_enabled returns whether fuzzer mode is enabled. See
1442
// |CRYPTO_set_fuzzer_mode|. In non-fuzzer builds, this function statically
1443
// returns zero so the codepaths will be deleted by the optimizer.
1444
int CRYPTO_fuzzer_mode_enabled();
1445
#else
1446
inline int CRYPTO_fuzzer_mode_enabled() { return 0; }
1447
#endif
1448
1449
1450
// Arithmetic functions.
1451
1452
// CRYPTO_addc_* returns |x + y + carry|, and sets |*out_carry| to the carry
1453
// bit. |carry| must be zero or one.
1454
1455
// NOTE: Unoptimized GCC builds may compile these builtins to non-constant-time
1456
// code. For correct constant-time behavior, ensure builds are optimized.
1457
#if OPENSSL_HAS_BUILTIN(__builtin_addc)
1458
1459
inline unsigned int CRYPTO_addc_impl(unsigned int x, unsigned int y,
1460
                                     unsigned int carry,
1461
0
                                     unsigned int *out_carry) {
1462
0
  return __builtin_addc(x, y, carry, out_carry);
1463
0
}
1464
1465
inline unsigned long CRYPTO_addc_impl(unsigned long x, unsigned long y,
1466
                                      unsigned long carry,
1467
4.04M
                                      unsigned long *out_carry) {
1468
4.04M
  return __builtin_addcl(x, y, carry, out_carry);
1469
4.04M
}
1470
1471
inline unsigned long long CRYPTO_addc_impl(unsigned long long x,
1472
                                           unsigned long long y,
1473
                                           unsigned long long carry,
1474
0
                                           unsigned long long *out_carry) {
1475
0
  return __builtin_addcll(x, y, carry, out_carry);
1476
0
}
1477
1478
inline uint32_t CRYPTO_addc_u32(uint32_t x, uint32_t y, uint32_t carry,
1479
0
                                uint32_t *out_carry) {
1480
0
  return CRYPTO_addc_impl(x, y, carry, out_carry);
1481
0
}
1482
1483
inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry,
1484
4.04M
                                uint64_t *out_carry) {
1485
4.04M
  return CRYPTO_addc_impl(x, y, carry, out_carry);
1486
4.04M
}
1487
1488
#else
1489
1490
inline uint32_t CRYPTO_addc_u32(uint32_t x, uint32_t y, uint32_t carry,
1491
                                uint32_t *out_carry) {
1492
  declassify_assert(carry <= 1);
1493
#if defined(_M_IX86)
1494
  uint32_t sum = 0;
1495
  *out_carry = _addcarry_u32(carry, x, y, &sum);
1496
  return sum;
1497
#else
1498
  uint64_t ret = carry;
1499
  ret += (uint64_t)x + y;
1500
  *out_carry = (uint32_t)(ret >> 32);
1501
  return (uint32_t)ret;
1502
#endif
1503
}
1504
1505
inline uint64_t CRYPTO_addc_u64(uint64_t x, uint64_t y, uint64_t carry,
1506
                                uint64_t *out_carry) {
1507
  declassify_assert(carry <= 1);
1508
#if defined(_M_X64)
1509
  uint64_t sum = 0;
1510
  *out_carry = _addcarry_u64(carry, x, y, &sum);
1511
  return sum;
1512
#elif defined(BORINGSSL_HAS_UINT128)
1513
  uint128_t ret = carry;
1514
  ret += (uint128_t)x + y;
1515
  *out_carry = (uint64_t)(ret >> 64);
1516
  return (uint64_t)ret;
1517
#else
1518
  x += carry;
1519
  carry = x < carry;
1520
  uint64_t ret = x + y;
1521
  carry += ret < x;
1522
  *out_carry = carry;
1523
  return ret;
1524
#endif
1525
}
1526
#endif
1527
1528
1529
// CRYPTO_subc_* returns |x - y - borrow|, and sets |*out_borrow| to the borrow
1530
// bit. |borrow| must be zero or one.
1531
#if OPENSSL_HAS_BUILTIN(__builtin_subc)
1532
1533
inline unsigned int CRYPTO_subc_impl(unsigned int x, unsigned int y,
1534
                                     unsigned int borrow,
1535
0
                                     unsigned int *out_borrow) {
1536
0
  return __builtin_subc(x, y, borrow, out_borrow);
1537
0
}
1538
1539
inline unsigned long CRYPTO_subc_impl(unsigned long x, unsigned long y,
1540
                                      unsigned long borrow,
1541
83.3k
                                      unsigned long *out_borrow) {
1542
83.3k
  return __builtin_subcl(x, y, borrow, out_borrow);
1543
83.3k
}
1544
1545
inline unsigned long long CRYPTO_subc_impl(unsigned long long x,
1546
                                           unsigned long long y,
1547
                                           unsigned long long borrow,
1548
0
                                           unsigned long long *out_borrow) {
1549
0
  return __builtin_subcll(x, y, borrow, out_borrow);
1550
0
}
1551
1552
inline uint32_t CRYPTO_subc_u32(uint32_t x, uint32_t y, uint32_t borrow,
1553
0
                                uint32_t *out_borrow) {
1554
0
  return CRYPTO_subc_impl(x, y, borrow, out_borrow);
1555
0
}
1556
1557
inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow,
1558
83.3k
                                uint64_t *out_borrow) {
1559
83.3k
  return CRYPTO_subc_impl(x, y, borrow, out_borrow);
1560
83.3k
}
1561
1562
#else
1563
1564
inline uint32_t CRYPTO_subc_u32(uint32_t x, uint32_t y, uint32_t borrow,
1565
                                uint32_t *out_borrow) {
1566
  declassify_assert(borrow <= 1);
1567
#if defined(_M_IX86)
1568
  uint32_t diff = 0;
1569
  *out_borrow = _subborrow_u32(borrow, x, y, &diff);
1570
  return diff;
1571
#else
1572
  uint32_t ret = x - y - borrow;
1573
  *out_borrow = (x < y) | ((x == y) & borrow);
1574
  return ret;
1575
#endif
1576
}
1577
1578
inline uint64_t CRYPTO_subc_u64(uint64_t x, uint64_t y, uint64_t borrow,
1579
                                uint64_t *out_borrow) {
1580
  declassify_assert(borrow <= 1);
1581
#if defined(_M_X64)
1582
  uint64_t diff = 0;
1583
  *out_borrow = _subborrow_u64(borrow, x, y, &diff);
1584
  return diff;
1585
#else
1586
  uint64_t ret = x - y - borrow;
1587
  *out_borrow = (x < y) | ((x == y) & borrow);
1588
  return ret;
1589
#endif
1590
}
1591
#endif
1592
1593
#if defined(OPENSSL_64_BIT)
1594
4.04M
#define CRYPTO_addc_w CRYPTO_addc_u64
1595
83.3k
#define CRYPTO_subc_w CRYPTO_subc_u64
1596
#else
1597
#define CRYPTO_addc_w CRYPTO_addc_u32
1598
#define CRYPTO_subc_w CRYPTO_subc_u32
1599
#endif
1600
1601
1602
// Cleanup implements a custom scope guard, when the cleanup logic does not fit
1603
// in a destructor. Usage:
1604
//
1605
//     bssl::Cleanup cleanup = [&] { SomeCleanupWork(local_var); };
1606
template <typename F>
1607
class Cleanup {
1608
 public:
1609
  static_assert(std::is_invocable_v<F>);
1610
  static_assert(std::is_same_v<std::invoke_result_t<F>, void>);
1611
1612
18.7k
  Cleanup(F func) : func_(func) {}
Unexecuted instantiation: bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_seal::$_0>::Cleanup(EVP_AEAD_CTX_seal::$_0)
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_seal_scatter::$_0>::Cleanup(EVP_AEAD_CTX_seal_scatter::$_0)
Line
Count
Source
1612
2.06k
  Cleanup(F func) : func_(func) {}
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_sealv::$_0>::Cleanup(EVP_AEAD_CTX_sealv::$_0)
Line
Count
Source
1612
2.06k
  Cleanup(F func) : func_(func) {}
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_open::$_0>::Cleanup(EVP_AEAD_CTX_open::$_0)
Line
Count
Source
1612
7.31k
  Cleanup(F func) : func_(func) {}
Unexecuted instantiation: bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_open_gather::$_0>::Cleanup(EVP_AEAD_CTX_open_gather::$_0)
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_openv::$_0>::Cleanup(EVP_AEAD_CTX_openv::$_0)
Line
Count
Source
1612
4.02k
  Cleanup(F func) : func_(func) {}
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_openv_detached::$_0>::Cleanup(EVP_AEAD_CTX_openv_detached::$_0)
Line
Count
Source
1612
3.28k
  Cleanup(F func) : func_(func) {}
Unexecuted instantiation: x_all.cc:bssl::Cleanup<X509_sign_ctx::$_0>::Cleanup(X509_sign_ctx::$_0)
Unexecuted instantiation: a_sign.cc:bssl::Cleanup<ASN1_item_sign_ctx::$_0>::Cleanup(ASN1_item_sign_ctx::$_0)
1613
  Cleanup(const Cleanup &) = delete;
1614
  Cleanup &operator=(const Cleanup &) = delete;
1615
18.7k
  ~Cleanup() { func_(); }
Unexecuted instantiation: bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_seal::$_0>::~Cleanup()
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_seal_scatter::$_0>::~Cleanup()
Line
Count
Source
1615
2.06k
  ~Cleanup() { func_(); }
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_sealv::$_0>::~Cleanup()
Line
Count
Source
1615
2.06k
  ~Cleanup() { func_(); }
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_open::$_0>::~Cleanup()
Line
Count
Source
1615
7.31k
  ~Cleanup() { func_(); }
Unexecuted instantiation: bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_open_gather::$_0>::~Cleanup()
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_openv::$_0>::~Cleanup()
Line
Count
Source
1615
4.02k
  ~Cleanup() { func_(); }
bcm.cc:bssl::Cleanup<EVP_AEAD_CTX_openv_detached::$_0>::~Cleanup()
Line
Count
Source
1615
3.28k
  ~Cleanup() { func_(); }
Unexecuted instantiation: x_all.cc:bssl::Cleanup<X509_sign_ctx::$_0>::~Cleanup()
Unexecuted instantiation: a_sign.cc:bssl::Cleanup<ASN1_item_sign_ctx::$_0>::~Cleanup()
1616
1617
 private:
1618
  F func_;
1619
};
1620
template <typename F>
1621
Cleanup(F func) -> Cleanup<F>;
1622
1623
// DECLARE_OPAQUE_STRUCT defines a public struct |public_name| with an
1624
// implementation struct |impl_name|.
1625
//
1626
// To prevent accidents, the |public_name| struct will be neither constructable,
1627
// nor copyable/movable, nor deletable.
1628
//
1629
// It must be used from inside the |bssl| namespace; however, |public_name| will
1630
// be defined outside.
1631
//
1632
// Usage:
1633
//
1634
// DECLARE_OPAQUE_STRUCT(public_st, PublicImpl)
1635
//
1636
// BSSL_NAMESPACE_BEGIN
1637
//
1638
// class PublicImpl : public public_st {
1639
//  public:
1640
//   PublicImpl();
1641
//   ~PublicImpl();
1642
//   void foo();
1643
// };
1644
//
1645
// BSSL_NAMESPACE_END
1646
//
1647
// The implementation struct can be converted to the public struct implicitly;
1648
// to convert the public struct to the implementation struct, call
1649
// |FromOpaque| on it. It is explicitly allowed to call |FromOpaque| on a
1650
// |nullptr|.
1651
#define DECLARE_OPAQUE_STRUCT(public_name, impl_name)                  \
1652
  BSSL_NAMESPACE_BEGIN                                                 \
1653
  class impl_name;                                                     \
1654
  BSSL_NAMESPACE_END                                                   \
1655
                                                                       \
1656
  /* This is unnamespaced but assumed to not create linker symbols. */ \
1657
  struct public_name {                                                 \
1658
    using ImplType = bssl::impl_name;                                  \
1659
                                                                       \
1660
   private:                                                            \
1661
    public_name() = default;                                           \
1662
    ~public_name() = default;                                          \
1663
    public_name(const public_name &) = delete;                         \
1664
    public_name &operator=(const public_name &) = delete;              \
1665
                                                                       \
1666
    friend class bssl::impl_name;                                      \
1667
  };
1668
1669
template <typename Public>
1670
83.6M
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
83.6M
  return static_cast<typename Public::ImplType *>(p);
1672
83.6M
}
bignum_ctx::ImplType* bssl::FromOpaque<bignum_ctx>(bignum_ctx*)
Line
Count
Source
1670
68.9M
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
68.9M
  return static_cast<typename Public::ImplType *>(p);
1672
68.9M
}
Unexecuted instantiation: dh_st::ImplType* bssl::FromOpaque<dh_st>(dh_st*)
evp_pkey_ctx_st::ImplType* bssl::FromOpaque<evp_pkey_ctx_st>(evp_pkey_ctx_st*)
Line
Count
Source
1670
641k
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
641k
  return static_cast<typename Public::ImplType *>(p);
1672
641k
}
ec_key_st::ImplType* bssl::FromOpaque<ec_key_st>(ec_key_st*)
Line
Count
Source
1670
186k
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
186k
  return static_cast<typename Public::ImplType *>(p);
1672
186k
}
rsa_st::ImplType* bssl::FromOpaque<rsa_st>(rsa_st*)
Line
Count
Source
1670
460k
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
460k
  return static_cast<typename Public::ImplType *>(p);
1672
460k
}
bio_st::ImplType* bssl::FromOpaque<bio_st>(bio_st*)
Line
Count
Source
1670
8.30M
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
8.30M
  return static_cast<typename Public::ImplType *>(p);
1672
8.30M
}
evp_pkey_st::ImplType* bssl::FromOpaque<evp_pkey_st>(evp_pkey_st*)
Line
Count
Source
1670
1.18M
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
1.18M
  return static_cast<typename Public::ImplType *>(p);
1672
1.18M
}
dsa_st::ImplType* bssl::FromOpaque<dsa_st>(dsa_st*)
Line
Count
Source
1670
14.0k
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
14.0k
  return static_cast<typename Public::ImplType *>(p);
1672
14.0k
}
crypto_buffer_st::ImplType* bssl::FromOpaque<crypto_buffer_st>(crypto_buffer_st*)
Line
Count
Source
1670
1.40M
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
1.40M
  return static_cast<typename Public::ImplType *>(p);
1672
1.40M
}
x509_st::ImplType* bssl::FromOpaque<x509_st>(x509_st*)
Line
Count
Source
1670
757k
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
757k
  return static_cast<typename Public::ImplType *>(p);
1672
757k
}
x509_store_st::ImplType* bssl::FromOpaque<x509_store_st>(x509_store_st*)
Line
Count
Source
1670
12.2k
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
12.2k
  return static_cast<typename Public::ImplType *>(p);
1672
12.2k
}
X509_name_st::ImplType* bssl::FromOpaque<X509_name_st>(X509_name_st*)
Line
Count
Source
1670
1.74M
inline typename Public::ImplType *FromOpaque(Public *p) {
1671
1.74M
  return static_cast<typename Public::ImplType *>(p);
1672
1.74M
}
1673
1674
template <typename Public>
1675
4.35M
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
4.35M
  return static_cast<const typename Public::ImplType *>(p);
1677
4.35M
}
Unexecuted instantiation: dh_st::ImplType const* bssl::FromOpaque<dh_st>(dh_st const*)
ec_key_st::ImplType const* bssl::FromOpaque<ec_key_st>(ec_key_st const*)
Line
Count
Source
1675
62.7k
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
62.7k
  return static_cast<const typename Public::ImplType *>(p);
1677
62.7k
}
rsa_st::ImplType const* bssl::FromOpaque<rsa_st>(rsa_st const*)
Line
Count
Source
1675
538k
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
538k
  return static_cast<const typename Public::ImplType *>(p);
1677
538k
}
bio_st::ImplType const* bssl::FromOpaque<bio_st>(bio_st const*)
Line
Count
Source
1675
1.44M
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
1.44M
  return static_cast<const typename Public::ImplType *>(p);
1677
1.44M
}
evp_pkey_st::ImplType const* bssl::FromOpaque<evp_pkey_st>(evp_pkey_st const*)
Line
Count
Source
1675
658k
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
658k
  return static_cast<const typename Public::ImplType *>(p);
1677
658k
}
crypto_buffer_st::ImplType const* bssl::FromOpaque<crypto_buffer_st>(crypto_buffer_st const*)
Line
Count
Source
1675
435k
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
435k
  return static_cast<const typename Public::ImplType *>(p);
1677
435k
}
x509_st::ImplType const* bssl::FromOpaque<x509_st>(x509_st const*)
Line
Count
Source
1675
214k
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
214k
  return static_cast<const typename Public::ImplType *>(p);
1677
214k
}
X509_name_st::ImplType const* bssl::FromOpaque<X509_name_st>(X509_name_st const*)
Line
Count
Source
1675
997k
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
997k
  return static_cast<const typename Public::ImplType *>(p);
1677
997k
}
dsa_st::ImplType const* bssl::FromOpaque<dsa_st>(dsa_st const*)
Line
Count
Source
1675
881
inline const typename Public::ImplType *FromOpaque(const Public *p) {
1676
881
  return static_cast<const typename Public::ImplType *>(p);
1677
881
}
1678
1679
BSSL_NAMESPACE_END
1680
1681
1682
#endif  // OPENSSL_HEADER_CRYPTO_INTERNAL_H