Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion density/include/density_sketch.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class density_sketch {
/**
* Constructor
* @param k controls the size and error of the sketch.
* @param dim dimension of the input domain
* @param dim dimension of the input domain, at least 1
* @param kernel to use by this instance
* @param allocator to use by this instance
*/
Expand Down Expand Up @@ -220,6 +220,9 @@ class density_sketch {
static void check_serial_version(uint8_t serial_version);
static void check_family_id(uint8_t family_id, uint8_t serial_version);
static void check_header_validity(uint8_t preamble_ints, uint8_t flags_byte, uint8_t serial_version);
static void check_dim(uint32_t dim);
static void check_num_retained(uint32_t num_retained);
static void check_level_size(uint32_t level_size, int64_t num_to_read);

density_sketch(uint16_t k, uint32_t dim, uint32_t num_retained, uint64_t n, Levels&& levels,
const Kernel& kernel = Kernel());
Expand Down
30 changes: 30 additions & 0 deletions density/include/density_sketch_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ n_(0),
levels_(1, Level(allocator), allocator)
{
check_k(k);
check_dim(dim);
}

template<typename T, typename K, typename A>
Expand All @@ -51,6 +52,7 @@ n_(n),
levels_(std::move(levels))
{
check_k(k);
check_dim(dim);
}

template<typename T, typename K, typename A>
Expand Down Expand Up @@ -283,7 +285,9 @@ density_sketch<T, K, A> density_sketch<T, K, A>::deserialize(std::istream& is, c
return density_sketch(k, dim, kernel, allocator);
}

check_dim(dim);
const auto num_retained = read<uint32_t>(is);
check_num_retained(num_retained);
const auto n = read<uint64_t>(is);

// levels arrays
Expand All @@ -292,6 +296,8 @@ density_sketch<T, K, A> density_sketch<T, K, A>::deserialize(std::istream& is, c
int64_t num_to_read = num_retained; // num_retrained is uint32_t so this allows error checking
while (num_to_read > 0) {
const auto level_size = read<uint32_t>(is);
if (!is.good()) throw std::runtime_error("error reading from std::istream");
check_level_size(level_size, num_to_read);
Level lvl(allocator);
lvl.reserve(level_size);
for (uint32_t i = 0; i < level_size; ++i) {
Expand Down Expand Up @@ -340,9 +346,11 @@ density_sketch<T, K, A> density_sketch<T, K, A>::deserialize(const void* bytes,
return density_sketch(k, dim, kernel, allocator);
}

check_dim(dim);
ensure_minimum_memory(size, PREAMBLE_INTS_LONG * sizeof(uint32_t));
uint32_t num_retained;
ptr += copy_from_mem(ptr, num_retained);
check_num_retained(num_retained);
uint64_t n;
ptr += copy_from_mem(ptr, n);

Expand All @@ -356,8 +364,10 @@ density_sketch<T, K, A> density_sketch<T, K, A>::deserialize(const void* bytes,
Levels levels(allocator);
int64_t num_to_read = num_retained; // num_retained is uint32_t so this allows error checking

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non-empty sketch case, so we should check "num_retained" is not 0 in here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks. A non-empty image with num_retained 0 loaded as a sketch with no levels, and the next update() never returned. Both readers now reject it, with a test (62c4072).

while (num_to_read > 0) {
ensure_minimum_memory(end_ptr - ptr, sizeof(uint32_t));
uint32_t level_size;
ptr += copy_from_mem(ptr, level_size);
check_level_size(level_size, num_to_read);
ensure_minimum_memory(end_ptr - ptr, level_size * pt_size);
Level lvl(allocator);
lvl.reserve(level_size);
Expand All @@ -377,6 +387,26 @@ density_sketch<T, K, A> density_sketch<T, K, A>::deserialize(const void* bytes,
return density_sketch(k, dim, num_retained, n, std::move(levels), kernel);
}

template<typename T, typename K, typename A>
void density_sketch<T, K, A>::check_dim(uint32_t dim) {
if (dim == 0) throw std::invalid_argument("dimension must be at least 1");
}

template<typename T, typename K, typename A>
void density_sketch<T, K, A>::check_num_retained(uint32_t num_retained) {
if (num_retained == 0) {
throw std::invalid_argument("Possible corruption: a non-empty sketch must retain at least one item");
}
}

template<typename T, typename K, typename A>
void density_sketch<T, K, A>::check_level_size(uint32_t level_size, int64_t num_to_read) {
if (level_size > num_to_read) {
throw std::invalid_argument("Possible corruption: level size " + std::to_string(level_size)
+ " exceeds the " + std::to_string(num_to_read) + " retained items left to read");
}
}

template<typename T, typename K, typename A>
void density_sketch<T, K, A>::check_k(uint16_t k) {
if (k < 2)
Expand Down
61 changes: 61 additions & 0 deletions density/test/density_sketch_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
* under the License.
*/

#include <algorithm>
#include <cmath>
#include <cstring>
#include <sstream>
#include <catch2/catch.hpp>

#include <density_sketch.hpp>
Expand Down Expand Up @@ -498,4 +501,62 @@ TEST_CASE("density sketch: serialize with a header", "[density_sketch]") {
}
}


TEST_CASE("density sketch: level sizes and dimension are checked on deserialize", "[density_sketch]") {
density_sketch<float> sk(10, 3);
sk.update(std::vector<float>{1, 2, 3});
const auto valid = sk.serialize();
const size_t header_size = 24; // 6 preamble ints
const size_t dim_offset = 8;
REQUIRE(valid.size() == header_size + sizeof(uint32_t) + 3 * sizeof(float));

auto check = [](const std::vector<uint8_t>& bytes) {
REQUIRE_THROWS(density_sketch<float>::deserialize(bytes.data(), bytes.size()));
std::stringstream ss;
ss.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
REQUIRE_THROWS(density_sketch<float>::deserialize(ss));
};

SECTION("empty levels to the end of the input") {
auto bytes = valid;
std::fill(bytes.begin() + header_size, bytes.end(), 0);
check(bytes);
}

SECTION("level larger than the retained items") {
auto bytes = valid;
const uint32_t level_size = 2;
std::memcpy(bytes.data() + header_size, &level_size, sizeof(level_size));
check(bytes);
}

SECTION("no retained items in a non-empty sketch") {
auto bytes = valid;
const size_t num_retained_offset = 12;
const uint32_t num_retained = 0;
std::memcpy(bytes.data() + num_retained_offset, &num_retained, sizeof(num_retained));
bytes.resize(header_size);
check(bytes);
}

SECTION("dimension 0") {
auto bytes = valid;
const uint32_t dim = 0;
std::memcpy(bytes.data() + dim_offset, &dim, sizeof(dim));
check(bytes);
}

SECTION("dimension 0, empty") {
density_sketch<float> empty(10, 3);
auto bytes = empty.serialize();
const uint32_t dim = 0;
std::memcpy(bytes.data() + dim_offset, &dim, sizeof(dim));
check(bytes);
}
}

TEST_CASE("density sketch: dimension must be at least 1", "[density_sketch]") {
REQUIRE_THROWS_AS(density_sketch<float>(10, 0), std::invalid_argument);
}

} /* namespace datasketches */
3 changes: 3 additions & 0 deletions filters/include/bloom_filter.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,9 @@ class bloom_filter_alloc {
uint8_t* memory,
const A& allocator);

// checks the header of a non-empty image before its bit array is read
static void check_non_empty_header(uint8_t prelongs, uint16_t num_hashes, uint64_t num_bits);

static bloom_filter_alloc internal_deserialize_or_wrap(void* bytes,
size_t length_bytes,
bool read_only,
Expand Down
30 changes: 20 additions & 10 deletions filters/include/bloom_filter_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,7 @@ bloom_filter_alloc<A> bloom_filter_alloc<A>::deserialize(std::istream& is, const
if (is_empty) {
return bloom_filter_alloc<A>(num_bits, num_hashes, seed, allocator);
}
// a non-empty filter has a bit array: this keeps capacity_bits_ positive,
// and keeps allocate() from being called with 0
if (num_bytes == 0) {
throw std::invalid_argument("Possible corruption: non-empty filter with an empty bit array");
}
check_non_empty_header(prelongs, num_hashes, num_bits);

const uint64_t raw_num_bits_set = read<uint64_t>(is);

Expand Down Expand Up @@ -344,6 +340,24 @@ bloom_filter_alloc<A> bloom_filter_alloc<A>::writable_wrap(void* bytes, size_t l
return internal_deserialize_or_wrap(bytes, length_bytes, false, true, allocator);
}

template<typename A>
void bloom_filter_alloc<A>::check_non_empty_header(uint8_t prelongs, uint16_t num_hashes, uint64_t num_bits) {
// the number of bits set follows the empty preamble, so a shorter preamble would read past it
if (prelongs != PREAMBLE_LONGS_STANDARD) {
throw std::invalid_argument("Possible corruption: non-empty filter with " + std::to_string(prelongs)
+ " preamble longs, expected " + std::to_string(PREAMBLE_LONGS_STANDARD));
}
// the public constructors check these, but the one used for a non-empty image does not
if (num_hashes == 0) {
throw std::invalid_argument("Possible corruption: non-empty filter with no hash functions");
}
// a non-empty filter has a bit array: this keeps capacity_bits_ positive,
// and keeps allocate() from being called with 0
if (num_bits == 0) {
throw std::invalid_argument("Possible corruption: non-empty filter with an empty bit array");
}
}

template<typename A>
bloom_filter_alloc<A> bloom_filter_alloc<A>::internal_deserialize_or_wrap(void* bytes,
size_t length_bytes,
Expand Down Expand Up @@ -396,11 +410,7 @@ bloom_filter_alloc<A> bloom_filter_alloc<A>::internal_deserialize_or_wrap(void*
} else if (is_empty) {
return bloom_filter_alloc<A>(num_bits, num_hashes, seed, allocator);
}
// a non-empty filter has a bit array: this keeps capacity_bits_ positive,
// and keeps allocate() from being called with 0
if (num_bytes == 0) {
throw std::invalid_argument("Possible corruption: non-empty filter with an empty bit array");
}
check_non_empty_header(prelongs, num_hashes, num_bits);

uint64_t raw_num_bits_set;
ptr += copy_from_mem(ptr, raw_num_bits_set);
Expand Down
36 changes: 36 additions & 0 deletions filters/test/bloom_filter_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,42 @@ TEST_CASE("bloom_filter: image with zero bit array length is rejected", "[bloom_
REQUIRE_THROWS_AS(bloom_filter::deserialize(empty_is), std::invalid_argument);
}

TEST_CASE("bloom_filter: non-empty image header is checked", "[bloom_filter]") {
const size_t prelongs_offset = 0;
const size_t num_hashes_offset = 4;

auto bf = bloom_filter::builder::create_by_size(64, 3);
bf.update("apple");
const auto good = bf.serialize();

auto check_rejected = [](std::vector<uint8_t> bytes) {
REQUIRE_THROWS_AS(bloom_filter::deserialize(bytes.data(), bytes.size()), std::invalid_argument);
REQUIRE_THROWS_AS(bloom_filter::wrap(bytes.data(), bytes.size()), std::invalid_argument);
REQUIRE_THROWS_AS(bloom_filter::writable_wrap(bytes.data(), bytes.size()), std::invalid_argument);
const std::string serialized(reinterpret_cast<const char*>(bytes.data()), bytes.size());
std::istringstream is(serialized, std::ios::in | std::ios::binary);
REQUIRE_THROWS_AS(bloom_filter::deserialize(is), std::invalid_argument);
};

SECTION("empty preamble length") {
// only the empty preamble's 24 bytes: the number of bits set would be read past the end
std::vector<uint8_t> bytes(good.begin(), good.begin() + 24);
bytes[prelongs_offset] = 3;
check_rejected(bytes);
// with the whole image, the preamble length still has to match
bytes.assign(good.begin(), good.end());
bytes[prelongs_offset] = 3;
check_rejected(bytes);
}

SECTION("no hash functions") {
std::vector<uint8_t> bytes(good.begin(), good.end());
const uint16_t num_hashes = 0;
std::memcpy(bytes.data() + num_hashes_offset, &num_hashes, sizeof(num_hashes));
check_rejected(bytes);
}
}

TEST_CASE("bloom_filter: capacity is rounded up to a multiple of 64 bits", "[bloom_filter]") {
// so the bit array of a filter is never shorter than 8 bytes
REQUIRE(bloom_filter::builder::create_by_size(1, 3).get_capacity() == 64);
Expand Down
14 changes: 12 additions & 2 deletions hll/include/HllArray-internal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,12 @@ HllArray<A>* HllArray<A>::newHll(const void* bytes, size_t len, const A& allocat
uint32_t numAtCurMin, auxCount;
std::memcpy(&numAtCurMin, data + hll_constants::CUR_MIN_COUNT_INT, sizeof(int));
std::memcpy(&auxCount, data + hll_constants::AUX_COUNT_INT, sizeof(int));
checkAuxCount(auxCount, tgtHllType);

AuxHashMap<A>* auxHashMap = nullptr;
typedef std::unique_ptr<AuxHashMap<A>, std::function<void(AuxHashMap<A>*)>> aux_hash_map_ptr;
aux_hash_map_ptr aux_ptr;
if (auxCount > 0) { // necessarily TgtHllType == HLL_4
if (auxCount > 0) { // TgtHllType == HLL_4, see checkAuxCount()
uint8_t auxLgIntArrSize = data[4];
const size_t offset = hll_constants::HLL_BYTE_ARR_START + arrayBytes;
const uint8_t* auxDataStart = data + offset;
Expand Down Expand Up @@ -200,12 +201,13 @@ HllArray<A>* HllArray<A>::newHll(std::istream& is, const A& allocator) {

const auto numAtCurMin = read<uint32_t>(is);
const auto auxCount = read<uint32_t>(is);
checkAuxCount(auxCount, tgtHllType);
sketch->putNumAtCurMin(numAtCurMin);

read(is, sketch->hllByteArr_.data(), sketch->getHllByteArrBytes());
if (tgtHllType == HLL_8) { checkHll8Registers(sketch->hllByteArr_.data(), sketch->getHllByteArrBytes()); }

if (auxCount > 0) { // necessarily TgtHllType == HLL_4
if (auxCount > 0) { // TgtHllType == HLL_4, see checkAuxCount()
uint8_t auxLgIntArrSize = listHeader[4];
AuxHashMap<A>* auxHashMap = AuxHashMap<A>::deserialize(is, lgK, auxCount, auxLgIntArrSize, comapctFlag, allocator);
((Hll4Array<A>*)sketch)->putAuxHashMap(auxHashMap);
Expand All @@ -216,6 +218,14 @@ HllArray<A>* HllArray<A>::newHll(std::istream& is, const A& allocator) {
return sketch_ptr.release();
}

template<typename A>
void HllArray<A>::checkAuxCount(uint32_t auxCount, target_hll_type tgtHllType) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about adding hllByteArr's token count and auxCount comparison too here? Maybe corrupted image can be different two counts.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, that is worth checking. It is part of a follow-up PR on the HLL readers that I will open after this one, to keep this one small. There, each HLL_4 register holding the aux token must have an aux entry whose value does not fit in the register, and the number of such registers must equal auxCount, in both readers.

// only HLL_4 has an aux map
if (auxCount > 0 && tgtHllType != HLL_4) {
throw std::invalid_argument("Possible corruption: aux entries in a non-HLL_4 image");
}
}

template<typename A>
auto HllArray<A>::serialize(bool compact, unsigned header_size_bytes) const -> vector_bytes {
const size_t sketchSizeBytes = (compact ? getCompactSerializationBytes() : getUpdatableSerializationBytes()) + header_size_bytes;
Expand Down
1 change: 1 addition & 0 deletions hll/include/HllArray.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ class HllArray : public HllSketchImpl<A> {

// an HLL_8 register holds a value from 0 to 63
static void checkHll8Registers(const uint8_t* registers, uint32_t numRegisters);
static void checkAuxCount(uint32_t auxCount, target_hll_type tgtHllType);

virtual AuxHashMap<A>* getAuxHashMap() const;

Expand Down
21 changes: 21 additions & 0 deletions hll/test/HllArrayTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include "hll.hpp"

#include <cstring>
#include <exception>
#include <sstream>
#include <stdexcept>
Expand Down Expand Up @@ -212,4 +213,24 @@ TEST_CASE("hll array: check corrupt stream", "[hll_array]") {
ss.put((char)tmp);
}


TEST_CASE("hll array: aux count is checked against the target type", "[hll_array]") {
for (const target_hll_type type : {HLL_6, HLL_8}) {
hll_sketch sk(8, type);
for (int i = 0; i < 1000; ++i) sk.update(i);
auto bytes = sk.serialize_compact();
const uint32_t aux_count = 1;
std::memcpy(bytes.data() + hll_constants::AUX_COUNT_INT, &aux_count, sizeof(aux_count));
// one compact aux entry after the registers: slot 1, value 20
const uint32_t aux_entry = (20u << 26) | 1u;
const uint8_t* entry_bytes = reinterpret_cast<const uint8_t*>(&aux_entry);
bytes.insert(bytes.end(), entry_bytes, entry_bytes + sizeof(aux_entry));

REQUIRE_THROWS_AS(hll_sketch::deserialize(bytes.data(), bytes.size()), std::invalid_argument);
std::stringstream ss;
ss.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
REQUIRE_THROWS_AS(hll_sketch::deserialize(ss), std::invalid_argument);
}
}

} /* namespace datasketches */
12 changes: 9 additions & 3 deletions sampling/include/var_opt_sketch_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1364,14 +1364,20 @@ uint32_t var_opt_sketch<T, A>::validate_and_get_target_size(uint32_t preamble_lo
throw std::invalid_argument("Possible corruption: deserializing with n > k but not in full mode. "
"Found n = " + std::to_string(n) + ", k = " + std::to_string(k));
}
if (h + r != k) {
throw std::invalid_argument("Possible corruption: deserializing in full mode but h + r != n. "
"Found h = " + std::to_string(h) + ", r = " + std::to_string(r) + ", n = " + std::to_string(n));
if (static_cast<uint64_t>(h) + r != k) {
throw std::invalid_argument("Possible corruption: deserializing in full mode but h + r != k. "
"Found h = " + std::to_string(h) + ", r = " + std::to_string(r) + ", k = " + std::to_string(k));
}

array_size = k + 1;
}

// the readers copy h weights and items into arrays of this size
if (h > array_size) {
throw std::invalid_argument("Possible corruption: h = " + std::to_string(h)
+ " exceeds the array size " + std::to_string(array_size));
}

return array_size;
}

Expand Down
Loading
Loading