1 /* $OpenBSD: mmaptest.c,v 1.7 2014/09/27 06:28:45 doug Exp $ */
2 /*
3 * Copyright (c) 2002 Marc Espie.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT AND CONTRIBUTORS
15 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBSD
18 * PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 #include <sys/types.h>
28 #include <sys/mman.h>
29 #include <fcntl.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <err.h>
33 #include <unistd.h>
34
35 #define AREA (16 * 4096)
36 /*
37 * Check for mmap/ftruncate interaction. Specifically, ftruncate on
38 * a short file may lose modifications made through an mmapped area.
39 */
40 int
main(int argc,char * argv[])41 main(int argc, char *argv[])
42 {
43 int i;
44 int fd;
45 char area[AREA];
46 char *a2;
47 for (i = 0 ; i < AREA; i++)
48 area[i] = 5;
49
50 fd = open("test.out", O_WRONLY|O_CREAT|O_TRUNC, 0600);
51 if (fd == -1)
52 err(1, "open(test.out)");
53 if (write(fd, area, AREA) != AREA)
54 err(1, "write");
55 if (close(fd))
56 err(1, "close");
57 fd = open("test.out", O_RDWR);
58 if (fd == -1)
59 err(1, "open(test.out) 2");
60 a2 = mmap(NULL, AREA, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
61 if (a2 == MAP_FAILED)
62 err(1, "mmap");
63 a2[10] = 3;
64 msync(a2, AREA, MS_SYNC|MS_INVALIDATE);
65 if (mlock(a2, AREA))
66 err(1, "mlock");
67 if (ftruncate(fd, 128))
68 err(1, "ftruncate");
69 if (munlock(a2, AREA))
70 err(1, "munlock");
71 if (close(fd))
72 err(1, "close");
73 fd = open("test.out", O_RDONLY);
74 if (fd == -1)
75 err(1, "open(test.out) 3");
76 if (read(fd, area, AREA) != 128)
77 err(1, "read");
78 if (area[10] != 3)
79 errx(1, "area[10] != 3");
80 if (close(fd))
81 err(1, "close");
82 return 0;
83 }
84
85