• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(void *, const void *, const void *);
97 #elif defined(I_AM_QSORT_S)
98 typedef int		 cmp_t(const void *, const void *, void *);
99 #else
100 typedef int		 cmp_t(const void *, const void *);
101 #endif
102 static inline char	*med3(char *, char *, char *, cmp_t *, void *);
103 
104 #define	MIN(a, b)	((a) < (b) ? a : b)
105 
106 /*
107  * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
108  */
109 
110 static inline void
swapfunc(char * a,char * b,size_t es)111 swapfunc(char *a, char *b, size_t es)
112 {
113 	char t;
114 
115 	do {
116 		t = *a;
117 		*a++ = *b;
118 		*b++ = t;
119 	} while (--es > 0);
120 }
121 
122 #define	vecswap(a, b, n)				\
123 	if ((n) > 0) swapfunc(a, b, n)
124 
125 #if defined(I_AM_QSORT_R)
126 #define	CMP(t, x, y) (cmp((t), (x), (y)))
127 #elif defined(I_AM_QSORT_S)
128 #define	CMP(t, x, y) (cmp((x), (y), (t)))
129 #else
130 #define	CMP(t, x, y) (cmp((x), (y)))
131 #endif
132 
133 static inline char *
med3(char * a,char * b,char * c,cmp_t * cmp,void * thunk __unused)134 med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk
135 #if !defined(I_AM_QSORT_R) && !defined(I_AM_QSORT_S)
136 __unused
137 #endif
138 )
139 {
140 	return CMP(thunk, a, b) < 0 ?
141 	       (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a ))
142 	      :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c ));
143 }
144 
145 /*
146  * The actual qsort() implementation is static to avoid preemptible calls when
147  * recursing. Also give them different names for improved debugging.
148  */
149 #if defined(I_AM_QSORT_R)
150 #define local_qsort local_qsort_r
151 #elif defined(I_AM_QSORT_S)
152 #define local_qsort local_qsort_s
153 #endif
154 static void
local_qsort(void * a,size_t n,size_t es,cmp_t * cmp,void * thunk)155 local_qsort(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
156 {
157 	char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
158 	size_t d1, d2;
159 	int cmp_result;
160 	int swap_cnt;
161 
162 	if (__predict_false(n == 0))
163 		return;
164 loop:
165 	swap_cnt = 0;
166 	if (n < 7) {
167 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
168 			for (pl = pm;
169 			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
170 			     pl -= es)
171 				swapfunc(pl, pl - es, es);
172 		return;
173 	}
174 	pm = (char *)a + (n / 2) * es;
175 	if (n > 7) {
176 		pl = a;
177 		pn = (char *)a + (n - 1) * es;
178 		if (n > 40) {
179 			size_t d = (n / 8) * es;
180 
181 			pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk);
182 			pm = med3(pm - d, pm, pm + d, cmp, thunk);
183 			pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk);
184 		}
185 		pm = med3(pl, pm, pn, cmp, thunk);
186 	}
187 	swapfunc(a, pm, es);
188 	pa = pb = (char *)a + es;
189 
190 	pc = pd = (char *)a + (n - 1) * es;
191 	for (;;) {
192 		while (pb <= pc && (cmp_result = CMP(thunk, pb, a)) <= 0) {
193 			if (cmp_result == 0) {
194 				swap_cnt = 1;
195 				swapfunc(pa, pb, es);
196 				pa += es;
197 			}
198 			pb += es;
199 		}
200 		while (pb <= pc && (cmp_result = CMP(thunk, pc, a)) >= 0) {
201 			if (cmp_result == 0) {
202 				swap_cnt = 1;
203 				swapfunc(pc, pd, es);
204 				pd -= es;
205 			}
206 			pc -= es;
207 		}
208 		if (pb > pc)
209 			break;
210 		swapfunc(pb, pc, es);
211 		swap_cnt = 1;
212 		pb += es;
213 		pc -= es;
214 	}
215 	if (swap_cnt == 0) {  /* Switch to insertion sort */
216 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
217 			for (pl = pm;
218 			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
219 			     pl -= es)
220 				swapfunc(pl, pl - es, es);
221 		return;
222 	}
223 
224 	pn = (char *)a + n * es;
225 	d1 = MIN(pa - (char *)a, pb - pa);
226 	vecswap(a, pb - d1, d1);
227 	d1 = MIN(pd - pc, pn - pd - es);
228 	vecswap(pb, pn - d1, d1);
229 
230 	d1 = pb - pa;
231 	d2 = pd - pc;
232 	if (d1 <= d2) {
233 		/* Recurse on left partition, then iterate on right partition */
234 		if (d1 > es) {
235 			local_qsort(a, d1 / es, es, cmp, thunk);
236 		}
237 		if (d2 > es) {
238 			/* Iterate rather than recurse to save stack space */
239 			/* qsort(pn - d2, d2 / es, es, cmp); */
240 			a = pn - d2;
241 			n = d2 / es;
242 			goto loop;
243 		}
244 	} else {
245 		/* Recurse on right partition, then iterate on left partition */
246 		if (d2 > es) {
247 			local_qsort(pn - d2, d2 / es, es, cmp, thunk);
248 		}
249 		if (d1 > es) {
250 			/* Iterate rather than recurse to save stack space */
251 			/* qsort(a, d1 / es, es, cmp); */
252 			n = d1 / es;
253 			goto loop;
254 		}
255 	}
256 }
257 
258 #if defined(I_AM_QSORT_R)
259 void
qsort_r(void * a,size_t n,size_t es,void * thunk,cmp_t * cmp)260 qsort_r(void *a, size_t n, size_t es, void *thunk, cmp_t *cmp)
261 {
262 	local_qsort_r(a, n, es, cmp, thunk);
263 }
264 #elif defined(I_AM_QSORT_S)
265 errno_t
qsort_s(void * a,rsize_t n,rsize_t es,cmp_t * cmp,void * thunk)266 qsort_s(void *a, rsize_t n, rsize_t es, cmp_t *cmp, void *thunk)
267 {
268 	if (n > RSIZE_MAX) {
269 		__throw_constraint_handler_s("qsort_s : n > RSIZE_MAX", EINVAL);
270 		return (EINVAL);
271 	} else if (es > RSIZE_MAX) {
272 		__throw_constraint_handler_s("qsort_s : es > RSIZE_MAX",
273 		    EINVAL);
274 		return (EINVAL);
275 	} else if (n != 0) {
276 		if (a == NULL) {
277 			__throw_constraint_handler_s("qsort_s : a == NULL",
278 			    EINVAL);
279 			return (EINVAL);
280 		} else if (cmp == NULL) {
281 			__throw_constraint_handler_s("qsort_s : cmp == NULL",
282 			    EINVAL);
283 			return (EINVAL);
284 		}
285 	}
286 
287 	local_qsort_s(a, n, es, cmp, thunk);
288 	return (0);
289 }
290 #else
291 void
qsort(void * a,size_t n,size_t es,cmp_t * cmp)292 qsort(void *a, size_t n, size_t es, cmp_t *cmp)
293 {
294 	local_qsort(a, n, es, cmp, NULL);
295 }
296 #endif