How to mprotect the data section?

313 views Asked by At

I want to mprotect the data section. The following program will not run correctly. I understand the first argument of mprotect() should be aligned. But how to get an aligned memory address for the data section?

#include <string.h>
#include <sys/mman.h>
#include <stdio.h>

char s[] = "Hello World!";

int main() {
    if(mprotect(s, strlen(s) + 1, PROT_EXEC) == -1) {
        perror("mprotect()");
        return 1;
    }
}
$ ./mprotect_prog
mprotect(): Invalid argument

EDIT: I use the following code to get the page size.

{
    builtin printf %s '#define PAGESIZE '
    getconf PAGESIZE
} > pagesize.h

Then the C code is changed to the following.

#include <string.h>
#include <sys/mman.h>
#include <stdio.h>

#include "pagesize.h"

char s[] __attribute__((aligned(PAGESIZE))) = "Hello World!";

int main() {
    if(mprotect(s, strlen(s) + 1, PROT_EXEC) == -1) {
        perror("mprotect()");
        return 1;
    }
}

Then, I get a segmentation fault. Can anybody reproduce this error? What is wrong with it?

$ ./mprotect_prog
Segmentation fault

EDIT2: I have to add the following line below the 's' line to make sure s occupies a whole page on its own. Then, the program works.

char r[] __attribute__((aligned(PAGESIZE))) = "Hello World!";
1

There are 1 answers

0
AudioBubble On
{
    builtin printf %s '#define PAGESIZE '
    getconf PAGESIZE
} > pagesize.h
#include <string.h>
#include <sys/mman.h>
#include <stdio.h>

#include "pagesize.h"

char s[] __attribute__((aligned(PAGESIZE))) = "Hello World!";
char r[] __attribute__((aligned(PAGESIZE))) = "Hello World!";

int main() {
    if(mprotect(s, strlen(s) + 1, PROT_EXEC) == -1) {
        perror("mprotect()");
        return 1;
    }
}