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 add an extra reference to the file
10 * associated with the file descriptor fildes which is not removed
11 * by a subsequent close() on that file descriptor.
12 * This reference shall be removed when there are no more
13 * mappings to the file.
14 *
15 * Test Steps:
16 * 1. Create a file, while it is open call unlink().
17 * 2. mmap the file to memory, then call close(). If mmap() added
18 * extra reference to the file, the file content should be accesible
19 * 3. Acces and msync the mapped file
20 */
21
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <sys/mman.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <errno.h>
33
34 #include "posixtest.h"
35 #include "tempfile.h"
36
main(void)37 int main(void)
38 {
39 char tmpfname[PATH_MAX];
40 void *pa;
41 ssize_t size = 1024;
42 int fd, i;
43
44 PTS_GET_TMP_FILENAME(tmpfname, "pts_mmap_12_1");
45 unlink(tmpfname);
46 fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR);
47 if (fd == -1) {
48 printf("Error at open(): %s\n", strerror(errno));
49 return PTS_UNRESOLVED;
50 }
51
52 unlink(tmpfname);
53
54 if (ftruncate(fd, size) == -1) {
55 printf("Error at ftruncate(): %s\n", strerror(errno));
56 return PTS_UNRESOLVED;
57 }
58
59 pa = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
60 if (pa == MAP_FAILED) {
61 printf("Error at mmap: %s\n", strerror(errno));
62 return PTS_FAIL;
63 }
64
65 /* Close the file, now it's referenced only by the mapping */
66 close(fd);
67
68 /* Fill the buffer */
69 for (i = 0; i < size; i++)
70 ((char *)pa)[i] = (13 * i) % 21;
71
72 /* Force the data to be written to disk */
73 msync(pa, size, MS_SYNC);
74
75 /* Check if the buffer still contains data */
76 for (i = 0; i < size; i++) {
77 if (((char *)pa)[i] != (13 * i) % 21) {
78 printf("FAILED: Mapped buffer was not preserved\n");
79 return PTS_FAIL;
80 }
81 }
82
83 /*
84 * Unmap the buffer, now data should be freed
85 * Unfortunaltely we have no definitive way to check
86 */
87 munmap(pa, size);
88
89 printf("Test PASSED\n");
90 return PTS_PASS;
91 }
92