Skip to content

Instantly share code, notes, and snippets.

@vasi
Last active October 26, 2025 06:04
Show Gist options
  • Select an option

  • Save vasi/470bc6d9ebaf1920846730685b9bb46f to your computer and use it in GitHub Desktop.

Select an option

Save vasi/470bc6d9ebaf1920846730685b9bb46f to your computer and use it in GitHub Desktop.
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sched.h>
void print_maps(void *addr) {
char cmd[256];
snprintf(cmd, sizeof(cmd), "grep %lx /proc/%d/maps",
((unsigned long)addr) & ~0xFFF, getpid());
system(cmd);
}
int main() {
size_t page_size = sysconf(_SC_PAGESIZE);
volatile char *page = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (page == MAP_FAILED) {
perror("mmap"); return 1;
}
printf("Page mapped at: %p\n", (void*)page);
memset((char*)page, 'a', page_size);
printf("Before mprotect:\n");
print_maps((void*)page);
if (mprotect((char*)page, page_size, PROT_READ) == -1) {
perror("mprotect"); return 1;
}
printf("\nAfter mprotect:\n");
print_maps((void*)page);
printf("Before write: %c\n", page[0]);
printf("\nAttempting write...\n");
page[0] = 'x';
printf("After write: %c\n", page[0]);
return 0;
}
#include <sys/mman.h>
#include <stdio.h>
int main() {
int *ptr = mmap(NULL, 4096, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
*ptr = 42; // Write should work
mprotect(ptr, 4096, PROT_READ); // Make read-only
fprintf(stderr, "Trying write after mprotect(PROT_READ)...\n");
*ptr = 99; // This should SEGFAULT
fprintf(stderr, "BUG: Write succeeded! *ptr = %d\n", *ptr);
fprintf(stderr, "\n\n\n\n");
fflush(stderr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment