Skip to content

Instantly share code, notes, and snippets.

@DrPizza
Created April 22, 2016 03:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrPizza/a99c5e7bcf983846d585967defc8df87 to your computer and use it in GitHub Desktop.
Save DrPizza/a99c5e7bcf983846d585967defc8df87 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <ucontext.h>
void sighandler(int signum, siginfo_t* info, ucontext_t* ctxt) {
printf("handler %d addr=%p rip=%#x\n", signum, info->si_addr, ctxt->uc_mcontext.gregs[REG_RIP]);
signal(signum, SIG_DFL);
kill(getpid(), signum);
}
int main(int argc, char *argv[]) {
struct sigaction sa_new = {0};
sa_new.sa_sigaction = (void (*)(int, siginfo_t*, void *))sighandler;
sa_new.sa_flags = SA_ONESHOT | SA_SIGINFO;
sigaction(SIGSEGV, &sa_new, 0);
int total_pages = argc > 1 ? atoi(argv[1]) : 10;
int page_to_unmap = argc > 2 ? atoi(argv[2]) : 0;
int section = shm_open("section", O_RDWR | O_CREAT, (mode_t)0600);
if(section == -1) {
perror("Error creating section");
exit(EXIT_FAILURE);
}
if(ftruncate(section, total_pages * getpagesize()) == -1) {
perror("Error setting section size");
exit(EXIT_FAILURE);
}
int* map = mmap(0, total_pages * getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED, section, 0);
printf("memory mapped at %p\n", map);
if(map == MAP_FAILED) {
perror("Error creating mmap");
exit(EXIT_FAILURE);
}
for(int i = 0; i < (total_pages * getpagesize()) / sizeof(int); ++i) {
map[i] = 2 * i;
}
void* target = map + (page_to_unmap * (getpagesize() / sizeof(int)));
printf("unmapping single page at %p\n", target);
if(munmap(target, getpagesize()) == -1) {
perror("Error unmapping page.");
exit(EXIT_FAILURE);
}
for(int i = 0; i < (total_pages * getpagesize()) / sizeof(int); ++i) {
map[i] = 2 * i;
}
if(munmap(map, total_pages * sizeof(int)) == -1) {
perror("Error unmapping the memory.");
exit(EXIT_FAILURE);
}
close(section);
shm_unlink("section");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment