ptr_valid: test whether a ptr is valid.
[ccan] / ccan / ptr_valid / test / run-string.c
1 #include <ccan/ptr_valid/ptr_valid.h>
2 /* Include the C files directly. */
3 #include <ccan/ptr_valid/ptr_valid.c>
4 #include <ccan/tap/tap.h>
5 #include <sys/mman.h>
6
7 int main(void)
8 {
9         char *page;
10         struct ptr_valid_batch *batch = malloc(sizeof *batch);
11
12         /* This is how many tests you plan to run */
13         plan_tests(14);
14
15         page = mmap(NULL, getpagesize(), PROT_READ|PROT_WRITE,
16                     MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
17         strcpy(page, "hello");
18         ok1(ptr_valid_read(page));
19         ok1(ptr_valid_write(page));
20         ok1(ptr_valid_string(page));
21
22         ok1(ptr_valid_batch_start(batch));
23         ok1(ptr_valid_batch_string(batch, page));
24         ptr_valid_batch_end(batch);
25
26         /* Check invalid case. */
27         munmap(page, getpagesize());
28         ok1(!ptr_valid_string(page));
29
30         ok1(ptr_valid_batch_start(batch));
31         ok1(!ptr_valid_batch_string(batch, page));
32         ptr_valid_batch_end(batch);
33
34         /* Check for overrun. */
35         page = mmap(NULL, getpagesize()*2, PROT_READ|PROT_WRITE,
36                     MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
37         munmap(page + getpagesize(), getpagesize());
38
39         memset(page, 'a', getpagesize());
40         ok1(!ptr_valid_string(page));
41         ok1(ptr_valid_batch_start(batch));
42         ok1(!ptr_valid_batch_string(batch, page));
43         ptr_valid_batch_end(batch);
44
45         page[getpagesize()-1] = '\0';
46         ok1(ptr_valid_string(page));
47
48         ok1(ptr_valid_batch_start(batch));
49         ok1(ptr_valid_batch_string(batch, page));
50         ptr_valid_batch_end(batch);
51         munmap(page, getpagesize());
52
53         free(batch);
54         /* This exits depending on whether all tests passed */
55         return exit_status();
56 }