1*b7041c07Sderaadt /* $OpenBSD: mmap_4g.c,v 1.5 2021/10/24 21:24:21 deraadt Exp $ */
20e9624c9Sotto
30e9624c9Sotto /*
40e9624c9Sotto * Public domain. 2005, Otto Moerbeek <otto@drijf.net>
50e9624c9Sotto */
60e9624c9Sotto
70e9624c9Sotto #include <sys/types.h>
80e9624c9Sotto #include <sys/mman.h>
90e9624c9Sotto #include <err.h>
100e9624c9Sotto #include <fcntl.h>
110e9624c9Sotto #include <stdio.h>
12bc1257b2Sphessler #include <string.h>
130e9624c9Sotto #include <unistd.h>
140e9624c9Sotto
150e9624c9Sotto /*
160e9624c9Sotto * Write near the 4g boundary using a mmaped file and check if the
170e9624c9Sotto * bytes do not wrap to offset 0.
180e9624c9Sotto */
190e9624c9Sotto
200e9624c9Sotto int
main()210e9624c9Sotto main()
220e9624c9Sotto {
236bceb37aSbluhm int fd;
240e9624c9Sotto off_t offset;
256bceb37aSbluhm size_t i, sz;
260e9624c9Sotto char *p, buf[100];
270e9624c9Sotto const char * file = "foo";
280e9624c9Sotto
290e9624c9Sotto fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
300e9624c9Sotto if (fd == -1)
310e9624c9Sotto err(1, "open");
320e9624c9Sotto
3323322319Sotto sz = sizeof(buf);
340e9624c9Sotto offset = 4LL * 1024LL * 1024LL * 1024LL - sz/2;
350e9624c9Sotto
360e9624c9Sotto if (lseek(fd, offset, SEEK_SET) != offset)
370e9624c9Sotto err(1, "lseek");
380e9624c9Sotto memset(buf, 0, sz);
390e9624c9Sotto if (write(fd, buf, sz) != sz)
400e9624c9Sotto err(1, "write");
410e9624c9Sotto close(fd);
420e9624c9Sotto
43*b7041c07Sderaadt fd = open(file, O_RDWR);
440e9624c9Sotto if (fd == -1)
450e9624c9Sotto err(1, "open");
460e9624c9Sotto p = mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED,
470e9624c9Sotto fd, offset);
480e9624c9Sotto if (p == MAP_FAILED)
490e9624c9Sotto err(1, "mmap");
500e9624c9Sotto for (i = 0; i < sz; i++)
510e9624c9Sotto p[i] = i + 1;
520e9624c9Sotto if (munmap(p, sz) == -1)
530e9624c9Sotto err(1, "munmap");
540e9624c9Sotto close(fd);
550e9624c9Sotto
56*b7041c07Sderaadt fd = open(file, O_RDONLY);
570e9624c9Sotto if (fd == -1)
580e9624c9Sotto err(1, "open");
590e9624c9Sotto if (read(fd, buf, sz) != sz)
600e9624c9Sotto err(1, "read");
610e9624c9Sotto for (i = 0; i < sz; i++)
620e9624c9Sotto if (buf[i])
630e9624c9Sotto errx(1, "nonzero byte 0x%02x found at offset %zu",
640e9624c9Sotto buf[i], i);
650e9624c9Sotto
660e9624c9Sotto if (lseek(fd, offset, SEEK_SET) != offset)
670e9624c9Sotto err(1, "lseek");
680e9624c9Sotto if (read(fd, buf, sz) != sz)
690e9624c9Sotto err(1, "read");
700e9624c9Sotto for (i = 0; i < sz; i++)
710e9624c9Sotto if (buf[i] != i + 1)
720e9624c9Sotto err(1, "incorrect value 0x%02x at offset %llx",
730e9624c9Sotto p[i], offset + i);
740e9624c9Sotto
750e9624c9Sotto close(fd);
760e9624c9Sotto unlink(file);
770e9624c9Sotto return 0;
780e9624c9Sotto }
79