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