1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57 /* ====================================================================
58 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
70 * distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 * acknowledgment:
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
108
109 #ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
110 #define OPENSSL_HEADER_CRYPTO_INTERNAL_H
111
112 #include <openssl/ex_data.h>
113 #include <openssl/stack.h>
114 #include <openssl/thread.h>
115
116 #include <assert.h>
117 #include <string.h>
118
119 #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
120 #include <valgrind/memcheck.h>
121 #endif
122
123 #if !defined(__cplusplus)
124 #if defined(_MSC_VER)
125 #define alignas(x) __declspec(align(x))
126 #define alignof __alignof
127 #else
128 #include <stdalign.h>
129 #endif
130 #endif
131
132 #if defined(OPENSSL_THREADS) && \
133 (!defined(OPENSSL_WINDOWS) || defined(__MINGW32__))
134 #include <pthread.h>
135 #define OPENSSL_PTHREADS
136 #endif
137
138 #if defined(OPENSSL_THREADS) && !defined(OPENSSL_PTHREADS) && \
139 defined(OPENSSL_WINDOWS)
140 #define OPENSSL_WINDOWS_THREADS
141 OPENSSL_MSVC_PRAGMA(warning(push, 3))
142 #include <windows.h>
OPENSSL_MSVC_PRAGMA(warning (pop))143 OPENSSL_MSVC_PRAGMA(warning(pop))
144 #endif
145
146 #if defined(__cplusplus)
147 extern "C" {
148 #endif
149
150
151 #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \
152 defined(OPENSSL_AARCH64) || defined(OPENSSL_PPC64LE)
153 // OPENSSL_cpuid_setup initializes the platform-specific feature cache.
154 void OPENSSL_cpuid_setup(void);
155 #endif
156
157 #if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \
158 !defined(OPENSSL_STATIC_ARMCAP)
159 // OPENSSL_get_armcap_pointer_for_test returns a pointer to |OPENSSL_armcap_P|
160 // for unit tests. Any modifications to the value must be made after
161 // |CRYPTO_library_init| but before any other function call in BoringSSL.
162 OPENSSL_EXPORT uint32_t *OPENSSL_get_armcap_pointer_for_test(void);
163 #endif
164
165
166 #if (!defined(_MSC_VER) || defined(__clang__)) && defined(OPENSSL_64_BIT)
167 #define BORINGSSL_HAS_UINT128
168 typedef __int128_t int128_t;
169 typedef __uint128_t uint128_t;
170
171 // clang-cl supports __uint128_t but modulus and division don't work.
172 // https://crbug.com/787617.
173 #if !defined(_MSC_VER) || !defined(__clang__)
174 #define BORINGSSL_CAN_DIVIDE_UINT128
175 #endif
176 #endif
177
178 #define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
179
180 // Have a generic fall-through for different versions of C/C++.
181 #if defined(__cplusplus) && __cplusplus >= 201703L
182 #define OPENSSL_FALLTHROUGH [[fallthrough]]
183 #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__clang__)
184 #define OPENSSL_FALLTHROUGH [[clang::fallthrough]]
185 #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__GNUC__) && \
186 __GNUC__ >= 7
187 #define OPENSSL_FALLTHROUGH [[gnu::fallthrough]]
188 #elif defined(__GNUC__) && __GNUC__ >= 7 // gcc 7
189 #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
190 #elif defined(__clang__)
191 #if __has_attribute(fallthrough) && __clang_major__ >= 5
192 // Clang 3.5, at least, complains about "error: declaration does not declare
193 // anything", possibily because we put a semicolon after this macro in
194 // practice. Thus limit it to >= Clang 5, which does work.
195 #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
196 #else // clang versions that do not support fallthrough.
197 #define OPENSSL_FALLTHROUGH
198 #endif
199 #else // C++11 on gcc 6, and all other cases
200 #define OPENSSL_FALLTHROUGH
201 #endif
202
203 // buffers_alias returns one if |a| and |b| alias and zero otherwise.
204 static inline int buffers_alias(const uint8_t *a, size_t a_len,
205 const uint8_t *b, size_t b_len) {
206 // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
207 // objects are undefined whereas pointer to integer conversions are merely
208 // implementation-defined. We assume the implementation defined it in a sane
209 // way.
210 uintptr_t a_u = (uintptr_t)a;
211 uintptr_t b_u = (uintptr_t)b;
212 return a_u + a_len > b_u && b_u + b_len > a_u;
213 }
214
215
216 // Constant-time utility functions.
217 //
218 // The following methods return a bitmask of all ones (0xff...f) for true and 0
219 // for false. This is useful for choosing a value based on the result of a
220 // conditional in constant time. For example,
221 //
222 // if (a < b) {
223 // c = a;
224 // } else {
225 // c = b;
226 // }
227 //
228 // can be written as
229 //
230 // crypto_word_t lt = constant_time_lt_w(a, b);
231 // c = constant_time_select_w(lt, a, b);
232
233 // crypto_word_t is the type that most constant-time functions use. Ideally we
234 // would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit
235 // pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64
236 // bits. Since we want to be able to do constant-time operations on a
237 // |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native
238 // word length.
239 #if defined(OPENSSL_64_BIT)
240 typedef uint64_t crypto_word_t;
241 #elif defined(OPENSSL_32_BIT)
242 typedef uint32_t crypto_word_t;
243 #else
244 #error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
245 #endif
246
247 #define CONSTTIME_TRUE_W ~((crypto_word_t)0)
248 #define CONSTTIME_FALSE_W ((crypto_word_t)0)
249 #define CONSTTIME_TRUE_8 ((uint8_t)0xff)
250 #define CONSTTIME_FALSE_8 ((uint8_t)0)
251
252 // value_barrier_w returns |a|, but prevents GCC and Clang from reasoning about
253 // the returned value. This is used to mitigate compilers undoing constant-time
254 // code, until we can express our requirements directly in the language.
255 //
256 // Note the compiler is aware that |value_barrier_w| has no side effects and
257 // always has the same output for a given input. This allows it to eliminate
258 // dead code, move computations across loops, and vectorize.
259 static inline crypto_word_t value_barrier_w(crypto_word_t a) {
260 #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
261 __asm__("" : "+r"(a) : /* no inputs */);
262 #endif
263 return a;
264 }
265
266 // value_barrier_u32 behaves like |value_barrier_w| but takes a |uint32_t|.
267 static inline uint32_t value_barrier_u32(uint32_t a) {
268 #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
269 __asm__("" : "+r"(a) : /* no inputs */);
270 #endif
271 return a;
272 }
273
274 // value_barrier_u64 behaves like |value_barrier_w| but takes a |uint64_t|.
275 static inline uint64_t value_barrier_u64(uint64_t a) {
276 #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
277 __asm__("" : "+r"(a) : /* no inputs */);
278 #endif
279 return a;
280 }
281
282 // constant_time_msb_w returns the given value with the MSB copied to all the
283 // other bits.
284 static inline crypto_word_t constant_time_msb_w(crypto_word_t a) {
285 return 0u - (a >> (sizeof(a) * 8 - 1));
286 }
287
288 // constant_time_lt_w returns 0xff..f if a < b and 0 otherwise.
289 static inline crypto_word_t constant_time_lt_w(crypto_word_t a,
290 crypto_word_t b) {
291 // Consider the two cases of the problem:
292 // msb(a) == msb(b): a < b iff the MSB of a - b is set.
293 // msb(a) != msb(b): a < b iff the MSB of b is set.
294 //
295 // If msb(a) == msb(b) then the following evaluates as:
296 // msb(a^((a^b)|((a-b)^a))) ==
297 // msb(a^((a-b) ^ a)) == (because msb(a^b) == 0)
298 // msb(a^a^(a-b)) == (rearranging)
299 // msb(a-b) (because ∀x. x^x == 0)
300 //
301 // Else, if msb(a) != msb(b) then the following evaluates as:
302 // msb(a^((a^b)|((a-b)^a))) ==
303 // msb(a^( | ((a-b)^a))) == (because msb(a^b) == 1 and
304 // represents a value s.t. msb() = 1)
305 // msb(a^) == (because ORing with 1 results in 1)
306 // msb(b)
307 //
308 //
309 // Here is an SMT-LIB verification of this formula:
310 //
311 // (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
312 // (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
313 // )
314 //
315 // (declare-fun a () (_ BitVec 32))
316 // (declare-fun b () (_ BitVec 32))
317 //
318 // (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
319 // (check-sat)
320 // (get-model)
321 return constant_time_msb_w(a^((a^b)|((a-b)^a)));
322 }
323
324 // constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit
325 // mask.
326 static inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) {
327 return (uint8_t)(constant_time_lt_w(a, b));
328 }
329
330 // constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise.
331 static inline crypto_word_t constant_time_ge_w(crypto_word_t a,
332 crypto_word_t b) {
333 return ~constant_time_lt_w(a, b);
334 }
335
336 // constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit
337 // mask.
338 static inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) {
339 return (uint8_t)(constant_time_ge_w(a, b));
340 }
341
342 // constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise.
343 static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) {
344 // Here is an SMT-LIB verification of this formula:
345 //
346 // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
347 // (bvand (bvnot a) (bvsub a #x00000001))
348 // )
349 //
350 // (declare-fun a () (_ BitVec 32))
351 //
352 // (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a #x00000000))))
353 // (check-sat)
354 // (get-model)
355 return constant_time_msb_w(~a & (a - 1));
356 }
357
358 // constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an
359 // 8-bit mask.
360 static inline uint8_t constant_time_is_zero_8(crypto_word_t a) {
361 return (uint8_t)(constant_time_is_zero_w(a));
362 }
363
364 // constant_time_eq_w returns 0xff..f if a == b and 0 otherwise.
365 static inline crypto_word_t constant_time_eq_w(crypto_word_t a,
366 crypto_word_t b) {
367 return constant_time_is_zero_w(a ^ b);
368 }
369
370 // constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit
371 // mask.
372 static inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) {
373 return (uint8_t)(constant_time_eq_w(a, b));
374 }
375
376 // constant_time_eq_int acts like |constant_time_eq_w| but works on int
377 // values.
378 static inline crypto_word_t constant_time_eq_int(int a, int b) {
379 return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b));
380 }
381
382 // constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
383 // mask.
384 static inline uint8_t constant_time_eq_int_8(int a, int b) {
385 return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b));
386 }
387
388 // constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all
389 // 1s or all 0s (as returned by the methods above), the select methods return
390 // either |a| (if |mask| is nonzero) or |b| (if |mask| is zero).
391 static inline crypto_word_t constant_time_select_w(crypto_word_t mask,
392 crypto_word_t a,
393 crypto_word_t b) {
394 // Clang recognizes this pattern as a select. While it usually transforms it
395 // to a cmov, it sometimes further transforms it into a branch, which we do
396 // not want.
397 //
398 // Adding barriers to both |mask| and |~mask| breaks the relationship between
399 // the two, which makes the compiler stick with bitmasks.
400 return (value_barrier_w(mask) & a) | (value_barrier_w(~mask) & b);
401 }
402
403 // constant_time_select_8 acts like |constant_time_select| but operates on
404 // 8-bit values.
405 static inline uint8_t constant_time_select_8(uint8_t mask, uint8_t a,
406 uint8_t b) {
407 return (uint8_t)(constant_time_select_w(mask, a, b));
408 }
409
410 // constant_time_select_int acts like |constant_time_select| but operates on
411 // ints.
412 static inline int constant_time_select_int(crypto_word_t mask, int a, int b) {
413 return (int)(constant_time_select_w(mask, (crypto_word_t)(a),
414 (crypto_word_t)(b)));
415 }
416
417 #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
418
419 // CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region
420 // of memory as secret. Secret data is tracked as it flows to registers and
421 // other parts of a memory. If secret data is used as a condition for a branch,
422 // or as a memory index, it will trigger warnings in valgrind.
423 #define CONSTTIME_SECRET(x, y) VALGRIND_MAKE_MEM_UNDEFINED(x, y)
424
425 // CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that
426 // region of memory as public. Public data is not subject to constant-time
427 // rules.
428 #define CONSTTIME_DECLASSIFY(x, y) VALGRIND_MAKE_MEM_DEFINED(x, y)
429
430 #else
431
432 #define CONSTTIME_SECRET(x, y)
433 #define CONSTTIME_DECLASSIFY(x, y)
434
435 #endif // BORINGSSL_CONSTANT_TIME_VALIDATION
436
437
438 // Thread-safe initialisation.
439
440 #if !defined(OPENSSL_THREADS)
441 typedef uint32_t CRYPTO_once_t;
442 #define CRYPTO_ONCE_INIT 0
443 #elif defined(OPENSSL_WINDOWS_THREADS)
444 typedef INIT_ONCE CRYPTO_once_t;
445 #define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
446 #elif defined(OPENSSL_PTHREADS)
447 typedef pthread_once_t CRYPTO_once_t;
448 #define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
449 #else
450 #error "Unknown threading library"
451 #endif
452
453 // CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
454 // concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
455 // then they will block until |init| completes, but |init| will have only been
456 // called once.
457 //
458 // The |once| argument must be a |CRYPTO_once_t| that has been initialised with
459 // the value |CRYPTO_ONCE_INIT|.
460 OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));
461
462
463 // Reference counting.
464
465 // CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates.
466 #define CRYPTO_REFCOUNT_MAX 0xffffffff
467
468 // CRYPTO_refcount_inc atomically increments the value at |*count| unless the
469 // value would overflow. It's safe for multiple threads to concurrently call
470 // this or |CRYPTO_refcount_dec_and_test_zero| on the same
471 // |CRYPTO_refcount_t|.
472 OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
473
474 // CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
475 // if it's zero, it crashes the address space.
476 // if it's the maximum value, it returns zero.
477 // otherwise, it atomically decrements it and returns one iff the resulting
478 // value is zero.
479 //
480 // It's safe for multiple threads to concurrently call this or
481 // |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|.
482 OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
483
484
485 // Locks.
486 //
487 // Two types of locks are defined: |CRYPTO_MUTEX|, which can be used in
488 // structures as normal, and |struct CRYPTO_STATIC_MUTEX|, which can be used as
489 // a global lock. A global lock must be initialised to the value
490 // |CRYPTO_STATIC_MUTEX_INIT|.
491 //
492 // |CRYPTO_MUTEX| can appear in public structures and so is defined in
493 // thread.h as a structure large enough to fit the real type. The global lock is
494 // a different type so it may be initialized with platform initializer macros.
495
496 #if !defined(OPENSSL_THREADS)
497 struct CRYPTO_STATIC_MUTEX {
498 char padding; // Empty structs have different sizes in C and C++.
499 };
500 #define CRYPTO_STATIC_MUTEX_INIT { 0 }
501 #elif defined(OPENSSL_WINDOWS_THREADS)
502 struct CRYPTO_STATIC_MUTEX {
503 SRWLOCK lock;
504 };
505 #define CRYPTO_STATIC_MUTEX_INIT { SRWLOCK_INIT }
506 #elif defined(OPENSSL_PTHREADS)
507 struct CRYPTO_STATIC_MUTEX {
508 pthread_rwlock_t lock;
509 };
510 #define CRYPTO_STATIC_MUTEX_INIT { PTHREAD_RWLOCK_INITIALIZER }
511 #else
512 #error "Unknown threading library"
513 #endif
514
515 // CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
516 // |CRYPTO_STATIC_MUTEX|.
517 OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);
518
519 // CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
520 // read lock, but none may have a write lock.
521 OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);
522
523 // CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
524 // of lock on it.
525 OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);
526
527 // CRYPTO_MUTEX_unlock_read unlocks |lock| for reading.
528 OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);
529
530 // CRYPTO_MUTEX_unlock_write unlocks |lock| for writing.
531 OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);
532
533 // CRYPTO_MUTEX_cleanup releases all resources held by |lock|.
534 OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);
535
536 // CRYPTO_STATIC_MUTEX_lock_read locks |lock| such that other threads may also
537 // have a read lock, but none may have a write lock. The |lock| variable does
538 // not need to be initialised by any function, but must have been statically
539 // initialised with |CRYPTO_STATIC_MUTEX_INIT|.
540 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_read(
541 struct CRYPTO_STATIC_MUTEX *lock);
542
543 // CRYPTO_STATIC_MUTEX_lock_write locks |lock| such that no other thread has
544 // any type of lock on it. The |lock| variable does not need to be initialised
545 // by any function, but must have been statically initialised with
546 // |CRYPTO_STATIC_MUTEX_INIT|.
547 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_write(
548 struct CRYPTO_STATIC_MUTEX *lock);
549
550 // CRYPTO_STATIC_MUTEX_unlock_read unlocks |lock| for reading.
551 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_read(
552 struct CRYPTO_STATIC_MUTEX *lock);
553
554 // CRYPTO_STATIC_MUTEX_unlock_write unlocks |lock| for writing.
555 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_write(
556 struct CRYPTO_STATIC_MUTEX *lock);
557
558 #if defined(__cplusplus)
559 extern "C++" {
560
561 BSSL_NAMESPACE_BEGIN
562
563 namespace internal {
564
565 // MutexLockBase is a RAII helper for CRYPTO_MUTEX locking.
566 template <void (*LockFunc)(CRYPTO_MUTEX *), void (*ReleaseFunc)(CRYPTO_MUTEX *)>
567 class MutexLockBase {
568 public:
569 explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
570 assert(mu_ != nullptr);
571 LockFunc(mu_);
572 }
573 ~MutexLockBase() { ReleaseFunc(mu_); }
574 MutexLockBase(const MutexLockBase<LockFunc, ReleaseFunc> &) = delete;
575 MutexLockBase &operator=(const MutexLockBase<LockFunc, ReleaseFunc> &) =
576 delete;
577
578 private:
579 CRYPTO_MUTEX *const mu_;
580 };
581
582 } // namespace internal
583
584 using MutexWriteLock =
585 internal::MutexLockBase<CRYPTO_MUTEX_lock_write, CRYPTO_MUTEX_unlock_write>;
586 using MutexReadLock =
587 internal::MutexLockBase<CRYPTO_MUTEX_lock_read, CRYPTO_MUTEX_unlock_read>;
588
589 BSSL_NAMESPACE_END
590
591 } // extern "C++"
592 #endif // defined(__cplusplus)
593
594
595 // Thread local storage.
596
597 // thread_local_data_t enumerates the types of thread-local data that can be
598 // stored.
599 typedef enum {
600 OPENSSL_THREAD_LOCAL_ERR = 0,
601 OPENSSL_THREAD_LOCAL_RAND,
602 OPENSSL_THREAD_LOCAL_TEST,
603 NUM_OPENSSL_THREAD_LOCALS,
604 } thread_local_data_t;
605
606 // thread_local_destructor_t is the type of a destructor function that will be
607 // called when a thread exits and its thread-local storage needs to be freed.
608 typedef void (*thread_local_destructor_t)(void *);
609
610 // CRYPTO_get_thread_local gets the pointer value that is stored for the
611 // current thread for the given index, or NULL if none has been set.
612 OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);
613
614 // CRYPTO_set_thread_local sets a pointer value for the current thread at the
615 // given index. This function should only be called once per thread for a given
616 // |index|: rather than update the pointer value itself, update the data that
617 // is pointed to.
618 //
619 // The destructor function will be called when a thread exits to free this
620 // thread-local data. All calls to |CRYPTO_set_thread_local| with the same
621 // |index| should have the same |destructor| argument. The destructor may be
622 // called with a NULL argument if a thread that never set a thread-local
623 // pointer for |index|, exits. The destructor may be called concurrently with
624 // different arguments.
625 //
626 // This function returns one on success or zero on error. If it returns zero
627 // then |destructor| has been called with |value| already.
628 OPENSSL_EXPORT int CRYPTO_set_thread_local(
629 thread_local_data_t index, void *value,
630 thread_local_destructor_t destructor);
631
632
633 // ex_data
634
635 typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;
636
637 DECLARE_STACK_OF(CRYPTO_EX_DATA_FUNCS)
638
639 // CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
640 // supports ex_data. It should defined as a static global within the module
641 // which defines that type.
642 typedef struct {
643 struct CRYPTO_STATIC_MUTEX lock;
644 STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
645 // num_reserved is one if the ex_data index zero is reserved for legacy
646 // |TYPE_get_app_data| functions.
647 uint8_t num_reserved;
648 } CRYPTO_EX_DATA_CLASS;
649
650 #define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_STATIC_MUTEX_INIT, NULL, 0}
651 #define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
652 {CRYPTO_STATIC_MUTEX_INIT, NULL, 1}
653
654 // CRYPTO_get_ex_new_index allocates a new index for |ex_data_class| and writes
655 // it to |*out_index|. Each class of object should provide a wrapper function
656 // that uses the correct |CRYPTO_EX_DATA_CLASS|. It returns one on success and
657 // zero otherwise.
658 OPENSSL_EXPORT int CRYPTO_get_ex_new_index(CRYPTO_EX_DATA_CLASS *ex_data_class,
659 int *out_index, long argl,
660 void *argp,
661 CRYPTO_EX_free *free_func);
662
663 // CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
664 // of object should provide a wrapper function.
665 OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);
666
667 // CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
668 // if no such index exists. Each class of object should provide a wrapper
669 // function.
670 OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);
671
672 // CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|.
673 OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);
674
675 // CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an
676 // object of the given class.
677 OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
678 void *obj, CRYPTO_EX_DATA *ad);
679
680
681 // Endianness conversions.
682
683 #if defined(__GNUC__) && __GNUC__ >= 2
684 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
685 return __builtin_bswap32(x);
686 }
687
688 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
689 return __builtin_bswap64(x);
690 }
691 #elif defined(_MSC_VER)
692 OPENSSL_MSVC_PRAGMA(warning(push, 3))
693 #include <stdlib.h>
694 OPENSSL_MSVC_PRAGMA(warning(pop))
695 #pragma intrinsic(_byteswap_uint64, _byteswap_ulong)
696 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
697 return _byteswap_ulong(x);
698 }
699
700 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
701 return _byteswap_uint64(x);
702 }
703 #else
704 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
705 x = (x >> 16) | (x << 16);
706 x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
707 return x;
708 }
709
710 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
711 return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32);
712 }
713 #endif
714
715
716 // Language bug workarounds.
717 //
718 // Most C standard library functions are undefined if passed NULL, even when the
719 // corresponding length is zero. This gives them (and, in turn, all functions
720 // which call them) surprising behavior on empty arrays. Some compilers will
721 // miscompile code due to this rule. See also
722 // https://www.imperialviolet.org/2016/06/26/nonnull.html
723 //
724 // These wrapper functions behave the same as the corresponding C standard
725 // functions, but behave as expected when passed NULL if the length is zero.
726 //
727 // Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|.
728
729 // C++ defines |memchr| as a const-correct overload.
730 #if defined(__cplusplus)
731 extern "C++" {
732
733 static inline const void *OPENSSL_memchr(const void *s, int c, size_t n) {
734 if (n == 0) {
735 return NULL;
736 }
737
738 return memchr(s, c, n);
739 }
740
741 static inline void *OPENSSL_memchr(void *s, int c, size_t n) {
742 if (n == 0) {
743 return NULL;
744 }
745
746 return memchr(s, c, n);
747 }
748
749 } // extern "C++"
750 #else // __cplusplus
751
752 static inline void *OPENSSL_memchr(const void *s, int c, size_t n) {
753 if (n == 0) {
754 return NULL;
755 }
756
757 return memchr(s, c, n);
758 }
759
760 #endif // __cplusplus
761
762 static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) {
763 if (n == 0) {
764 return 0;
765 }
766
767 return memcmp(s1, s2, n);
768 }
769
770 static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) {
771 if (n == 0) {
772 return dst;
773 }
774
775 return memcpy(dst, src, n);
776 }
777
778 static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) {
779 if (n == 0) {
780 return dst;
781 }
782
783 return memmove(dst, src, n);
784 }
785
786 static inline void *OPENSSL_memset(void *dst, int c, size_t n) {
787 if (n == 0) {
788 return dst;
789 }
790
791 return memset(dst, c, n);
792 }
793
794 #if defined(BORINGSSL_FIPS)
795 // BORINGSSL_FIPS_abort is called when a FIPS power-on or continuous test
796 // fails. It prevents any further cryptographic operations by the current
797 // process.
798 void BORINGSSL_FIPS_abort(void) __attribute__((noreturn));
799 #endif
800
801 // boringssl_fips_self_test runs the FIPS KAT-based self tests. It returns one
802 // on success and zero on error. The argument is the integrity hash of the FIPS
803 // module and may be used to check and write flag files to suppress duplicate
804 // self-tests. If |module_hash_len| is zero then no flag file will be checked
805 // nor written and tests will always be run.
806 int boringssl_fips_self_test(const uint8_t *module_hash,
807 size_t module_hash_len);
808
809
810 #if defined(__cplusplus)
811 } // extern C
812 #endif
813
814 #endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H
815