PageRenderTime 25ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/src/secp256k1/src/util.h

https://github.com/cdecker/bitcoin
C Header | 273 lines | 197 code | 29 blank | 47 comment | 63 complexity | 9db17302be29886f32046c92d8a028f3 MD5 | raw file
  1. /**********************************************************************
  2. * Copyright (c) 2013, 2014 Pieter Wuille *
  3. * Distributed under the MIT software license, see the accompanying *
  4. * file COPYING or http://www.opensource.org/licenses/mit-license.php.*
  5. **********************************************************************/
  6. #ifndef SECP256K1_UTIL_H
  7. #define SECP256K1_UTIL_H
  8. #if defined HAVE_CONFIG_H
  9. #include "libsecp256k1-config.h"
  10. #endif
  11. #include <stdlib.h>
  12. #include <stdint.h>
  13. #include <stdio.h>
  14. #include <limits.h>
  15. typedef struct {
  16. void (*fn)(const char *text, void* data);
  17. const void* data;
  18. } secp256k1_callback;
  19. static SECP256K1_INLINE void secp256k1_callback_call(const secp256k1_callback * const cb, const char * const text) {
  20. cb->fn(text, (void*)cb->data);
  21. }
  22. #ifdef DETERMINISTIC
  23. #define TEST_FAILURE(msg) do { \
  24. fprintf(stderr, "%s\n", msg); \
  25. abort(); \
  26. } while(0);
  27. #else
  28. #define TEST_FAILURE(msg) do { \
  29. fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \
  30. abort(); \
  31. } while(0)
  32. #endif
  33. #if SECP256K1_GNUC_PREREQ(3, 0)
  34. #define EXPECT(x,c) __builtin_expect((x),(c))
  35. #else
  36. #define EXPECT(x,c) (x)
  37. #endif
  38. #ifdef DETERMINISTIC
  39. #define CHECK(cond) do { \
  40. if (EXPECT(!(cond), 0)) { \
  41. TEST_FAILURE("test condition failed"); \
  42. } \
  43. } while(0)
  44. #else
  45. #define CHECK(cond) do { \
  46. if (EXPECT(!(cond), 0)) { \
  47. TEST_FAILURE("test condition failed: " #cond); \
  48. } \
  49. } while(0)
  50. #endif
  51. /* Like assert(), but when VERIFY is defined, and side-effect safe. */
  52. #if defined(COVERAGE)
  53. #define VERIFY_CHECK(check)
  54. #define VERIFY_SETUP(stmt)
  55. #elif defined(VERIFY)
  56. #define VERIFY_CHECK CHECK
  57. #define VERIFY_SETUP(stmt) do { stmt; } while(0)
  58. #else
  59. #define VERIFY_CHECK(cond) do { (void)(cond); } while(0)
  60. #define VERIFY_SETUP(stmt)
  61. #endif
  62. /* Define `VG_UNDEF` and `VG_CHECK` when VALGRIND is defined */
  63. #if !defined(VG_CHECK)
  64. # if defined(VALGRIND)
  65. # include <valgrind/memcheck.h>
  66. # define VG_UNDEF(x,y) VALGRIND_MAKE_MEM_UNDEFINED((x),(y))
  67. # define VG_CHECK(x,y) VALGRIND_CHECK_MEM_IS_DEFINED((x),(y))
  68. # else
  69. # define VG_UNDEF(x,y)
  70. # define VG_CHECK(x,y)
  71. # endif
  72. #endif
  73. /* Like `VG_CHECK` but on VERIFY only */
  74. #if defined(VERIFY)
  75. #define VG_CHECK_VERIFY(x,y) VG_CHECK((x), (y))
  76. #else
  77. #define VG_CHECK_VERIFY(x,y)
  78. #endif
  79. static SECP256K1_INLINE void *checked_malloc(const secp256k1_callback* cb, size_t size) {
  80. void *ret = malloc(size);
  81. if (ret == NULL) {
  82. secp256k1_callback_call(cb, "Out of memory");
  83. }
  84. return ret;
  85. }
  86. static SECP256K1_INLINE void *checked_realloc(const secp256k1_callback* cb, void *ptr, size_t size) {
  87. void *ret = realloc(ptr, size);
  88. if (ret == NULL) {
  89. secp256k1_callback_call(cb, "Out of memory");
  90. }
  91. return ret;
  92. }
  93. #if defined(__BIGGEST_ALIGNMENT__)
  94. #define ALIGNMENT __BIGGEST_ALIGNMENT__
  95. #else
  96. /* Using 16 bytes alignment because common architectures never have alignment
  97. * requirements above 8 for any of the types we care about. In addition we
  98. * leave some room because currently we don't care about a few bytes. */
  99. #define ALIGNMENT 16
  100. #endif
  101. #define ROUND_TO_ALIGN(size) (((size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT)
  102. /* Assume there is a contiguous memory object with bounds [base, base + max_size)
  103. * of which the memory range [base, *prealloc_ptr) is already allocated for usage,
  104. * where *prealloc_ptr is an aligned pointer. In that setting, this functions
  105. * reserves the subobject [*prealloc_ptr, *prealloc_ptr + alloc_size) of
  106. * alloc_size bytes by increasing *prealloc_ptr accordingly, taking into account
  107. * alignment requirements.
  108. *
  109. * The function returns an aligned pointer to the newly allocated subobject.
  110. *
  111. * This is useful for manual memory management: if we're simply given a block
  112. * [base, base + max_size), the caller can use this function to allocate memory
  113. * in this block and keep track of the current allocation state with *prealloc_ptr.
  114. *
  115. * It is VERIFY_CHECKed that there is enough space left in the memory object and
  116. * *prealloc_ptr is aligned relative to base.
  117. */
  118. static SECP256K1_INLINE void *manual_alloc(void** prealloc_ptr, size_t alloc_size, void* base, size_t max_size) {
  119. size_t aligned_alloc_size = ROUND_TO_ALIGN(alloc_size);
  120. void* ret;
  121. VERIFY_CHECK(prealloc_ptr != NULL);
  122. VERIFY_CHECK(*prealloc_ptr != NULL);
  123. VERIFY_CHECK(base != NULL);
  124. VERIFY_CHECK((unsigned char*)*prealloc_ptr >= (unsigned char*)base);
  125. VERIFY_CHECK(((unsigned char*)*prealloc_ptr - (unsigned char*)base) % ALIGNMENT == 0);
  126. VERIFY_CHECK((unsigned char*)*prealloc_ptr - (unsigned char*)base + aligned_alloc_size <= max_size);
  127. ret = *prealloc_ptr;
  128. *((unsigned char**)prealloc_ptr) += aligned_alloc_size;
  129. return ret;
  130. }
  131. /* Macro for restrict, when available and not in a VERIFY build. */
  132. #if defined(SECP256K1_BUILD) && defined(VERIFY)
  133. # define SECP256K1_RESTRICT
  134. #else
  135. # if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) )
  136. # if SECP256K1_GNUC_PREREQ(3,0)
  137. # define SECP256K1_RESTRICT __restrict__
  138. # elif (defined(_MSC_VER) && _MSC_VER >= 1400)
  139. # define SECP256K1_RESTRICT __restrict
  140. # else
  141. # define SECP256K1_RESTRICT
  142. # endif
  143. # else
  144. # define SECP256K1_RESTRICT restrict
  145. # endif
  146. #endif
  147. #if defined(_WIN32)
  148. # define I64FORMAT "I64d"
  149. # define I64uFORMAT "I64u"
  150. #else
  151. # define I64FORMAT "lld"
  152. # define I64uFORMAT "llu"
  153. #endif
  154. #if defined(__GNUC__)
  155. # define SECP256K1_GNUC_EXT __extension__
  156. #else
  157. # define SECP256K1_GNUC_EXT
  158. #endif
  159. /* If SECP256K1_{LITTLE,BIG}_ENDIAN is not explicitly provided, infer from various other system macros. */
  160. #if !defined(SECP256K1_LITTLE_ENDIAN) && !defined(SECP256K1_BIG_ENDIAN)
  161. /* Inspired by https://github.com/rofl0r/endianness.h/blob/9853923246b065a3b52d2c43835f3819a62c7199/endianness.h#L52L73 */
  162. # if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || \
  163. defined(_X86_) || defined(__x86_64__) || defined(__i386__) || \
  164. defined(__i486__) || defined(__i586__) || defined(__i686__) || \
  165. defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) || \
  166. defined(__ARMEL__) || defined(__AARCH64EL__) || \
  167. (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__ == 1) || \
  168. (defined(_LITTLE_ENDIAN) && _LITTLE_ENDIAN == 1) || \
  169. defined(_M_IX86) || defined(_M_AMD64) || defined(_M_ARM) /* MSVC */
  170. # define SECP256K1_LITTLE_ENDIAN
  171. # endif
  172. # if (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || \
  173. defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) || \
  174. defined(__MICROBLAZEEB__) || defined(__ARMEB__) || defined(__AARCH64EB__) || \
  175. (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__ == 1) || \
  176. (defined(_BIG_ENDIAN) && _BIG_ENDIAN == 1)
  177. # define SECP256K1_BIG_ENDIAN
  178. # endif
  179. #endif
  180. #if defined(SECP256K1_LITTLE_ENDIAN) == defined(SECP256K1_BIG_ENDIAN)
  181. # error Please make sure that either SECP256K1_LITTLE_ENDIAN or SECP256K1_BIG_ENDIAN is set, see src/util.h.
  182. #endif
  183. /* Zero memory if flag == 1. Flag must be 0 or 1. Constant time. */
  184. static SECP256K1_INLINE void memczero(void *s, size_t len, int flag) {
  185. unsigned char *p = (unsigned char *)s;
  186. /* Access flag with a volatile-qualified lvalue.
  187. This prevents clang from figuring out (after inlining) that flag can
  188. take only be 0 or 1, which leads to variable time code. */
  189. volatile int vflag = flag;
  190. unsigned char mask = -(unsigned char) vflag;
  191. while (len) {
  192. *p &= ~mask;
  193. p++;
  194. len--;
  195. }
  196. }
  197. /** Semantics like memcmp. Variable-time.
  198. *
  199. * We use this to avoid possible compiler bugs with memcmp, e.g.
  200. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95189
  201. */
  202. static SECP256K1_INLINE int secp256k1_memcmp_var(const void *s1, const void *s2, size_t n) {
  203. const unsigned char *p1 = s1, *p2 = s2;
  204. size_t i;
  205. for (i = 0; i < n; i++) {
  206. int diff = p1[i] - p2[i];
  207. if (diff != 0) {
  208. return diff;
  209. }
  210. }
  211. return 0;
  212. }
  213. /** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. Both *r and *a must be initialized and non-negative.*/
  214. static SECP256K1_INLINE void secp256k1_int_cmov(int *r, const int *a, int flag) {
  215. unsigned int mask0, mask1, r_masked, a_masked;
  216. /* Access flag with a volatile-qualified lvalue.
  217. This prevents clang from figuring out (after inlining) that flag can
  218. take only be 0 or 1, which leads to variable time code. */
  219. volatile int vflag = flag;
  220. /* Casting a negative int to unsigned and back to int is implementation defined behavior */
  221. VERIFY_CHECK(*r >= 0 && *a >= 0);
  222. mask0 = (unsigned int)vflag + ~0u;
  223. mask1 = ~mask0;
  224. r_masked = ((unsigned int)*r & mask0);
  225. a_masked = ((unsigned int)*a & mask1);
  226. *r = (int)(r_masked | a_masked);
  227. }
  228. /* If USE_FORCE_WIDEMUL_{INT128,INT64} is set, use that wide multiplication implementation.
  229. * Otherwise use the presence of __SIZEOF_INT128__ to decide.
  230. */
  231. #if defined(USE_FORCE_WIDEMUL_INT128)
  232. # define SECP256K1_WIDEMUL_INT128 1
  233. #elif defined(USE_FORCE_WIDEMUL_INT64)
  234. # define SECP256K1_WIDEMUL_INT64 1
  235. #elif defined(__SIZEOF_INT128__)
  236. # define SECP256K1_WIDEMUL_INT128 1
  237. #else
  238. # define SECP256K1_WIDEMUL_INT64 1
  239. #endif
  240. #if defined(SECP256K1_WIDEMUL_INT128)
  241. SECP256K1_GNUC_EXT typedef unsigned __int128 uint128_t;
  242. SECP256K1_GNUC_EXT typedef __int128 int128_t;
  243. #endif
  244. #endif /* SECP256K1_UTIL_H */