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