#include #include #include #include #include // if defined, uses mmap(), otherwise uses malloc() // if using malloc() will mprotect cause trouble with dlmalloc? // i.e. if you PROT_NONE and then free(), would the next time malloc // allocates that memory still be protected? That's bad.. #define USE_MMAP int main() { char *p, *buf, *prot, *saved_p; int i; int buffer_size = 1024; int page_size = getpagesize(); int total = buffer_size + page_size; // round total up to the nearest page total = (total + page_size - 1) & ~(page_size-1); #ifdef USE_MMAP p = mmap(0, total, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0); if (p == MAP_FAILED) { perror("mmap"); exit(1); } #else saved_p = p = malloc(total+page_size); // realign p to page p = (void *) (((unsigned int) p + page_size - 1) & ~(page_size-1)); #endif printf("p: %p\n", p); buf = p; prot = p + total - page_size; if (mprotect(prot, page_size, PROT_NONE) < 0) { perror("mprotect"); exit(1); } printf("Set buf to 0\n"); fflush(stdout); for (i = 0; i < buffer_size; i++) { buf[i] = 0; } printf("Overflowing...\n"); fflush(stdout); for (i = total - page_size; i < total; i++) { printf("i: %d\n", i); fflush(stdout); buf[i] = 0; } printf("We shouldn't reach here.\n"); fflush(stdout); #ifdef USE_MMAP munmap(p, total); #else free(saved_p); #endif return 0; }