From 0a91ea1f23787b4ea9d8ad12c4b0b2742014fb32 Mon Sep 17 00:00:00 2001 From: dor-forer Date: Wed, 13 May 2026 14:08:22 +0300 Subject: [PATCH] Fix overflow in query blob size helper --- src/VecSim/vec_sim.cpp | 11 ++++++++++- tests/unit/test_common.cpp | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/VecSim/vec_sim.cpp b/src/VecSim/vec_sim.cpp index 485ecf950..d6dc8f201 100644 --- a/src/VecSim/vec_sim.cpp +++ b/src/VecSim/vec_sim.cpp @@ -258,8 +258,17 @@ extern "C" size_t VecSimParams_GetQueryBlobSize(VecSimType type, size_t dim, Vec assert(type == VecSimType_FLOAT32 || type == VecSimType_FLOAT64 || type == VecSimType_BFLOAT16 || type == VecSimType_FLOAT16 || type == VecSimType_INT8 || type == VecSimType_UINT8); - size_t blobSize = VecSimType_sizeof(type) * dim; + + size_t element_size = VecSimType_sizeof(type); + if (dim != 0 && element_size > SIZE_MAX / dim) { + return 0; + } + + size_t blobSize = element_size * dim; if (metric == VecSimMetric_Cosine && (type == VecSimType_INT8 || type == VecSimType_UINT8)) { + if (blobSize > SIZE_MAX - sizeof(float)) { + return 0; + } blobSize += sizeof(float); // For the norm } return blobSize; diff --git a/tests/unit/test_common.cpp b/tests/unit/test_common.cpp index 5e4cb95ed..6015aa271 100644 --- a/tests/unit/test_common.cpp +++ b/tests/unit/test_common.cpp @@ -907,6 +907,23 @@ TEST_P(CommonTypeMetricTests, TestGetQueryBlobSize) { ASSERT_EQ(actual, expected); } +TEST_P(CommonTypeMetricTests, TestGetQueryBlobSizeOverflow) { + // We don't need to create an index for this test, set to nullptr to avoid cleanup issues + this->index = nullptr; + + VecSimType type = std::get<0>(GetParam()); + VecSimMetric metric = std::get<1>(GetParam()); + + size_t element_size = VecSimType_sizeof(type); + size_t overflow_dim = SIZE_MAX / element_size + 1; + ASSERT_EQ(VecSimParams_GetQueryBlobSize(type, overflow_dim, metric), 0); + + if (metric == VecSimMetric_Cosine && (type == VecSimType_INT8 || type == VecSimType_UINT8)) { + size_t add_overflow_dim = SIZE_MAX - sizeof(float) + 1; + ASSERT_EQ(VecSimParams_GetQueryBlobSize(type, add_overflow_dim, metric), 0); + } +} + class CommonTypeMetricTieredTests : public CommonTypeMetricTests { protected: virtual void TearDown() override {}