From 53da15d1efbb1f6d3ec40838ba04d80ddea1c43b Mon Sep 17 00:00:00 2001 From: ethanglaser Date: Fri, 22 May 2026 11:49:12 -0700 Subject: [PATCH 1/2] Add test for div by zero --- tests/svs/core/io/binary.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/svs/core/io/binary.cpp b/tests/svs/core/io/binary.cpp index 73460115e..714379e11 100644 --- a/tests/svs/core/io/binary.cpp +++ b/tests/svs/core/io/binary.cpp @@ -29,6 +29,7 @@ #include "catch2/matchers/catch_matchers_string.hpp" // stl +#include #include #include #include @@ -133,4 +134,31 @@ CATCH_TEST_CASE("Testing Binary Reader Iterator", "[core][io]") { ) ); } + + CATCH_SECTION("Malformed Header (zero dimensions)") { + // Crafted file with num_vectors == 0 and vector_dim == 0 must not trigger + // a divide-by-zero — the parser should reject it cleanly. + auto write_zero_header = [](const std::string& path) { + std::ofstream f(path, std::ios::binary | std::ios::trunc); + const uint32_t zero = 0; + f.write(reinterpret_cast(&zero), sizeof(zero)); + f.write(reinterpret_cast(&zero), sizeof(zero)); + }; + + std::string bad_file = + svs_test::prepare_temp_directory_v2() / "malformed_header.fbin"; + write_zero_header(bad_file); + + CATCH_REQUIRE_THROWS_MATCHES( + svs::io::binary::BinaryFile(bad_file).get_dims(), + svs::ANNException, + svs_test::ExceptionMatcher(Catch::Matchers::ContainsSubstring(bad_file)) + ); + + CATCH_REQUIRE_THROWS_MATCHES( + svs::io::binary::BinaryReader(bad_file), + svs::ANNException, + svs_test::ExceptionMatcher(Catch::Matchers::ContainsSubstring(bad_file)) + ); + } } From 0f822b230014c49ab64ca55858adf9413f2af6cd Mon Sep 17 00:00:00 2001 From: ethanglaser Date: Fri, 22 May 2026 12:14:57 -0700 Subject: [PATCH 2/2] zero checks on input --- include/svs/core/io/binary.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/include/svs/core/io/binary.h b/include/svs/core/io/binary.h index e500f05f2..2d6b73417 100644 --- a/include/svs/core/io/binary.h +++ b/include/svs/core/io/binary.h @@ -53,6 +53,15 @@ get_dims(std::ifstream& stream, std::string_view source = {}, size_t elsize_hint size_t filesize = stream.tellg(); stream.seekg(0, std::ifstream::beg); + if (header.num_vectors == 0 || header.vector_dim == 0) { + throw ANNEXCEPTION( + "Binary file {} has an invalid header (num_vectors={}, vector_dim={}).", + source.empty() ? "(unknown)"sv : source, + header.num_vectors, + header.vector_dim + ); + } + size_t filesize_minus_header = filesize - sizeof(header); size_t n_vec_elements = lib::narrow(header.num_vectors) * lib::narrow(header.vector_dim);