bench: pass N as argument, update readme
[libc-test] / common / t.c
1 #define _POSIX_C_SOURCE 200809L
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <stdarg.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <sys/types.h>
8 #include <sys/wait.h>
9 #include <unistd.h>
10 #include "test.h"
11
12 #define B(f)
13 #define T(f) void f();
14 #include "tests.h"
15 #undef T
16
17 static int failed;
18 static const char *name;
19
20 static int verbose;
21 static int count;
22 static int nfailed;
23
24 static void errtimer() { error("use *_timer in benchmarks only\n"); }
25 void start_timer() { errtimer(); }
26 void stop_timer() { errtimer(); }
27 void reset_timer() { errtimer(); }
28
29 void error__(const char *n, int l, const char *s, ...) {
30         va_list ap;
31
32         failed = 1;
33         fprintf(stderr, "- ERROR %s at %s:%d: ", name, n, l);
34         va_start(ap, s);
35         vfprintf(stderr, s, ap);
36         va_end(ap);
37 }
38
39 static void run(const char *n, void (*f)()) {
40         pid_t pid;
41         int s;
42
43         count++;
44         failed = 0;
45         name = n;
46         if (verbose)
47                 fprintf(stderr, "running %s:\n", name);
48
49         pid = fork();
50         if (pid == 0) {
51                 /* run test in a child process */
52                 f();
53                 exit(failed);
54         }
55
56         if (pid == -1)
57                 error("fork failed: %s\n", strerror(errno));
58         else {
59                 if (waitpid(pid, &s, 0) == -1)
60                         error("waitpid failed: %s\n", strerror(errno));
61                 else if (!WIFEXITED(s))
62                         error("abnormal exit: %s\n", WIFSIGNALED(s) ? strsignal(WTERMSIG(s)) : "(unknown)");
63                 else
64                         failed = !!WEXITSTATUS(s);
65         }
66
67         if (failed) {
68                 nfailed++;
69                 fprintf(stderr, "FAILED %s\n", name);
70         } else if (verbose)
71                 fprintf(stderr, "PASSED %s\n", name);
72 }
73
74 static int summary() {
75         fprintf(stderr, "PASS:%d FAIL:%d\n", count-nfailed, nfailed);
76         return !!nfailed;
77 }
78
79 int main() {
80 #define T(t) run(#t, t);
81 #include "tests.h"
82         return summary();
83 }