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