Skip to content

Instantly share code, notes, and snippets.

@kamalmarhubi
Last active Aug 29, 2015
Embed
What would you like to do?
What signal gets delivered for accessing past end of a memory mapped file?
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
static int fd;
static void handler(int signo, siginfo_t *siginfo, void *context __attribute__((unused))) {
printf("Received signal while accessing %p: %s\n", siginfo->si_addr, strsignal(signo));
printf("Going to ftruncate\n");
if (ftruncate(fd, 256) == -1) {
perror("could not ftruncate");
exit(EXIT_FAILURE);
}
}
int main() {
char filename[64];
void *mapped_region;
struct sigaction sa;
char* poker;
memset(&sa, '\0', sizeof(sa));
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = handler;
if (sigaction(SIGBUS, &sa, NULL) == -1) {
perror("could not set SIGBUS handler");
exit(EXIT_FAILURE);
}
if (sigaction(SIGSEGV, &sa, NULL) == -1) {
perror("could not set SIGSEGV handler");
exit(EXIT_FAILURE);
}
strcpy(filename, "/tmp/mapme-XXXXXX");
if ((fd = mkstemp(filename)) == -1) {
perror("could not create tmp file");
exit(EXIT_FAILURE);
}
if ((mapped_region = mmap(NULL, 256, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
perror("could not mmap file");
exit(EXIT_FAILURE);
}
poker = mapped_region;
printf("Read: %d\n", *poker);
*poker = 1;
printf("Wrote and read: %d\n", *poker);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment