Bitcoin Core  22.99.0
P2P Digital Currency
addition_overflow.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
6 #include <test/fuzz/fuzz.h>
7 #include <test/fuzz/util.h>
8 #include <util/overflow.h>
9 
10 #include <cstdint>
11 #include <string>
12 #include <vector>
13 
14 #if defined(__has_builtin)
15 #if __has_builtin(__builtin_add_overflow)
16 #define HAVE_BUILTIN_ADD_OVERFLOW
17 #endif
18 #elif defined(__GNUC__)
19 #define HAVE_BUILTIN_ADD_OVERFLOW
20 #endif
21 
22 namespace {
23 template <typename T>
24 void TestAdditionOverflow(FuzzedDataProvider& fuzzed_data_provider)
25 {
26  const T i = fuzzed_data_provider.ConsumeIntegral<T>();
27  const T j = fuzzed_data_provider.ConsumeIntegral<T>();
28  const bool is_addition_overflow_custom = AdditionOverflow(i, j);
29 #if defined(HAVE_BUILTIN_ADD_OVERFLOW)
30  T result_builtin;
31  const bool is_addition_overflow_builtin = __builtin_add_overflow(i, j, &result_builtin);
32  assert(is_addition_overflow_custom == is_addition_overflow_builtin);
33  if (!is_addition_overflow_custom) {
34  assert(i + j == result_builtin);
35  }
36 #else
37  if (!is_addition_overflow_custom) {
38  (void)(i + j);
39  }
40 #endif
41 }
42 } // namespace
43 
44 FUZZ_TARGET(addition_overflow)
45 {
46  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
47  TestAdditionOverflow<int64_t>(fuzzed_data_provider);
48  TestAdditionOverflow<uint64_t>(fuzzed_data_provider);
49  TestAdditionOverflow<int32_t>(fuzzed_data_provider);
50  TestAdditionOverflow<uint32_t>(fuzzed_data_provider);
51  TestAdditionOverflow<int16_t>(fuzzed_data_provider);
52  TestAdditionOverflow<uint16_t>(fuzzed_data_provider);
53  TestAdditionOverflow<char>(fuzzed_data_provider);
54  TestAdditionOverflow<unsigned char>(fuzzed_data_provider);
55  TestAdditionOverflow<signed char>(fuzzed_data_provider);
56 }
assert
assert(!tx.IsCoinBase())
util.h
FUZZ_TARGET
FUZZ_TARGET(addition_overflow)
Definition: addition_overflow.cpp:44
FuzzedDataProvider.h
AdditionOverflow
bool AdditionOverflow(const T i, const T j) noexcept
Definition: overflow.h:12
fuzz.h
FuzzedDataProvider
Definition: FuzzedDataProvider.h:31
FuzzedDataProvider::ConsumeIntegral
T ConsumeIntegral()
Definition: FuzzedDataProvider.h:194
T
#define T(expected, seed, data)
overflow.h