So I am trying to check if I can properly change the access rights on mmapped allocated memory using mprotect
and this is what I wrote:
#include <stdio.h>
#include <sys/mman.h>
#include <malloc.h>
#include <unistd.h>
void main()
{
int pagesize;
pagesize = getpagesize();
void *p;
p = malloc(pagesize);
getchar();
int q = posix_memalign(&p, pagesize, pagesize);
getchar();
int a = mprotect(p, pagesize, PROT_READ | PROT_WRITE | PROT_EXEC);
getchar();
free(p);
}
Now after each function i am using getchar
to analyze my memory segment using cat /proc/<pid>/maps
file and this is what I get:
(only showing the information regarding heap as that is my only concern)
After the posix_memalign
:
01776000-01798000 rw-p 00000000 00:00 0 [heap]
After the mprotect
function:
01776000-01778000 rw-p 00000000 00:00 0 [heap]
01778000-01779000 rwxp 00000000 00:00 0 [heap]
01779000-01798000 rw-p 00000000 00:00 0 [heap]
So if you notice the heap allocated before gets divided into three parts after i use mprotect
and only the second part of the heap gets the access permissions that i gave in the function.
Why does this division happens and why does only the second region of the divided heap gets the permissions?
Note: I have searched manpages and have found absolutely nothing regarding this.