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, 40, "[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, 40, 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, 40, "[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, 40, 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, 40, "[SKIPPED]\n"); else ret += expect_eq(expr, llen, val); } while (0)
160 
161 static int expect_eq(int expr, int llen, int val)
162 {
163 	int ret = !(expr == val);
164 
165 	llen += printf(" = %d ", expr);
166 	pad_spc(llen, 40, 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, 40, "[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, 40, 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, 40, "[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, 40, 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, 40, "[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, 40, 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, 40, "[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, 40, 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, 40, "[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, 40, ret ? "[FAIL]\n" : " [OK]\n");
232 	return ret;
233 }
234 
235 
236 #define EXPECT_SYSZR(cond, expr)				\
237 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
247 	} else {
248 		llen += printf(" = %d ", expr);
249 		llen += pad_spc(llen, 40, " [OK]\n");
250 	}
251 	return ret;
252 }
253 
254 
255 #define EXPECT_SYSEQ(cond, expr, val)				\
256 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
266 	} else {
267 		llen += printf(" = %d ", expr);
268 		llen += pad_spc(llen, 40, " [OK]\n");
269 	}
270 	return ret;
271 }
272 
273 
274 #define EXPECT_SYSNE(cond, expr, val)				\
275 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
285 	} else {
286 		llen += printf(" = %d ", expr);
287 		llen += pad_spc(llen, 40, " [OK]\n");
288 	}
289 	return ret;
290 }
291 
292 
293 #define EXPECT_SYSER(cond, expr, expret, experr)			\
294 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
306 	} else {
307 		llen += pad_spc(llen, 40, " [OK]\n");
308 	}
309 	return ret;
310 }
311 
312 
313 #define EXPECT_PTRZR(cond, expr)				\
314 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
324 	} else {
325 		llen += pad_spc(llen, 40, " [OK]\n");
326 	}
327 	return ret;
328 }
329 
330 
331 #define EXPECT_PTRNZ(cond, expr)				\
332 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
342 	} else {
343 		llen += pad_spc(llen, 40, " [OK]\n");
344 	}
345 	return ret;
346 }
347 
348 
349 #define EXPECT_STRZR(cond, expr)				\
350 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
360 	} else {
361 		llen += pad_spc(llen, 40, " [OK]\n");
362 	}
363 	return ret;
364 }
365 
366 
367 #define EXPECT_STRNZ(cond, expr)				\
368 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
378 	} else {
379 		llen += pad_spc(llen, 40, " [OK]\n");
380 	}
381 	return ret;
382 }
383 
384 
385 #define EXPECT_STREQ(cond, expr, cmp)				\
386 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
396 	} else {
397 		llen += pad_spc(llen, 40, " [OK]\n");
398 	}
399 	return ret;
400 }
401 
402 
403 #define EXPECT_STRNE(cond, expr, cmp)				\
404 	do { if (!cond) pad_spc(llen, 40, "[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, 40, "[FAIL]\n");
414 	} else {
415 		llen += pad_spc(llen, 40, " [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 /* Run syscall tests between IDs <min> and <max>.
446  * Return 0 on success, non-zero on failure.
447  */
448 int run_syscall(int min, int max)
449 {
450 	struct stat stat_buf;
451 	int proc;
452 	int test;
453 	int tmp;
454 	int ret = 0;
455 	void *p1, *p2;
456 
457 	/* <proc> indicates whether or not /proc is mounted */
458 	proc = stat("/proc", &stat_buf) == 0;
459 
460 	for (test = min; test >= 0 && test <= max; test++) {
461 		int llen = 0; // line length
462 
463 		/* avoid leaving empty lines below, this will insert holes into
464 		 * test numbers.
465 		 */
466 		switch (test + __LINE__ + 1) {
467 		CASE_TEST(getpid);            EXPECT_SYSNE(1, getpid(), -1); break;
468 		CASE_TEST(getppid);           EXPECT_SYSNE(1, getppid(), -1); break;
469 #ifdef NOLIBC
470 		CASE_TEST(gettid);            EXPECT_SYSNE(1, gettid(), -1); break;
471 #endif
472 		CASE_TEST(getpgid_self);      EXPECT_SYSNE(1, getpgid(0), -1); break;
473 		CASE_TEST(getpgid_bad);       EXPECT_SYSER(1, getpgid(-1), -1, ESRCH); break;
474 		CASE_TEST(kill_0);            EXPECT_SYSZR(1, kill(getpid(), 0)); break;
475 		CASE_TEST(kill_CONT);         EXPECT_SYSZR(1, kill(getpid(), 0)); break;
476 		CASE_TEST(kill_BADPID);       EXPECT_SYSER(1, kill(INT_MAX, 0), -1, ESRCH); break;
477 		CASE_TEST(sbrk);              if ((p1 = p2 = sbrk(4096)) != (void *)-1) p2 = sbrk(-4096); EXPECT_SYSZR(1, (p2 == (void *)-1) || p2 == p1); break;
478 		CASE_TEST(brk);               EXPECT_SYSZR(1, brk(sbrk(0))); break;
479 		CASE_TEST(chdir_root);        EXPECT_SYSZR(1, chdir("/")); break;
480 		CASE_TEST(chdir_dot);         EXPECT_SYSZR(1, chdir(".")); break;
481 		CASE_TEST(chdir_blah);        EXPECT_SYSER(1, chdir("/blah"), -1, ENOENT); break;
482 		CASE_TEST(chmod_net);         EXPECT_SYSZR(proc, chmod("/proc/self/net", 0555)); break;
483 		CASE_TEST(chmod_self);        EXPECT_SYSER(proc, chmod("/proc/self", 0555), -1, EPERM); break;
484 		CASE_TEST(chown_self);        EXPECT_SYSER(proc, chown("/proc/self", 0, 0), -1, EPERM); break;
485 		CASE_TEST(chroot_root);       EXPECT_SYSZR(1, chroot("/")); break;
486 		CASE_TEST(chroot_blah);       EXPECT_SYSER(1, chroot("/proc/self/blah"), -1, ENOENT); break;
487 		CASE_TEST(chroot_exe);        EXPECT_SYSER(proc, chroot("/proc/self/exe"), -1, ENOTDIR); break;
488 		CASE_TEST(close_m1);          EXPECT_SYSER(1, close(-1), -1, EBADF); break;
489 		CASE_TEST(close_dup);         EXPECT_SYSZR(1, close(dup(0))); break;
490 		CASE_TEST(dup_0);             tmp = dup(0);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
491 		CASE_TEST(dup_m1);            tmp = dup(-1); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
492 		CASE_TEST(dup2_0);            tmp = dup2(0, 100);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
493 		CASE_TEST(dup2_m1);           tmp = dup2(-1, 100); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
494 		CASE_TEST(dup3_0);            tmp = dup3(0, 100, 0);  EXPECT_SYSNE(1, tmp, -1); close(tmp); break;
495 		CASE_TEST(dup3_m1);           tmp = dup3(-1, 100, 0); EXPECT_SYSER(1, tmp, -1, EBADF); if (tmp != -1) close(tmp); break;
496 		CASE_TEST(execve_root);       EXPECT_SYSER(1, execve("/", (char*[]){ [0] = "/", [1] = NULL }, NULL), -1, EACCES); break;
497 		CASE_TEST(getdents64_root);   EXPECT_SYSNE(1, test_getdents64("/"), -1); break;
498 		CASE_TEST(getdents64_null);   EXPECT_SYSER(1, test_getdents64("/dev/null"), -1, ENOTDIR); break;
499 		CASE_TEST(gettimeofday_null); EXPECT_SYSZR(1, gettimeofday(NULL, NULL)); break;
500 #ifdef NOLIBC
501 		CASE_TEST(gettimeofday_bad1); EXPECT_SYSER(1, gettimeofday((void *)1, NULL), -1, EFAULT); break;
502 		CASE_TEST(gettimeofday_bad2); EXPECT_SYSER(1, gettimeofday(NULL, (void *)1), -1, EFAULT); break;
503 		CASE_TEST(gettimeofday_bad2); EXPECT_SYSER(1, gettimeofday(NULL, (void *)1), -1, EFAULT); break;
504 #endif
505 		CASE_TEST(ioctl_tiocinq);     EXPECT_SYSZR(1, ioctl(0, TIOCINQ, &tmp)); break;
506 		CASE_TEST(ioctl_tiocinq);     EXPECT_SYSZR(1, ioctl(0, TIOCINQ, &tmp)); break;
507 		CASE_TEST(link_root1);        EXPECT_SYSER(1, link("/", "/"), -1, EEXIST); break;
508 		CASE_TEST(link_blah);         EXPECT_SYSER(1, link("/proc/self/blah", "/blah"), -1, ENOENT); break;
509 		CASE_TEST(link_dir);          EXPECT_SYSER(1, link("/", "/blah"), -1, EPERM); break;
510 		CASE_TEST(link_cross);        EXPECT_SYSER(proc, link("/proc/self/net", "/blah"), -1, EXDEV); break;
511 		CASE_TEST(lseek_m1);          EXPECT_SYSER(1, lseek(-1, 0, SEEK_SET), -1, EBADF); break;
512 		CASE_TEST(lseek_0);           EXPECT_SYSER(1, lseek(0, 0, SEEK_SET), -1, ESPIPE); break;
513 		CASE_TEST(mkdir_root);        EXPECT_SYSER(1, mkdir("/", 0755), -1, EEXIST); break;
514 		CASE_TEST(open_tty);          EXPECT_SYSNE(1, tmp = open("/dev/null", 0), -1); if (tmp != -1) close(tmp); break;
515 		CASE_TEST(open_blah);         EXPECT_SYSER(1, tmp = open("/proc/self/blah", 0), -1, ENOENT); if (tmp != -1) close(tmp); break;
516 		CASE_TEST(poll_null);         EXPECT_SYSZR(1, poll(NULL, 0, 0)); break;
517 		CASE_TEST(poll_stdout);       EXPECT_SYSNE(1, ({ struct pollfd fds = { 1, POLLOUT, 0}; poll(&fds, 1, 0); }), -1); break;
518 		CASE_TEST(poll_fault);        EXPECT_SYSER(1, poll((void *)1, 1, 0), -1, EFAULT); break;
519 		CASE_TEST(read_badf);         EXPECT_SYSER(1, read(-1, &tmp, 1), -1, EBADF); break;
520 		CASE_TEST(sched_yield);       EXPECT_SYSZR(1, sched_yield()); break;
521 		CASE_TEST(select_null);       EXPECT_SYSZR(1, ({ struct timeval tv = { 0 }; select(0, NULL, NULL, NULL, &tv); })); break;
522 		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;
523 		CASE_TEST(select_fault);      EXPECT_SYSER(1, select(1, (void *)1, NULL, NULL, 0), -1, EFAULT); break;
524 		CASE_TEST(stat_blah);         EXPECT_SYSER(1, stat("/proc/self/blah", &stat_buf), -1, ENOENT); break;
525 		CASE_TEST(stat_fault);        EXPECT_SYSER(1, stat(NULL, &stat_buf), -1, EFAULT); break;
526 		CASE_TEST(symlink_root);      EXPECT_SYSER(1, symlink("/", "/"), -1, EEXIST); break;
527 		CASE_TEST(unlink_root);       EXPECT_SYSER(1, unlink("/"), -1, EISDIR); break;
528 		CASE_TEST(unlink_blah);       EXPECT_SYSER(1, unlink("/proc/self/blah"), -1, ENOENT); break;
529 		CASE_TEST(wait_child);        EXPECT_SYSER(1, wait(&tmp), -1, ECHILD); break;
530 		CASE_TEST(waitpid_min);       EXPECT_SYSER(1, waitpid(INT_MIN, &tmp, WNOHANG), -1, ESRCH); break;
531 		CASE_TEST(waitpid_child);     EXPECT_SYSER(1, waitpid(getpid(), &tmp, WNOHANG), -1, ECHILD); break;
532 		CASE_TEST(write_badf);        EXPECT_SYSER(1, write(-1, &tmp, 1), -1, EBADF); break;
533 		CASE_TEST(write_zero);        EXPECT_SYSZR(1, write(1, &tmp, 0)); break;
534 		case __LINE__:
535 			return ret; /* must be last */
536 		/* note: do not set any defaults so as to permit holes above */
537 		}
538 	}
539 	return ret;
540 }
541 
542 int run_stdlib(int min, int max)
543 {
544 	int test;
545 	int tmp;
546 	int ret = 0;
547 	void *p1, *p2;
548 
549 	for (test = min; test >= 0 && test <= max; test++) {
550 		int llen = 0; // line length
551 
552 		/* avoid leaving empty lines below, this will insert holes into
553 		 * test numbers.
554 		 */
555 		switch (test + __LINE__ + 1) {
556 		CASE_TEST(getenv_TERM);        EXPECT_STRNZ(1, getenv("TERM")); break;
557 		CASE_TEST(getenv_blah);        EXPECT_STRZR(1, getenv("blah")); break;
558 		CASE_TEST(setcmp_blah_blah);   EXPECT_EQ(1, strcmp("blah", "blah"), 0); break;
559 		CASE_TEST(setcmp_blah_blah2);  EXPECT_NE(1, strcmp("blah", "blah2"), 0); break;
560 		CASE_TEST(setncmp_blah_blah);  EXPECT_EQ(1, strncmp("blah", "blah", 10), 0); break;
561 		CASE_TEST(setncmp_blah_blah4); EXPECT_EQ(1, strncmp("blah", "blah4", 4), 0); break;
562 		CASE_TEST(setncmp_blah_blah5); EXPECT_NE(1, strncmp("blah", "blah5", 5), 0); break;
563 		CASE_TEST(setncmp_blah_blah6); EXPECT_NE(1, strncmp("blah", "blah6", 6), 0); break;
564 		CASE_TEST(strchr_foobar_o);    EXPECT_STREQ(1, strchr("foobar", 'o'), "oobar"); break;
565 		CASE_TEST(strchr_foobar_z);    EXPECT_STRZR(1, strchr("foobar", 'z')); break;
566 		CASE_TEST(strrchr_foobar_o);   EXPECT_STREQ(1, strrchr("foobar", 'o'), "obar"); break;
567 		CASE_TEST(strrchr_foobar_z);   EXPECT_STRZR(1, strrchr("foobar", 'z')); break;
568 		CASE_TEST(memcmp_20_20);       EXPECT_EQ(1, memcmp("aaa\x20", "aaa\x20", 4), 0); break;
569 		CASE_TEST(memcmp_20_60);       EXPECT_LT(1, memcmp("aaa\x20", "aaa\x60", 4), 0); break;
570 		CASE_TEST(memcmp_60_20);       EXPECT_GT(1, memcmp("aaa\x60", "aaa\x20", 4), 0); break;
571 		CASE_TEST(memcmp_20_e0);       EXPECT_LT(1, memcmp("aaa\x20", "aaa\xe0", 4), 0); break;
572 		CASE_TEST(memcmp_e0_20);       EXPECT_GT(1, memcmp("aaa\xe0", "aaa\x20", 4), 0); break;
573 		CASE_TEST(memcmp_80_e0);       EXPECT_LT(1, memcmp("aaa\x80", "aaa\xe0", 4), 0); break;
574 		CASE_TEST(memcmp_e0_80);       EXPECT_GT(1, memcmp("aaa\xe0", "aaa\x80", 4), 0); break;
575 		case __LINE__:
576 			return ret; /* must be last */
577 		/* note: do not set any defaults so as to permit holes above */
578 		}
579 	}
580 	return ret;
581 }
582 
583 /* prepare what needs to be prepared for pid 1 (stdio, /dev, /proc, etc) */
584 int prepare(void)
585 {
586 	struct stat stat_buf;
587 
588 	/* It's possible that /dev doesn't even exist or was not mounted, so
589 	 * we'll try to create it, mount it, or create minimal entries into it.
590 	 * We want at least /dev/null and /dev/console.
591 	 */
592 	if (stat("/dev/.", &stat_buf) == 0 || mkdir("/dev", 0755) == 0) {
593 		if (stat("/dev/console", &stat_buf) != 0 ||
594 		    stat("/dev/null", &stat_buf) != 0) {
595 			/* try devtmpfs first, otherwise fall back to manual creation */
596 			if (mount("/dev", "/dev", "devtmpfs", 0, 0) != 0) {
597 				mknod("/dev/console", 0600 | S_IFCHR, makedev(5, 1));
598 				mknod("/dev/null",    0666 | S_IFCHR, makedev(1, 3));
599 			}
600 		}
601 	}
602 
603 	/* If no /dev/console was found before calling init, stdio is closed so
604 	 * we need to reopen it from /dev/console. If it failed above, it will
605 	 * still fail here and we cannot emit a message anyway.
606 	 */
607 	if (close(dup(1)) == -1) {
608 		int fd = open("/dev/console", O_RDWR);
609 
610 		if (fd >= 0) {
611 			if (fd != 0)
612 				dup2(fd, 0);
613 			if (fd != 1)
614 				dup2(fd, 1);
615 			if (fd != 2)
616 				dup2(fd, 2);
617 			if (fd > 2)
618 				close(fd);
619 			puts("\nSuccessfully reopened /dev/console.");
620 		}
621 	}
622 
623 	/* try to mount /proc if not mounted. Silently fail otherwise */
624 	if (stat("/proc/.", &stat_buf) == 0 || mkdir("/proc", 0755) == 0) {
625 		if (stat("/proc/self", &stat_buf) != 0)
626 			mount("/proc", "/proc", "proc", 0, 0);
627 	}
628 
629 	return 0;
630 }
631 
632 /* This is the definition of known test names, with their functions */
633 static struct test test_names[] = {
634 	/* add new tests here */
635 	{ .name = "syscall",   .func = run_syscall  },
636 	{ .name = "stdlib",    .func = run_stdlib   },
637 	{ 0 }
638 };
639 
640 int main(int argc, char **argv, char **envp)
641 {
642 	int min = 0;
643 	int max = __INT_MAX__;
644 	int ret = 0;
645 	int err;
646 	int idx;
647 	char *test;
648 
649 	environ = envp;
650 
651 	/* when called as init, it's possible that no console was opened, for
652 	 * example if no /dev file system was provided. We'll check that fd#1
653 	 * was opened, and if not we'll attempt to create and open /dev/console
654 	 * and /dev/null that we'll use for later tests.
655 	 */
656 	if (getpid() == 1)
657 		prepare();
658 
659 	/* the definition of a series of tests comes from either argv[1] or the
660 	 * "NOLIBC_TEST" environment variable. It's made of a comma-delimited
661 	 * series of test names and optional ranges:
662 	 *    syscall:5-15[:.*],stdlib:8-10
663 	 */
664 	test = argv[1];
665 	if (!test)
666 		test = getenv("NOLIBC_TEST");
667 
668 	if (test) {
669 		char *comma, *colon, *dash, *value;
670 
671 		do {
672 			comma = strchr(test, ',');
673 			if (comma)
674 				*(comma++) = '\0';
675 
676 			colon = strchr(test, ':');
677 			if (colon)
678 				*(colon++) = '\0';
679 
680 			for (idx = 0; test_names[idx].name; idx++) {
681 				if (strcmp(test, test_names[idx].name) == 0)
682 					break;
683 			}
684 
685 			if (test_names[idx].name) {
686 				/* The test was named, it will be called at least
687 				 * once. We may have an optional range at <colon>
688 				 * here, which defaults to the full range.
689 				 */
690 				do {
691 					min = 0; max = __INT_MAX__;
692 					value = colon;
693 					if (value && *value) {
694 						colon = strchr(value, ':');
695 						if (colon)
696 							*(colon++) = '\0';
697 
698 						dash = strchr(value, '-');
699 						if (dash)
700 							*(dash++) = '\0';
701 
702 						/* support :val: :min-max: :min-: :-max: */
703 						if (*value)
704 							min = atoi(value);
705 						if (!dash)
706 							max = min;
707 						else if (*dash)
708 							max = atoi(dash);
709 
710 						value = colon;
711 					}
712 
713 					/* now's time to call the test */
714 					printf("Running test '%s'\n", test_names[idx].name);
715 					err = test_names[idx].func(min, max);
716 					ret += err;
717 					printf("Errors during this test: %d\n\n", err);
718 				} while (colon && *colon);
719 			} else
720 				printf("Ignoring unknown test name '%s'\n", test);
721 
722 			test = comma;
723 		} while (test && *test);
724 	} else {
725 		/* no test mentioned, run everything */
726 		for (idx = 0; test_names[idx].name; idx++) {
727 			printf("Running test '%s'\n", test_names[idx].name);
728 			err = test_names[idx].func(min, max);
729 			ret += err;
730 			printf("Errors during this test: %d\n\n", err);
731 		}
732 	}
733 
734 	printf("Total number of errors: %d\n", ret);
735 
736 	if (getpid() == 1) {
737 		/* we're running as init, there's no other process on the
738 		 * system, thus likely started from a VM for a quick check.
739 		 * Exiting will provoke a kernel panic that may be reported
740 		 * as an error by Qemu or the hypervisor, while stopping
741 		 * cleanly will often be reported as a success. This allows
742 		 * to use the output of this program for bisecting kernels.
743 		 */
744 		printf("Leaving init with final status: %d\n", !!ret);
745 		if (ret == 0)
746 			reboot(LINUX_REBOOT_CMD_POWER_OFF);
747 #if defined(__x86_64__)
748 		/* QEMU started with "-device isa-debug-exit -no-reboot" will
749 		 * exit with status code 2N+1 when N is written to 0x501. We
750 		 * hard-code the syscall here as it's arch-dependent.
751 		 */
752 #if defined(_NOLIBC_SYS_H)
753 		else if (my_syscall3(__NR_ioperm, 0x501, 1, 1) == 0)
754 #else
755 		else if (ioperm(0x501, 1, 1) == 0)
756 #endif
757 			asm volatile ("outb %%al, %%dx" :: "d"(0x501), "a"(0));
758 		/* if it does nothing, fall back to the regular panic */
759 #endif
760 	}
761 
762 	printf("Exiting with status %d\n", !!ret);
763 	return !!ret;
764 }
765