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 * MAP_SHARED and MAP_PRIVATE describe the disposition of write references
10 * to the memory object. If MAP_SHARED is specified, write references shall
11 * change the underlying object. If MAP_PRIVATE is specified, modifications
12 * to the mapped data by the calling process shall be visible only to the
13 * calling process and shall not change the underlying object.
14 * It is unspecified whether modifications to the underlying object done
15 * after the MAP_PRIVATE mapping is established are visible through
16 * the MAP_PRIVATE mapping.
17 *
18 * Test Steps:
19 * 1. mmap a file into memory. Set flag as MAP_PRIVATE.
20 * 2. Modify the mapped memory, and call msync to try to synchronize the change.
21 * 3. munmap the mapped memory.
22 * 4. mmap the same file again into memory.
23 * 5. If the modification in step 2 appears in the mapped memory, then fail,
24 * otherwise pass.
25 */
26
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <sys/mman.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <fcntl.h>
36 #include <string.h>
37 #include <errno.h>
38 #include "posixtest.h"
39
main(void)40 int main(void)
41 {
42 char tmpfname[256];
43 ssize_t size = 1024;
44 char data[size];
45 void *pa;
46 int fd;
47
48 snprintf(tmpfname, sizeof(tmpfname), "/tmp/pts_mmap_7_2_%d", getpid());
49 unlink(tmpfname);
50 fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
51 if (fd == -1) {
52 printf("Error at open(): %s\n", strerror(errno));
53 return PTS_UNRESOLVED;
54 }
55 unlink(tmpfname);
56
57 memset(data, 'a', size);
58 if (write(fd, data, size) != size) {
59 printf("Error at write(): %s\n", strerror(errno));
60 return PTS_UNRESOLVED;
61 }
62
63 pa = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
64 if (pa == MAP_FAILED) {
65 printf("Error at mmap(): %s\n", strerror(errno));
66 return PTS_FAIL;
67 }
68
69 *(char *)pa = 'b';
70
71 /* Try to flush changes back to the file */
72 if (msync(pa, size, MS_SYNC) != 0) {
73 printf("Error at msync(): %s\n", strerror(errno));
74 return PTS_UNRESOLVED;
75 }
76
77 munmap(pa, size);
78
79 /* Mmap again */
80 pa = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
81 if (pa == MAP_FAILED) {
82 printf("Error at 2nd mmap(): %s\n", strerror(errno));
83 return PTS_FAIL;
84 }
85
86 if (*(char *)pa == 'b') {
87 printf("Memory write with MAP_PRIVATE has changed "
88 "the underlying file\n" "Test FAILED\n");
89 exit(PTS_FAIL);
90 }
91
92 close(fd);
93 printf("Memory write with MAP_PRIVATE has not changed "
94 "the underlying file\n" "Test PASSED\n");
95 return PTS_PASS;
96 }
97