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