• 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  * If MAP_FIXED is set,
10  * mmap() may return MAP_FAILED and set errno to [EINVAL].
11  *
12  * [EINVAL] The addr argument (if MAP_FIXED was specified) or off is not a
13  * multiple of the page size as returned by sysconf(), or is considered invalid
14  * by the implementation.
15  *
16  * Test Steps:
17  * 1. Set 'addr' as an illegal address, which is not a multiple of page size;
18  * 2. Call mmap() and get EINVAL;
19  */
20 
21 
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <sys/mman.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <fcntl.h>
30 #include <string.h>
31 #include <errno.h>
32 
33 #include "posixtest.h"
34 #include "tempfile.h"
35 
main(void)36 int main(void)
37 {
38 	char tmpfname[PATH_MAX];
39 	long page_size;
40 	long total_size;
41 
42 	void *illegal_addr;
43 	void *pa;
44 	size_t size;
45 	int fd, saved_errno;
46 
47 	page_size = sysconf(_SC_PAGE_SIZE);
48 	total_size = page_size;
49 	size = total_size;
50 
51 	/* Create tmp file */
52 	PTS_GET_TMP_FILENAME(tmpfname, "pts_mmap_9_1");
53 	unlink(tmpfname);
54 	fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
55 	if (fd == -1) {
56 		printf("Error at open(): %s\n", strerror(errno));
57 		return PTS_UNRESOLVED;
58 	}
59 	unlink(tmpfname);
60 	if (ftruncate(fd, total_size) == -1) {
61 		printf("Error at ftruncate(): %s\n", strerror(errno));
62 		return PTS_UNRESOLVED;
63 	}
64 
65 	/* Map the file for the first time, to get a legal address, pa */
66 	pa = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
67 
68 	if ((unsigned long)pa % page_size) {
69 		printf("pa is not multiple of page_size\n");
70 		illegal_addr = pa;
71 	} else {
72 		printf("pa is a multiple of page_size\n");
73 		illegal_addr = pa + 1;
74 	}
75 
76 	munmap(pa, size);
77 
78 	/* Mmap again using the illegal address, setting MAP_FIXED */
79 	pa = mmap(illegal_addr, size, PROT_READ | PROT_WRITE, MAP_FIXED, fd, 0);
80 
81 	saved_errno = errno;
82 
83 	close(fd);
84 	munmap(pa, size);
85 
86 	if (pa == MAP_FAILED && saved_errno == EINVAL) {
87 		printf("Test PASSED\n");
88 		return PTS_PASS;
89 	}
90 
91 	printf("Test FAILED, mmap with MAP_FIXED did not get EINVAL"
92 	       " when 'addr' is illegal\n");
93 	return PTS_FAIL;
94 }
95