]> git.ipfire.org Git - thirdparty/git.git/commitdiff
reftable/basics: fix OOB read on binary search of empty range
authorPatrick Steinhardt <ps@pks.im>
Wed, 24 Jun 2026 08:23:06 +0000 (10:23 +0200)
committerJunio C Hamano <gitster@pobox.com>
Wed, 24 Jun 2026 16:30:25 +0000 (09:30 -0700)
`binsearch()` performs a binary search over a range of `sz` elements by
repeatedly calling the comparison function with indices into that range.
When the range is empty though, there is no valid index to call the
comparison function with. We still end up executing the comparison
function though with an index of 0, which of course will cause an
out-of-bounds read.

Return early when the range is empty.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
reftable/basics.c
t/unit-tests/u-reftable-basics.c

index e969927b615fc193ef3368acc922fcb414bfdc04..f0442a46cf7c1382451927e9cea4d302a9b17fc2 100644 (file)
@@ -152,6 +152,9 @@ size_t binsearch(size_t sz, int (*f)(size_t k, void *args), void *args)
        size_t lo = 0;
        size_t hi = sz;
 
+       if (!sz)
+               return 0;
+
        /* Invariants:
         *
         *  (hi == sz) || f(hi) == true
index 73566ed0eb7e0731bd93d117f7fc30b19254d854..c5d83b6714d2eb838258e3c2ff672708d95ac165 100644 (file)
@@ -60,6 +60,17 @@ void test_reftable_basics__binsearch(void)
        }
 }
 
+static int unreachable_lesseq(size_t i UNUSED, void *args UNUSED)
+{
+       cl_fail("comparison function called for empty range");
+       return 0;
+}
+
+void test_reftable_basics__binsearch_empty(void)
+{
+       cl_assert_equal_i(binsearch(0, &unreachable_lesseq, NULL), 0);
+}
+
 void test_reftable_basics__names_length(void)
 {
        const char *a[] = { "a", "b", NULL };