Skip to content

Commit 55364e1

Browse files
committed
stdlib: Handle various corner cases in the fallback heapsort for qsort
The previous implementation did not consistently apply the rule that the child nodes of node K are at 2 * K + 1 and 2 * K + 2, or that the parent node is at (K - 1) / 2. Add an internal test that targets the heapsort implementation directly. Reported-by: Stepan Golosunov <stepan@golosunov.pp.ru> Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
1 parent e4d8117 commit 55364e1

File tree

3 files changed

+173
-17
lines changed

3 files changed

+173
-17
lines changed

stdlib/Makefile

+1
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ tests := \
261261
# tests
262262

263263
tests-internal := \
264+
tst-qsort4 \
264265
tst-strtod1i \
265266
tst-strtod3 \
266267
tst-strtod4 \

stdlib/qsort.c

+38-17
Original file line numberDiff line numberDiff line change
@@ -125,29 +125,44 @@ pop (stack_node *top, char **lo, char **hi, size_t *depth)
125125
return top;
126126
}
127127

128-
/* NB: N is inclusive bound for BASE. */
128+
/* Establish the heap condition at index K, that is, the key at K will
129+
not be less than either of its children, at 2 * K + 1 and 2 * K + 2
130+
(if they exist). N is the last valid index. */
129131
static inline void
130132
siftdown (void *base, size_t size, size_t k, size_t n,
131133
enum swap_type_t swap_type, __compar_d_fn_t cmp, void *arg)
132134
{
133-
while (k <= n / 2)
135+
/* There can only be a heap condition violation if there are
136+
children. */
137+
while (2 * k + 1 <= n)
134138
{
135-
size_t j = 2 * k;
139+
/* Left child. */
140+
size_t j = 2 * k + 1;
141+
/* If the right child is larger, use it. */
136142
if (j < n && cmp (base + (j * size), base + ((j + 1) * size), arg) < 0)
137143
j++;
138144

145+
/* If k is already >= to its children, we are done. */
139146
if (j == k || cmp (base + (k * size), base + (j * size), arg) >= 0)
140147
break;
141148

149+
/* Heal the violation. */
142150
do_swap (base + (size * j), base + (k * size), size, swap_type);
151+
152+
/* Swapping with j may have introduced a violation at j. Fix
153+
it in the next loop iteration. */
143154
k = j;
144155
}
145156
}
146157

