1 // SPDX-License-Identifier: GPL-2.0
2 
3 #define _GNU_SOURCE
4 
5 /* platform-specific include files coming from the compiler */
6 #include <limits.h>
7 
8 /* libc-specific include files
9  * The program may be built in 3 ways:
10  *   $(CC) -nostdlib -include /path/to/nolibc.h => NOLIBC already defined
11  *   $(CC) -nostdlib -I/path/to/nolibc/sysroot  => _NOLIBC_* guards are present
12  *   $(CC) with default libc                    => NOLIBC* never defined
13  */
14 #ifndef NOLIBC
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #ifndef _NOLIBC_STDIO_H
19 /* standard libcs need more includes */
20 #include <linux/reboot.h>
21 #include <sys/io.h>
22 #include <sys/ioctl.h>
23 #include <sys/mount.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 <unistd.h>
38 #endif
39 #endif
40 
41 /* will be used by nolibc by getenv() */
42 char **environ;
43 
44 /* definition of a series of tests */
45 struct test {
46 	const char *name;              // test name
47 	int (*func)(int min, int max); // handler
48 };
49 
50 #ifndef _NOLIBC_STDLIB_H
51 char *itoa(int i)
52 {
53 	static char buf[12];
54 	int ret;
55 
56 	ret = snprintf(buf, sizeof(buf), "%d", i);
57 	return (ret >= 0 && ret < sizeof(buf)) ? buf : "#err";
58 }
59 #endif
60 
61 #define CASE_ERR(err) \
62 	case err: return #err
63 
64 /* returns the error name (e.g. "ENOENT") for common errors, "SUCCESS" for 0,
65  * or the decimal value for less common ones.
66  */
67 const char *errorname(int err)
68 {
69 	switch (err) {
70 	case 0: return "SUCCESS";
71 	CASE_ERR(EPERM);
72 	CASE_ERR(ENOENT);
73 	CASE_ERR(ESRCH);
74 	CASE_ERR(EINTR);
75 	CASE_ERR(EIO);
76 	CASE_ERR(ENXIO);
77 	CASE_ERR(E2BIG);
78 	CASE_ERR(ENOEXEC);
79 	CASE_ERR(EBADF);
80 	CASE_ERR(ECHILD);
81 	CASE_ERR(EAGAIN);
82 	CASE_ERR(ENOMEM);
83 	CASE_ERR(EACCES);
84 	CASE_ERR(EFAULT);
85 	CASE_ERR(ENOTBLK);
86 	CASE_ERR(EBUSY);
87 	CASE_ERR(EEXIST);
88 	CASE_ERR(EXDEV);
89 	CASE_ERR(ENODEV);
90 	CASE_ERR(ENOTDIR);
91 	CASE_ERR(EISDIR);
92 	CASE_ERR(EINVAL);
93 	CASE_ERR(ENFILE);
94 	CASE_ERR(EMFILE);
95 	CASE_ERR(ENOTTY);
96 	CASE_ERR(ETXTBSY);
97 	CASE_ERR(EFBIG);
98 	CASE_ERR(ENOSPC);
99 	CASE_ERR(ESPIPE);
100 	CASE_ERR(EROFS);
101 	CASE_ERR(EMLINK);
102 	CASE_ERR(EPIPE);
103 	CASE_ERR(EDOM);
104 	CASE_ERR(ERANGE);
105 	CASE_ERR(ENOSYS);
106 	default:
107 		return itoa(err);
108 	}
109 }
110 
111 static int pad_spc(int llen, int cnt, const char *fmt, ...)
112 {
113 	va_list args;
114 	int len;
115 	int ret;
116 
117 	for (len = 0; len < cnt - llen; len++)
118 		putchar(' ');
119 
120 	va_start(args, fmt);
121 	ret = vfprintf(stdout, fmt, args);
122 	va_end(args);
123 	return ret < 0 ? ret : ret + len;
124 }
125 
126 /* The tests below are intended to be used by the macroes, which evaluate
127  * expression <expr>, print the status to stdout, and update the "ret"
128  * variable to count failures. The functions themselves return the number
129  * of failures, thus either 0 or 1.
130  */
131 
132 #define EXPECT_ZR(cond, expr)				\
133 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_zr(expr, llen); } while (0)
134 
135 static int expect_zr(int expr, int llen)
136 {
137 	int ret = !(expr == 0);
138 
139 	llen += printf(" = %d ", expr);
140 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
141 	return ret;
142 }
143 
144 
145 #define EXPECT_NZ(cond, expr, val)			\
146 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_nz(expr, llen; } while (0)
147 
148 static int expect_nz(int expr, int llen)
149 {
150 	int ret = !(expr != 0);
151 
152 	llen += printf(" = %d ", expr);
153 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
154 	return ret;
155 }
156 
157 
158 #define EXPECT_EQ(cond, expr, val)				\
159 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_eq(expr, llen, val); } while (0)
160 
161 static int expect_eq(uint64_t expr, int llen, uint64_t val)
162 {
163 	int ret = !(expr == val);
164 
165 	llen += printf(" = %lld ", expr);
166 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
167 	return ret;
168 }
169 
170 
171 #define EXPECT_NE(cond, expr, val)				\
172 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_ne(expr, llen, val); } while (0)
173 
174 static int expect_ne(int expr, int llen, int val)
175 {
176 	int ret = !(expr != val);
177 
178 	llen += printf(" = %d ", expr);
179 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
180 	return ret;
181 }
182 
183 
184 #define EXPECT_GE(cond, expr, val)				\
185 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_ge(expr, llen, val); } while (0)
186 
187 static int expect_ge(int expr, int llen, int val)
188 {
189 	int ret = !(expr >= val);
190 
191 	llen += printf(" = %d ", expr);
192 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
193 	return ret;
194 }
195 
196 
197 #define EXPECT_GT(cond, expr, val)				\
198 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_gt(expr, llen, val); } while (0)
199 
200 static int expect_gt(int expr, int llen, int val)
201 {
202 	int ret = !(expr > val);
203 
204 	llen += printf(" = %d ", expr);
205 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
206 	return ret;
207 }
208 
209 
210 #define EXPECT_LE(cond, expr, val)				\
211 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_le(expr, llen, val); } while (0)
212 
213 static int expect_le(int expr, int llen, int val)
214 {
215 	int ret = !(expr <= val);
216 
217 	llen += printf(" = %d ", expr);
218 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
219 	return ret;
220 }
221 
222 
223 #define EXPECT_LT(cond, expr, val)				\
224 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_lt(expr, llen, val); } while (0)
225 
226 static int expect_lt(int expr, int llen, int val)
227 {
228 	int ret = !(expr < val);
229 
230 	llen += printf(" = %d ", expr);
231 	pad_spc(llen, 64, ret ? "[FAIL]\n" : " [OK]\n");
232 	return ret;
233 }
234 
235 
236 #define EXPECT_SYSZR(cond, expr)				\
237 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_syszr(expr, llen); } while (0)
238 
239 static int expect_syszr(int expr, int llen)
240 {
241 	int ret = 0;
242 
243 	if (expr) {
244 		ret = 1;
245 		llen += printf(" = %d %s ", expr, errorname(errno));
246 		llen += pad_spc(llen, 64, "[FAIL]\n");
247 	} else {
248 		llen += printf(" = %d ", expr);
249 		llen += pad_spc(llen, 64, " [OK]\n");
250 	}
251 	return ret;
252 }
253 
254 
255 #define EXPECT_SYSEQ(cond, expr, val)				\
256 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_syseq(expr, llen, val); } while (0)
257 
258 static int expect_syseq(int expr, int llen, int val)
259 {
260 	int ret = 0;
261 
262 	if (expr != val) {
263 		ret = 1;
264 		llen += printf(" = %d %s ", expr, errorname(errno));
265 		llen += pad_spc(llen, 64, "[FAIL]\n");
266 	} else {
267 		llen += printf(" = %d ", expr);
268 		llen += pad_spc(llen, 64, " [OK]\n");
269 	}
270 	return ret;
271 }
272 
273 
274 #define EXPECT_SYSNE(cond, expr, val)				\
275 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_sysne(expr, llen, val); } while (0)
276 
277 static int expect_sysne(int expr, int llen, int val)
278 {
279 	int ret = 0;
280 
281 	if (expr == val) {
282 		ret = 1;
283 		llen += printf(" = %d %s ", expr, errorname(errno));
284 		llen += pad_spc(llen, 64, "[FAIL]\n");
285 	} else {
286 		llen += printf(" = %d ", expr);
287 		llen += pad_spc(llen, 64, " [OK]\n");
288 	}
289 	return ret;
290 }
291 
292 
293 #define EXPECT_SYSER(cond, expr, expret, experr)			\
294 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_syserr(expr, expret, experr, llen); } while (0)
295 
296 static int expect_syserr(int expr, int expret, int experr, int llen)
297 {
298 	int ret = 0;
299 	int _errno = errno;
300 
301 	llen += printf(" = %d %s ", expr, errorname(_errno));
302 	if (expr != expret || _errno != experr) {
303 		ret = 1;
304 		llen += printf(" != (%d %s) ", expret, errorname(experr));
305 		llen += pad_spc(llen, 64, "[FAIL]\n");
306 	} else {
307 		llen += pad_spc(llen, 64, " [OK]\n");
308 	}
309 	return ret;
310 }
311 
312 
313 #define EXPECT_PTRZR(cond, expr)				\
314 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_ptrzr(expr, llen); } while (0)
315 
316 static int expect_ptrzr(const void *expr, int llen)
317 {
318 	int ret = 0;
319 
320 	llen += printf(" = <%p> ", expr);
321 	if (expr) {
322 		ret = 1;
323 		llen += pad_spc(llen, 64, "[FAIL]\n");
324 	} else {
325 		llen += pad_spc(llen, 64, " [OK]\n");
326 	}
327 	return ret;
328 }
329 
330 
331 #define EXPECT_PTRNZ(cond, expr)				\
332 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_ptrnz(expr, llen); } while (0)
333 
334 static int expect_ptrnz(const void *expr, int llen)
335 {
336 	int ret = 0;
337 
338 	llen += printf(" = <%p> ", expr);
339 	if (!expr) {
340 		ret = 1;
341 		llen += pad_spc(llen, 64, "[FAIL]\n");
342 	} else {
343 		llen += pad_spc(llen, 64, " [OK]\n");
344 	}
345 	return ret;
346 }
347 
348 
349 #define EXPECT_STRZR(cond, expr)				\
350 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_strzr(expr, llen); } while (0)
351 
352 static int expect_strzr(const char *expr, int llen)
353 {
354 	int ret = 0;
355 
356 	llen += printf(" = <%s> ", expr);
357 	if (expr) {
358 		ret = 1;
359 		llen += pad_spc(llen, 64, "[FAIL]\n");
360 	} else {
361 		llen += pad_spc(llen, 64, " [OK]\n");
362 	}
363 	return ret;
364 }
365 
366 
367 #define EXPECT_STRNZ(cond, expr)				\
368 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_strnz(expr, llen); } while (0)
369 
370 static int expect_strnz(const char *expr, int llen)
371 {
372 	int ret = 0;
373 
374 	llen += printf(" = <%s> ", expr);
375 	if (!expr) {
376 		ret = 1;
377 		llen += pad_spc(llen, 64, "[FAIL]\n");
378 	} else {
379 		llen += pad_spc(llen, 64, " [OK]\n");
380 	}
381 	return ret;
382 }
383 
384 
385 #define EXPECT_STREQ(cond, expr, cmp)				\
386 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_streq(expr, llen, cmp); } while (0)
387 
388 static int expect_streq(const char *expr, int llen, const char *cmp)
389 {
390 	int ret = 0;
391 
392 	llen += printf(" = <%s> ", expr);
393 	if (strcmp(expr, cmp) != 0) {
394 		ret = 1;
395 		llen += pad_spc(llen, 64, "[FAIL]\n");
396 	} else {
397 		llen += pad_spc(llen, 64, " [OK]\n");
398 	}
399 	return ret;
400 }
401 
402 
403 #define EXPECT_STRNE(cond, expr, cmp)				\
404 	do { if (!cond) pad_spc(llen, 64, "[SKIPPED]\n"); else ret += expect_strne(expr, llen, cmp); } while (0)
405 
406 static int expect_strne(const char *expr, int llen, const char *cmp)
407 {
408 	int ret = 0;
409 
410 	llen += printf(" = <%s> ", expr);
411 	if (strcmp(expr, cmp) == 0) {
412 		ret = 1;
413 		llen += pad_spc(llen, 64, "[FAIL]\n");
414 	} else {
415 		llen += pad_spc(llen, 64, " [OK]\n");
416 	}
417 	return ret;
418 }
419 
420 
421 /* declare tests based on line numbers. There must be exactly one test per line. */
422 #define CASE_TEST(name) \
423 	case __LINE__: llen += printf("%d %s", test, #name);
424 
425 
426 /* used by some syscall tests below */
427 int test_getdents64(const char *dir)
428 {
429 	char buffer[4096];
430 	int fd, ret;
431 	int err;
432 
433 	ret = fd = open(dir, O_RDONLY | O_DIRECTORY, 0);
434 	if (ret < 0)
435 		return ret;
436 
437 	ret = getdents64(fd, (void *)buffer, sizeof(buffer));
438 	err = errno;
439 	close(fd);
440 
441 	errno = err;
442 	return ret;
443 }
444 
445 static int test_getpagesize(void)
446 {
447 	long x = getpagesize();
448 	int c;
449 
450 	if (x < 0)
451 		return x;
452 
453 #if defined(__x86_64__) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__)
454 	/*
455 	 * x86 family is always 4K page.
456 	 */
457 	c = (x == 4096);
458 #elif defined(__aarch64__)
459 	/*
460 	 * Linux aarch64 supports three values of page size: 4K, 16K, and 64K
461 	 * which are selected at kernel compilation time.
462 	 */
463 	c = (x == 4096 || x == (16 * 1024) || x == (64 * 1024));
464 #else
465 	/*
466 	 * Assuming other architectures must have at least 4K page.
467 	 */
468 	c = (x >= 4096);
469 #endif
470 
471 	return !c;
472 }
473 
474 /* Run syscall tests between IDs <min> and <max>.
475  * Return 0 on success, non-zero on failure.
476  */
477 int run_syscall(int min, int max)
478 {
479 	struct stat stat_buf;
480 	int euid0;
481 	int proc;
482 	int test;
483 	int tmp;
484 	int ret = 0;
485 	void *p1, *p2;
486 
487 	/* <proc> indicates whether or not /proc is mounted */
488 	proc = stat("/proc", &stat_buf) == 0;
489 
490 	/* this will be used to skip certain tests that can't be run unprivileged */
491 	euid0 = geteuid() == 0;
492 
493 	for (test = min; test >= 0 && test <= max; test++) {
494 		int llen = 0; // line length
495 
496 		/* avoid leaving empty lines below, this will insert holes into
497 		 * test numbers.
498 		 */
499 		switch (test + __LINE__ + 1) {
500 		CASE_TEST(getpid);            EXPECT_SYSNE(1, getpid(), -1); break;
501 		CASE_TEST(getppid);           EXPECT_SYSNE(1, getppid(), -1); break;
502 #ifdef NOLIBC
503 		CASE_TEST(gettid);            EXPECT_SYSNE(1, gettid(), -1); break;
504 #endif
505 		CASE_TEST(getpgid_self);      EXPECT_SYSNE(1, getpgid(0), -1); break;
506 		CASE_TEST(getpgid_bad);       EXPECT_SYSER(1, getpgid(-1), -1, ESRCH); break;
507 		CASE_TEST(kill_0);            EXPECT_SYSZR(1, kill(getpid(), 0)); break;
508 		CASE_TEST(kill_CONT);         EXPECT_SYSZR(1, kill(getpid(), 0)); break;
509 		CASE_TEST(kill_BADPID);       EXPECT_SYSER(1, kill(INT_MAX, 0), -1, ESRCH); break;
510 		CASE_TEST(sbrk);              if ((p1 = p2 = sbrk(4096)) != (void *)-1) p2 = sbrk(-4096); EXPECT_SYSZR(1, (p2 == (void *)-1) || p2 == p1); break;
511 		CASE_TEST(brk);               EXPECT_SYSZR(1, brk(sbrk(0))); break;
512 		CASE_TEST(chdir_root);        EXPECT_SYSZR(1, chdir("/")); break;
513 		CASE_TEST(chdir_dot);         EXPECT_SYSZR(1, chdir(".")); break;
514 		CASE_TEST(chdir_blah);        EXPECT_SYSER(1, chdir("/blah"), -1, ENOENT); break;
515 		CASE_TEST(chmod_net);         EXPECT_SYSZR(proc, chmod("/proc/self/net", 0555)); break;
516 		CASE_TEST(chmod_self);        EXPECT_SYSER(proc, chmod("/proc/self", 0555), -1, EPERM); break;
517 		CASE_TEST(chown_self);        EXPECT_SYSER(proc, chown("/proc/self", 0, 0), -1, EPERM); break;
518 		CASE_TEST(chroot_root);       EXPECT_SYSZR(euid0, chroot("/")); break;
519 		CASE_TEST(chroot_blah);       EXPECT_SYSER(1, chroot("/proc/self/blah"), -1, ENOENT); break;
520 		CASE_TEST(chroot_exe);        EXPECT_SYSER(proc, chroot("/proc/self/exe"), -1, ENOTDIR); break;
521 		CASE_TEST(close_m1);          EXPECT_SYSER(1, close(-1), -1, EBADF); break;
522 		CASE_TEST(close_dup);         EXPECT_SYSZR(1, close(dup(0))); break;
523 		CASE_TEST(dup_0);             tmp = dup(0);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
524 		CASE_TEST(dup_m1);            tmp = dup(-1); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
525 		CASE_TEST(dup2_0);            tmp = dup2(0, 100);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
526 		CASE_TEST(dup2_m1);           tmp = dup2(-1, 100); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
527 		CASE_TEST(dup3_0);            tmp = dup3(0, 100, 0);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
528 		CASE_TEST(dup3_m1);           tmp = dup3(-1, 100, 0); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
529 		CASE_TEST(execve_root);       EXPECT_SYSER(1, execve("/", (char*[]){ [0] = "/", [1] = NULL }, NULL), -1, EACCES); break;
530 		CASE_TEST(getdents64_root);   EXPECT_SYSNE(1, test_getdents64("/"), -1); break;
531 		CASE_TEST(getdents64_null);   EXPECT_SYSER(1, test_getdents64("/dev/null"), -1, ENOTDIR); break;
532 		CASE_TEST(gettimeofday_null); EXPECT_SYSZR(1, gettimeofday(NULL, NULL)); break;
533 #ifdef NOLIBC
534 		CASE_TEST(gettimeofday_bad1); EXPECT_SYSER(1, gettimeofday((void *)1, NULL), -1, EFAULT); break;
535 		CASE_TEST(gettimeofday_bad2); EXPECT_SYSER(1, gettimeofday(NULL, (void *)1), -1, EFAULT); break;
536 		CASE_TEST(gettimeofday_bad2); EXPECT_SYSER(1, gettimeofday(NULL, (void *)1), -1, EFAULT); break;
537 #endif
538 		CASE_TEST(getpagesize);       EXPECT_SYSZR(1, test_getpagesize()); break;
539 		CASE_TEST(ioctl_tiocinq);     EXPECT_SYSZR(1, ioctl(0, TIOCINQ, &tmp)); break;
540 		CASE_TEST(ioctl_tiocinq);     EXPECT_SYSZR(1, ioctl(0, TIOCINQ, &tmp)); break;
541 		CASE_TEST(link_root1);        EXPECT_SYSER(1, link("/", "/"), -1, EEXIST); break;
542 		CASE_TEST(link_blah);         EXPECT_SYSER(1, link("/proc/self/blah", "/blah"), -1, ENOENT); break;
543 		CASE_TEST(link_dir);          EXPECT_SYSER(euid0, link("/", "/blah"), -1, EPERM); break;
544 		CASE_TEST(link_cross);        EXPECT_SYSER(proc, link("/proc/self/net", "/blah"), -1, EXDEV); break;
545 		CASE_TEST(lseek_m1);          EXPECT_SYSER(1, lseek(-1, 0, SEEK_SET), -1, EBADF); break;
546 		CASE_TEST(lseek_0);           EXPECT_SYSER(1, lseek(0, 0, SEEK_SET), -1, ESPIPE); break;
547 		CASE_TEST(mkdir_root);        EXPECT_SYSER(1, mkdir("/", 0755), -1, EEXIST); break;
548 		CASE_TEST(open_tty);          EXPECT_SYSNE(1, tmp = open("/dev/null", 0), -1); if (tmp != -1) close(tmp); break;
549 		CASE_TEST(open_blah);         EXPECT_SYSER(1, tmp = open("/proc/self/blah", 0), -1, ENOENT); if (tmp != -1) close(tmp); break;
550 		CASE_TEST(poll_null);         EXPECT_SYSZR(1, poll(NULL, 0, 0)); break;
551 		CASE_TEST(poll_stdout);       EXPECT_SYSNE(1, ({ struct pollfd fds = { 1, POLLOUT, 0}; poll(&fds, 1, 0); }), -1); break;
552 		CASE_TEST(poll_fault);        EXPECT_SYSER(1, poll((void *)1, 1, 0), -1, EFAULT); break;
553 		CASE_TEST(read_badf);         EXPECT_SYSER(1, read(-1, &tmp, 1), -1, EBADF); break;
554 		CASE_TEST(sched_yield);       EXPECT_SYSZR(1, sched_yield()); break;
555 		CASE_TEST(select_null);       EXPECT_SYSZR(1, ({ struct timeval tv = { 0 }; select(0, NULL, NULL, NULL, &tv); })); break;
556 		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;
557 		CASE_TEST(select_fault);      EXPECT_SYSER(1, select(1, (void *)1, NULL, NULL, 0), -1, EFAULT); break;
558 		CASE_TEST(stat_blah);         EXPECT_SYSER(1, stat("/proc/self/blah", &stat_buf), -1, ENOENT); break;
559 		CASE_TEST(stat_fault);        EXPECT_SYSER(1, stat(NULL, &stat_buf), -1, EFAULT); break;
560 		CASE_TEST(symlink_root);      EXPECT_SYSER(1, symlink("/", "/"), -1, EEXIST); break;
561 		CASE_TEST(unlink_root);       EXPECT_SYSER(1, unlink("/"), -1, EISDIR); break;
562 		CASE_TEST(unlink_blah);       EXPECT_SYSER(1, unlink("/proc/self/blah"), -1, ENOENT); break;
563 		CASE_TEST(wait_child);        EXPECT_SYSER(1, wait(&tmp), -1, ECHILD); break;
564 		CASE_TEST(waitpid_min);       EXPECT_SYSER(1, waitpid(INT_MIN, &tmp, WNOHANG), -1, ESRCH); break;
565 		CASE_TEST(waitpid_child);     EXPECT_SYSER(1, waitpid(getpid(), &tmp, WNOHANG), -1, ECHILD); break;
566 		CASE_TEST(write_badf);        EXPECT_SYSER(1, write(-1, &tmp, 1), -1, EBADF); break;
567 		CASE_TEST(write_zero);        EXPECT_SYSZR(1, write(1, &tmp, 0)); break;
568 		case __LINE__:
569 			return ret; /* must be last */
570 		/* note: do not set any defaults so as to permit holes above */
571 		}
572 	}
573 	return ret;
574 }
575 
576 int run_stdlib(int min, int max)
577 {
578 	int test;
579 	int tmp;
580 	int ret = 0;
581 	void *p1, *p2;
582 
583 	for (test = min; test >= 0 && test <= max; test++) {
584 		int llen = 0; // line length
585 
586 		/* avoid leaving empty lines below, this will insert holes into
587 		 * test numbers.
588 		 */
589 		switch (test + __LINE__ + 1) {
590 		CASE_TEST(getenv_TERM);        EXPECT_STRNZ(1, getenv("TERM")); break;
591 		CASE_TEST(getenv_blah);        EXPECT_STRZR(1, getenv("blah")); break;
592 		CASE_TEST(setcmp_blah_blah);   EXPECT_EQ(1, strcmp("blah", "blah"), 0); break;
593 		CASE_TEST(setcmp_blah_blah2);  EXPECT_NE(1, strcmp("blah", "blah2"), 0); break;
594 		CASE_TEST(setncmp_blah_blah);  EXPECT_EQ(1, strncmp("blah", "blah", 10), 0); break;
595 		CASE_TEST(setncmp_blah_blah4); EXPECT_EQ(1, strncmp("blah", "blah4", 4), 0); break;
596 		CASE_TEST(setncmp_blah_blah5); EXPECT_NE(1, strncmp("blah", "blah5", 5), 0); break;
597 		CASE_TEST(setncmp_blah_blah6); EXPECT_NE(1, strncmp("blah", "blah6", 6), 0); break;
598 		CASE_TEST(strchr_foobar_o);    EXPECT_STREQ(1, strchr("foobar", 'o'), "oobar"); break;
599 		CASE_TEST(strchr_foobar_z);    EXPECT_STRZR(1, strchr("foobar", 'z')); break;
600 		CASE_TEST(strrchr_foobar_o);   EXPECT_STREQ(1, strrchr("foobar", 'o'), "obar"); break;
601 		CASE_TEST(strrchr_foobar_z);   EXPECT_STRZR(1, strrchr("foobar", 'z')); break;
602 		CASE_TEST(memcmp_20_20);       EXPECT_EQ(1, memcmp("aaa\x20", "aaa\x20", 4), 0); break;
603 		CASE_TEST(memcmp_20_60);       EXPECT_LT(1, memcmp("aaa\x20", "aaa\x60", 4), 0); break;
604 		CASE_TEST(memcmp_60_20);       EXPECT_GT(1, memcmp("aaa\x60", "aaa\x20", 4), 0); break;
605 		CASE_TEST(memcmp_20_e0);       EXPECT_LT(1, memcmp("aaa\x20", "aaa\xe0", 4), 0); break;
606 		CASE_TEST(memcmp_e0_20);       EXPECT_GT(1, memcmp("aaa\xe0", "aaa\x20", 4), 0); break;
607 		CASE_TEST(memcmp_80_e0);       EXPECT_LT(1, memcmp("aaa\x80", "aaa\xe0", 4), 0); break;
608 		CASE_TEST(memcmp_e0_80);       EXPECT_GT(1, memcmp("aaa\xe0", "aaa\x80", 4), 0); break;
609 		CASE_TEST(limit_int8_max);          EXPECT_EQ(1, INT8_MAX,         (int8_t)          0x7f); break;
610 		CASE_TEST(limit_int8_min);          EXPECT_EQ(1, INT8_MIN,         (int8_t)          0x80); break;
611 		CASE_TEST(limit_uint8_max);         EXPECT_EQ(1, UINT8_MAX,        (uint8_t)         0xff); break;
612 		CASE_TEST(limit_int16_max);         EXPECT_EQ(1, INT16_MAX,        (int16_t)         0x7fff); break;
613 		CASE_TEST(limit_int16_min);         EXPECT_EQ(1, INT16_MIN,        (int16_t)         0x8000); break;
614 		CASE_TEST(limit_uint16_max);        EXPECT_EQ(1, UINT16_MAX,       (uint16_t)        0xffff); break;
615 		CASE_TEST(limit_int32_max);         EXPECT_EQ(1, INT32_MAX,        (int32_t)         0x7fffffff); break;
616 		CASE_TEST(limit_int32_min);         EXPECT_EQ(1, INT32_MIN,        (int32_t)         0x80000000); break;
617 		CASE_TEST(limit_uint32_max);        EXPECT_EQ(1, UINT32_MAX,       (uint32_t)        0xffffffff); break;
618 		CASE_TEST(limit_int64_max);         EXPECT_EQ(1, INT64_MAX,        (int64_t)         0x7fffffffffffffff); break;
619 		CASE_TEST(limit_int64_min);         EXPECT_EQ(1, INT64_MIN,        (int64_t)         0x8000000000000000); break;
620 		CASE_TEST(limit_uint64_max);        EXPECT_EQ(1, UINT64_MAX,       (uint64_t)        0xffffffffffffffff); break;
621 		CASE_TEST(limit_int_least8_max);    EXPECT_EQ(1, INT_LEAST8_MAX,   (int_least8_t)    0x7f); break;
622 		CASE_TEST(limit_int_least8_min);    EXPECT_EQ(1, INT_LEAST8_MIN,   (int_least8_t)    0x80); break;
623 		CASE_TEST(limit_uint_least8_max);   EXPECT_EQ(1, UINT_LEAST8_MAX,  (uint_least8_t)   0xff); break;
624 		CASE_TEST(limit_int_least16_max);   EXPECT_EQ(1, INT_LEAST16_MAX,  (int_least16_t)   0x7fff); break;
625 		CASE_TEST(limit_int_least16_min);   EXPECT_EQ(1, INT_LEAST16_MIN,  (int_least16_t)   0x8000); break;
626 		CASE_TEST(limit_uint_least16_max);  EXPECT_EQ(1, UINT_LEAST16_MAX, (uint_least16_t)  0xffff); break;
627 		CASE_TEST(limit_int_least32_max);   EXPECT_EQ(1, INT_LEAST32_MAX,  (int_least32_t)   0x7fffffff); break;
628 		CASE_TEST(limit_int_least32_min);   EXPECT_EQ(1, INT_LEAST32_MIN,  (int_least32_t)   0x80000000); break;
629 		CASE_TEST(limit_uint_least32_max);  EXPECT_EQ(1, UINT_LEAST32_MAX, (uint_least32_t)  0xffffffffU); break;
630 		CASE_TEST(limit_int_least64_min);   EXPECT_EQ(1, INT_LEAST64_MIN,  (int_least64_t)   0x8000000000000000LL); break;
631 		CASE_TEST(limit_int_least64_max);   EXPECT_EQ(1, INT_LEAST64_MAX,  (int_least64_t)   0x7fffffffffffffffLL); break;
632 		CASE_TEST(limit_uint_least64_max);  EXPECT_EQ(1, UINT_LEAST64_MAX, (uint_least64_t)  0xffffffffffffffffULL); break;
633 		CASE_TEST(limit_int_fast8_max);     EXPECT_EQ(1, INT_FAST8_MAX,    (int_fast8_t)     0x7f); break;
634 		CASE_TEST(limit_int_fast8_min);     EXPECT_EQ(1, INT_FAST8_MIN,    (int_fast8_t)     0x80); break;
635 		CASE_TEST(limit_uint_fast8_max);    EXPECT_EQ(1, UINT_FAST8_MAX,   (uint_fast8_t)    0xff); break;
636 		CASE_TEST(limit_int_fast16_min);    EXPECT_EQ(1, INT_FAST16_MIN,   (int_fast16_t)    INTPTR_MIN); break;
637 		CASE_TEST(limit_int_fast16_max);    EXPECT_EQ(1, INT_FAST16_MAX,   (int_fast16_t)    INTPTR_MAX); break;
638 		CASE_TEST(limit_uint_fast16_max);   EXPECT_EQ(1, UINT_FAST16_MAX,  (uint_fast16_t)   UINTPTR_MAX); break;
639 		CASE_TEST(limit_int_fast32_min);    EXPECT_EQ(1, INT_FAST32_MIN,   (int_fast32_t)    INTPTR_MIN); break;
640 		CASE_TEST(limit_int_fast32_max);    EXPECT_EQ(1, INT_FAST32_MAX,   (int_fast32_t)    INTPTR_MAX); break;
641 		CASE_TEST(limit_uint_fast32_max);   EXPECT_EQ(1, UINT_FAST32_MAX,  (uint_fast32_t)   UINTPTR_MAX); break;
642 		CASE_TEST(limit_int_fast64_min);    EXPECT_EQ(1, INT_FAST64_MIN,   (int_fast64_t)    INTPTR_MIN); break;
643 		CASE_TEST(limit_int_fast64_max);    EXPECT_EQ(1, INT_FAST64_MAX,   (int_fast64_t)    INTPTR_MAX); break;
644 		CASE_TEST(limit_uint_fast64_max);   EXPECT_EQ(1, UINT_FAST64_MAX,  (uint_fast64_t)   UINTPTR_MAX); break;
645 #if __SIZEOF_LONG__ == 8
646 		CASE_TEST(limit_intptr_min);        EXPECT_EQ(1, INTPTR_MIN,       (intptr_t)        0x8000000000000000LL); break;
647 		CASE_TEST(limit_intptr_max);        EXPECT_EQ(1, INTPTR_MAX,       (intptr_t)        0x7fffffffffffffffLL); break;
648 		CASE_TEST(limit_uintptr_max);       EXPECT_EQ(1, UINTPTR_MAX,      (uintptr_t)       0xffffffffffffffffULL); break;
649 		CASE_TEST(limit_ptrdiff_min);       EXPECT_EQ(1, PTRDIFF_MIN,      (ptrdiff_t)       0x8000000000000000LL); break;
650 		CASE_TEST(limit_ptrdiff_max);       EXPECT_EQ(1, PTRDIFF_MAX,      (ptrdiff_t)       0x7fffffffffffffffLL); break;
651 		CASE_TEST(limit_size_max);          EXPECT_EQ(1, SIZE_MAX,         (size_t)          0xffffffffffffffffULL); break;
652 #elif __SIZEOF_LONG__ == 4
653 		CASE_TEST(limit_intptr_min);        EXPECT_EQ(1, INTPTR_MIN,       (intptr_t)        0x80000000); break;
654 		CASE_TEST(limit_intptr_max);        EXPECT_EQ(1, INTPTR_MAX,       (intptr_t)        0x7fffffff); break;
655 		CASE_TEST(limit_uintptr_max);       EXPECT_EQ(1, UINTPTR_MAX,      (uintptr_t)       0xffffffffU); break;
656 		CASE_TEST(limit_ptrdiff_min);       EXPECT_EQ(1, PTRDIFF_MIN,      (ptrdiff_t)       0x80000000); break;
657 		CASE_TEST(limit_ptrdiff_max);       EXPECT_EQ(1, PTRDIFF_MAX,      (ptrdiff_t)       0x7fffffff); break;
658 		CASE_TEST(limit_size_max);          EXPECT_EQ(1, SIZE_MAX,         (size_t)          0xffffffffU); break;
659 #else
660 # warning "__SIZEOF_LONG__ is undefined"
661 #endif /* __SIZEOF_LONG__ */
662 		case __LINE__:
663 			return ret; /* must be last */
664 		/* note: do not set any defaults so as to permit holes above */
665 		}
666 	}
667 	return ret;
668 }
669 
670 #if defined(__clang__)
671 __attribute__((optnone))
672 #elif defined(__GNUC__)
673 __attribute__((optimize("O0")))
674 #endif
675 static int smash_stack(void)
676 {
677 	char buf[100];
678 
679 	for (size_t i = 0; i < 200; i++)
680 		buf[i] = 'P';
681 
682 	return 1;
683 }
684 
685 static int run_protection(int min, int max)
686 {
687 	pid_t pid;
688 	int llen = 0, status;
689 
690 	llen += printf("0 -fstackprotector ");
691 
692 #if !defined(NOLIBC_STACKPROTECTOR)
693 	llen += printf("not supported");
694 	pad_spc(llen, 64, "[SKIPPED]\n");
695 	return 0;
696 #endif
697 
698 	pid = -1;
699 	pid = fork();
700 
701 	switch (pid) {
702 	case -1:
703 		llen += printf("fork()");
704 		pad_spc(llen, 64, "[FAIL]\n");
705 		return 1;
706 
707 	case 0:
708 		close(STDOUT_FILENO);
709 		close(STDERR_FILENO);
710 
711 		smash_stack();
712 		return 1;
713 
714 	default:
715 		pid = waitpid(pid, &status, 0);
716 
717 		if (pid == -1 || !WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT) {
718 			llen += printf("waitpid()");
719 			pad_spc(llen, 64, "[FAIL]\n");
720 			return 1;
721 		}
722 		pad_spc(llen, 64, " [OK]\n");
723 		return 0;
724 	}
725 }
726 
727 /* prepare what needs to be prepared for pid 1 (stdio, /dev, /proc, etc) */
728 int prepare(void)
729 {
730 	struct stat stat_buf;
731 
732 	/* It's possible that /dev doesn't even exist or was not mounted, so
733 	 * we'll try to create it, mount it, or create minimal entries into it.
734 	 * We want at least /dev/null and /dev/console.
735 	 */
736 	if (stat("/dev/.", &stat_buf) == 0 || mkdir("/dev", 0755) == 0) {
737 		if (stat("/dev/console", &stat_buf) != 0 ||
738 		    stat("/dev/null", &stat_buf) != 0) {
739 			/* try devtmpfs first, otherwise fall back to manual creation */
740 			if (mount("/dev", "/dev", "devtmpfs", 0, 0) != 0) {
741 				mknod("/dev/console", 0600 | S_IFCHR, makedev(5, 1));
742 				mknod("/dev/null",    0666 | S_IFCHR, makedev(1, 3));
743 			}
744 		}
745 	}
746 
747 	/* If no /dev/console was found before calling init, stdio is closed so
748 	 * we need to reopen it from /dev/console. If it failed above, it will
749 	 * still fail here and we cannot emit a message anyway.
750 	 */
751 	if (close(dup(1)) == -1) {
752 		int fd = open("/dev/console", O_RDWR);
753 
754 		if (fd >= 0) {
755 			if (fd != 0)
756 				dup2(fd, 0);
757 			if (fd != 1)
758 				dup2(fd, 1);
759 			if (fd != 2)
760 				dup2(fd, 2);
761 			if (fd > 2)
762 				close(fd);
763 			puts("\nSuccessfully reopened /dev/console.");
764 		}
765 	}
766 
767 	/* try to mount /proc if not mounted. Silently fail otherwise */
768 	if (stat("/proc/.", &stat_buf) == 0 || mkdir("/proc", 0755) == 0) {
769 		if (stat("/proc/self", &stat_buf) != 0)
770 			mount("/proc", "/proc", "proc", 0, 0);
771 	}
772 
773 	return 0;
774 }
775 
776 /* This is the definition of known test names, with their functions */
777 static const struct test test_names[] = {
778 	/* add new tests here */
779 	{ .name = "syscall",    .func = run_syscall    },
780 	{ .name = "stdlib",     .func = run_stdlib     },
781 	{ .name = "protection", .func = run_protection },
782 	{ 0 }
783 };
784 
785 int main(int argc, char **argv, char **envp)
786 {
787 	int min = 0;
788 	int max = __INT_MAX__;
789 	int ret = 0;
790 	int err;
791 	int idx;
792 	char *test;
793 
794 	environ = envp;
795 
796 	/* when called as init, it's possible that no console was opened, for
797 	 * example if no /dev file system was provided. We'll check that fd#1
798 	 * was opened, and if not we'll attempt to create and open /dev/console
799 	 * and /dev/null that we'll use for later tests.
800 	 */
801 	if (getpid() == 1)
802 		prepare();
803 
804 	/* the definition of a series of tests comes from either argv[1] or the
805 	 * "NOLIBC_TEST" environment variable. It's made of a comma-delimited
806 	 * series of test names and optional ranges:
807 	 *    syscall:5-15[:.*],stdlib:8-10
808 	 */
809 	test = argv[1];
810 	if (!test)
811 		test = getenv("NOLIBC_TEST");
812 
813 	if (test) {
814 		char *comma, *colon, *dash, *value;
815 
816 		do {
817 			comma = strchr(test, ',');
818 			if (comma)
819 				*(comma++) = '\0';
820 
821 			colon = strchr(test, ':');
822 			if (colon)
823 				*(colon++) = '\0';
824 
825 			for (idx = 0; test_names[idx].name; idx++) {
826 				if (strcmp(test, test_names[idx].name) == 0)
827 					break;
828 			}
829 
830 			if (test_names[idx].name) {
831 				/* The test was named, it will be called at least
832 				 * once. We may have an optional range at <colon>
833 				 * here, which defaults to the full range.
834 				 */
835 				do {
836 					min = 0; max = __INT_MAX__;
837 					value = colon;
838 					if (value && *value) {
839 						colon = strchr(value, ':');
840 						if (colon)
841 							*(colon++) = '\0';
842 
843 						dash = strchr(value, '-');
844 						if (dash)
845 							*(dash++) = '\0';
846 
847 						/* support :val: :min-max: :min-: :-max: */
848 						if (*value)
849 							min = atoi(value);
850 						if (!dash)
851 							max = min;
852 						else if (*dash)
853 							max = atoi(dash);
854 
855 						value = colon;
856 					}
857 
858 					/* now's time to call the test */
859 					printf("Running test '%s'\n", test_names[idx].name);
860 					err = test_names[idx].func(min, max);
861 					ret += err;
862 					printf("Errors during this test: %d\n\n", err);
863 				} while (colon && *colon);
864 			} else
865 				printf("Ignoring unknown test name '%s'\n", test);
866 
867 			test = comma;
868 		} while (test && *test);
869 	} else {
870 		/* no test mentioned, run everything */
871 		for (idx = 0; test_names[idx].name; idx++) {
872 			printf("Running test '%s'\n", test_names[idx].name);
873 			err = test_names[idx].func(min, max);
874 			ret += err;
875 			printf("Errors during this test: %d\n\n", err);
876 		}
877 	}
878 
879 	printf("Total number of errors: %d\n", ret);
880 
881 	if (getpid() == 1) {
882 		/* we're running as init, there's no other process on the
883 		 * system, thus likely started from a VM for a quick check.
884 		 * Exiting will provoke a kernel panic that may be reported
885 		 * as an error by Qemu or the hypervisor, while stopping
886 		 * cleanly will often be reported as a success. This allows
887 		 * to use the output of this program for bisecting kernels.
888 		 */
889 		printf("Leaving init with final status: %d\n", !!ret);
890 		if (ret == 0)
891 			reboot(LINUX_REBOOT_CMD_POWER_OFF);
892 #if defined(__x86_64__)
893 		/* QEMU started with "-device isa-debug-exit -no-reboot" will
894 		 * exit with status code 2N+1 when N is written to 0x501. We
895 		 * hard-code the syscall here as it's arch-dependent.
896 		 */
897 #if defined(_NOLIBC_SYS_H)
898 		else if (my_syscall3(__NR_ioperm, 0x501, 1, 1) == 0)
899 #else
900 		else if (ioperm(0x501, 1, 1) == 0)
901 #endif
902 			asm volatile ("outb %%al, %%dx" :: "d"(0x501), "a"(0));
903 		/* if it does nothing, fall back to the regular panic */
904 #endif
905 	}
906 
907 	printf("Exiting with status %d\n", !!ret);
908 	return !!ret;
909 }
910