From the manual:
On Linux it is always permissible to call mprotect() on any address in
a process's address space (except for the kernel vsyscall area). In
particular it can be used to change existing code mappings to be
writable.
Here's a sample program to demonstrate.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#define PAGE_SIZE 4096
const unsigned char rodata[3*PAGE_SIZE] = {1,2,3};
int main(void)
{
printf("rodata = %p\n", rodata);
uintptr_t page_base = ((uintptr_t)rodata / PAGE_SIZE + 1) * PAGE_SIZE;
unsigned char *p = (unsigned char *)rodata + PAGE_SIZE;
//*p = '!'; // this would cause a segfault
puts("Before mprotect:");
system("cat /proc/$PPID/maps");
if (mprotect((void*)page_base, 1, PROT_READ | PROT_WRITE) < 0) {
perror("mprotect");
return 1;
}
puts("After mprotect:");
system("cat /proc/$PPID/maps");
*p = '!';
return 0;
}
Of course any data that you write to the page will remain in memory. Linux sees that the process is writing to a page that's currently mapped read-only and makes a copy. At the time of the write, the kernel doesn't distinguish this from copy-on-write after a process has forked. You can observe this by forking, writing in one process and reading in the other: the other process won't see the write since it's a write to the writing process's memory, not to the reading process's memory.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#define PAGE_SIZE 4096
const unsigned char rodata[3*PAGE_SIZE] = {0};
void writer(char *p)
{
if (mprotect(p, 1, PROT_READ | PROT_WRITE) < 0) {
perror("mprotect");
return 1;
}
puts("After mprotect:");
system("cat /proc/$PPID/maps");
*p = 1;
printf("wrote %d\n", *p);
}
void reader(char *p)
{
printf("read %d\n", *p);
}
int main(void)
{
printf("rodata = %p\n", rodata);
uintptr_t page_base = (((uintptr_t)rodata / PAGE_SIZE + 1) * PAGE_SIZE);
volatile char *p = (volatile char *)page_base;
//*p = '!'; // this would cause a segfault
puts("Before mprotect:");
system("cat /proc/$PPID/maps");
if (fork() == 0) {
writer(p);
} else {
sleep(1);
reader(p);
}
return 0;
}
I suspect there are hardening patches that prevent a process from changing its own memory mappings, but I don't have one to offer.