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