xref: /linux/tools/testing/selftests/nolibc/nolibc-test.c (revision 79997eda0d31bc68203c95ecb978773ee6ce7a1f)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 
3 #define _GNU_SOURCE
4 #define _LARGEFILE64_SOURCE
5 
6 /* libc-specific include files
7  * The program may be built in 3 ways:
8  *   $(CC) -nostdlib -include /path/to/nolibc.h => NOLIBC already defined
9  *   $(CC) -nostdlib -I/path/to/nolibc/sysroot  => _NOLIBC_* guards are present
10  *   $(CC) with default libc                    => NOLIBC* never defined
11  */
12 #ifndef NOLIBC
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #ifndef _NOLIBC_STDIO_H
17 /* standard libcs need more includes */
18 #include <sys/auxv.h>
19 #include <sys/io.h>
20 #include <sys/ioctl.h>
21 #include <sys/mman.h>
22 #include <sys/mount.h>
23 #include <sys/prctl.h>
24 #include <sys/reboot.h>
25 #include <sys/stat.h>
26 #include <sys/syscall.h>
27 #include <sys/sysmacros.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <dirent.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <poll.h>
34 #include <sched.h>
35 #include <signal.h>
36 #include <stdarg.h>
37 #include <stddef.h>
38 #include <stdint.h>
39 #include <unistd.h>
40 #include <limits.h>
41 #endif
42 #endif
43 
44 #include "nolibc-test-linkage.h"
45 
46 /* for the type of int_fast16_t and int_fast32_t, musl differs from glibc and nolibc */
47 #define SINT_MAX_OF_TYPE(type) (((type)1 << (sizeof(type) * 8 - 2)) - (type)1 + ((type)1 << (sizeof(type) * 8 - 2)))
48 #define SINT_MIN_OF_TYPE(type) (-SINT_MAX_OF_TYPE(type) - 1)
49 
50 /* will be used to test initialization of environ */
51 static char **test_envp;
52 
53 /* will be used to test initialization of argv */
54 static char **test_argv;
55 
56 /* will be used to test initialization of argc */
57 static int test_argc;
58 
59 /* will be used by some test cases as readable file, please don't write it */
60 static const char *argv0;
61 
62 /* will be used by constructor tests */
63 static int constructor_test_value;
64 
65 /* definition of a series of tests */
66 struct test {
67 	const char *name;              /* test name */
68 	int (*func)(int min, int max); /* handler */
69 };
70 
71 #ifndef _NOLIBC_STDLIB_H
72 char *itoa(int i)
73 {
74 	static char buf[12];
75 	int ret;
76 
77 	ret = snprintf(buf, sizeof(buf), "%d", i);
78 	return (ret >= 0 && ret < sizeof(buf)) ? buf : "#err";
79 }
80 #endif
81 
82 #define CASE_ERR(err) \
83 	case err: return #err
84 
85 /* returns the error name (e.g. "ENOENT") for common errors, "SUCCESS" for 0,
86  * or the decimal value for less common ones.
87  */
88 static const char *errorname(int err)
89 {
90 	switch (err) {
91 	case 0: return "SUCCESS";
92 	CASE_ERR(EPERM);
93 	CASE_ERR(ENOENT);
94 	CASE_ERR(ESRCH);
95 	CASE_ERR(EINTR);
96 	CASE_ERR(EIO);
97 	CASE_ERR(ENXIO);
98 	CASE_ERR(E2BIG);
99 	CASE_ERR(ENOEXEC);
100 	CASE_ERR(EBADF);
101 	CASE_ERR(ECHILD);
102 	CASE_ERR(EAGAIN);
103 	CASE_ERR(ENOMEM);
104 	CASE_ERR(EACCES);
105 	CASE_ERR(EFAULT);
106 	CASE_ERR(ENOTBLK);
107 	CASE_ERR(EBUSY);
108 	CASE_ERR(EEXIST);
109 	CASE_ERR(EXDEV);
110 	CASE_ERR(ENODEV);
111 	CASE_ERR(ENOTDIR);
112 	CASE_ERR(EISDIR);
113 	CASE_ERR(EINVAL);
114 	CASE_ERR(ENFILE);
115 	CASE_ERR(EMFILE);
116 	CASE_ERR(ENOTTY);
117 	CASE_ERR(ETXTBSY);
118 	CASE_ERR(EFBIG);
119 	CASE_ERR(ENOSPC);
120 	CASE_ERR(ESPIPE);
121 	CASE_ERR(EROFS);
122 	CASE_ERR(EMLINK);
123 	CASE_ERR(EPIPE);
124 	CASE_ERR(EDOM);
125 	CASE_ERR(ERANGE);
126 	CASE_ERR(ENOSYS);
127 	CASE_ERR(EOVERFLOW);
128 	default:
129 		return itoa(err);
130 	}
131 }
132 
133 static void putcharn(char c, size_t n)
134 {
135 	char buf[64];
136 
137 	memset(buf, c, n);
138 	buf[n] = '\0';
139 	fputs(buf, stdout);
140 }
141 
142 enum RESULT {
143 	OK,
144 	FAIL,
145 	SKIPPED,
146 };
147 
148 static void result(int llen, enum RESULT r)
149 {
150 	const char *msg;
151 
152 	if (r == OK)
153 		msg = " [OK]";
154 	else if (r == SKIPPED)
155 		msg = "[SKIPPED]";
156 	else
157 		msg = "[FAIL]";
158 
159 	if (llen < 64)
160 		putcharn(' ', 64 - llen);
161 	puts(msg);
162 }
163 
164 /* The tests below are intended to be used by the macroes, which evaluate
165  * expression <expr>, print the status to stdout, and update the "ret"
166  * variable to count failures. The functions themselves return the number
167  * of failures, thus either 0 or 1.
168  */
169 
170 #define EXPECT_ZR(cond, expr)				\
171 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_zr(expr, llen); } while (0)
172 
173 static __attribute__((unused))
174 int expect_zr(int expr, int llen)
175 {
176 	int ret = !(expr == 0);
177 
178 	llen += printf(" = %d ", expr);
179 	result(llen, ret ? FAIL : OK);
180 	return ret;
181 }
182 
183 
184 #define EXPECT_NZ(cond, expr, val)			\
185 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_nz(expr, llen; } while (0)
186 
187 static __attribute__((unused))
188 int expect_nz(int expr, int llen)
189 {
190 	int ret = !(expr != 0);
191 
192 	llen += printf(" = %d ", expr);
193 	result(llen, ret ? FAIL : OK);
194 	return ret;
195 }
196 
197 
198 #define EXPECT_EQ(cond, expr, val)				\
199 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_eq(expr, llen, val); } while (0)
200 
201 static __attribute__((unused))
202 int expect_eq(uint64_t expr, int llen, uint64_t val)
203 {
204 	int ret = !(expr == val);
205 
206 	llen += printf(" = %lld ", (long long)expr);
207 	result(llen, ret ? FAIL : OK);
208 	return ret;
209 }
210 
211 
212 #define EXPECT_NE(cond, expr, val)				\
213 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ne(expr, llen, val); } while (0)
214 
215 static __attribute__((unused))
216 int expect_ne(int expr, int llen, int val)
217 {
218 	int ret = !(expr != val);
219 
220 	llen += printf(" = %d ", expr);
221 	result(llen, ret ? FAIL : OK);
222 	return ret;
223 }
224 
225 
226 #define EXPECT_GE(cond, expr, val)				\
227 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ge(expr, llen, val); } while (0)
228 
229 static __attribute__((unused))
230 int expect_ge(int expr, int llen, int val)
231 {
232 	int ret = !(expr >= val);
233 
234 	llen += printf(" = %d ", expr);
235 	result(llen, ret ? FAIL : OK);
236 	return ret;
237 }
238 
239 
240 #define EXPECT_GT(cond, expr, val)				\
241 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_gt(expr, llen, val); } while (0)
242 
243 static __attribute__((unused))
244 int expect_gt(int expr, int llen, int val)
245 {
246 	int ret = !(expr > val);
247 
248 	llen += printf(" = %d ", expr);
249 	result(llen, ret ? FAIL : OK);
250 	return ret;
251 }
252 
253 
254 #define EXPECT_LE(cond, expr, val)				\
255 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_le(expr, llen, val); } while (0)
256 
257 static __attribute__((unused))
258 int expect_le(int expr, int llen, int val)
259 {
260 	int ret = !(expr <= val);
261 
262 	llen += printf(" = %d ", expr);
263 	result(llen, ret ? FAIL : OK);
264 	return ret;
265 }
266 
267 
268 #define EXPECT_LT(cond, expr, val)				\
269 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_lt(expr, llen, val); } while (0)
270 
271 static __attribute__((unused))
272 int expect_lt(int expr, int llen, int val)
273 {
274 	int ret = !(expr < val);
275 
276 	llen += printf(" = %d ", expr);
277 	result(llen, ret ? FAIL : OK);
278 	return ret;
279 }
280 
281 
282 #define EXPECT_SYSZR(cond, expr)				\
283 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_syszr(expr, llen); } while (0)
284 
285 static __attribute__((unused))
286 int expect_syszr(int expr, int llen)
287 {
288 	int ret = 0;
289 
290 	if (expr) {
291 		ret = 1;
292 		llen += printf(" = %d %s ", expr, errorname(errno));
293 		result(llen, FAIL);
294 	} else {
295 		llen += printf(" = %d ", expr);
296 		result(llen, OK);
297 	}
298 	return ret;
299 }
300 
301 
302 #define EXPECT_SYSEQ(cond, expr, val)				\
303 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_syseq(expr, llen, val); } while (0)
304 
305 static __attribute__((unused))
306 int expect_syseq(int expr, int llen, int val)
307 {
308 	int ret = 0;
309 
310 	if (expr != val) {
311 		ret = 1;
312 		llen += printf(" = %d %s ", expr, errorname(errno));
313 		result(llen, FAIL);
314 	} else {
315 		llen += printf(" = %d ", expr);
316 		result(llen, OK);
317 	}
318 	return ret;
319 }
320 
321 
322 #define EXPECT_SYSNE(cond, expr, val)				\
323 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_sysne(expr, llen, val); } while (0)
324 
325 static __attribute__((unused))
326 int expect_sysne(int expr, int llen, int val)
327 {
328 	int ret = 0;
329 
330 	if (expr == val) {
331 		ret = 1;
332 		llen += printf(" = %d %s ", expr, errorname(errno));
333 		result(llen, FAIL);
334 	} else {
335 		llen += printf(" = %d ", expr);
336 		result(llen, OK);
337 	}
338 	return ret;
339 }
340 
341 
342 #define EXPECT_SYSER2(cond, expr, expret, experr1, experr2)		\
343 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_syserr2(expr, expret, experr1, experr2, llen); } while (0)
344 
345 #define EXPECT_SYSER(cond, expr, expret, experr)			\
346 	EXPECT_SYSER2(cond, expr, expret, experr, 0)
347 
348 static __attribute__((unused))
349 int expect_syserr2(int expr, int expret, int experr1, int experr2, int llen)
350 {
351 	int ret = 0;
352 	int _errno = errno;
353 
354 	llen += printf(" = %d %s ", expr, errorname(_errno));
355 	if (expr != expret || (_errno != experr1 && _errno != experr2)) {
356 		ret = 1;
357 		if (experr2 == 0)
358 			llen += printf(" != (%d %s) ", expret, errorname(experr1));
359 		else
360 			llen += printf(" != (%d %s %s) ", expret, errorname(experr1), errorname(experr2));
361 		result(llen, FAIL);
362 	} else {
363 		result(llen, OK);
364 	}
365 	return ret;
366 }
367 
368 
369 #define EXPECT_PTRZR(cond, expr)				\
370 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrzr(expr, llen); } while (0)
371 
372 static __attribute__((unused))
373 int expect_ptrzr(const void *expr, int llen)
374 {
375 	int ret = 0;
376 
377 	llen += printf(" = <%p> ", expr);
378 	if (expr) {
379 		ret = 1;
380 		result(llen, FAIL);
381 	} else {
382 		result(llen, OK);
383 	}
384 	return ret;
385 }
386 
387 
388 #define EXPECT_PTRNZ(cond, expr)				\
389 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrnz(expr, llen); } while (0)
390 
391 static __attribute__((unused))
392 int expect_ptrnz(const void *expr, int llen)
393 {
394 	int ret = 0;
395 
396 	llen += printf(" = <%p> ", expr);
397 	if (!expr) {
398 		ret = 1;
399 		result(llen, FAIL);
400 	} else {
401 		result(llen, OK);
402 	}
403 	return ret;
404 }
405 
406 #define EXPECT_PTREQ(cond, expr, cmp)				\
407 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptreq(expr, llen, cmp); } while (0)
408 
409 static __attribute__((unused))
410 int expect_ptreq(const void *expr, int llen, const void *cmp)
411 {
412 	int ret = 0;
413 
414 	llen += printf(" = <%p> ", expr);
415 	if (expr != cmp) {
416 		ret = 1;
417 		result(llen, FAIL);
418 	} else {
419 		result(llen, OK);
420 	}
421 	return ret;
422 }
423 
424 #define EXPECT_PTRNE(cond, expr, cmp)				\
425 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrne(expr, llen, cmp); } while (0)
426 
427 static __attribute__((unused))
428 int expect_ptrne(const void *expr, int llen, const void *cmp)
429 {
430 	int ret = 0;
431 
432 	llen += printf(" = <%p> ", expr);
433 	if (expr == cmp) {
434 		ret = 1;
435 		result(llen, FAIL);
436 	} else {
437 		result(llen, OK);
438 	}
439 	return ret;
440 }
441 
442 #define EXPECT_PTRGE(cond, expr, cmp)				\
443 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrge(expr, llen, cmp); } while (0)
444 
445 static __attribute__((unused))
446 int expect_ptrge(const void *expr, int llen, const void *cmp)
447 {
448 	int ret = !(expr >= cmp);
449 
450 	llen += printf(" = <%p> ", expr);
451 	result(llen, ret ? FAIL : OK);
452 	return ret;
453 }
454 
455 #define EXPECT_PTRGT(cond, expr, cmp)				\
456 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrgt(expr, llen, cmp); } while (0)
457 
458 static __attribute__((unused))
459 int expect_ptrgt(const void *expr, int llen, const void *cmp)
460 {
461 	int ret = !(expr > cmp);
462 
463 	llen += printf(" = <%p> ", expr);
464 	result(llen, ret ? FAIL : OK);
465 	return ret;
466 }
467 
468 
469 #define EXPECT_PTRLE(cond, expr, cmp)				\
470 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrle(expr, llen, cmp); } while (0)
471 
472 static __attribute__((unused))
473 int expect_ptrle(const void *expr, int llen, const void *cmp)
474 {
475 	int ret = !(expr <= cmp);
476 
477 	llen += printf(" = <%p> ", expr);
478 	result(llen, ret ? FAIL : OK);
479 	return ret;
480 }
481 
482 
483 #define EXPECT_PTRLT(cond, expr, cmp)				\
484 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrlt(expr, llen, cmp); } while (0)
485 
486 static __attribute__((unused))
487 int expect_ptrlt(const void *expr, int llen, const void *cmp)
488 {
489 	int ret = !(expr < cmp);
490 
491 	llen += printf(" = <%p> ", expr);
492 	result(llen, ret ? FAIL : OK);
493 	return ret;
494 }
495 
496 #define EXPECT_PTRER2(cond, expr, expret, experr1, experr2)		\
497 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_ptrerr2(expr, expret, experr1, experr2, llen); } while (0)
498 
499 #define EXPECT_PTRER(cond, expr, expret, experr)			\
500 	EXPECT_PTRER2(cond, expr, expret, experr, 0)
501 
502 static __attribute__((unused))
503 int expect_ptrerr2(const void *expr, const void *expret, int experr1, int experr2, int llen)
504 {
505 	int ret = 0;
506 	int _errno = errno;
507 
508 	llen += printf(" = <%p> %s ", expr, errorname(_errno));
509 	if (expr != expret || (_errno != experr1 && _errno != experr2)) {
510 		ret = 1;
511 		if (experr2 == 0)
512 			llen += printf(" != (<%p> %s) ", expret, errorname(experr1));
513 		else
514 			llen += printf(" != (<%p> %s %s) ", expret, errorname(experr1), errorname(experr2));
515 		result(llen, FAIL);
516 	} else {
517 		result(llen, OK);
518 	}
519 	return ret;
520 }
521 
522 #define EXPECT_STRZR(cond, expr)				\
523 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_strzr(expr, llen); } while (0)
524 
525 static __attribute__((unused))
526 int expect_strzr(const char *expr, int llen)
527 {
528 	int ret = 0;
529 
530 	llen += printf(" = <%s> ", expr);
531 	if (expr) {
532 		ret = 1;
533 		result(llen, FAIL);
534 	} else {
535 		result(llen, OK);
536 	}
537 	return ret;
538 }
539 
540 
541 #define EXPECT_STRNZ(cond, expr)				\
542 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_strnz(expr, llen); } while (0)
543 
544 static __attribute__((unused))
545 int expect_strnz(const char *expr, int llen)
546 {
547 	int ret = 0;
548 
549 	llen += printf(" = <%s> ", expr);
550 	if (!expr) {
551 		ret = 1;
552 		result(llen, FAIL);
553 	} else {
554 		result(llen, OK);
555 	}
556 	return ret;
557 }
558 
559 
560 #define EXPECT_STREQ(cond, expr, cmp)				\
561 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_streq(expr, llen, cmp); } while (0)
562 
563 static __attribute__((unused))
564 int expect_streq(const char *expr, int llen, const char *cmp)
565 {
566 	int ret = 0;
567 
568 	llen += printf(" = <%s> ", expr);
569 	if (strcmp(expr, cmp) != 0) {
570 		ret = 1;
571 		result(llen, FAIL);
572 	} else {
573 		result(llen, OK);
574 	}
575 	return ret;
576 }
577 
578 
579 #define EXPECT_STRNE(cond, expr, cmp)				\
580 	do { if (!(cond)) result(llen, SKIPPED); else ret += expect_strne(expr, llen, cmp); } while (0)
581 
582 static __attribute__((unused))
583 int expect_strne(const char *expr, int llen, const char *cmp)
584 {
585 	int ret = 0;
586 
587 	llen += printf(" = <%s> ", expr);
588 	if (strcmp(expr, cmp) == 0) {
589 		ret = 1;
590 		result(llen, FAIL);
591 	} else {
592 		result(llen, OK);
593 	}
594 	return ret;
595 }
596 
597 
598 /* declare tests based on line numbers. There must be exactly one test per line. */
599 #define CASE_TEST(name) \
600 	case __LINE__: llen += printf("%d %s", test, #name);
601 
602 /* constructors validate that they are executed in definition order */
603 __attribute__((constructor))
604 static void constructor1(void)
605 {
606 	constructor_test_value = 1;
607 }
608 
609 __attribute__((constructor))
610 static void constructor2(void)
611 {
612 	constructor_test_value *= 2;
613 }
614 
615 int run_startup(int min, int max)
616 {
617 	int test;
618 	int ret = 0;
619 	/* kernel at least passes HOME and TERM, shell passes more */
620 	int env_total = 2;
621 	/* checking NULL for argv/argv0, environ and _auxv is not enough, let's compare with sbrk(0) or &end */
622 	extern char end;
623 	char *brk = sbrk(0) != (void *)-1 ? sbrk(0) : &end;
624 	/* differ from nolibc, both glibc and musl have no global _auxv */
625 	const unsigned long *test_auxv = (void *)-1;
626 #ifdef NOLIBC
627 	test_auxv = _auxv;
628 #endif
629 
630 	for (test = min; test >= 0 && test <= max; test++) {
631 		int llen = 0; /* line length */
632 
633 		/* avoid leaving empty lines below, this will insert holes into
634 		 * test numbers.
635 		 */
636 		switch (test + __LINE__ + 1) {
637 		CASE_TEST(argc);             EXPECT_GE(1, test_argc, 1); break;
638 		CASE_TEST(argv_addr);        EXPECT_PTRGT(1, test_argv, brk); break;
639 		CASE_TEST(argv_environ);     EXPECT_PTRLT(1, test_argv, environ); break;
640 		CASE_TEST(argv_total);       EXPECT_EQ(1, environ - test_argv - 1, test_argc ?: 1); break;
641 		CASE_TEST(argv0_addr);       EXPECT_PTRGT(1, argv0, brk); break;
642 		CASE_TEST(argv0_str);        EXPECT_STRNZ(1, argv0 > brk ? argv0 : NULL); break;
643 		CASE_TEST(argv0_len);        EXPECT_GE(1,  argv0 > brk ? strlen(argv0) : 0, 1); break;
644 		CASE_TEST(environ_addr);     EXPECT_PTRGT(1, environ, brk); break;
645 		CASE_TEST(environ_envp);     EXPECT_PTREQ(1, environ, test_envp); break;
646 		CASE_TEST(environ_auxv);     EXPECT_PTRLT(test_auxv != (void *)-1, environ, test_auxv); break;
647 		CASE_TEST(environ_total);    EXPECT_GE(test_auxv != (void *)-1, (void *)test_auxv - (void *)environ - 1, env_total); break;
648 		CASE_TEST(environ_HOME);     EXPECT_PTRNZ(1, getenv("HOME")); break;
649 		CASE_TEST(auxv_addr);        EXPECT_PTRGT(test_auxv != (void *)-1, test_auxv, brk); break;
650 		CASE_TEST(auxv_AT_UID);      EXPECT_EQ(1, getauxval(AT_UID), getuid()); break;
651 		CASE_TEST(constructor);      EXPECT_EQ(1, constructor_test_value, 2); break;
652 		CASE_TEST(linkage_errno);    EXPECT_PTREQ(1, linkage_test_errno_addr(), &errno); break;
653 		CASE_TEST(linkage_constr);   EXPECT_EQ(1, linkage_test_constructor_test_value, 6); break;
654 		case __LINE__:
655 			return ret; /* must be last */
656 		/* note: do not set any defaults so as to permit holes above */
657 		}
658 	}
659 	return ret;
660 }
661 
662 
663 /* used by some syscall tests below */
664 int test_getdents64(const char *dir)
665 {
666 	char buffer[4096];
667 	int fd, ret;
668 	int err;
669 
670 	ret = fd = open(dir, O_RDONLY | O_DIRECTORY, 0);
671 	if (ret < 0)
672 		return ret;
673 
674 	ret = getdents64(fd, (void *)buffer, sizeof(buffer));
675 	err = errno;
676 	close(fd);
677 
678 	errno = err;
679 	return ret;
680 }
681 
682 int test_getpagesize(void)
683 {
684 	int x = getpagesize();
685 	int c;
686 
687 	if (x < 0)
688 		return x;
689 
690 #if defined(__x86_64__) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__)
691 	/*
692 	 * x86 family is always 4K page.
693 	 */
694 	c = (x == 4096);
695 #elif defined(__aarch64__)
696 	/*
697 	 * Linux aarch64 supports three values of page size: 4K, 16K, and 64K
698 	 * which are selected at kernel compilation time.
699 	 */
700 	c = (x == 4096 || x == (16 * 1024) || x == (64 * 1024));
701 #else
702 	/*
703 	 * Assuming other architectures must have at least 4K page.
704 	 */
705 	c = (x >= 4096);
706 #endif
707 
708 	return !c;
709 }
710 
711 int test_fork(void)
712 {
713 	int status;
714 	pid_t pid;
715 
716 	/* flush the printf buffer to avoid child flush it */
717 	fflush(stdout);
718 	fflush(stderr);
719 
720 	pid = fork();
721 
722 	switch (pid) {
723 	case -1:
724 		return 1;
725 
726 	case 0:
727 		exit(123);
728 
729 	default:
730 		pid = waitpid(pid, &status, 0);
731 
732 		return pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 123;
733 	}
734 }
735 
736 int test_stat_timestamps(void)
737 {
738 	struct stat st;
739 
740 	if (sizeof(st.st_atim.tv_sec) != sizeof(st.st_atime))
741 		return 1;
742 
743 	if (stat("/proc/self/", &st) && stat(argv0, &st) && stat("/", &st))
744 		return 1;
745 
746 	if (st.st_atim.tv_sec != st.st_atime || st.st_atim.tv_nsec > 1000000000)
747 		return 1;
748 
749 	if (st.st_mtim.tv_sec != st.st_mtime || st.st_mtim.tv_nsec > 1000000000)
750 		return 1;
751 
752 	if (st.st_ctim.tv_sec != st.st_ctime || st.st_ctim.tv_nsec > 1000000000)
753 		return 1;
754 
755 	return 0;
756 }
757 
758 int test_mmap_munmap(void)
759 {
760 	int ret, fd, i, page_size;
761 	void *mem;
762 	size_t file_size, length;
763 	off_t offset, pa_offset;
764 	struct stat stat_buf;
765 	const char * const files[] = {
766 		"/dev/zero",
767 		"/proc/1/exe", "/proc/self/exe",
768 		argv0,
769 		NULL
770 	};
771 
772 	page_size = getpagesize();
773 	if (page_size < 0)
774 		return 1;
775 
776 	/* find a right file to mmap, existed and accessible */
777 	for (i = 0; files[i] != NULL; i++) {
778 		ret = fd = open(files[i], O_RDONLY);
779 		if (ret == -1)
780 			continue;
781 		else
782 			break;
783 	}
784 	if (ret == -1)
785 		return 1;
786 
787 	ret = stat(files[i], &stat_buf);
788 	if (ret == -1)
789 		goto end;
790 
791 	/* file size of the special /dev/zero is 0, let's assign one manually */
792 	if (i == 0)
793 		file_size = 3*page_size;
794 	else
795 		file_size = stat_buf.st_size;
796 
797 	offset = file_size - 1;
798 	if (offset < 0)
799 		offset = 0;
800 	length = file_size - offset;
801 	pa_offset = offset & ~(page_size - 1);
802 
803 	mem = mmap(NULL, length + offset - pa_offset, PROT_READ, MAP_SHARED, fd, pa_offset);
804 	if (mem == MAP_FAILED) {
805 		ret = 1;
806 		goto end;
807 	}
808 
809 	ret = munmap(mem, length + offset - pa_offset);
810 
811 end:
812 	close(fd);
813 	return !!ret;
814 }
815 
816 int test_pipe(void)
817 {
818 	const char *const msg = "hello, nolibc";
819 	int pipefd[2];
820 	char buf[32];
821 	size_t len;
822 
823 	if (pipe(pipefd) == -1)
824 		return 1;
825 
826 	write(pipefd[1], msg, strlen(msg));
827 	close(pipefd[1]);
828 	len = read(pipefd[0], buf, sizeof(buf));
829 	close(pipefd[0]);
830 
831 	if (len != strlen(msg))
832 		return 1;
833 
834 	return !!memcmp(buf, msg, len);
835 }
836 
837 
838 /* Run syscall tests between IDs <min> and <max>.
839  * Return 0 on success, non-zero on failure.
840  */
841 int run_syscall(int min, int max)
842 {
843 	struct timeval tv;
844 	struct timezone tz;
845 	struct stat stat_buf;
846 	int euid0;
847 	int proc;
848 	int test;
849 	int tmp;
850 	int ret = 0;
851 	void *p1, *p2;
852 	int has_gettid = 1;
853 
854 	/* <proc> indicates whether or not /proc is mounted */
855 	proc = stat("/proc", &stat_buf) == 0;
856 
857 	/* this will be used to skip certain tests that can't be run unprivileged */
858 	euid0 = geteuid() == 0;
859 
860 	/* from 2.30, glibc provides gettid() */
861 #if defined(__GLIBC_MINOR__) && defined(__GLIBC__)
862 	has_gettid = __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 30);
863 #endif
864 
865 	for (test = min; test >= 0 && test <= max; test++) {
866 		int llen = 0; /* line length */
867 
868 		/* avoid leaving empty lines below, this will insert holes into
869 		 * test numbers.
870 		 */
871 		switch (test + __LINE__ + 1) {
872 		CASE_TEST(getpid);            EXPECT_SYSNE(1, getpid(), -1); break;
873 		CASE_TEST(getppid);           EXPECT_SYSNE(1, getppid(), -1); break;
874 		CASE_TEST(gettid);            EXPECT_SYSNE(has_gettid, gettid(), -1); break;
875 		CASE_TEST(getpgid_self);      EXPECT_SYSNE(1, getpgid(0), -1); break;
876 		CASE_TEST(getpgid_bad);       EXPECT_SYSER(1, getpgid(-1), -1, ESRCH); break;
877 		CASE_TEST(kill_0);            EXPECT_SYSZR(1, kill(getpid(), 0)); break;
878 		CASE_TEST(kill_CONT);         EXPECT_SYSZR(1, kill(getpid(), 0)); break;
879 		CASE_TEST(kill_BADPID);       EXPECT_SYSER(1, kill(INT_MAX, 0), -1, ESRCH); break;
880 		CASE_TEST(sbrk_0);            EXPECT_PTRNE(1, sbrk(0), (void *)-1); break;
881 		CASE_TEST(sbrk);              if ((p1 = p2 = sbrk(4096)) != (void *)-1) p2 = sbrk(-4096); EXPECT_SYSZR(1, (p2 == (void *)-1) || p2 == p1); break;
882 		CASE_TEST(brk);               EXPECT_SYSZR(1, brk(sbrk(0))); break;
883 		CASE_TEST(chdir_root);        EXPECT_SYSZR(1, chdir("/")); chdir(getenv("PWD")); break;
884 		CASE_TEST(chdir_dot);         EXPECT_SYSZR(1, chdir(".")); break;
885 		CASE_TEST(chdir_blah);        EXPECT_SYSER(1, chdir("/blah"), -1, ENOENT); break;
886 		CASE_TEST(chmod_argv0);       EXPECT_SYSZR(1, chmod(argv0, 0555)); break;
887 		CASE_TEST(chmod_self);        EXPECT_SYSER(proc, chmod("/proc/self", 0555), -1, EPERM); break;
888 		CASE_TEST(chown_self);        EXPECT_SYSER(proc, chown("/proc/self", 0, 0), -1, EPERM); break;
889 		CASE_TEST(chroot_root);       EXPECT_SYSZR(euid0, chroot("/")); break;
890 		CASE_TEST(chroot_blah);       EXPECT_SYSER(1, chroot("/proc/self/blah"), -1, ENOENT); break;
891 		CASE_TEST(chroot_exe);        EXPECT_SYSER(1, chroot(argv0), -1, ENOTDIR); break;
892 		CASE_TEST(close_m1);          EXPECT_SYSER(1, close(-1), -1, EBADF); break;
893 		CASE_TEST(close_dup);         EXPECT_SYSZR(1, close(dup(0))); break;
894 		CASE_TEST(dup_0);             tmp = dup(0);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
895 		CASE_TEST(dup_m1);            tmp = dup(-1); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
896 		CASE_TEST(dup2_0);            tmp = dup2(0, 100);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
897 		CASE_TEST(dup2_m1);           tmp = dup2(-1, 100); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
898 		CASE_TEST(dup3_0);            tmp = dup3(0, 100, 0);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
899 		CASE_TEST(dup3_m1);           tmp = dup3(-1, 100, 0); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
900 		CASE_TEST(execve_root);       EXPECT_SYSER(1, execve("/", (char*[]){ [0] = "/", [1] = NULL }, NULL), -1, EACCES); break;
901 		CASE_TEST(fork);              EXPECT_SYSZR(1, test_fork()); break;
902 		CASE_TEST(getdents64_root);   EXPECT_SYSNE(1, test_getdents64("/"), -1); break;
903 		CASE_TEST(getdents64_null);   EXPECT_SYSER(1, test_getdents64("/dev/null"), -1, ENOTDIR); break;
904 		CASE_TEST(gettimeofday_tv);   EXPECT_SYSZR(1, gettimeofday(&tv, NULL)); break;
905 		CASE_TEST(gettimeofday_tv_tz);EXPECT_SYSZR(1, gettimeofday(&tv, &tz)); break;
906 		CASE_TEST(getpagesize);       EXPECT_SYSZR(1, test_getpagesize()); break;
907 		CASE_TEST(ioctl_tiocinq);     EXPECT_SYSZR(1, ioctl(0, TIOCINQ, &tmp)); break;
908 		CASE_TEST(ioctl_tiocinq);     EXPECT_SYSZR(1, ioctl(0, TIOCINQ, &tmp)); break;
909 		CASE_TEST(link_root1);        EXPECT_SYSER(1, link("/", "/"), -1, EEXIST); break;
910 		CASE_TEST(link_blah);         EXPECT_SYSER(1, link("/proc/self/blah", "/blah"), -1, ENOENT); break;
911 		CASE_TEST(link_dir);          EXPECT_SYSER(euid0, link("/", "/blah"), -1, EPERM); break;
912 		CASE_TEST(link_cross);        EXPECT_SYSER(proc, link("/proc/self/cmdline", "/blah"), -1, EXDEV); break;
913 		CASE_TEST(lseek_m1);          EXPECT_SYSER(1, lseek(-1, 0, SEEK_SET), -1, EBADF); break;
914 		CASE_TEST(lseek_0);           EXPECT_SYSER(1, lseek(0, 0, SEEK_SET), -1, ESPIPE); break;
915 		CASE_TEST(mkdir_root);        EXPECT_SYSER(1, mkdir("/", 0755), -1, EEXIST); break;
916 		CASE_TEST(mmap_bad);          EXPECT_PTRER(1, mmap(NULL, 0, PROT_READ, MAP_PRIVATE, 0, 0), MAP_FAILED, EINVAL); break;
917 		CASE_TEST(munmap_bad);        EXPECT_SYSER(1, munmap(NULL, 0), -1, EINVAL); break;
918 		CASE_TEST(mmap_munmap_good);  EXPECT_SYSZR(1, test_mmap_munmap()); break;
919 		CASE_TEST(open_tty);          EXPECT_SYSNE(1, tmp = open("/dev/null", 0), -1); if (tmp != -1) close(tmp); break;
920 		CASE_TEST(open_blah);         EXPECT_SYSER(1, tmp = open("/proc/self/blah", 0), -1, ENOENT); if (tmp != -1) close(tmp); break;
921 		CASE_TEST(pipe);              EXPECT_SYSZR(1, test_pipe()); break;
922 		CASE_TEST(poll_null);         EXPECT_SYSZR(1, poll(NULL, 0, 0)); break;
923 		CASE_TEST(poll_stdout);       EXPECT_SYSNE(1, ({ struct pollfd fds = { 1, POLLOUT, 0}; poll(&fds, 1, 0); }), -1); break;
924 		CASE_TEST(poll_fault);        EXPECT_SYSER(1, poll(NULL, 1, 0), -1, EFAULT); break;
925 		CASE_TEST(prctl);             EXPECT_SYSER(1, prctl(PR_SET_NAME, (unsigned long)NULL, 0, 0, 0), -1, EFAULT); break;
926 		CASE_TEST(read_badf);         EXPECT_SYSER(1, read(-1, &tmp, 1), -1, EBADF); break;
927 		CASE_TEST(rmdir_blah);        EXPECT_SYSER(1, rmdir("/blah"), -1, ENOENT); break;
928 		CASE_TEST(sched_yield);       EXPECT_SYSZR(1, sched_yield()); break;
929 		CASE_TEST(select_null);       EXPECT_SYSZR(1, ({ struct timeval tv = { 0 }; select(0, NULL, NULL, NULL, &tv); })); break;
930 		CASE_TEST(select_stdout);     EXPECT_SYSNE(1, ({ fd_set fds; FD_ZERO(&fds); FD_SET(1, &fds); select(2, NULL, &fds, NULL, NULL); }), -1); break;
931 		CASE_TEST(select_fault);      EXPECT_SYSER(1, select(1, (void *)1, NULL, NULL, 0), -1, EFAULT); break;
932 		CASE_TEST(stat_blah);         EXPECT_SYSER(1, stat("/proc/self/blah", &stat_buf), -1, ENOENT); break;
933 		CASE_TEST(stat_fault);        EXPECT_SYSER(1, stat(NULL, &stat_buf), -1, EFAULT); break;
934 		CASE_TEST(stat_timestamps);   EXPECT_SYSZR(1, test_stat_timestamps()); break;
935 		CASE_TEST(symlink_root);      EXPECT_SYSER(1, symlink("/", "/"), -1, EEXIST); break;
936 		CASE_TEST(unlink_root);       EXPECT_SYSER(1, unlink("/"), -1, EISDIR); break;
937 		CASE_TEST(unlink_blah);       EXPECT_SYSER(1, unlink("/proc/self/blah"), -1, ENOENT); break;
938 		CASE_TEST(wait_child);        EXPECT_SYSER(1, wait(&tmp), -1, ECHILD); break;
939 		CASE_TEST(waitpid_min);       EXPECT_SYSER(1, waitpid(INT_MIN, &tmp, WNOHANG), -1, ESRCH); break;
940 		CASE_TEST(waitpid_child);     EXPECT_SYSER(1, waitpid(getpid(), &tmp, WNOHANG), -1, ECHILD); break;
941 		CASE_TEST(write_badf);        EXPECT_SYSER(1, write(-1, &tmp, 1), -1, EBADF); break;
942 		CASE_TEST(write_zero);        EXPECT_SYSZR(1, write(1, &tmp, 0)); break;
943 		CASE_TEST(syscall_noargs);    EXPECT_SYSEQ(1, syscall(__NR_getpid), getpid()); break;
944 		CASE_TEST(syscall_args);      EXPECT_SYSER(1, syscall(__NR_statx, 0, NULL, 0, 0, NULL), -1, EFAULT); break;
945 		case __LINE__:
946 			return ret; /* must be last */
947 		/* note: do not set any defaults so as to permit holes above */
948 		}
949 	}
950 	return ret;
951 }
952 
953 int run_stdlib(int min, int max)
954 {
955 	int test;
956 	int ret = 0;
957 
958 	for (test = min; test >= 0 && test <= max; test++) {
959 		int llen = 0; /* line length */
960 
961 		/* avoid leaving empty lines below, this will insert holes into
962 		 * test numbers.
963 		 */
964 		switch (test + __LINE__ + 1) {
965 		CASE_TEST(getenv_TERM);        EXPECT_STRNZ(1, getenv("TERM")); break;
966 		CASE_TEST(getenv_blah);        EXPECT_STRZR(1, getenv("blah")); break;
967 		CASE_TEST(setcmp_blah_blah);   EXPECT_EQ(1, strcmp("blah", "blah"), 0); break;
968 		CASE_TEST(setcmp_blah_blah2);  EXPECT_NE(1, strcmp("blah", "blah2"), 0); break;
969 		CASE_TEST(setncmp_blah_blah);  EXPECT_EQ(1, strncmp("blah", "blah", 10), 0); break;
970 		CASE_TEST(setncmp_blah_blah4); EXPECT_EQ(1, strncmp("blah", "blah4", 4), 0); break;
971 		CASE_TEST(setncmp_blah_blah5); EXPECT_NE(1, strncmp("blah", "blah5", 5), 0); break;
972 		CASE_TEST(setncmp_blah_blah6); EXPECT_NE(1, strncmp("blah", "blah6", 6), 0); break;
973 		CASE_TEST(strchr_foobar_o);    EXPECT_STREQ(1, strchr("foobar", 'o'), "oobar"); break;
974 		CASE_TEST(strchr_foobar_z);    EXPECT_STRZR(1, strchr("foobar", 'z')); break;
975 		CASE_TEST(strrchr_foobar_o);   EXPECT_STREQ(1, strrchr("foobar", 'o'), "obar"); break;
976 		CASE_TEST(strrchr_foobar_z);   EXPECT_STRZR(1, strrchr("foobar", 'z')); break;
977 		CASE_TEST(memcmp_20_20);       EXPECT_EQ(1, memcmp("aaa\x20", "aaa\x20", 4), 0); break;
978 		CASE_TEST(memcmp_20_60);       EXPECT_LT(1, memcmp("aaa\x20", "aaa\x60", 4), 0); break;
979 		CASE_TEST(memcmp_60_20);       EXPECT_GT(1, memcmp("aaa\x60", "aaa\x20", 4), 0); break;
980 		CASE_TEST(memcmp_20_e0);       EXPECT_LT(1, memcmp("aaa\x20", "aaa\xe0", 4), 0); break;
981 		CASE_TEST(memcmp_e0_20);       EXPECT_GT(1, memcmp("aaa\xe0", "aaa\x20", 4), 0); break;
982 		CASE_TEST(memcmp_80_e0);       EXPECT_LT(1, memcmp("aaa\x80", "aaa\xe0", 4), 0); break;
983 		CASE_TEST(memcmp_e0_80);       EXPECT_GT(1, memcmp("aaa\xe0", "aaa\x80", 4), 0); break;
984 		CASE_TEST(limit_int8_max);          EXPECT_EQ(1, INT8_MAX,         (int8_t)          0x7f); break;
985 		CASE_TEST(limit_int8_min);          EXPECT_EQ(1, INT8_MIN,         (int8_t)          0x80); break;
986 		CASE_TEST(limit_uint8_max);         EXPECT_EQ(1, UINT8_MAX,        (uint8_t)         0xff); break;
987 		CASE_TEST(limit_int16_max);         EXPECT_EQ(1, INT16_MAX,        (int16_t)         0x7fff); break;
988 		CASE_TEST(limit_int16_min);         EXPECT_EQ(1, INT16_MIN,        (int16_t)         0x8000); break;
989 		CASE_TEST(limit_uint16_max);        EXPECT_EQ(1, UINT16_MAX,       (uint16_t)        0xffff); break;
990 		CASE_TEST(limit_int32_max);         EXPECT_EQ(1, INT32_MAX,        (int32_t)         0x7fffffff); break;
991 		CASE_TEST(limit_int32_min);         EXPECT_EQ(1, INT32_MIN,        (int32_t)         0x80000000); break;
992 		CASE_TEST(limit_uint32_max);        EXPECT_EQ(1, UINT32_MAX,       (uint32_t)        0xffffffff); break;
993 		CASE_TEST(limit_int64_max);         EXPECT_EQ(1, INT64_MAX,        (int64_t)         0x7fffffffffffffff); break;
994 		CASE_TEST(limit_int64_min);         EXPECT_EQ(1, INT64_MIN,        (int64_t)         0x8000000000000000); break;
995 		CASE_TEST(limit_uint64_max);        EXPECT_EQ(1, UINT64_MAX,       (uint64_t)        0xffffffffffffffff); break;
996 		CASE_TEST(limit_int_least8_max);    EXPECT_EQ(1, INT_LEAST8_MAX,   (int_least8_t)    0x7f); break;
997 		CASE_TEST(limit_int_least8_min);    EXPECT_EQ(1, INT_LEAST8_MIN,   (int_least8_t)    0x80); break;
998 		CASE_TEST(limit_uint_least8_max);   EXPECT_EQ(1, UINT_LEAST8_MAX,  (uint_least8_t)   0xff); break;
999 		CASE_TEST(limit_int_least16_max);   EXPECT_EQ(1, INT_LEAST16_MAX,  (int_least16_t)   0x7fff); break;
1000 		CASE_TEST(limit_int_least16_min);   EXPECT_EQ(1, INT_LEAST16_MIN,  (int_least16_t)   0x8000); break;
1001 		CASE_TEST(limit_uint_least16_max);  EXPECT_EQ(1, UINT_LEAST16_MAX, (uint_least16_t)  0xffff); break;
1002 		CASE_TEST(limit_int_least32_max);   EXPECT_EQ(1, INT_LEAST32_MAX,  (int_least32_t)   0x7fffffff); break;
1003 		CASE_TEST(limit_int_least32_min);   EXPECT_EQ(1, INT_LEAST32_MIN,  (int_least32_t)   0x80000000); break;
1004 		CASE_TEST(limit_uint_least32_max);  EXPECT_EQ(1, UINT_LEAST32_MAX, (uint_least32_t)  0xffffffffU); break;
1005 		CASE_TEST(limit_int_least64_min);   EXPECT_EQ(1, INT_LEAST64_MIN,  (int_least64_t)   0x8000000000000000LL); break;
1006 		CASE_TEST(limit_int_least64_max);   EXPECT_EQ(1, INT_LEAST64_MAX,  (int_least64_t)   0x7fffffffffffffffLL); break;
1007 		CASE_TEST(limit_uint_least64_max);  EXPECT_EQ(1, UINT_LEAST64_MAX, (uint_least64_t)  0xffffffffffffffffULL); break;
1008 		CASE_TEST(limit_int_fast8_max);     EXPECT_EQ(1, INT_FAST8_MAX,    (int_fast8_t)     0x7f); break;
1009 		CASE_TEST(limit_int_fast8_min);     EXPECT_EQ(1, INT_FAST8_MIN,    (int_fast8_t)     0x80); break;
1010 		CASE_TEST(limit_uint_fast8_max);    EXPECT_EQ(1, UINT_FAST8_MAX,   (uint_fast8_t)    0xff); break;
1011 		CASE_TEST(limit_int_fast16_min);    EXPECT_EQ(1, INT_FAST16_MIN,   (int_fast16_t)    SINT_MIN_OF_TYPE(int_fast16_t)); break;
1012 		CASE_TEST(limit_int_fast16_max);    EXPECT_EQ(1, INT_FAST16_MAX,   (int_fast16_t)    SINT_MAX_OF_TYPE(int_fast16_t)); break;
1013 		CASE_TEST(limit_uint_fast16_max);   EXPECT_EQ(1, UINT_FAST16_MAX,  (uint_fast16_t)   UINTPTR_MAX); break;
1014 		CASE_TEST(limit_int_fast32_min);    EXPECT_EQ(1, INT_FAST32_MIN,   (int_fast32_t)    SINT_MIN_OF_TYPE(int_fast32_t)); break;
1015 		CASE_TEST(limit_int_fast32_max);    EXPECT_EQ(1, INT_FAST32_MAX,   (int_fast32_t)    SINT_MAX_OF_TYPE(int_fast32_t)); break;
1016 		CASE_TEST(limit_uint_fast32_max);   EXPECT_EQ(1, UINT_FAST32_MAX,  (uint_fast32_t)   UINTPTR_MAX); break;
1017 		CASE_TEST(limit_int_fast64_min);    EXPECT_EQ(1, INT_FAST64_MIN,   (int_fast64_t)    INT64_MIN); break;
1018 		CASE_TEST(limit_int_fast64_max);    EXPECT_EQ(1, INT_FAST64_MAX,   (int_fast64_t)    INT64_MAX); break;
1019 		CASE_TEST(limit_uint_fast64_max);   EXPECT_EQ(1, UINT_FAST64_MAX,  (uint_fast64_t)   UINT64_MAX); break;
1020 		CASE_TEST(sizeof_long_sane);        EXPECT_EQ(1, sizeof(long) == 8 || sizeof(long) == 4, 1); break;
1021 		CASE_TEST(limit_intptr_min);        EXPECT_EQ(1, INTPTR_MIN,  sizeof(long) == 8 ? (intptr_t)  0x8000000000000000LL  : (intptr_t)  0x80000000); break;
1022 		CASE_TEST(limit_intptr_max);        EXPECT_EQ(1, INTPTR_MAX,  sizeof(long) == 8 ? (intptr_t)  0x7fffffffffffffffLL  : (intptr_t)  0x7fffffff); break;
1023 		CASE_TEST(limit_uintptr_max);       EXPECT_EQ(1, UINTPTR_MAX, sizeof(long) == 8 ? (uintptr_t) 0xffffffffffffffffULL : (uintptr_t) 0xffffffffU); break;
1024 		CASE_TEST(limit_ptrdiff_min);       EXPECT_EQ(1, PTRDIFF_MIN, sizeof(long) == 8 ? (ptrdiff_t) 0x8000000000000000LL  : (ptrdiff_t) 0x80000000); break;
1025 		CASE_TEST(limit_ptrdiff_max);       EXPECT_EQ(1, PTRDIFF_MAX, sizeof(long) == 8 ? (ptrdiff_t) 0x7fffffffffffffffLL  : (ptrdiff_t) 0x7fffffff); break;
1026 		CASE_TEST(limit_size_max);          EXPECT_EQ(1, SIZE_MAX,    sizeof(long) == 8 ? (size_t)    0xffffffffffffffffULL : (size_t)    0xffffffffU); break;
1027 
1028 		case __LINE__:
1029 			return ret; /* must be last */
1030 		/* note: do not set any defaults so as to permit holes above */
1031 		}
1032 	}
1033 	return ret;
1034 }
1035 
1036 #define EXPECT_VFPRINTF(c, expected, fmt, ...)				\
1037 	ret += expect_vfprintf(llen, c, expected, fmt, ##__VA_ARGS__)
1038 
1039 static int expect_vfprintf(int llen, int c, const char *expected, const char *fmt, ...)
1040 {
1041 	int ret, fd;
1042 	ssize_t w, r;
1043 	char buf[100];
1044 	FILE *memfile;
1045 	va_list args;
1046 
1047 	fd = open("/tmp", O_TMPFILE | O_EXCL | O_RDWR, 0600);
1048 	if (fd == -1) {
1049 		result(llen, SKIPPED);
1050 		return 0;
1051 	}
1052 
1053 	memfile = fdopen(fd, "w+");
1054 	if (!memfile) {
1055 		result(llen, FAIL);
1056 		return 1;
1057 	}
1058 
1059 	va_start(args, fmt);
1060 	w = vfprintf(memfile, fmt, args);
1061 	va_end(args);
1062 
1063 	if (w != c) {
1064 		llen += printf(" written(%d) != %d", (int)w, c);
1065 		result(llen, FAIL);
1066 		return 1;
1067 	}
1068 
1069 	fflush(memfile);
1070 	lseek(fd, 0, SEEK_SET);
1071 
1072 	r = read(fd, buf, sizeof(buf) - 1);
1073 
1074 	fclose(memfile);
1075 
1076 	if (r != w) {
1077 		llen += printf(" written(%d) != read(%d)", (int)w, (int)r);
1078 		result(llen, FAIL);
1079 		return 1;
1080 	}
1081 
1082 	buf[r] = '\0';
1083 	llen += printf(" \"%s\" = \"%s\"", expected, buf);
1084 	ret = strncmp(expected, buf, c);
1085 
1086 	result(llen, ret ? FAIL : OK);
1087 	return ret;
1088 }
1089 
1090 static int run_vfprintf(int min, int max)
1091 {
1092 	int test;
1093 	int ret = 0;
1094 
1095 	for (test = min; test >= 0 && test <= max; test++) {
1096 		int llen = 0; /* line length */
1097 
1098 		/* avoid leaving empty lines below, this will insert holes into
1099 		 * test numbers.
1100 		 */
1101 		switch (test + __LINE__ + 1) {
1102 		CASE_TEST(empty);        EXPECT_VFPRINTF(0, "", ""); break;
1103 		CASE_TEST(simple);       EXPECT_VFPRINTF(3, "foo", "foo"); break;
1104 		CASE_TEST(string);       EXPECT_VFPRINTF(3, "foo", "%s", "foo"); break;
1105 		CASE_TEST(number);       EXPECT_VFPRINTF(4, "1234", "%d", 1234); break;
1106 		CASE_TEST(negnumber);    EXPECT_VFPRINTF(5, "-1234", "%d", -1234); break;
1107 		CASE_TEST(unsigned);     EXPECT_VFPRINTF(5, "12345", "%u", 12345); break;
1108 		CASE_TEST(char);         EXPECT_VFPRINTF(1, "c", "%c", 'c'); break;
1109 		CASE_TEST(hex);          EXPECT_VFPRINTF(1, "f", "%x", 0xf); break;
1110 		CASE_TEST(pointer);      EXPECT_VFPRINTF(3, "0x1", "%p", (void *) 0x1); break;
1111 		case __LINE__:
1112 			return ret; /* must be last */
1113 		/* note: do not set any defaults so as to permit holes above */
1114 		}
1115 	}
1116 	return ret;
1117 }
1118 
1119 static int smash_stack(void)
1120 {
1121 	char buf[100];
1122 	volatile char *ptr = buf;
1123 	size_t i;
1124 
1125 	for (i = 0; i < 200; i++)
1126 		ptr[i] = 'P';
1127 
1128 	return 1;
1129 }
1130 
1131 static int run_protection(int min __attribute__((unused)),
1132 			  int max __attribute__((unused)))
1133 {
1134 	pid_t pid;
1135 	int llen = 0, status;
1136 
1137 	llen += printf("0 -fstackprotector ");
1138 
1139 #if !defined(_NOLIBC_STACKPROTECTOR)
1140 	llen += printf("not supported");
1141 	result(llen, SKIPPED);
1142 	return 0;
1143 #endif
1144 
1145 #if defined(_NOLIBC_STACKPROTECTOR)
1146 	if (!__stack_chk_guard) {
1147 		llen += printf("__stack_chk_guard not initialized");
1148 		result(llen, FAIL);
1149 		return 1;
1150 	}
1151 #endif
1152 
1153 	pid = -1;
1154 	pid = fork();
1155 
1156 	switch (pid) {
1157 	case -1:
1158 		llen += printf("fork()");
1159 		result(llen, FAIL);
1160 		return 1;
1161 
1162 	case 0:
1163 		close(STDOUT_FILENO);
1164 		close(STDERR_FILENO);
1165 
1166 		prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
1167 		smash_stack();
1168 		return 1;
1169 
1170 	default:
1171 		pid = waitpid(pid, &status, 0);
1172 
1173 		if (pid == -1 || !WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT) {
1174 			llen += printf("waitpid()");
1175 			result(llen, FAIL);
1176 			return 1;
1177 		}
1178 		result(llen, OK);
1179 		return 0;
1180 	}
1181 }
1182 
1183 /* prepare what needs to be prepared for pid 1 (stdio, /dev, /proc, etc) */
1184 int prepare(void)
1185 {
1186 	struct stat stat_buf;
1187 
1188 	/* It's possible that /dev doesn't even exist or was not mounted, so
1189 	 * we'll try to create it, mount it, or create minimal entries into it.
1190 	 * We want at least /dev/null and /dev/console.
1191 	 */
1192 	if (stat("/dev/.", &stat_buf) == 0 || mkdir("/dev", 0755) == 0) {
1193 		if (stat("/dev/console", &stat_buf) != 0 ||
1194 		    stat("/dev/null", &stat_buf) != 0 ||
1195 		    stat("/dev/zero", &stat_buf) != 0) {
1196 			/* try devtmpfs first, otherwise fall back to manual creation */
1197 			if (mount("/dev", "/dev", "devtmpfs", 0, 0) != 0) {
1198 				mknod("/dev/console", 0600 | S_IFCHR, makedev(5, 1));
1199 				mknod("/dev/null",    0666 | S_IFCHR, makedev(1, 3));
1200 				mknod("/dev/zero",    0666 | S_IFCHR, makedev(1, 5));
1201 			}
1202 		}
1203 	}
1204 
1205 	/* If no /dev/console was found before calling init, stdio is closed so
1206 	 * we need to reopen it from /dev/console. If it failed above, it will
1207 	 * still fail here and we cannot emit a message anyway.
1208 	 */
1209 	if (close(dup(1)) == -1) {
1210 		int fd = open("/dev/console", O_RDWR);
1211 
1212 		if (fd >= 0) {
1213 			if (fd != 0)
1214 				dup2(fd, 0);
1215 			if (fd != 1)
1216 				dup2(fd, 1);
1217 			if (fd != 2)
1218 				dup2(fd, 2);
1219 			if (fd > 2)
1220 				close(fd);
1221 			puts("\nSuccessfully reopened /dev/console.");
1222 		}
1223 	}
1224 
1225 	/* try to mount /proc if not mounted. Silently fail otherwise */
1226 	if (stat("/proc/.", &stat_buf) == 0 || mkdir("/proc", 0755) == 0) {
1227 		if (stat("/proc/self", &stat_buf) != 0) {
1228 			/* If not mountable, remove /proc completely to avoid misuse */
1229 			if (mount("none", "/proc", "proc", 0, 0) != 0)
1230 				rmdir("/proc");
1231 		}
1232 	}
1233 
1234 	/* some tests rely on a writable /tmp */
1235 	mkdir("/tmp", 0755);
1236 
1237 	return 0;
1238 }
1239 
1240 /* This is the definition of known test names, with their functions */
1241 static const struct test test_names[] = {
1242 	/* add new tests here */
1243 	{ .name = "startup",    .func = run_startup    },
1244 	{ .name = "syscall",    .func = run_syscall    },
1245 	{ .name = "stdlib",     .func = run_stdlib     },
1246 	{ .name = "vfprintf",   .func = run_vfprintf   },
1247 	{ .name = "protection", .func = run_protection },
1248 	{ 0 }
1249 };
1250 
1251 static int is_setting_valid(char *test)
1252 {
1253 	int idx, len, test_len, valid = 0;
1254 	char delimiter;
1255 
1256 	if (!test)
1257 		return valid;
1258 
1259 	test_len = strlen(test);
1260 
1261 	for (idx = 0; test_names[idx].name; idx++) {
1262 		len = strlen(test_names[idx].name);
1263 		if (test_len < len)
1264 			continue;
1265 
1266 		if (strncmp(test, test_names[idx].name, len) != 0)
1267 			continue;
1268 
1269 		delimiter = test[len];
1270 		if (delimiter != ':' && delimiter != ',' && delimiter != '\0')
1271 			continue;
1272 
1273 		valid = 1;
1274 		break;
1275 	}
1276 
1277 	return valid;
1278 }
1279 
1280 int main(int argc, char **argv, char **envp)
1281 {
1282 	int min = 0;
1283 	int max = INT_MAX;
1284 	int ret = 0;
1285 	int err;
1286 	int idx;
1287 	char *test;
1288 
1289 	argv0 = argv[0];
1290 	test_argc = argc;
1291 	test_argv = argv;
1292 	test_envp = envp;
1293 
1294 	/* when called as init, it's possible that no console was opened, for
1295 	 * example if no /dev file system was provided. We'll check that fd#1
1296 	 * was opened, and if not we'll attempt to create and open /dev/console
1297 	 * and /dev/null that we'll use for later tests.
1298 	 */
1299 	if (getpid() == 1)
1300 		prepare();
1301 
1302 	/* the definition of a series of tests comes from either argv[1] or the
1303 	 * "NOLIBC_TEST" environment variable. It's made of a comma-delimited
1304 	 * series of test names and optional ranges:
1305 	 *    syscall:5-15[:.*],stdlib:8-10
1306 	 */
1307 	test = argv[1];
1308 	if (!is_setting_valid(test))
1309 		test = getenv("NOLIBC_TEST");
1310 
1311 	if (is_setting_valid(test)) {
1312 		char *comma, *colon, *dash, *value;
1313 
1314 		do {
1315 			comma = strchr(test, ',');
1316 			if (comma)
1317 				*(comma++) = '\0';
1318 
1319 			colon = strchr(test, ':');
1320 			if (colon)
1321 				*(colon++) = '\0';
1322 
1323 			for (idx = 0; test_names[idx].name; idx++) {
1324 				if (strcmp(test, test_names[idx].name) == 0)
1325 					break;
1326 			}
1327 
1328 			if (test_names[idx].name) {
1329 				/* The test was named, it will be called at least
1330 				 * once. We may have an optional range at <colon>
1331 				 * here, which defaults to the full range.
1332 				 */
1333 				do {
1334 					min = 0; max = INT_MAX;
1335 					value = colon;
1336 					if (value && *value) {
1337 						colon = strchr(value, ':');
1338 						if (colon)
1339 							*(colon++) = '\0';
1340 
1341 						dash = strchr(value, '-');
1342 						if (dash)
1343 							*(dash++) = '\0';
1344 
1345 						/* support :val: :min-max: :min-: :-max: */
1346 						if (*value)
1347 							min = atoi(value);
1348 						if (!dash)
1349 							max = min;
1350 						else if (*dash)
1351 							max = atoi(dash);
1352 
1353 						value = colon;
1354 					}
1355 
1356 					/* now's time to call the test */
1357 					printf("Running test '%s'\n", test_names[idx].name);
1358 					err = test_names[idx].func(min, max);
1359 					ret += err;
1360 					printf("Errors during this test: %d\n\n", err);
1361 				} while (colon && *colon);
1362 			} else
1363 				printf("Ignoring unknown test name '%s'\n", test);
1364 
1365 			test = comma;
1366 		} while (test && *test);
1367 	} else {
1368 		/* no test mentioned, run everything */
1369 		for (idx = 0; test_names[idx].name; idx++) {
1370 			printf("Running test '%s'\n", test_names[idx].name);
1371 			err = test_names[idx].func(min, max);
1372 			ret += err;
1373 			printf("Errors during this test: %d\n\n", err);
1374 		}
1375 	}
1376 
1377 	printf("Total number of errors: %d\n", ret);
1378 
1379 	if (getpid() == 1) {
1380 		/* we're running as init, there's no other process on the
1381 		 * system, thus likely started from a VM for a quick check.
1382 		 * Exiting will provoke a kernel panic that may be reported
1383 		 * as an error by Qemu or the hypervisor, while stopping
1384 		 * cleanly will often be reported as a success. This allows
1385 		 * to use the output of this program for bisecting kernels.
1386 		 */
1387 		printf("Leaving init with final status: %d\n", !!ret);
1388 		if (ret == 0)
1389 			reboot(RB_POWER_OFF);
1390 #if defined(__x86_64__)
1391 		/* QEMU started with "-device isa-debug-exit -no-reboot" will
1392 		 * exit with status code 2N+1 when N is written to 0x501. We
1393 		 * hard-code the syscall here as it's arch-dependent.
1394 		 */
1395 		else if (syscall(__NR_ioperm, 0x501, 1, 1) == 0)
1396 			__asm__ volatile ("outb %%al, %%dx" :: "d"(0x501), "a"(0));
1397 		/* if it does nothing, fall back to the regular panic */
1398 #endif
1399 	}
1400 
1401 	printf("Exiting with status %d\n", !!ret);
1402 	return !!ret;
1403 }
1404