xref: /openbsd/regress/sys/uvm/mmap_4g/mmap_4g.c (revision 5dea098c)
1 /*	$OpenBSD: mmap_4g.c,v 1.5 2021/10/24 21:24:21 deraadt Exp $	*/
2 
3 /*
4  * Public domain. 2005, Otto Moerbeek <otto@drijf.net>
5  */
6 
7 #include <sys/types.h>
8 #include <sys/mman.h>
9 #include <err.h>
10 #include <fcntl.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 
15 /*
16  * Write near the 4g boundary using a mmaped file and check if the
17  * bytes do not wrap to offset 0.
18  */
19 
20 int
21 main()
22 {
23 	int fd;
24 	off_t offset;
25 	size_t i, sz;
26 	char *p, buf[100];
27 	const char * file = "foo";
28 
29 	fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
30 	if (fd == -1)
31 		err(1, "open");
32 
33 	sz = sizeof(buf);
34 	offset = 4LL * 1024LL * 1024LL * 1024LL - sz/2;
35 
36 	if (lseek(fd, offset, SEEK_SET) != offset)
37 		err(1, "lseek");
38 	memset(buf, 0, sz);
39 	if (write(fd, buf, sz) != sz)
40 		err(1, "write");
41 	close(fd);
42 
43 	fd = open(file, O_RDWR);
44 	if (fd == -1)
45 		err(1, "open");
46 	p = mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED,
47 	    fd, offset);
48 	if (p == MAP_FAILED)
49 		err(1, "mmap");
50 	for (i = 0; i < sz; i++)
51 		p[i] = i + 1;
52 	if (munmap(p, sz) == -1)
53 		err(1, "munmap");
54 	close(fd);
55 
56 	fd = open(file, O_RDONLY);
57 	if (fd == -1)
58 		err(1, "open");
59 	if (read(fd, buf, sz) != sz)
60 		err(1, "read");
61 	for (i = 0; i < sz; i++)
62 		if (buf[i])
63 			errx(1, "nonzero byte 0x%02x found at offset %zu",
64 			    buf[i], i);
65 
66 	if (lseek(fd, offset, SEEK_SET) != offset)
67 		err(1, "lseek");
68 	if (read(fd, buf, sz) != sz)
69 		err(1, "read");
70 	for (i = 0; i < sz; i++)
71 		if (buf[i] != i + 1)
72 			err(1, "incorrect value 0x%02x at offset %llx",
73 			    p[i], offset + i);
74 
75 	close(fd);
76 	unlink(file);
77 	return 0;
78 }
79