Bitcoin Core 31.99.0
P2P Digital Currency
util.h
Go to the documentation of this file.
1/***********************************************************************
2 * Copyright (c) 2013, 2014 Pieter Wuille *
3 * Distributed under the MIT software license, see the accompanying *
4 * file COPYING or https://www.opensource.org/licenses/mit-license.php.*
5 ***********************************************************************/
6
7#ifndef SECP256K1_UTIL_H
8#define SECP256K1_UTIL_H
9
10#include "checkmem.h"
11
12#include <string.h>
13#include <stdlib.h>
14#include <stdint.h>
15#include <stdio.h>
16#include <limits.h>
17#if defined(_MSC_VER)
18/* For SecureZeroMemory */
19#include <Windows.h>
20#endif
21
22#define STR_(x) #x
23#define STR(x) STR_(x)
24#define DEBUG_CONFIG_MSG(x) "DEBUG_CONFIG: " x
25#define DEBUG_CONFIG_DEF(x) DEBUG_CONFIG_MSG(#x "=" STR(x))
26
27/* Debug helper for printing arrays of unsigned char. */
28#define PRINT_BUF(buf, len) do { \
29 printf("%s[%lu] = ", #buf, (unsigned long)len); \
30 print_buf_plain(buf, len); \
31} while(0)
32
33static void print_buf_plain(const unsigned char *buf, size_t len) {
34 size_t i;
35 printf("{");
36 for (i = 0; i < len; i++) {
37 if (i % 8 == 0) {
38 printf("\n ");
39 } else {
40 printf(" ");
41 }
42 printf("0x%02X,", buf[i]);
43 }
44 printf("\n}\n");
45}
46
47# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) )
48# if defined(__GNUC__)
49# define SECP256K1_INLINE __inline__
50# elif (defined(_MSC_VER))
51# define SECP256K1_INLINE __inline
52# else
53# define SECP256K1_INLINE
54# endif
55# else
56# define SECP256K1_INLINE inline
57# endif
58
59# if !defined(_DEBUG) && !defined(__NO_INLINE__) && !defined(__OPTIMIZE_SIZE__)
60# if defined(__OPTIMIZE__) && defined(__GNUC__)
61# define SECP256K1_FORCE_INLINE SECP256K1_INLINE __attribute__((always_inline))
62# elif defined(_MSC_VER)
63# define SECP256K1_FORCE_INLINE __forceinline
64# endif
65# endif
66# ifndef SECP256K1_FORCE_INLINE
67# define SECP256K1_FORCE_INLINE SECP256K1_INLINE
68# endif
69
74#define STATIC_ASSERT(expr) do { \
75 switch(0) { \
76 case 0: \
77 /* If expr evaluates to 0, we have two case labels "0", which is illegal. */ \
78 case /* ERROR: static assertion failed */ (expr): \
79 ; \
80 } \
81} while(0)
82
87#define ASSERT_INT_CONST_AND_DO(expr, stmt) do { \
88 switch(42) { \
89 /* C allows only integer constant expressions as case labels. */ \
90 case /* ERROR: integer argument is not constant */ (expr): \
91 break; \
92 default: ; \
93 } \
94 stmt; \
95} while(0)
96
97typedef struct {
98 void (*fn)(const char *text, void* data);
99 const void* data;
101
102static SECP256K1_INLINE void secp256k1_callback_call(const secp256k1_callback * const cb, const char * const text) {
103 cb->fn(text, (void*)cb->data);
104}
105
106#ifndef USE_EXTERNAL_DEFAULT_CALLBACKS
107static void secp256k1_default_illegal_callback_fn(const char* str, void* data) {
108 (void)data;
109 fprintf(stderr, "[libsecp256k1] illegal argument: %s\n", str);
110 abort();
111}
112static void secp256k1_default_error_callback_fn(const char* str, void* data) {
113 (void)data;
114 fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str);
115 abort();
116}
117#else
118void secp256k1_default_illegal_callback_fn(const char* str, void* data);
119void secp256k1_default_error_callback_fn(const char* str, void* data);
120#endif
121
124 NULL
125};
126
129 NULL
130};
131
132
133#ifdef DETERMINISTIC
134#define TEST_FAILURE(msg) do { \
135 fprintf(stderr, "%s\n", msg); \
136 abort(); \
137} while(0);
138#else
139#define TEST_FAILURE(msg) do { \
140 fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \
141 abort(); \
142} while(0)
143#endif
144
145#if defined(__GNUC__)
146#define EXPECT(x,c) __builtin_expect((x),(c))
147#else
148#define EXPECT(x,c) (x)
149#endif
150
151#ifdef DETERMINISTIC
152#define CHECK(cond) do { \
153 if (EXPECT(!(cond), 0)) { \
154 TEST_FAILURE("test condition failed"); \
155 } \
156} while(0)
157#else
158#define CHECK(cond) do { \
159 if (EXPECT(!(cond), 0)) { \
160 TEST_FAILURE("test condition failed: " #cond); \
161 } \
162} while(0)
163#endif
164
165/* Like assert(), but when VERIFY is defined. */
166#if defined(VERIFY)
167#define VERIFY_CHECK CHECK
168#else
169#define VERIFY_CHECK(cond)
170#endif
171
172static SECP256K1_INLINE void *checked_malloc(const secp256k1_callback* cb, size_t size) {
173 void *ret = malloc(size);
174 if (ret == NULL) {
175 secp256k1_callback_call(cb, "Out of memory");
176 }
177 return ret;
178}
179
180#if defined(__BIGGEST_ALIGNMENT__)
181#define ALIGNMENT __BIGGEST_ALIGNMENT__
182#else
183/* Using 16 bytes alignment because common architectures never have alignment
184 * requirements above 8 for any of the types we care about. In addition we
185 * leave some room because currently we don't care about a few bytes. */
186#define ALIGNMENT 16
187#endif
188
189/* ceil(x/y) for integers x > 0 and y > 0. Here, / denotes rational division. */
190#define CEIL_DIV(x, y) (1 + ((x) - 1) / (y))
191
192#define ROUND_TO_ALIGN(size) (CEIL_DIV(size, ALIGNMENT) * ALIGNMENT)
193
194#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
195
196/* Macro for restrict, when available and not in a VERIFY build. */
197#if defined(SECP256K1_BUILD) && defined(VERIFY)
198# define SECP256K1_RESTRICT
199#else
200# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) )
201# if defined(__GNUC__)
202# define SECP256K1_RESTRICT __restrict__
203# elif (defined(_MSC_VER) && _MSC_VER >= 1400)
204# define SECP256K1_RESTRICT __restrict
205# else
206# define SECP256K1_RESTRICT
207# endif
208# else
209# define SECP256K1_RESTRICT restrict
210# endif
211#endif
212
213#if defined(__GNUC__)
214# define SECP256K1_GNUC_EXT __extension__
215#else
216# define SECP256K1_GNUC_EXT
217#endif
218
219/* Zero memory if flag == 1. Flag must be 0 or 1. Constant time. */
220static SECP256K1_INLINE void secp256k1_memczero(void *s, size_t len, int flag) {
221 unsigned char *p = (unsigned char *)s;
222 /* Access flag with a volatile-qualified lvalue.
223 This prevents clang from figuring out (after inlining) that flag can
224 take only be 0 or 1, which leads to variable time code. */
225 volatile int vflag = flag;
226 unsigned char mask = -(unsigned char) vflag;
227 VERIFY_CHECK(flag == 0 || flag == 1);
228 while (len) {
229 *p &= ~mask;
230 p++;
231 len--;
232 }
233}
234
235/* Zeroes memory to prevent leaking sensitive info. Won't be optimized out. */
236static SECP256K1_INLINE void secp256k1_memzero_explicit(void *ptr, size_t len) {
237#if defined(_MSC_VER)
238 /* SecureZeroMemory is guaranteed not to be optimized out by MSVC. */
239 SecureZeroMemory(ptr, len);
240#elif defined(__GNUC__)
241 /* We use a memory barrier that scares the compiler away from optimizing out the memset.
242 *
243 * Quoting Adam Langley <agl@google.com> in commit ad1907fe73334d6c696c8539646c21b11178f20f
244 * in BoringSSL (ISC License):
245 * As best as we can tell, this is sufficient to break any optimisations that
246 * might try to eliminate "superfluous" memsets.
247 * This method is used in memzero_explicit() the Linux kernel, too. Its advantage is that it
248 * is pretty efficient, because the compiler can still implement the memset() efficiently,
249 * just not remove it entirely. See "Dead Store Elimination (Still) Considered Harmful" by
250 * Yang et al. (USENIX Security 2017) for more background.
251 */
252 memset(ptr, 0, len);
253 __asm__ __volatile__("" : : "r"(ptr) : "memory");
254#else
255 void *(*volatile const volatile_memset)(void *, int, size_t) = memset;
256 volatile_memset(ptr, 0, len);
257#endif
258}
259
260/* Cleanses memory to prevent leaking sensitive info. Won't be optimized out.
261 * The state of the memory after this call is unspecified so callers must not
262 * make any assumptions about its contents.
263 *
264 * In VERIFY builds, it has the side effect of marking the memory as undefined.
265 * This helps to detect use-after-clear bugs where code incorrectly reads from
266 * cleansed memory during testing.
267 */
268static SECP256K1_INLINE void secp256k1_memclear_explicit(void *ptr, size_t len) {
269 /* The current implementation zeroes, but callers must not rely on this */
271#ifdef VERIFY
273#endif
274}
275
281static SECP256K1_INLINE int secp256k1_memcmp_var(const void *s1, const void *s2, size_t n) {
282 const unsigned char *p1 = s1, *p2 = s2;
283 size_t i;
284
285 for (i = 0; i < n; i++) {
286 int diff = p1[i] - p2[i];
287 if (diff != 0) {
288 return diff;
289 }
290 }
291 return 0;
292}
293
294/* Return 1 if all elements of array s are 0 and otherwise return 0.
295 * Constant-time. */
296static SECP256K1_INLINE int secp256k1_is_zero_array(const unsigned char *s, size_t len) {
297 unsigned char acc = 0;
298 int ret;
299 size_t i;
300
301 for (i = 0; i < len; i++) {
302 acc |= s[i];
303 }
304 ret = (acc == 0);
305 /* acc may contain secret values. Try to explicitly clear it. */
306 secp256k1_memclear_explicit(&acc, sizeof(acc));
307 return ret;
308}
309
312static SECP256K1_INLINE void secp256k1_int_cmov(int *r, const int *a, int flag) {
313 unsigned int mask0, mask1, r_masked, a_masked;
314 /* Access flag with a volatile-qualified lvalue.
315 This prevents clang from figuring out (after inlining) that flag can
316 take only be 0 or 1, which leads to variable time code. */
317 volatile int vflag = flag;
318
319 VERIFY_CHECK(flag == 0 || flag == 1);
320 /* Casting a negative int to unsigned and back to int is implementation defined behavior */
321 VERIFY_CHECK(*r >= 0 && *a >= 0);
322
323 mask0 = (unsigned int)vflag + ~0u;
324 mask1 = ~mask0;
325 r_masked = ((unsigned int)*r & mask0);
326 a_masked = ((unsigned int)*a & mask1);
327
328 *r = (int)(r_masked | a_masked);
329}
330
331#if defined(USE_FORCE_WIDEMUL_INT128_STRUCT)
332/* If USE_FORCE_WIDEMUL_INT128_STRUCT is set, use int128_struct. */
333# define SECP256K1_WIDEMUL_INT128 1
334# define SECP256K1_INT128_STRUCT 1
335#elif defined(USE_FORCE_WIDEMUL_INT128)
336/* If USE_FORCE_WIDEMUL_INT128 is set, use int128. */
337# define SECP256K1_WIDEMUL_INT128 1
338# define SECP256K1_INT128_NATIVE 1
339#elif defined(USE_FORCE_WIDEMUL_INT64)
340/* If USE_FORCE_WIDEMUL_INT64 is set, use int64. */
341# define SECP256K1_WIDEMUL_INT64 1
342#elif defined(UINT128_MAX) || defined(__SIZEOF_INT128__)
343/* If a native 128-bit integer type exists, use int128. */
344# define SECP256K1_WIDEMUL_INT128 1
345# define SECP256K1_INT128_NATIVE 1
346#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
347/* On 64-bit MSVC targets (x86_64 and arm64), use int128_struct
348 * (which has special logic to implement using intrinsics on those systems). */
349# define SECP256K1_WIDEMUL_INT128 1
350# define SECP256K1_INT128_STRUCT 1
351#elif SIZE_MAX > 0xffffffff
352/* Systems with 64-bit pointers (and thus registers) very likely benefit from
353 * using 64-bit based arithmetic (even if we need to fall back to 32x32->64 based
354 * multiplication logic). */
355# define SECP256K1_WIDEMUL_INT128 1
356# define SECP256K1_INT128_STRUCT 1
357#else
358/* Lastly, fall back to int64 based arithmetic. */
359# define SECP256K1_WIDEMUL_INT64 1
360#endif
361
362#ifndef __has_builtin
363#define __has_builtin(x) 0
364#endif
365
366/* Determine the number of trailing zero bits in a (non-zero) 32-bit x.
367 * This function is only intended to be used as fallback for
368 * secp256k1_ctz32_var, but permits it to be tested separately. */
370 static const uint8_t debruijn[32] = {
371 0x00, 0x01, 0x02, 0x18, 0x03, 0x13, 0x06, 0x19, 0x16, 0x04, 0x14, 0x0A,
372 0x10, 0x07, 0x0C, 0x1A, 0x1F, 0x17, 0x12, 0x05, 0x15, 0x09, 0x0F, 0x0B,
373 0x1E, 0x11, 0x08, 0x0E, 0x1D, 0x0D, 0x1C, 0x1B
374 };
375 return debruijn[(uint32_t)((x & -x) * 0x04D7651FU) >> 27];
376}
377
378/* Determine the number of trailing zero bits in a (non-zero) 64-bit x.
379 * This function is only intended to be used as fallback for
380 * secp256k1_ctz64_var, but permits it to be tested separately. */
382 static const uint8_t debruijn[64] = {
383 0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
384 62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
385 63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
386 51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
387 };
388 return debruijn[(uint64_t)((x & -x) * 0x022FDD63CC95386DU) >> 58];
389}
390
391/* Determine the number of trailing zero bits in a (non-zero) 32-bit x. */
392static SECP256K1_INLINE int secp256k1_ctz32_var(uint32_t x) {
393 VERIFY_CHECK(x != 0);
394#if (__has_builtin(__builtin_ctz) || defined(__GNUC__))
395 /* If the unsigned type is sufficient to represent the largest uint32_t, consider __builtin_ctz. */
396 if (((unsigned)UINT32_MAX) == UINT32_MAX) {
397 return __builtin_ctz(x);
398 }
399#endif
400#if (__has_builtin(__builtin_ctzl) || defined(__GNUC__))
401 /* Otherwise consider __builtin_ctzl (the unsigned long type is always at least 32 bits). */
402 return __builtin_ctzl(x);
403#else
404 /* If no suitable CTZ builtin is available, use a (variable time) software emulation. */
406#endif
407}
408
409/* Determine the number of trailing zero bits in a (non-zero) 64-bit x. */
410static SECP256K1_INLINE int secp256k1_ctz64_var(uint64_t x) {
411 VERIFY_CHECK(x != 0);
412#if (__has_builtin(__builtin_ctzl) || defined(__GNUC__))
413 /* If the unsigned long type is sufficient to represent the largest uint64_t, consider __builtin_ctzl. */
414 if (((unsigned long)UINT64_MAX) == UINT64_MAX) {
415 return __builtin_ctzl(x);
416 }
417#endif
418#if (__has_builtin(__builtin_ctzll) || defined(__GNUC__))
419 /* Otherwise consider __builtin_ctzll (the unsigned long long type is always at least 64 bits). */
420 return __builtin_ctzll(x);
421#else
422 /* If no suitable CTZ builtin is available, use a (variable time) software emulation. */
424#endif
425}
426
427/* Read a uint32_t in big endian */
428SECP256K1_INLINE static uint32_t secp256k1_read_be32(const unsigned char* p) {
429 return (uint32_t)p[0] << 24 |
430 (uint32_t)p[1] << 16 |
431 (uint32_t)p[2] << 8 |
432 (uint32_t)p[3];
433}
434
435/* Write a uint32_t in big endian */
436SECP256K1_INLINE static void secp256k1_write_be32(unsigned char* p, uint32_t x) {
437 p[3] = x;
438 p[2] = x >> 8;
439 p[1] = x >> 16;
440 p[0] = x >> 24;
441}
442
443/* Read a uint64_t in big endian */
444SECP256K1_INLINE static uint64_t secp256k1_read_be64(const unsigned char* p) {
445 return (uint64_t)p[0] << 56 |
446 (uint64_t)p[1] << 48 |
447 (uint64_t)p[2] << 40 |
448 (uint64_t)p[3] << 32 |
449 (uint64_t)p[4] << 24 |
450 (uint64_t)p[5] << 16 |
451 (uint64_t)p[6] << 8 |
452 (uint64_t)p[7];
453}
454
455/* Write a uint64_t in big endian */
456SECP256K1_INLINE static void secp256k1_write_be64(unsigned char* p, uint64_t x) {
457 p[7] = x;
458 p[6] = x >> 8;
459 p[5] = x >> 16;
460 p[4] = x >> 24;
461 p[3] = x >> 32;
462 p[2] = x >> 40;
463 p[1] = x >> 48;
464 p[0] = x >> 56;
465}
466
467/* Rotate a uint32_t to the right. */
468SECP256K1_INLINE static uint32_t secp256k1_rotr32(const uint32_t x, const unsigned int by) {
469#if defined(_MSC_VER)
470 return _rotr(x, by); /* needs <stdlib.h> */
471#else
472 /* Reduce rotation amount to avoid UB when shifting. */
473 const unsigned int mask = CHAR_BIT * sizeof(x) - 1;
474 /* Turned into a rot instruction by GCC and clang. */
475 return (x >> (by & mask)) | (x << ((-by) & mask));
476#endif
477}
478
479#endif /* SECP256K1_UTIL_H */
int ret
#define SECP256K1_CHECKMEM_UNDEFINE(p, len)
Definition: checkmem.h:105
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
void printf(FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to std::cout, according to the given format string.
Definition: tinyformat.h:1096
static SECP256K1_INLINE int secp256k1_ctz64_var(uint64_t x)
Definition: util.h:410
static SECP256K1_INLINE void secp256k1_memclear_explicit(void *ptr, size_t len)
Definition: util.h:268
static SECP256K1_INLINE int secp256k1_memcmp_var(const void *s1, const void *s2, size_t n)
Semantics like memcmp.
Definition: util.h:281
static SECP256K1_INLINE void secp256k1_int_cmov(int *r, const int *a, int flag)
If flag is 1, set *r equal to *a; if flag is 0, leave it.
Definition: util.h:312
static SECP256K1_INLINE void secp256k1_memzero_explicit(void *ptr, size_t len)
Definition: util.h:236
static void secp256k1_default_error_callback_fn(const char *str, void *data)
Definition: util.h:112
static SECP256K1_INLINE int secp256k1_is_zero_array(const unsigned char *s, size_t len)
Definition: util.h:296
static const secp256k1_callback default_error_callback
Definition: util.h:127
static SECP256K1_INLINE uint32_t secp256k1_read_be32(const unsigned char *p)
Definition: util.h:428
#define SECP256K1_INLINE
Definition: util.h:53
static SECP256K1_INLINE int secp256k1_ctz32_var(uint32_t x)
Definition: util.h:392
static SECP256K1_INLINE void secp256k1_write_be32(unsigned char *p, uint32_t x)
Definition: util.h:436
static SECP256K1_INLINE void secp256k1_write_be64(unsigned char *p, uint64_t x)
Definition: util.h:456
static SECP256K1_INLINE uint32_t secp256k1_rotr32(const uint32_t x, const unsigned int by)
Definition: util.h:468
static void secp256k1_default_illegal_callback_fn(const char *str, void *data)
Definition: util.h:107
static SECP256K1_INLINE int secp256k1_ctz64_var_debruijn(uint64_t x)
Definition: util.h:381
static void print_buf_plain(const unsigned char *buf, size_t len)
Definition: util.h:33
#define VERIFY_CHECK(cond)
Definition: util.h:169
static SECP256K1_INLINE int secp256k1_ctz32_var_debruijn(uint32_t x)
Definition: util.h:369
static SECP256K1_INLINE uint64_t secp256k1_read_be64(const unsigned char *p)
Definition: util.h:444
static SECP256K1_INLINE void * checked_malloc(const secp256k1_callback *cb, size_t size)
Definition: util.h:172
static SECP256K1_INLINE void secp256k1_memczero(void *s, size_t len, int flag)
Definition: util.h:220
static SECP256K1_INLINE void secp256k1_callback_call(const secp256k1_callback *const cb, const char *const text)
Definition: util.h:102
static const secp256k1_callback default_illegal_callback
Definition: util.h:122
void(* fn)(const char *text, void *data)
Definition: util.h:98
const void * data
Definition: util.h:99