Bitcoin Core 28.99.0
P2P Digital Currency
addition_overflow.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-2022 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
14namespace {
15template <typename T>
16void TestAdditionOverflow(FuzzedDataProvider& fuzzed_data_provider)
17{
18 const T i = fuzzed_data_provider.ConsumeIntegral<T>();
19 const T j = fuzzed_data_provider.ConsumeIntegral<T>();
20 const bool is_addition_overflow_custom = AdditionOverflow(i, j);
21 const auto maybe_add{CheckedAdd(i, j)};
22 const auto sat_add{SaturatingAdd(i, j)};
23 assert(is_addition_overflow_custom == !maybe_add.has_value());
24 assert(is_addition_overflow_custom == AdditionOverflow(j, i));
25 assert(maybe_add == CheckedAdd(j, i));
26 assert(sat_add == SaturatingAdd(j, i));
27#ifndef _MSC_VER
28 T result_builtin;
29 const bool is_addition_overflow_builtin = __builtin_add_overflow(i, j, &result_builtin);
30 assert(is_addition_overflow_custom == is_addition_overflow_builtin);
31 if (!is_addition_overflow_custom) {
32 assert(i + j == result_builtin);
33 }
34#endif
35 if (is_addition_overflow_custom) {
36 assert(sat_add == std::numeric_limits<T>::min() || sat_add == std::numeric_limits<T>::max());
37 } else {
38 const auto add{i + j};
39 assert(add == maybe_add.value());
40 assert(add == sat_add);
41 }
42}
43} // namespace
44
45FUZZ_TARGET(addition_overflow)
46{
47 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
48 TestAdditionOverflow<int64_t>(fuzzed_data_provider);
49 TestAdditionOverflow<uint64_t>(fuzzed_data_provider);
50 TestAdditionOverflow<int32_t>(fuzzed_data_provider);
51 TestAdditionOverflow<uint32_t>(fuzzed_data_provider);
52 TestAdditionOverflow<int16_t>(fuzzed_data_provider);
53 TestAdditionOverflow<uint16_t>(fuzzed_data_provider);
54 TestAdditionOverflow<char>(fuzzed_data_provider);
55 TestAdditionOverflow<unsigned char>(fuzzed_data_provider);
56 TestAdditionOverflow<signed char>(fuzzed_data_provider);
57}
FUZZ_TARGET(addition_overflow)
#define T(expected, seed, data)
std::optional< T > CheckedAdd(const T i, const T j) noexcept
Definition: overflow.h:24
bool AdditionOverflow(const T i, const T j) noexcept
Definition: overflow.h:13
T SaturatingAdd(const T i, const T j) noexcept
Definition: overflow.h:33
assert(!tx.IsCoinBase())