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
itoa(int i)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  */
errorname(int err)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 
pad_spc(int llen,int cnt,const char * fmt,...)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 
expect_zr(int expr,int llen)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 
expect_nz(int expr,int llen)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 
expect_eq(int expr,int llen,int val)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 
expect_ne(int expr,int llen,int val)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 
expect_ge(int expr,int llen,int val)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 
expect_gt(int expr,int llen,int val)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 
expect_le(int expr,int llen,int val)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 
expect_lt(int expr,int llen,int val)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 
expect_syszr(int expr,int llen)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 
expect_syseq(int expr,int llen,int val)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 
expect_sysne(int expr,int llen,int val)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 
expect_syserr(int expr,int expret,int experr,int llen)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 
expect_ptrzr(const void * expr,int llen)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 
expect_ptrnz(const void * expr,int llen)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 
expect_strzr(const char * expr,int llen)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 
expect_strnz(const char * expr,int llen)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 
expect_streq(const char * expr,int llen,const char * cmp)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 
expect_strne(const char * expr,int llen,const char * cmp)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 */
test_getdents64(const char * dir)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  */
run_syscall(int min,int max)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 
run_stdlib(int min,int max)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 __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 /* prepare what needs to be prepared for pid 1 (stdio, /dev, /proc, etc) */
prepare(void)577 int prepare(void)
578 {
579 	struct stat stat_buf;
580 
581 	/* It's possible that /dev doesn't even exist or was not mounted, so
582 	 * we'll try to create it, mount it, or create minimal entries into it.
583 	 * We want at least /dev/null and /dev/console.
584 	 */
585 	if (stat("/dev/.", &stat_buf) == 0 || mkdir("/dev", 0755) == 0) {
586 		if (stat("/dev/console", &stat_buf) != 0 ||
587 		    stat("/dev/null", &stat_buf) != 0) {
588 			/* try devtmpfs first, otherwise fall back to manual creation */
589 			if (mount("/dev", "/dev", "devtmpfs", 0, 0) != 0) {
590 				mknod("/dev/console", 0600 | S_IFCHR, makedev(5, 1));
591 				mknod("/dev/null",    0666 | S_IFCHR, makedev(1, 3));
592 			}
593 		}
594 	}
595 
596 	/* If no /dev/console was found before calling init, stdio is closed so
597 	 * we need to reopen it from /dev/console. If it failed above, it will
598 	 * still fail here and we cannot emit a message anyway.
599 	 */
600 	if (close(dup(1)) == -1) {
601 		int fd = open("/dev/console", O_RDWR);
602 
603 		if (fd >= 0) {
604 			if (fd != 0)
605 				dup2(fd, 0);
606 			if (fd != 1)
607 				dup2(fd, 1);
608 			if (fd != 2)
609 				dup2(fd, 2);
610 			if (fd > 2)
611 				close(fd);
612 			puts("\nSuccessfully reopened /dev/console.");
613 		}
614 	}
615 
616 	/* try to mount /proc if not mounted. Silently fail otherwise */
617 	if (stat("/proc/.", &stat_buf) == 0 || mkdir("/proc", 0755) == 0) {
618 		if (stat("/proc/self", &stat_buf) != 0)
619 			mount("/proc", "/proc", "proc", 0, 0);
620 	}
621 
622 	return 0;
623 }
624 
625 /* This is the definition of known test names, with their functions */
626 static struct test test_names[] = {
627 	/* add new tests here */
628 	{ .name = "syscall",   .func = run_syscall  },
629 	{ .name = "stdlib",    .func = run_stdlib   },
630 	{ 0 }
631 };
632 
main(int argc,char ** argv,char ** envp)633 int main(int argc, char **argv, char **envp)
634 {
635 	int min = 0;
636 	int max = __INT_MAX__;
637 	int ret = 0;
638 	int err;
639 	int idx;
640 	char *test;
641 
642 	environ = envp;
643 
644 	/* when called as init, it's possible that no console was opened, for
645 	 * example if no /dev file system was provided. We'll check that fd#1
646 	 * was opened, and if not we'll attempt to create and open /dev/console
647 	 * and /dev/null that we'll use for later tests.
648 	 */
649 	if (getpid() == 1)
650 		prepare();
651 
652 	/* the definition of a series of tests comes from either argv[1] or the
653 	 * "NOLIBC_TEST" environment variable. It's made of a comma-delimited
654 	 * series of test names and optional ranges:
655 	 *    syscall:5-15[:.*],stdlib:8-10
656 	 */
657 	test = argv[1];
658 	if (!test)
659 		test = getenv("NOLIBC_TEST");
660 
661 	if (test) {
662 		char *comma, *colon, *dash, *value;
663 
664 		do {
665 			comma = strchr(test, ',');
666 			if (comma)
667 				*(comma++) = '\0';
668 
669 			colon = strchr(test, ':');
670 			if (colon)
671 				*(colon++) = '\0';
672 
673 			for (idx = 0; test_names[idx].name; idx++) {
674 				if (strcmp(test, test_names[idx].name) == 0)
675 					break;
676 			}
677 
678 			if (test_names[idx].name) {
679 				/* The test was named, it will be called at least
680 				 * once. We may have an optional range at <colon>
681 				 * here, which defaults to the full range.
682 				 */
683 				do {
684 					min = 0; max = __INT_MAX__;
685 					value = colon;
686 					if (value && *value) {
687 						colon = strchr(value, ':');
688 						if (colon)
689 							*(colon++) = '\0';
690 
691 						dash = strchr(value, '-');
692 						if (dash)
693 							*(dash++) = '\0';
694 
695 						/* support :val: :min-max: :min-: :-max: */
696 						if (*value)
697 							min = atoi(value);
698 						if (!dash)
699 							max = min;
700 						else if (*dash)
701 							max = atoi(dash);
702 
703 						value = colon;
704 					}
705 
706 					/* now's time to call the test */
707 					printf("Running test '%s'\n", test_names[idx].name);
708 					err = test_names[idx].func(min, max);
709 					ret += err;
710 					printf("Errors during this test: %d\n\n", err);
711 				} while (colon && *colon);
712 			} else
713 				printf("Ignoring unknown test name '%s'\n", test);
714 
715 			test = comma;
716 		} while (test && *test);
717 	} else {
718 		/* no test mentioned, run everything */
719 		for (idx = 0; test_names[idx].name; idx++) {
720 			printf("Running test '%s'\n", test_names[idx].name);
721 			err = test_names[idx].func(min, max);
722 			ret += err;
723 			printf("Errors during this test: %d\n\n", err);
724 		}
725 	}
726 
727 	printf("Total number of errors: %d\n", ret);
728 
729 	if (getpid() == 1) {
730 		/* we're running as init, there's no other process on the
731 		 * system, thus likely started from a VM for a quick check.
732 		 * Exiting will provoke a kernel panic that may be reported
733 		 * as an error by Qemu or the hypervisor, while stopping
734 		 * cleanly will often be reported as a success. This allows
735 		 * to use the output of this program for bisecting kernels.
736 		 */
737 		printf("Leaving init with final status: %d\n", !!ret);
738 		if (ret == 0)
739 			reboot(LINUX_REBOOT_CMD_POWER_OFF);
740 #if defined(__x86_64__)
741 		/* QEMU started with "-device isa-debug-exit -no-reboot" will
742 		 * exit with status code 2N+1 when N is written to 0x501. We
743 		 * hard-code the syscall here as it's arch-dependent.
744 		 */
745 #if defined(_NOLIBC_SYS_H)
746 		else if (my_syscall3(__NR_ioperm, 0x501, 1, 1) == 0)
747 #else
748 		else if (ioperm(0x501, 1, 1) == 0)
749 #endif
750 			asm volatile ("outb %%al, %%dx" :: "d"(0x501), "a"(0));
751 		/* if it does nothing, fall back to the regular panic */
752 #endif
753 	}
754 
755 	printf("Exiting with status %d\n", !!ret);
756 	return !!ret;
757 }
758