You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

740 line
27 KiB

  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. #ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
  109. #define OPENSSL_HEADER_CRYPTO_INTERNAL_H
  110. #include <openssl/ex_data.h>
  111. #include <openssl/stack.h>
  112. #include <openssl/thread.h>
  113. #include <assert.h>
  114. #include <string.h>
  115. #if defined(__GNUC__) && \
  116. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  117. // |alignas| and |alignof| were added in C11. GCC added support in version 4.8.
  118. // Testing for __STDC_VERSION__/__cplusplus doesn't work because 4.7 already
  119. // reports support for C11.
  120. #define alignas(x) __attribute__ ((aligned (x)))
  121. #define alignof(x) __alignof__ (x)
  122. #elif !defined(__cplusplus)
  123. #if defined(_MSC_VER)
  124. #define alignas(x) __declspec(align(x))
  125. #define alignof __alignof
  126. #else
  127. #include <stdalign.h>
  128. #endif
  129. #endif
  130. #if !defined(OPENSSL_NO_THREADS) && \
  131. (!defined(OPENSSL_WINDOWS) || defined(__MINGW32__))
  132. #include <pthread.h>
  133. #define OPENSSL_PTHREADS
  134. #endif
  135. #if !defined(OPENSSL_NO_THREADS) && !defined(OPENSSL_PTHREADS) && \
  136. defined(OPENSSL_WINDOWS)
  137. #define OPENSSL_WINDOWS_THREADS
  138. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  139. #include <windows.h>
  140. OPENSSL_MSVC_PRAGMA(warning(pop))
  141. #endif
  142. #if defined(__cplusplus)
  143. extern "C" {
  144. #endif
  145. #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \
  146. defined(OPENSSL_AARCH64) || defined(OPENSSL_PPC64LE)
  147. // OPENSSL_cpuid_setup initializes the platform-specific feature cache.
  148. void OPENSSL_cpuid_setup(void);
  149. #endif
  150. #if (!defined(_MSC_VER) || defined(__clang__)) && defined(OPENSSL_64_BIT)
  151. #define BORINGSSL_HAS_UINT128
  152. typedef __int128_t int128_t;
  153. typedef __uint128_t uint128_t;
  154. // clang-cl supports __uint128_t but modulus and division don't work.
  155. // https://crbug.com/787617.
  156. #if !defined(_MSC_VER) || !defined(__clang__)
  157. #define BORINGSSL_CAN_DIVIDE_UINT128
  158. #endif
  159. #endif
  160. #define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
  161. // Have a generic fall-through for different versions of C/C++.
  162. #if defined(__cplusplus) && __cplusplus >= 201703L
  163. #define OPENSSL_FALLTHROUGH [[fallthrough]]
  164. #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__clang__)
  165. #define OPENSSL_FALLTHROUGH [[clang::fallthrough]]
  166. #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__GNUC__) && \
  167. __GNUC__ >= 7
  168. #define OPENSSL_FALLTHROUGH [[gnu::fallthrough]]
  169. #elif defined(__GNUC__) && __GNUC__ >= 7 // gcc 7
  170. #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
  171. #else // C++11 on gcc 6, and all other cases
  172. #define OPENSSL_FALLTHROUGH
  173. #endif
  174. // buffers_alias returns one if |a| and |b| alias and zero otherwise.
  175. static inline int buffers_alias(const uint8_t *a, size_t a_len,
  176. const uint8_t *b, size_t b_len) {
  177. // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
  178. // objects are undefined whereas pointer to integer conversions are merely
  179. // implementation-defined. We assume the implementation defined it in a sane
  180. // way.
  181. uintptr_t a_u = (uintptr_t)a;
  182. uintptr_t b_u = (uintptr_t)b;
  183. return a_u + a_len > b_u && b_u + b_len > a_u;
  184. }
  185. // Constant-time utility functions.
  186. //
  187. // The following methods return a bitmask of all ones (0xff...f) for true and 0
  188. // for false. This is useful for choosing a value based on the result of a
  189. // conditional in constant time. For example,
  190. //
  191. // if (a < b) {
  192. // c = a;
  193. // } else {
  194. // c = b;
  195. // }
  196. //
  197. // can be written as
  198. //
  199. // crypto_word_t lt = constant_time_lt_w(a, b);
  200. // c = constant_time_select_w(lt, a, b);
  201. // crypto_word_t is the type that most constant-time functions use. Ideally we
  202. // would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit
  203. // pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64
  204. // bits. Since we want to be able to do constant-time operations on a
  205. // |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native
  206. // word length.
  207. #if defined(OPENSSL_64_BIT)
  208. typedef uint64_t crypto_word_t;
  209. #elif defined(OPENSSL_32_BIT)
  210. typedef uint32_t crypto_word_t;
  211. #else
  212. #error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
  213. #endif
  214. #define CONSTTIME_TRUE_W ~((crypto_word_t)0)
  215. #define CONSTTIME_FALSE_W ((crypto_word_t)0)
  216. #define CONSTTIME_TRUE_8 ((uint8_t)0xff)
  217. #define CONSTTIME_TRUE_W ~((crypto_word_t)0)
  218. #define CONSTTIME_FALSE_W ((crypto_word_t)0)
  219. #define CONSTTIME_TRUE_8 ((uint8_t)0xff)
  220. #define CONSTTIME_FALSE_8 ((uint8_t)0)
  221. // constant_time_msb_w returns the given value with the MSB copied to all the
  222. // other bits.
  223. static inline crypto_word_t constant_time_msb_w(crypto_word_t a) {
  224. return 0u - (a >> (sizeof(a) * 8 - 1));
  225. }
  226. // constant_time_lt_w returns 0xff..f if a < b and 0 otherwise.
  227. static inline crypto_word_t constant_time_lt_w(crypto_word_t a,
  228. crypto_word_t b) {
  229. // Consider the two cases of the problem:
  230. // msb(a) == msb(b): a < b iff the MSB of a - b is set.
  231. // msb(a) != msb(b): a < b iff the MSB of b is set.
  232. //
  233. // If msb(a) == msb(b) then the following evaluates as:
  234. // msb(a^((a^b)|((a-b)^a))) ==
  235. // msb(a^((a-b) ^ a)) == (because msb(a^b) == 0)
  236. // msb(a^a^(a-b)) == (rearranging)
  237. // msb(a-b) (because ∀x. x^x == 0)
  238. //
  239. // Else, if msb(a) != msb(b) then the following evaluates as:
  240. // msb(a^((a^b)|((a-b)^a))) ==
  241. // msb(a^(𝟙 | ((a-b)^a))) == (because msb(a^b) == 1 and 𝟙
  242. // represents a value s.t. msb(𝟙) = 1)
  243. // msb(a^𝟙) == (because ORing with 1 results in 1)
  244. // msb(b)
  245. //
  246. //
  247. // Here is an SMT-LIB verification of this formula:
  248. //
  249. // (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
  250. // (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
  251. // )
  252. //
  253. // (declare-fun a () (_ BitVec 32))
  254. // (declare-fun b () (_ BitVec 32))
  255. //
  256. // (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
  257. // (check-sat)
  258. // (get-model)
  259. return constant_time_msb_w(a^((a^b)|((a-b)^a)));
  260. }
  261. // constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit
  262. // mask.
  263. static inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) {
  264. return (uint8_t)(constant_time_lt_w(a, b));
  265. }
  266. // constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise.
  267. static inline crypto_word_t constant_time_ge_w(crypto_word_t a,
  268. crypto_word_t b) {
  269. return ~constant_time_lt_w(a, b);
  270. }
  271. // constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit
  272. // mask.
  273. static inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) {
  274. return (uint8_t)(constant_time_ge_w(a, b));
  275. }
  276. // constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise.
  277. static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) {
  278. // Here is an SMT-LIB verification of this formula:
  279. //
  280. // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
  281. // (bvand (bvnot a) (bvsub a #x00000001))
  282. // )
  283. //
  284. // (declare-fun a () (_ BitVec 32))
  285. //
  286. // (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a #x00000000))))
  287. // (check-sat)
  288. // (get-model)
  289. return constant_time_msb_w(~a & (a - 1));
  290. }
  291. // constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an
  292. // 8-bit mask.
  293. static inline uint8_t constant_time_is_zero_8(crypto_word_t a) {
  294. return (uint8_t)(constant_time_is_zero_w(a));
  295. }
  296. // constant_time_eq_w returns 0xff..f if a == b and 0 otherwise.
  297. static inline crypto_word_t constant_time_eq_w(crypto_word_t a,
  298. crypto_word_t b) {
  299. return constant_time_is_zero_w(a ^ b);
  300. }
  301. // constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit
  302. // mask.
  303. static inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) {
  304. return (uint8_t)(constant_time_eq_w(a, b));
  305. }
  306. // constant_time_eq_int acts like |constant_time_eq_w| but works on int
  307. // values.
  308. static inline crypto_word_t constant_time_eq_int(int a, int b) {
  309. return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b));
  310. }
  311. // constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
  312. // mask.
  313. static inline uint8_t constant_time_eq_int_8(int a, int b) {
  314. return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b));
  315. }
  316. // constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all
  317. // 1s or all 0s (as returned by the methods above), the select methods return
  318. // either |a| (if |mask| is nonzero) or |b| (if |mask| is zero).
  319. static inline crypto_word_t constant_time_select_w(crypto_word_t mask,
  320. crypto_word_t a,
  321. crypto_word_t b) {
  322. return (mask & a) | (~mask & b);
  323. }
  324. // constant_time_select_8 acts like |constant_time_select| but operates on
  325. // 8-bit values.
  326. static inline uint8_t constant_time_select_8(uint8_t mask, uint8_t a,
  327. uint8_t b) {
  328. return (uint8_t)(constant_time_select_w(mask, a, b));
  329. }
  330. // constant_time_select_int acts like |constant_time_select| but operates on
  331. // ints.
  332. static inline int constant_time_select_int(crypto_word_t mask, int a, int b) {
  333. return (int)(constant_time_select_w(mask, (crypto_word_t)(a),
  334. (crypto_word_t)(b)));
  335. }
  336. // Thread-safe initialisation.
  337. #if defined(OPENSSL_NO_THREADS)
  338. typedef uint32_t CRYPTO_once_t;
  339. #define CRYPTO_ONCE_INIT 0
  340. #elif defined(OPENSSL_WINDOWS_THREADS)
  341. typedef INIT_ONCE CRYPTO_once_t;
  342. #define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
  343. #elif defined(OPENSSL_PTHREADS)
  344. typedef pthread_once_t CRYPTO_once_t;
  345. #define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
  346. #else
  347. #error "Unknown threading library"
  348. #endif
  349. // CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
  350. // concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
  351. // then they will block until |init| completes, but |init| will have only been
  352. // called once.
  353. //
  354. // The |once| argument must be a |CRYPTO_once_t| that has been initialised with
  355. // the value |CRYPTO_ONCE_INIT|.
  356. OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));
  357. // Reference counting.
  358. // CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates.
  359. #define CRYPTO_REFCOUNT_MAX 0xffffffff
  360. // CRYPTO_refcount_inc atomically increments the value at |*count| unless the
  361. // value would overflow. It's safe for multiple threads to concurrently call
  362. // this or |CRYPTO_refcount_dec_and_test_zero| on the same
  363. // |CRYPTO_refcount_t|.
  364. OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
  365. // CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
  366. // if it's zero, it crashes the address space.
  367. // if it's the maximum value, it returns zero.
  368. // otherwise, it atomically decrements it and returns one iff the resulting
  369. // value is zero.
  370. //
  371. // It's safe for multiple threads to concurrently call this or
  372. // |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|.
  373. OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
  374. // Locks.
  375. //
  376. // Two types of locks are defined: |CRYPTO_MUTEX|, which can be used in
  377. // structures as normal, and |struct CRYPTO_STATIC_MUTEX|, which can be used as
  378. // a global lock. A global lock must be initialised to the value
  379. // |CRYPTO_STATIC_MUTEX_INIT|.
  380. //
  381. // |CRYPTO_MUTEX| can appear in public structures and so is defined in
  382. // thread.h as a structure large enough to fit the real type. The global lock is
  383. // a different type so it may be initialized with platform initializer macros.
  384. #if defined(OPENSSL_NO_THREADS)
  385. struct CRYPTO_STATIC_MUTEX {
  386. char padding; // Empty structs have different sizes in C and C++.
  387. };
  388. #define CRYPTO_STATIC_MUTEX_INIT { 0 }
  389. #elif defined(OPENSSL_WINDOWS_THREADS)
  390. struct CRYPTO_STATIC_MUTEX {
  391. SRWLOCK lock;
  392. };
  393. #define CRYPTO_STATIC_MUTEX_INIT { SRWLOCK_INIT }
  394. #elif defined(OPENSSL_PTHREADS)
  395. struct CRYPTO_STATIC_MUTEX {
  396. pthread_rwlock_t lock;
  397. };
  398. #define CRYPTO_STATIC_MUTEX_INIT { PTHREAD_RWLOCK_INITIALIZER }
  399. #else
  400. #error "Unknown threading library"
  401. #endif
  402. // CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
  403. // |CRYPTO_STATIC_MUTEX|.
  404. OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);
  405. // CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
  406. // read lock, but none may have a write lock.
  407. OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);
  408. // CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
  409. // of lock on it.
  410. OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);
  411. // CRYPTO_MUTEX_unlock_read unlocks |lock| for reading.
  412. OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);
  413. // CRYPTO_MUTEX_unlock_write unlocks |lock| for writing.
  414. OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);
  415. // CRYPTO_MUTEX_cleanup releases all resources held by |lock|.
  416. OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);
  417. // CRYPTO_STATIC_MUTEX_lock_read locks |lock| such that other threads may also
  418. // have a read lock, but none may have a write lock. The |lock| variable does
  419. // not need to be initialised by any function, but must have been statically
  420. // initialised with |CRYPTO_STATIC_MUTEX_INIT|.
  421. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_read(
  422. struct CRYPTO_STATIC_MUTEX *lock);
  423. // CRYPTO_STATIC_MUTEX_lock_write locks |lock| such that no other thread has
  424. // any type of lock on it. The |lock| variable does not need to be initialised
  425. // by any function, but must have been statically initialised with
  426. // |CRYPTO_STATIC_MUTEX_INIT|.
  427. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_write(
  428. struct CRYPTO_STATIC_MUTEX *lock);
  429. // CRYPTO_STATIC_MUTEX_unlock_read unlocks |lock| for reading.
  430. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_read(
  431. struct CRYPTO_STATIC_MUTEX *lock);
  432. // CRYPTO_STATIC_MUTEX_unlock_write unlocks |lock| for writing.
  433. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_write(
  434. struct CRYPTO_STATIC_MUTEX *lock);
  435. #if defined(__cplusplus)
  436. extern "C++" {
  437. namespace bssl {
  438. namespace internal {
  439. // MutexLockBase is a RAII helper for CRYPTO_MUTEX locking.
  440. template <void (*LockFunc)(CRYPTO_MUTEX *), void (*ReleaseFunc)(CRYPTO_MUTEX *)>
  441. class MutexLockBase {
  442. public:
  443. explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
  444. assert(mu_ != nullptr);
  445. LockFunc(mu_);
  446. }
  447. ~MutexLockBase() { ReleaseFunc(mu_); }
  448. MutexLockBase(const MutexLockBase<LockFunc, ReleaseFunc> &) = delete;
  449. MutexLockBase &operator=(const MutexLockBase<LockFunc, ReleaseFunc> &) =
  450. delete;
  451. private:
  452. CRYPTO_MUTEX *const mu_;
  453. };
  454. } // namespace internal
  455. using MutexWriteLock =
  456. internal::MutexLockBase<CRYPTO_MUTEX_lock_write, CRYPTO_MUTEX_unlock_write>;
  457. using MutexReadLock =
  458. internal::MutexLockBase<CRYPTO_MUTEX_lock_read, CRYPTO_MUTEX_unlock_read>;
  459. } // namespace bssl
  460. } // extern "C++"
  461. #endif // defined(__cplusplus)
  462. // Thread local storage.
  463. // thread_local_data_t enumerates the types of thread-local data that can be
  464. // stored.
  465. typedef enum {
  466. OPENSSL_THREAD_LOCAL_ERR = 0,
  467. OPENSSL_THREAD_LOCAL_RAND,
  468. OPENSSL_THREAD_LOCAL_TEST,
  469. NUM_OPENSSL_THREAD_LOCALS,
  470. } thread_local_data_t;
  471. // thread_local_destructor_t is the type of a destructor function that will be
  472. // called when a thread exits and its thread-local storage needs to be freed.
  473. typedef void (*thread_local_destructor_t)(void *);
  474. // CRYPTO_get_thread_local gets the pointer value that is stored for the
  475. // current thread for the given index, or NULL if none has been set.
  476. OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);
  477. // CRYPTO_set_thread_local sets a pointer value for the current thread at the
  478. // given index. This function should only be called once per thread for a given
  479. // |index|: rather than update the pointer value itself, update the data that
  480. // is pointed to.
  481. //
  482. // The destructor function will be called when a thread exits to free this
  483. // thread-local data. All calls to |CRYPTO_set_thread_local| with the same
  484. // |index| should have the same |destructor| argument. The destructor may be
  485. // called with a NULL argument if a thread that never set a thread-local
  486. // pointer for |index|, exits. The destructor may be called concurrently with
  487. // different arguments.
  488. //
  489. // This function returns one on success or zero on error. If it returns zero
  490. // then |destructor| has been called with |value| already.
  491. OPENSSL_EXPORT int CRYPTO_set_thread_local(
  492. thread_local_data_t index, void *value,
  493. thread_local_destructor_t destructor);
  494. // ex_data
  495. typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;
  496. DECLARE_STACK_OF(CRYPTO_EX_DATA_FUNCS)
  497. // CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
  498. // supports ex_data. It should defined as a static global within the module
  499. // which defines that type.
  500. typedef struct {
  501. struct CRYPTO_STATIC_MUTEX lock;
  502. STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
  503. // num_reserved is one if the ex_data index zero is reserved for legacy
  504. // |TYPE_get_app_data| functions.
  505. uint8_t num_reserved;
  506. } CRYPTO_EX_DATA_CLASS;
  507. #define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_STATIC_MUTEX_INIT, NULL, 0}
  508. #define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
  509. {CRYPTO_STATIC_MUTEX_INIT, NULL, 1}
  510. // CRYPTO_get_ex_new_index allocates a new index for |ex_data_class| and writes
  511. // it to |*out_index|. Each class of object should provide a wrapper function
  512. // that uses the correct |CRYPTO_EX_DATA_CLASS|. It returns one on success and
  513. // zero otherwise.
  514. OPENSSL_EXPORT int CRYPTO_get_ex_new_index(CRYPTO_EX_DATA_CLASS *ex_data_class,
  515. int *out_index, long argl,
  516. void *argp,
  517. CRYPTO_EX_free *free_func);
  518. // CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
  519. // of object should provide a wrapper function.
  520. OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);
  521. // CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
  522. // if no such index exists. Each class of object should provide a wrapper
  523. // function.
  524. OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);
  525. // CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|.
  526. OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);
  527. // CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an
  528. // object of the given class.
  529. OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
  530. void *obj, CRYPTO_EX_DATA *ad);
  531. // Endianness conversions.
  532. #if defined(__GNUC__) && __GNUC__ >= 2
  533. static inline uint32_t CRYPTO_bswap4(uint32_t x) {
  534. return __builtin_bswap32(x);
  535. }
  536. static inline uint64_t CRYPTO_bswap8(uint64_t x) {
  537. return __builtin_bswap64(x);
  538. }
  539. #elif defined(_MSC_VER)
  540. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  541. #include <intrin.h>
  542. OPENSSL_MSVC_PRAGMA(warning(pop))
  543. #pragma intrinsic(_byteswap_uint64, _byteswap_ulong)
  544. static inline uint32_t CRYPTO_bswap4(uint32_t x) {
  545. return _byteswap_ulong(x);
  546. }
  547. static inline uint64_t CRYPTO_bswap8(uint64_t x) {
  548. return _byteswap_uint64(x);
  549. }
  550. #else
  551. static inline uint32_t CRYPTO_bswap4(uint32_t x) {
  552. x = (x >> 16) | (x << 16);
  553. x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
  554. return x;
  555. }
  556. static inline uint64_t CRYPTO_bswap8(uint64_t x) {
  557. return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32);
  558. }
  559. #endif
  560. // Language bug workarounds.
  561. //
  562. // Most C standard library functions are undefined if passed NULL, even when the
  563. // corresponding length is zero. This gives them (and, in turn, all functions
  564. // which call them) surprising behavior on empty arrays. Some compilers will
  565. // miscompile code due to this rule. See also
  566. // https://www.imperialviolet.org/2016/06/26/nonnull.html
  567. //
  568. // These wrapper functions behave the same as the corresponding C standard
  569. // functions, but behave as expected when passed NULL if the length is zero.
  570. //
  571. // Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|.
  572. // C++ defines |memchr| as a const-correct overload.
  573. #if defined(__cplusplus)
  574. extern "C++" {
  575. static inline const void *OPENSSL_memchr(const void *s, int c, size_t n) {
  576. if (n == 0) {
  577. return NULL;
  578. }
  579. return memchr(s, c, n);
  580. }
  581. static inline void *OPENSSL_memchr(void *s, int c, size_t n) {
  582. if (n == 0) {
  583. return NULL;
  584. }
  585. return memchr(s, c, n);
  586. }
  587. } // extern "C++"
  588. #else // __cplusplus
  589. static inline void *OPENSSL_memchr(const void *s, int c, size_t n) {
  590. if (n == 0) {
  591. return NULL;
  592. }
  593. return memchr(s, c, n);
  594. }
  595. #endif // __cplusplus
  596. static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) {
  597. if (n == 0) {
  598. return 0;
  599. }
  600. return memcmp(s1, s2, n);
  601. }
  602. static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) {
  603. if (n == 0) {
  604. return dst;
  605. }
  606. return memcpy(dst, src, n);
  607. }
  608. static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) {
  609. if (n == 0) {
  610. return dst;
  611. }
  612. return memmove(dst, src, n);
  613. }
  614. static inline void *OPENSSL_memset(void *dst, int c, size_t n) {
  615. if (n == 0) {
  616. return dst;
  617. }
  618. return memset(dst, c, n);
  619. }
  620. #if defined(BORINGSSL_FIPS)
  621. // BORINGSSL_FIPS_abort is called when a FIPS power-on or continuous test
  622. // fails. It prevents any further cryptographic operations by the current
  623. // process.
  624. void BORINGSSL_FIPS_abort(void) __attribute__((noreturn));
  625. #endif
  626. #if defined(__cplusplus)
  627. } // extern C
  628. #endif
  629. #endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H