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