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  * The mmap() function shall fail if:
10  * [ENOTSUP] MAP_FIXED or MAP_PRIVATE was specified
11  * in the flags argument and the
12  * implementation does not support this functionality.
13  * The implementation does not support the combination
14  * of accesses requested in the prot argument.
15  *
16  * Test Steps:
17  * 1. Try mmap with MAP_PRIVATE should either fail with ENOTSUP or SUCCEED
18  * 2. Try fixed mapping
19  */
20 
21 #define _XOPEN_SOURCE 600
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 <fcntl.h>
29 #include <string.h>
30 #include <errno.h>
31 #include "posixtest.h"
32 
main(void)33 int main(void)
34 {
35 	char tmpfname[256];
36 	int total_size = 1024;
37 
38 	void *pa;
39 	size_t len = total_size;
40 	int fd, err = 0;
41 
42 	snprintf(tmpfname, sizeof(tmpfname), "/tmp/pts_mmap_27_1_%d", getpid());
43 	unlink(tmpfname);
44 	fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
45 	if (fd == -1) {
46 		printf("Error at open(): %s\n", strerror(errno));
47 		return PTS_UNRESOLVED;
48 	}
49 
50 	/* Make sure the file is removed when it is closed */
51 	unlink(tmpfname);
52 
53 	if (ftruncate(fd, total_size) == -1) {
54 		printf("Error at ftruncate(): %s\n", strerror(errno));
55 		return PTS_UNRESOLVED;
56 	}
57 
58 	/* Trie to map file with MAP_PRIVATE */
59 	pa = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
60 	if (pa == MAP_FAILED) {
61 		if (errno != ENOTSUP) {
62 			printf("MAP_PRIVATE is not supported\n");
63 		} else {
64 			printf("MAP_PRIVATE failed with: %s\n",
65 			       strerror(errno));
66 			err++;
67 		}
68 	} else {
69 		printf("MAP_PRIVATE succeeded\n");
70 		munmap(pa, len);
71 	}
72 
73 	/* Now try to utilize MAP_FIXED */
74 	pa = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
75 	if (pa == MAP_FAILED) {
76 		printf("Error at mmap(): %s\n", strerror(errno));
77 		return PTS_UNRESOLVED;
78 	}
79 
80 	pa = mmap(pa, len / 2, PROT_READ, MAP_SHARED | MAP_FIXED, fd, 0);
81 
82 	if (pa == MAP_FAILED) {
83 		if (errno != ENOTSUP) {
84 			printf("MAP_FIXED is not supported\n");
85 		} else {
86 			printf("MAP_FIXED failed with: %s\n", strerror(errno));
87 			err++;
88 		}
89 	} else {
90 		printf("MAP_FIXED succeeded\n");
91 		munmap(pa, len);
92 	}
93 
94 	if (err)
95 		return PTS_FAIL;
96 
97 	printf("Test PASSED\n");
98 	return PTS_PASS;
99 }
100