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 shared memory object of size 1/2 * page_size,
15 * with len = 2 * page_size
16 * 2. If Memory Protection option is supported, read the second page
17 * beyond the end of the object, 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 #include "posixtest.h"
33
sigbus_handler(int signum)34 static void sigbus_handler(int signum)
35 {
36 if (signum == SIGBUS) {
37 PTS_WRITE_MSG("SIGBUS triggered\n");
38 PTS_WRITE_MSG("Test PASSED\n");
39 _exit(PTS_PASS);
40 }
41 }
42
main(void)43 int main(void)
44 {
45 #ifndef _POSIX_MEMORY_PROTECTION
46 printf("_POSIX_MEMORY_PROTECTION is not defined\n");
47 return PTS_UNTESTED;
48 #endif
49 char tmpfname[256];
50 long page_size;
51 long total_size;
52
53 void *pa;
54 size_t len;
55 int fd;
56
57 char *ch;
58
59 struct sigaction sa;
60
61 page_size = sysconf(_SC_PAGE_SIZE);
62
63 /* Size of the shared memory object to be mapped */
64 total_size = page_size / 2;
65
66 /* mmap will create a partial page */
67 len = page_size * 2;
68
69 sigfillset(&sa.sa_mask);
70 sa.sa_handler = sigbus_handler;
71 sigaction(SIGBUS, &sa, NULL);
72
73 snprintf(tmpfname, sizeof(tmpfname), "/pts_mmap_11_3_%d", getpid());
74 /* Create shared object */
75 shm_unlink(tmpfname);
76 fd = shm_open(tmpfname, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
77 if (fd == -1) {
78 printf("Error at shm_open(): %s\n", strerror(errno));
79 return PTS_UNRESOLVED;
80 }
81 shm_unlink(tmpfname);
82 if (ftruncate(fd, total_size) == -1) {
83 printf("Error at ftruncate(): %s\n", strerror(errno));
84 return PTS_UNRESOLVED;
85 }
86
87 pa = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
88 if (pa == MAP_FAILED) {
89 printf("Error at mmap(): %s\n", strerror(errno));
90 return PTS_FAIL;
91 }
92
93 ch = pa + page_size + 1;
94
95 /* This reference should trigger SIGBUS */
96 *ch = 0;
97
98 /* wait for a while */
99 sleep(1);
100
101 printf("Test FAILED: SIGBUS not triggered, "
102 "while Memory Protection is enabled\n");
103 return PTS_FAIL;
104 }
105