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