2 * Copyright (c) 2016-present, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
11 * Helper functions for fuzzing.
14 #ifndef FUZZ_HELPERS_H
15 #define FUZZ_HELPERS_H
28 #define MIN(a, b) ((a) < (b) ? (a) : (b))
29 #define MAX(a, b) ((a) > (b) ? (a) : (b))
31 #define FUZZ_QUOTE_IMPL(str) #str
32 #define FUZZ_QUOTE(str) FUZZ_QUOTE_IMPL(str)
35 * Asserts for fuzzing that are always enabled.
37 #define FUZZ_ASSERT_MSG(cond, msg) \
39 : (fprintf(stderr, "%s: %u: Assertion: `%s' failed. %s\n", __FILE__, \
40 __LINE__, FUZZ_QUOTE(cond), (msg)), \
42 #define FUZZ_ASSERT(cond) FUZZ_ASSERT_MSG((cond), "");
43 #define FUZZ_ZASSERT(code) \
44 FUZZ_ASSERT_MSG(!ZSTD_isError(code), ZSTD_getErrorName(code))
47 #define FUZZ_STATIC static __inline __attribute__((unused))
48 #elif defined(__cplusplus) || \
49 (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
50 #define FUZZ_STATIC static inline
51 #elif defined(_MSC_VER)
52 #define FUZZ_STATIC static __inline
54 #define FUZZ_STATIC static
58 * Determininistically constructs a seed based on the fuzz input.
59 * Consumes up to the first FUZZ_RNG_SEED_SIZE bytes of the input.
61 FUZZ_STATIC uint32_t FUZZ_seed(uint8_t const **src, size_t* size) {
62 uint8_t const *data = *src;
63 size_t const toHash = MIN(FUZZ_RNG_SEED_SIZE, *size);
66 return XXH32(data, toHash, 0);
69 #define FUZZ_rotl32(x, r) (((x) << (r)) | ((x) >> (32 - (r))))
71 FUZZ_STATIC uint32_t FUZZ_rand(uint32_t *state) {
72 static const uint32_t prime1 = 2654435761U;
73 static const uint32_t prime2 = 2246822519U;
74 uint32_t rand32 = *state;
77 rand32 = FUZZ_rotl32(rand32, 13);
82 /* Returns a random numer in the range [min, max]. */
83 FUZZ_STATIC uint32_t FUZZ_rand32(uint32_t *state, uint32_t min, uint32_t max) {
84 uint32_t random = FUZZ_rand(state);
85 return min + (random % (max - min + 1));