cuckoocache: Check for uint32 overflow in setup_bytes

This fixes an potential overflow which existed prior to this patchset.

If CuckooCache::cache<Element, Hash>::setup_bytes is called with a
`size_t bytes` which, when divided by sizeof(Element), does not fit into
an uint32_t, the implicit conversion to uint32_t in the call to setup
will result in an overflow.

At least on x86_64, this overflow is possible:

static_assert(std::numeric_limits<size_t>::max() / 32 <= std::numeric_limits<uint32_t>::max());
static_assert(std::numeric_limits<size_t>::max() / 4 <= std::numeric_limits<uint32_t>::max());

This commit detects such cases and signals to callers that the `size_t
bytes` input is too large.
This commit is contained in:
Carl Dong
2022-07-01 19:53:04 -04:00
parent b370164b31
commit 82d3058539
3 changed files with 15 additions and 5 deletions

View File

@@ -14,6 +14,7 @@
#include <algorithm>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <vector>
@@ -75,7 +76,7 @@ public:
std::unique_lock<std::shared_mutex> lock(cs_sigcache);
setValid.insert(entry);
}
std::pair<uint32_t, size_t> setup_bytes(size_t n)
std::optional<std::pair<uint32_t, size_t>> setup_bytes(size_t n)
{
return setValid.setup_bytes(n);
}
@@ -99,8 +100,9 @@ bool InitSignatureCache()
size_t nMaxCacheSize = std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2) * ((size_t) 1 << 20);
auto setup_results = signatureCache.setup_bytes(nMaxCacheSize);
if (!setup_results) return false;
const auto [num_elems, approx_size_bytes] = setup_results;
const auto [num_elems, approx_size_bytes] = *setup_results;
LogPrintf("Using %zu MiB out of %zu/2 requested for signature cache, able to store %zu elements\n",
approx_size_bytes >> 20, (nMaxCacheSize * 2) >> 20, num_elems);
return true;