|
| 1 | +#include "src/__support/CPP/bit.h" |
| 2 | +#include "src/__support/UInt.h" |
| 3 | +#include "src/string/memory_utils/inline_memcpy.h" |
| 4 | + |
| 5 | +using namespace LIBC_NAMESPACE; |
| 6 | + |
| 7 | +// Helper function when using gdb / lldb to set a breakpoint and inspect values. |
| 8 | +template <typename T> void debug_and_trap(const char *msg, T a, T b) { |
| 9 | + __builtin_trap(); |
| 10 | +} |
| 11 | + |
| 12 | +#define DEBUG_AND_TRAP() |
| 13 | + |
| 14 | +#define TEST_BINOP(OP) \ |
| 15 | + if ((a OP b) != (static_cast<T>(BigInt(a) OP BigInt(b)))) \ |
| 16 | + debug_and_trap(#OP, a, b); |
| 17 | + |
| 18 | +#define TEST_SHIFTOP(OP) \ |
| 19 | + if ((a OP b) != (static_cast<T>(BigInt(a) OP b))) \ |
| 20 | + debug_and_trap(#OP, a, b); |
| 21 | + |
| 22 | +#define TEST_FUNCTION(FUN) \ |
| 23 | + if (FUN(a) != FUN(BigInt(a))) \ |
| 24 | + debug_and_trap(#FUN, a, b); |
| 25 | + |
| 26 | +// Test that basic arithmetic operations of BigInt behave like their scalar |
| 27 | +// counterparts. |
| 28 | +template <typename T, typename BigInt> void run_tests(T a, T b) { |
| 29 | + TEST_BINOP(+) |
| 30 | + TEST_BINOP(-) |
| 31 | + TEST_BINOP(*) |
| 32 | + if (b != 0) |
| 33 | + TEST_BINOP(/) |
| 34 | + if (b >= 0 && b < cpp::numeric_limits<T>::digits) { |
| 35 | + TEST_SHIFTOP(<<) |
| 36 | + TEST_SHIFTOP(>>) |
| 37 | + } |
| 38 | + if constexpr (!BigInt::SIGNED) { |
| 39 | + TEST_FUNCTION(cpp::has_single_bit) |
| 40 | + TEST_FUNCTION(cpp::countr_zero) |
| 41 | + TEST_FUNCTION(cpp::countl_zero) |
| 42 | + TEST_FUNCTION(cpp::countl_one) |
| 43 | + TEST_FUNCTION(cpp::countr_one) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// Reads a T from libfuzzer data. |
| 48 | +template <typename T> T read(const uint8_t *data, size_t &remainder) { |
| 49 | + T out = 0; |
| 50 | + constexpr size_t T_SIZE = sizeof(T); |
| 51 | + const size_t copy_size = remainder < T_SIZE ? remainder : T_SIZE; |
| 52 | + inline_memcpy(&out, data, copy_size); |
| 53 | + remainder -= copy_size; |
| 54 | + return out; |
| 55 | +} |
| 56 | + |
| 57 | +template <typename T, typename BigInt> |
| 58 | +void run_tests(const uint8_t *data, size_t size) { |
| 59 | + const auto a = read<T>(data, size); |
| 60 | + const auto b = read<T>(data, size); |
| 61 | + run_tests<T, BigInt>(a, b); |
| 62 | +} |
| 63 | + |
| 64 | +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { |
| 65 | + // unsigned |
| 66 | + run_tests<uint64_t, BigInt<64, false, uint16_t>>(data, size); |
| 67 | + // signed |
| 68 | + run_tests<int64_t, BigInt<64, true, uint16_t>>(data, size); |
| 69 | + return 0; |
| 70 | +} |
0 commit comments