158+
/* Establish the heap condition for the indices 0 to N (inclusive). */
147159
static inline void
148160
heapify (void *base, size_t size, size_t n, enum swap_type_t swap_type,
149161
__compar_d_fn_t cmp, void *arg)
150162
{
163+
/* If n is odd, k = n / 2 has a left child at n, so this is the
164+
largest index that can have a heap condition violation regarding
165+
its children. */
151166
size_t k = n / 2;
152167
while (1)
153168
{
@@ -157,32 +172,38 @@ heapify (void *base, size_t size, size_t n, enum swap_type_t swap_type,
157172
}
158173
}
159174

160-
/* A non-recursive heapsort, used on introsort implementation as a fallback
161-
routine with worst-case performance of O(nlog n) and worst-case space
162-
complexity of O(1). It sorts the array starting at BASE and ending at
163-
END, with each element of SIZE bytes. The SWAP_TYPE is the callback
164-
function used to swap elements, and CMP is the function used to compare
165-
elements. */
175+
/* A non-recursive heapsort, used on introsort implementation as a
176+
fallback routine with worst-case performance of O(nlog n) and
177+
worst-case space complexity of O(1). It sorts the array starting
178+
at BASE and ending at END (inclusive), with each element of SIZE
179+
bytes. The SWAP_TYPE is the callback function used to swap
180+
elements, and CMP is the function used to compare elements. */
166181
static void
167182
heapsort_r (void *base, void *end, size_t size, enum swap_type_t swap_type,
168183
__compar_d_fn_t cmp, void *arg)
169184
{
170-
const size_t count = ((uintptr_t) end - (uintptr_t) base) / size;
171-
172-
if (count < 2)
185+
size_t n = ((uintptr_t) end - (uintptr_t) base) / size;
186+
if (n <= 1)
187+
/* Handled by insertion sort. */
173188
return;
174189

175-
size_t n = count - 1;
176-
177190
/* Build the binary heap, largest value at the base[0]. */
178191
heapify (base, size, n, swap_type, cmp, arg);
179192

180-
/* On each iteration base[0:n] is the binary heap, while base[n:count]
181-
is sorted. */
182-
while (n > 0)
193+
while (true)
183194
{
195+
/* Indices 0 .. n contain the binary heap. Extract the largest
196+
element put it into the final position in the array. */
184197
do_swap (base, base + (n * size), size, swap_type);
198+
199+
/* The heap is now one element shorter. */
185200
n--;
201+
if (n == 0)
202+
break;
203+
204+
/* By swapping in elements 0 and the previous value of n (now at
205+
n + 1), we likely introduced a heap condition violation. Fix
206+
it for the reduced heap. */
186207
siftdown (base, size, 0, n, swap_type, cmp, arg);
187208
}
188209
}

stdlib/tst-qsort4.c

+134
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/* Test the heapsort implementation behind qsort.
2+
Copyright (C) 2023 Free Software Foundation, Inc.
3+
This file is part of the GNU C Library.
4+
5+
The GNU C Library is free software; you can redistribute it and/or
6+
modify it under the terms of the GNU Lesser General Public
7+
License as published by the Free Software Foundation; either
8+
version 2.1 of the License, or (at your option) any later version.
9+
10+
The GNU C Library is distributed in the hope that it will be useful,
11+
but WITHOUT ANY WARRANTY; without even the implied warranty of
12+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13+
Lesser General Public License for more details.
14+
15+
You should have received a copy of the GNU Lesser General Public
16+
License along with the GNU C Library; if not, see
17+
<http://www.gnu.org/licenses/>. */
18+
19+
#include "qsort.c"
20+
21+
#include <stdio.h>
22+
#include <support/check.h>
23+
#include <support/support.h>
24+
25+
static int
26+
cmp (const void *a1, const void *b1, void *closure)
27+
{
28+
const signed char *a = a1;
29+
const signed char *b = b1;
30+
return *a - *b;
31+
}
32+
33+
/* Wrapper around heapsort_r that set ups the required variables. */
34+
static void
35+
heapsort_wrapper (void *const pbase, size_t total_elems, size_t size,
36+
__compar_d_fn_t cmp, void *arg)
37+
{
38+
char *base_ptr = (char *) pbase;
39+
char *lo = base_ptr;
40+
char *hi = &lo[size * (total_elems - 1)];
41+
42+
if (total_elems <= 1)
43+
/* Avoid lossage with unsigned arithmetic below. */
44+
return;
45+
46+
enum swap_type_t swap_type;
47+
if (is_aligned (pbase, size, 8))
48+
swap_type = SWAP_WORDS_64;
49+
else if (is_aligned (pbase, size, 4))
50+
swap_type = SWAP_WORDS_32;
51+
else
52+
swap_type = SWAP_BYTES;
53+
heapsort_r (lo, hi, size, swap_type, cmp, arg);
54+
}
55+
56+
static void
57+
check_one_sort (signed char *array, int length)
58+
{
59+
signed char *copy = xmalloc (length);
60+
memcpy (copy, array, length);
61+
heapsort_wrapper (copy, length, 1, cmp, NULL);
62+
63+
/* Verify that the result is sorted. */
64+
for (int i = 1; i < length; ++i)
65+
if (copy[i] < copy[i - 1])
66+
{
67+
support_record_failure ();
68+
printf ("error: sorting failure for length %d at offset %d\n",
69+
length, i - 1);
70+
printf ("input:");
71+
for (int i = 0; i < length; ++i)
72+
printf (" %d", array[i]);
73+
printf ("\noutput:");
74+
for (int i = 0; i < length; ++i)
75+
printf (" %d", copy[i]);
76+
putchar ('\n');
77+
break;
78+
}
79+
80+
/* Verify that no elements went away or were added. */
81+
{
82+
int expected_counts[256];
83+
for (int i = 0; i < length; ++i)
84+
++expected_counts[array[i] & 0xff];
85+
int actual_counts[256];
86+
for (int i = 0; i < length; ++i)
87+
++actual_counts[copy[i] & 0xff];
88+
for (int i = 0; i < 256; ++i)
89+
TEST_COMPARE (expected_counts[i], expected_counts[i]);
90+
}
91+
92+
free (copy);
93+
}
94+
95+
/* Enumerate all possible combinations of LENGTH elements. */
96+
static void
97+
check_combinations (int length, signed char *start, int offset)
98+
{
99+
if (offset == length)
100+
check_one_sort (start, length);
101+
else
102+
for (int i = 0; i < length; ++i)
103+
{
104+
start[offset] = i;
105+
check_combinations(length, start, offset + 1);
106+
}
107+
}
108+
109+
static int
110+
do_test (void)
111+
{
112+
/* A random permutation of 20 values. */
113+
check_one_sort ((signed char[20]) {5, 12, 16, 10, 14, 11, 9, 13, 8, 15,
114+
0, 17, 3, 7, 1, 18, 2, 19, 4, 6}, 20);
115+
116+
117+
/* A permutation that appeared during adversarial testing for the
118+
quicksort pass. */
119+
check_one_sort ((signed char[16]) {15, 3, 4, 2, 1, 0, 8, 7, 6, 5, 14,
120+
13, 12, 11, 10, 9}, 16);
121+
122+
/* Array lengths 2 and less are not handled by heapsort_r and
123+
deferred to insertion sort. */
124+
for (int i = 3; i <= 8; ++i)
125+
{
126+
signed char *buf = xmalloc (i);
127+
check_combinations (i, buf, 0);
128+
free (buf);
129+
}
130+
131+
return 0;
132+
}
133+
134+
#include <support/test-driver.c>

0 commit comments

Comments
 (0)