Skip to content

Instantly share code, notes, and snippets.

@LainLayer
Created January 29, 2025 20:26
Show Gist options
  • Save LainLayer/848863deac5254ad9a9d9e383d28859b to your computer and use it in GitHub Desktop.
Save LainLayer/848863deac5254ad9a9d9e383d28859b to your computer and use it in GitHub Desktop.
C example of mmap and mprotect
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
// comment to disable mprotect
#define DO_PROTECTION
int main(void) {
int page_size = getpagesize();
printf("Page size: %d\n", page_size);
char *mapped_memory = mmap(NULL, page_size * 10, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (mapped_memory == MAP_FAILED) {
printf("Mapping memory failed: %s\n", strerror(errno));
return 1;
}
printf("Mapped memory pointer: %p\n", mapped_memory);
for(size_t i = 0; i < page_size * 10; i++) {
mapped_memory[i] = 'a';
}
printf("Successfully filled mapped memory with 'a'\n");
#ifdef DO_PROTECTION
if(mprotect(mapped_memory + (page_size * 8), page_size * 2, PROT_READ) == -1) {
printf("Failed to mprotect the mapped memory: %s\n", strerror(errno));
return 1;
}
printf("Successfully set protection PROT_READ on last 2 pages of mapped memory\n");
#endif // DO_PROTECTION
for(size_t i = 0; i < 10; i++) {
printf("Writing data to page: %zu...", i);
for(size_t j = 0; j < page_size; j++) {
mapped_memory[i*page_size + j] = 'b';
}
printf(" OK\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment