• 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 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 #define _XOPEN_SOURCE 600
21 
22 #include <sys/mman.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include "posixtest.h"
34 
35 #define WRITE(str) write(STDOUT_FILENO, str, sizeof(str) - 1)
36 
sigbus_handler(int signum)37 void sigbus_handler(int signum)
38 {
39 	if (signum == SIGBUS) {
40 		WRITE("SIGBUS triggered\n");
41 		WRITE("Test PASSED\n");
42 		_exit(PTS_PASS);
43 	}
44 }
45 
main(void)46 int main(void)
47 {
48 #ifndef _POSIX_MEMORY_PROTECTION
49 	printf("_POSIX_MEMORY_PROTECTION is not defined\n");
50 	return PTS_UNTESTED;
51 #endif
52 	char tmpfname[256];
53 	long page_size;
54 	long total_size;
55 
56 	void *pa;
57 	size_t len;
58 	int fd;
59 
60 	char *ch;
61 	struct sigaction sa;
62 
63 	page_size = sysconf(_SC_PAGE_SIZE);
64 
65 	/* Size of the file to be mapped */
66 	total_size = page_size / 2;
67 
68 	/* mmap 2 pages */
69 	len = page_size * 2;
70 
71 	sigfillset(&sa.sa_mask);
72 	sa.sa_handler = sigbus_handler;
73 	sigaction(SIGBUS, &sa, NULL);
74 
75 	/* Create tmp file */
76 	snprintf(tmpfname, sizeof(tmpfname), "/tmp/pts_mmap_11_2_%d", getpid());
77 	unlink(tmpfname);
78 	fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
79 	if (fd == -1) {
80 		printf("Error at open(): %s\n", strerror(errno));
81 		return PTS_UNRESOLVED;
82 	}
83 	unlink(tmpfname);
84 
85 	if (ftruncate(fd, total_size) == -1) {
86 		printf("Error at ftruncate(): %s\n", strerror(errno));
87 		return PTS_UNRESOLVED;
88 	}
89 
90 	pa = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
91 	if (pa == MAP_FAILED) {
92 		printf("Error at mmap(): %s\n", strerror(errno));
93 		return PTS_FAIL;
94 	}
95 
96 	/* Read the second page */
97 	ch = pa + page_size + 1;
98 
99 	/* This reference should trigger SIGBUS */
100 	*ch = 0;
101 
102 	/* wait for a while */
103 	sleep(1);
104 
105 	printf("Test FAILED: SIGBUS not triggered, "
106 	       "while Memory Protection is enabled\n");
107 	return PTS_FAIL;
108 }
109