]> git.sesse.net Git - bcachefs-tools-debian/blob - tests/test_helper.c
Disable pristine-tar option in gbp.conf, since there is no pristine-tar branch.
[bcachefs-tools-debian] / tests / test_helper.c
1 #include <assert.h>
2 #include <malloc.h>
3 #include <signal.h>
4 #include <stdbool.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 void trick_compiler(int *x);
10
11 static void test_abort(void)
12 {
13         abort();
14 }
15
16 static void test_segfault(void)
17 {
18         raise(SIGSEGV);
19 }
20
21 static void test_leak(void)
22 {
23         int *p = malloc(sizeof *p);
24         trick_compiler(p);
25 }
26
27 static void test_undefined(void)
28 {
29         int *p = malloc(1);
30         printf("%d\n", *p);
31 }
32
33 static void test_undefined_branch(void)
34 {
35         int x;
36         trick_compiler(&x);
37
38         if (x)
39                 printf("1\n");
40         else
41                 printf("0\n");
42 }
43
44 static void test_read_after_free(void)
45 {
46         int *p = malloc(sizeof *p);
47         free(p);
48
49         printf("%d\n", *p);
50 }
51
52 static void test_write_after_free(void)
53 {
54         int *p = malloc(sizeof *p);
55         free(p);
56
57         printf("%d\n", *p);
58 }
59
60 typedef void (*test_fun)(void);
61
62 struct test {
63         const char      *name;
64         test_fun        fun;
65 };
66
67 #define TEST(f) { .name = #f, .fun = test_##f, }
68 static struct test tests[] = {
69         TEST(abort),
70         TEST(segfault),
71         TEST(leak),
72         TEST(undefined),
73         TEST(undefined_branch),
74         TEST(read_after_free),
75         TEST(write_after_free),
76 };
77 #define ntests (sizeof tests / sizeof *tests)
78
79 int main(int argc, char *argv[])
80 {
81         int i;
82
83         if (argc != 2) {
84                 fprintf(stderr, "Usage: test_helper <test>\n");
85                 exit(1);
86         }
87
88         bool found = false;
89         for (i = 0; i < ntests; ++i)
90                 if (!strcmp(argv[1], tests[i].name)) {
91                         found = true;
92                         printf("Running test: %s\n", tests[i].name);
93                         tests[i].fun();
94                         break;
95                 }
96
97         if (!found) {
98                 fprintf(stderr, "Unable to find test: %s\n", argv[1]);
99                 exit(1);
100         }
101
102         return 0;
103 }