1 /*
2 * Copyright (c) 2002, Intel Corporation. All rights reserved.
3 * Copyright (c) 2012, Cyril Hrubis <chrubis@suse.cz>
4 *
5 * This file is licensed under the GPL license. For the full content
6 * of this license, see the COPYING file at the top level of this
7 * source tree.
8 *
9 * MPR References within the address range starting at pa and
10 * continuing for len bytes to whole pages following the end
11 * of an object shall result in delivery of a SIGBUS signal.
12 *
13 * Test Steps:
14 * 1. Map a file with size = 1/2 page_size, while len = 2 * page_size
15 * 2. If Memory Protection option is supported, read the second page
16 * beyond the object (mapped file) size (NOT the patial page),
17 * should get SIGBUS;
18 */
19
20
21 #include <sys/mman.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 #include "posixtest.h"
34 #include "tempfile.h"
35
36 #define WRITE(str) write(STDOUT_FILENO, str, sizeof(str) - 1)
37
sigbus_handler(int signum)38 static void sigbus_handler(int signum)
39 {
40 if (signum == SIGBUS) {
41 WRITE("SIGBUS triggered\n");
42 WRITE("Test PASSED\n");
43 _exit(PTS_PASS);
44 }
45 }
46
main(void)47 int main(void)
48 {
49 #ifndef _POSIX_MEMORY_PROTECTION
50 printf("_POSIX_MEMORY_PROTECTION is not defined\n");
51 return PTS_UNTESTED;
52 #endif
53 char tmpfname[PATH_MAX];
54 long page_size;
55 long total_size;
56
57 void *pa;
58 size_t len;
59 int fd;
60
61 char *ch;
62 struct sigaction sa;
63
64 page_size = sysconf(_SC_PAGE_SIZE);
65
66 /* Size of the file to be mapped */
67 total_size = page_size / 2;
68
69 /* mmap 2 pages */
70 len = page_size * 2;
71
72 sigfillset(&sa.sa_mask);
73 sa.sa_handler = sigbus_handler;
74 sigaction(SIGBUS, &sa, NULL);
75
76 /* Create tmp file */
77 PTS_GET_TMP_FILENAME(tmpfname, "pts_mmap_11_2");
78 unlink(tmpfname);
79 fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
80 if (fd == -1) {
81 printf("Error at open(): %s\n", strerror(errno));
82 return PTS_UNRESOLVED;
83 }
84 unlink(tmpfname);
85
86 if (ftruncate(fd, total_size) == -1) {
87 printf("Error at ftruncate(): %s\n", strerror(errno));
88 return PTS_UNRESOLVED;
89 }
90
91 pa = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
92 if (pa == MAP_FAILED) {
93 printf("Error at mmap(): %s\n", strerror(errno));
94 return PTS_FAIL;
95 }
96
97 /* Read the second page */
98 ch = pa + page_size + 1;
99
100 /* This reference should trigger SIGBUS */
101 *ch = 0;
102
103 /* wait for a while */
104 sleep(1);
105
106 printf("Test FAILED: SIGBUS not triggered, "
107 "while Memory Protection is enabled\n");
108 return PTS_FAIL;
109 }
110