Skip to content

Instantly share code, notes, and snippets.

@weissi
Last active August 29, 2015 14:19
Show Gist options
  • Save weissi/e3a54459e9aa685e2e18 to your computer and use it in GitHub Desktop.
Save weissi/e3a54459e9aa685e2e18 to your computer and use it in GitHub Desktop.
This `mmap`s a region of a file beyond EOF.
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int main()
{
int exit_code = EXIT_SUCCESS;
int err = -1;
char temp_file[] = "/tmp/.mmap-test-XXXXXX";
long pagesize = sysconf(_SC_PAGESIZE);
const off_t file_length = pagesize;
const off_t mmap_offset = 2 * pagesize;
assert(0 == (mmap_offset & (pagesize -1)));
int fd = mkstemp(temp_file);
if (fd < 0) {
perror("mkstemp");
exit(EXIT_FAILURE);
}
err = ftruncate(fd, file_length);
if (err) {
goto cleanup_close_unlink_exit;
}
/* we should check here whether `mmap_offset` is within the file
or ftruncate(fd, big_enough_size) but both are racy */
void *m = mmap(0, pagesize, PROT_READ, MAP_PRIVATE, fd, mmap_offset);
if (MAP_FAILED == m) {
perror("mmap");
goto cleanup_close_unlink_exit;
} else {
printf("mmap ok (%p), offset = %lld\n", m, (long long int)mmap_offset);
}
fflush(stdout);
err = *(int *)m; /* read a bit from that page --> WILL CRASH RECEIVING SIGBUS */
printf("successfully read '%d'\n", err);
munmap(m, mmap_offset);
cleanup_close_unlink_exit:
err = close(fd);
if (err) {
perror("close");
}
err = unlink(temp_file);
if (err) {
perror("unlink");
exit_code = EXIT_FAILURE;
}
exit(exit_code);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment