| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <fcntl.h> |
| 8 |
#include <signal.h> |
| 9 |
#include <stdio.h> |
| 10 |
#include <string.h> |
| 11 |
#include <sys/mman.h> |
| 12 |
#include <sys/stat.h> |
| 13 |
#include <sys/types.h> |
| 14 |
#include <unistd.h> |
| 15 |
|
| 16 |
static int alloc_size; |
| 17 |
static char* memory; |
| 18 |
|
| 19 |
void segv_handler (int signal_number) |
| 20 |
{ |
| 21 |
printf ("memory accessed!\n"); |
| 22 |
mprotect (memory, alloc_size, PROT_READ | PROT_WRITE); |
| 23 |
} |
| 24 |
|
| 25 |
int main () |
| 26 |
{ |
| 27 |
int fd; |
| 28 |
struct sigaction sa; |
| 29 |
|
| 30 |
/* Install segv_handler as the handler for SIGSEGV. */ |
| 31 |
memset (&sa, 0, sizeof (sa)); |
| 32 |
sa.sa_handler = &segv_handler; |
| 33 |
sigaction (SIGSEGV, &sa, NULL); |
| 34 |
|
| 35 |
/* Allocate one page of memory by mapping /dev/zero. Map the memory |
| 36 |
as write-only, intially. */ |
| 37 |
alloc_size = getpagesize (); |
| 38 |
fd = open ("/dev/zero", O_RDONLY); |
| 39 |
memory = mmap (NULL, alloc_size, PROT_WRITE, MAP_PRIVATE, fd, 0); |
| 40 |
close (fd); |
| 41 |
/* Write to the page to obtain a private copy. */ |
| 42 |
memory[0] = 0; |
| 43 |
/* Make the the memory unwritable. */ |
| 44 |
mprotect (memory, alloc_size, PROT_NONE); |
| 45 |
|
| 46 |
/* Write to the allocated memory region. */ |
| 47 |
memory[0] = 1; |
| 48 |
|
| 49 |
/* All done; unmap the memory. */ |
| 50 |
printf ("all done\n"); |
| 51 |
munmap (memory, alloc_size); |
| 52 |
return 0; |
| 53 |
} |