1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1992, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #if defined(LIBC_SCCS) && !defined(lint)
33 static char sccsid[] = "@(#)qsort.c 8.1 (Berkeley) 6/4/93";
34 #endif /* LIBC_SCCS and not lint */
35 // #include <sys/cdefs.h>
36
37 #if defined(__GNUC__)
38 #define __IDSTRING(name,string) __asm__(".ident\t\"" string "\"")
39 #else
40 /*
41 * The following definition might not work well if used in header files,
42 * but it should be better than nothing. If you want a "do nothing"
43 * version, then it should generate some harmless declaration, such as:
44 * #define __IDSTRING(name,string) struct __hack
45 */
46 #define __IDSTRING(name,string) static const char name[] __unused = string
47 #endif
48
49 /*
50 * Embed the rcs id of a source file in the resulting library. Note that in
51 * more recent ELF binutils, we use .ident allowing the ID to be stripped.
52 * Usage:
53 * __FBSDID("$FreeBSD$");
54 */
55 #ifndef __FBSDID
56 #if !defined(STRIP_FBSDID)
57 #define __FBSDID(s) __IDSTRING(__CONCAT(__rcsid_,__LINE__),s)
58 #else
59 #define __FBSDID(s) struct __hack
60 #endif
61 #endif
62
63 #if defined(__GNUC__)
64 #define __GNUC_PREREQ__(ma, mi) \
65 (__GNUC__ > (ma) || __GNUC__ == (ma) && __GNUC_MINOR__ >= (mi))
66 #else
67 #define __GNUC_PREREQ__(ma, mi) 0
68 #endif
69
70 #if !__GNUC_PREREQ__(2, 5)
71 #define __unused
72 #endif
73 #if __GNUC__ == 2 && __GNUC_MINOR__ >= 5 && __GNUC_MINOR__ < 7
74 #define __unused
75 /* XXX Find out what to do for __packed, __aligned and __section */
76 #endif
77 #if __GNUC_PREREQ__(2, 7)
78 #define __unused __attribute__((__unused__))
79 #endif
80
81 #if __GNUC_PREREQ__(2, 96)
82 #define __predict_false(exp) __builtin_expect((exp), 0)
83 #else
84 #define __predict_false(exp) (exp)
85 #endif
86
87 __FBSDID("$FreeBSD$");
88
89 #include <errno.h>
90 #include <stdint.h>
91 #include <stdlib.h>
92 #include <string.h>
93 // #include "libc_private.h"
94
95 #if defined(I_AM_QSORT_R)
96 typedef int cmp_t(const void *, const void *, void *);
97 #elif defined(I_AM_QSORT_R_COMPAT)
98 typedef int cmp_t(void *, const void *, const void *);
99 #elif defined(I_AM_QSORT_S)
100 typedef int cmp_t(const void *, const void *, void *);
101 #else
102 typedef int cmp_t(const void *, const void *);
103 #endif
104 static inline char *med3(char *, char *, char *, cmp_t *, void *);
105
106 #define MIN(a, b) ((a) < (b) ? a : b)
107
108 /*
109 * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
110 */
111
112 static inline void
swapfunc(char * a,char * b,size_t es)113 swapfunc(char *a, char *b, size_t es)
114 {
115 char t;
116
117 do {
118 t = *a;
119 *a++ = *b;
120 *b++ = t;
121 } while (--es > 0);
122 }
123
124 #define vecswap(a, b, n) \
125 if ((n) > 0) swapfunc(a, b, n)
126
127 #if defined(I_AM_QSORT_R)
128 #define CMP(t, x, y) (cmp((x), (y), (t)))
129 #elif defined(I_AM_QSORT_R_COMPAT)
130 #define CMP(t, x, y) (cmp((t), (x), (y)))
131 #elif defined(I_AM_QSORT_S)
132 #define CMP(t, x, y) (cmp((x), (y), (t)))
133 #else
134 #define CMP(t, x, y) (cmp((x), (y)))
135 #endif
136
137 static inline char *
med3(char * a,char * b,char * c,cmp_t * cmp,void * thunk __unused)138 med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk
139 #if !defined(I_AM_QSORT_R) && !defined(I_AM_QSORT_R_COMPAT) && !defined(I_AM_QSORT_S)
140 __unused
141 #endif
142 )
143 {
144 return CMP(thunk, a, b) < 0 ?
145 (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a ))
146 :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c ));
147 }
148
149 /*
150 * The actual qsort() implementation is static to avoid preemptible calls when
151 * recursing. Also give them different names for improved debugging.
152 */
153 #if defined(I_AM_QSORT_R)
154 #define local_qsort local_qsort_r
155 #elif defined(I_AM_QSORT_R_COMPAT)
156 #define local_qsort local_qsort_r_compat
157 #elif defined(I_AM_QSORT_S)
158 #define local_qsort local_qsort_s
159 #endif
160 static void
local_qsort(void * a,size_t n,size_t es,cmp_t * cmp,void * thunk)161 local_qsort(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
162 {
163 char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
164 size_t d1, d2;
165 int cmp_result;
166 int swap_cnt;
167
168 /* if there are less than 2 elements, then sorting is not needed */
169 if (__predict_false(n < 2))
170 return;
171 loop:
172 swap_cnt = 0;
173 if (n < 7) {
174 for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
175 for (pl = pm;
176 pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
177 pl -= es)
178 swapfunc(pl, pl - es, es);
179 return;
180 }
181 pm = (char *)a + (n / 2) * es;
182 if (n > 7) {
183 pl = a;
184 pn = (char *)a + (n - 1) * es;
185 if (n > 40) {
186 size_t d = (n / 8) * es;
187
188 pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk);
189 pm = med3(pm - d, pm, pm + d, cmp, thunk);
190 pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk);
191 }
192 pm = med3(pl, pm, pn, cmp, thunk);
193 }
194 swapfunc(a, pm, es);
195 pa = pb = (char *)a + es;
196
197 pc = pd = (char *)a + (n - 1) * es;
198 for (;;) {
199 while (pb <= pc && (cmp_result = CMP(thunk, pb, a)) <= 0) {
200 if (cmp_result == 0) {
201 swap_cnt = 1;
202 swapfunc(pa, pb, es);
203 pa += es;
204 }
205 pb += es;
206 }
207 while (pb <= pc && (cmp_result = CMP(thunk, pc, a)) >= 0) {
208 if (cmp_result == 0) {
209 swap_cnt = 1;
210 swapfunc(pc, pd, es);
211 pd -= es;
212 }
213 pc -= es;
214 }
215 if (pb > pc)
216 break;
217 swapfunc(pb, pc, es);
218 swap_cnt = 1;
219 pb += es;
220 pc -= es;
221 }
222 if (swap_cnt == 0) { /* Switch to insertion sort */
223 for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
224 for (pl = pm;
225 pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
226 pl -= es)
227 swapfunc(pl, pl - es, es);
228 return;
229 }
230
231 pn = (char *)a + n * es;
232 d1 = MIN(pa - (char *)a, pb - pa);
233 vecswap(a, pb - d1, d1);
234 /*
235 * Cast es to preserve signedness of right-hand side of MIN()
236 * expression, to avoid sign ambiguity in the implied comparison. es
237 * is safely within [0, SSIZE_MAX].
238 */
239 d1 = MIN(pd - pc, pn - pd - es);
240 vecswap(pb, pn - d1, d1);
241
242 d1 = pb - pa;
243 d2 = pd - pc;
244 if (d1 <= d2) {
245 /* Recurse on left partition, then iterate on right partition */
246 if (d1 > es) {
247 local_qsort(a, d1 / es, es, cmp, thunk);
248 }
249 if (d2 > es) {
250 /* Iterate rather than recurse to save stack space */
251 /* qsort(pn - d2, d2 / es, es, cmp); */
252 a = pn - d2;
253 n = d2 / es;
254 goto loop;
255 }
256 } else {
257 /* Recurse on right partition, then iterate on left partition */
258 if (d2 > es) {
259 local_qsort(pn - d2, d2 / es, es, cmp, thunk);
260 }
261 if (d1 > es) {
262 /* Iterate rather than recurse to save stack space */
263 /* qsort(a, d1 / es, es, cmp); */
264 n = d1 / es;
265 goto loop;
266 }
267 }
268 }
269
270 #if defined(I_AM_QSORT_R)
271 void
272 (qsort_r)(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
273 {
274 local_qsort_r(a, n, es, cmp, thunk);
275 }
276 #elif defined(I_AM_QSORT_R_COMPAT)
277 void
__qsort_r_compat(void * a,size_t n,size_t es,void * thunk,cmp_t * cmp)278 __qsort_r_compat(void *a, size_t n, size_t es, void *thunk, cmp_t *cmp)
279 {
280 local_qsort_r_compat(a, n, es, cmp, thunk);
281 }
282 #elif defined(I_AM_QSORT_S)
283 errno_t
qsort_s(void * a,rsize_t n,rsize_t es,cmp_t * cmp,void * thunk)284 qsort_s(void *a, rsize_t n, rsize_t es, cmp_t *cmp, void *thunk)
285 {
286 if (n > RSIZE_MAX) {
287 __throw_constraint_handler_s("qsort_s : n > RSIZE_MAX", EINVAL);
288 return (EINVAL);
289 } else if (es > RSIZE_MAX) {
290 __throw_constraint_handler_s("qsort_s : es > RSIZE_MAX",
291 EINVAL);
292 return (EINVAL);
293 } else if (n != 0) {
294 if (a == NULL) {
295 __throw_constraint_handler_s("qsort_s : a == NULL",
296 EINVAL);
297 return (EINVAL);
298 } else if (cmp == NULL) {
299 __throw_constraint_handler_s("qsort_s : cmp == NULL",
300 EINVAL);
301 return (EINVAL);
302 } else if (es <= 0) {
303 __throw_constraint_handler_s("qsort_s : es <= 0",
304 EINVAL);
305 return (EINVAL);
306 }
307 }
308
309 local_qsort_s(a, n, es, cmp, thunk);
310 return (0);
311 }
312 #else
313 void
qsort(void * a,size_t n,size_t es,cmp_t * cmp)314 qsort(void *a, size_t n, size_t es, cmp_t *cmp)
315 {
316 local_qsort(a, n, es, cmp, NULL);
317 }
318 #endif