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