t-prio-queue: check result array bounds

Avoid reading past the end of the "result" array, which could otherwise happen if the prio-queue were to yield more items than were put into it due to an implementation bug, or if the array has not enough entries due to a test bug. Also check at the end whether all "result" entries were consumed, which would not be the case if the prio-queue forgot some entries or the test definition contained too many. Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Mar 16, 2024 at 22:09 UTC 30ff05094c145397d88ead89c3937d1a058ed98a
1 file changed +11 -3
t/unit-tests/t-prio-queue.c
+11 -3
@@ -19,11 +19,13 @@ static int show(int *v)
19 return v ? *v : MISSING;
20 }
21
22 -static void test_prio_queue(int *input, int *result, size_t input_size)
22 +static void test_prio_queue(int *input, size_t input_size,
23 + int *result, size_t result_size)
24 {
25 struct prio_queue pq = { intcmp };
26 + int j = 0;
27
26 - for (int i = 0, j = 0; i < input_size; i++) {
28 + for (int i = 0; i < input_size; i++) {
29 void *peek, *get;
30 switch(input[i]) {
31 case GET:
@@ -31,6 +33,8 @@ static void test_prio_queue(int *input, int *result, size_t input_size)
33 get = prio_queue_get(&pq);
34 if (!check(peek == get))
35 return;
36 + if (!check_uint(j, <, result_size))
37 + break;
38 if (!check_int(result[j], ==, show(get)))
39 test_msg(" j: %d", j);
40 j++;
@@ -40,6 +44,8 @@ static void test_prio_queue(int *input, int *result, size_t input_size)
44 get = prio_queue_get(&pq);
45 if (!check(peek == get))
46 return;
47 + if (!check_uint(j, <, result_size))
48 + break;
49 if (!check_int(result[j], ==, show(get)))
50 test_msg(" j: %d", j);
51 j++;
@@ -56,6 +62,7 @@ static void test_prio_queue(int *input, int *result, size_t input_size)
62 break;
63 }
64 }
65 + check_uint(j, ==, result_size);
66 clear_prio_queue(&pq);
67 }
68
@@ -79,7 +86,8 @@ static void test_prio_queue(int *input, int *result, size_t input_size)
86 { \
87 int input[] = {INPUT}; \
88 int result[] = {RESULT}; \
82 - test_prio_queue(input, result, ARRAY_SIZE(input)); \
89 + test_prio_queue(input, ARRAY_SIZE(input), \
90 + result, ARRAY_SIZE(result)); \
91 }
92
93 TEST_INPUT(BASIC_INPUT, BASIC_RESULT, basic)