reftable/basics: fix OOB read on binary search of empty range
`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>
Patrick Steinhardt committed
Jul 3, 2026 at 14:58 UTC
657654b1aa0c4a101a55c46ab14c96bdf95dc3b7
2 files changed
+14
reftable/basics.c
+3
@@ -152,6 +152,9 @@ size_t binsearch(size_t sz, int (*f)(size_t k, void *args), void *args)
152
size_t lo = 0;
153
size_t hi = sz;
154
155
+ if (!sz)
156
+ return 0;
157
+
158
/* Invariants:
159
*
160
* (hi == sz) || f(hi) == true
t/unit-tests/u-reftable-basics.c
+11
@@ -60,6 +60,17 @@ void test_reftable_basics__binsearch(void)
60
}
61
}
62
63
+static int unreachable_lesseq(size_t i UNUSED, void *args UNUSED)
64
+{
65
+ cl_fail("comparison function called for empty range");
66
+ return 0;
67
+}
68
+
69
+void test_reftable_basics__binsearch_empty(void)
70
+{
71
+ cl_assert_equal_i(binsearch(0, &unreachable_lesseq, NULL), 0);
72
+}
73
+
74
void test_reftable_basics__names_length(void)
75
{
76
const char *a[] = { "a", "b", NULL };