0

我想保护数据部分。以下程序将无法正确运行。我理解mprotect()应该对齐的第一个论点。但是如何获得数据段的对齐内存地址呢?

#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

编辑:我使用以下代码来获取页面大小。

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

然后C代码改成如下。

#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;
    }
}

然后,我得到一个分段错误。任何人都可以重现此错误吗?它有什么问题?

$ ./mprotect_prog
Segmentation fault

EDIT2:我必须在“s”行下方添加以下行,以确保s自己占据整个页面。然后,程序工作。

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

1 回答 1

1
{
    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;
    }
}
于 2021-04-08T16:39:08.833 回答