1 #include <assert.h>
2 #include <stdlib.h>
3 #include <sys/mman.h>
4 #include <unistd.h>
5
test_anonymous(void)6 static void test_anonymous(void)
7 {
8 int pagesize = getpagesize();
9 char *page;
10 int ret;
11
12 page = mmap(NULL, pagesize, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
13 assert(page != MAP_FAILED);
14
15 /* Check that mprotect() does not interfere with MADV_DONTNEED. */
16 ret = mprotect(page, pagesize, PROT_READ | PROT_WRITE);
17 assert(ret == 0);
18
19 /* Check that MADV_DONTNEED clears the page. */
20 *page = 42;
21 ret = madvise(page, pagesize, MADV_DONTNEED);
22 assert(ret == 0);
23 assert(*page == 0);
24
25 ret = munmap(page, pagesize);
26 assert(ret == 0);
27 }
28
test_file(void)29 static void test_file(void)
30 {
31 char tempname[] = "/tmp/.cmadviseXXXXXX";
32 int pagesize = getpagesize();
33 ssize_t written;
34 char c = 42;
35 char *page;
36 int ret;
37 int fd;
38
39 fd = mkstemp(tempname);
40 assert(fd != -1);
41 ret = unlink(tempname);
42 assert(ret == 0);
43 written = write(fd, &c, sizeof(c));
44 assert(written == sizeof(c));
45 ret = ftruncate(fd, pagesize);
46 assert(ret == 0);
47 page = mmap(NULL, pagesize, PROT_READ, MAP_PRIVATE, fd, 0);
48 assert(page != MAP_FAILED);
49
50 /* Check that mprotect() does not interfere with MADV_DONTNEED. */
51 ret = mprotect(page, pagesize, PROT_READ | PROT_WRITE);
52 assert(ret == 0);
53
54 /* Check that MADV_DONTNEED resets the page. */
55 *page = 0;
56 ret = madvise(page, pagesize, MADV_DONTNEED);
57 assert(ret == 0);
58 assert(*page == c);
59
60 ret = munmap(page, pagesize);
61 assert(ret == 0);
62 ret = close(fd);
63 assert(ret == 0);
64 }
65
main(void)66 int main(void)
67 {
68 test_anonymous();
69 test_file();
70
71 return EXIT_SUCCESS;
72 }
73