1 | #include <errno.h>
|
---|
2 | #include <fcntl.h>
|
---|
3 | #include <stdio.h>
|
---|
4 | #include <stdlib.h>
|
---|
5 | #include <string.h>
|
---|
6 | #include <sys/mman.h>
|
---|
7 | #include <unistd.h>
|
---|
8 | #include <OS.h>
|
---|
9 |
|
---|
10 | int
|
---|
11 | main()
|
---|
12 | {
|
---|
13 | // This file should be larger than available RAM.
|
---|
14 | const char* fileName = "/tmp/mmap-test-file";
|
---|
15 |
|
---|
16 | printf("opening file...\n");
|
---|
17 | int fd = open(fileName, O_RDONLY);
|
---|
18 | if (fd < 0) {
|
---|
19 | fprintf(stderr, "Failed to open \"%s\": %s\n", fileName,
|
---|
20 | strerror(errno));
|
---|
21 | exit(1);
|
---|
22 | }
|
---|
23 |
|
---|
24 | off_t fsize = lseek(fd, 0, SEEK_END);
|
---|
25 | fprintf(stderr, "File size: %" B_PRIuSIZE "\n", fsize);
|
---|
26 |
|
---|
27 | // map
|
---|
28 | printf("mapping file...\n");
|
---|
29 | void* address = mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
|
---|
30 | if (address == MAP_FAILED) {
|
---|
31 | fprintf(stderr, "Failed to map the file: %s\n", strerror(errno));
|
---|
32 | exit(1);
|
---|
33 | }
|
---|
34 |
|
---|
35 | // remap writable (should fail, not enough memory)
|
---|
36 | if (mprotect(address, fsize, PROT_WRITE) >= 0) {
|
---|
37 | fprintf(stderr, "Unexpected success on mprotect!");
|
---|
38 | exit(1);
|
---|
39 | }
|
---|
40 |
|
---|
41 | // remap just one part writable (should work)
|
---|
42 | if (mprotect(address, B_PAGE_SIZE, PROT_READ | PROT_WRITE) < 0) {
|
---|
43 | fprintf(stderr, "Failed to protect first page: %s\n", strerror(errno));
|
---|
44 | exit(1);
|
---|
45 | }
|
---|
46 | if (mprotect(address, B_PAGE_SIZE, PROT_READ) < 0) {
|
---|
47 | fprintf(stderr, "Failed to unprotect page: %s\n", strerror(errno));
|
---|
48 | exit(1);
|
---|
49 | }
|
---|
50 | if (mprotect(address, B_PAGE_SIZE * 10, PROT_READ | PROT_WRITE) < 0) {
|
---|
51 | fprintf(stderr, "Failed to protect multiple pages: %s\n", strerror(errno));
|
---|
52 | exit(1);
|
---|
53 | }
|
---|
54 |
|
---|
55 | return 0;
|
---|
56 | }
|
---|
57 |
|
---|