我不了解mprotect用法中的“对齐分配的内存”部分。

我指的是http://linux.die.net/man/2/mprotect上给出的代码示例

char *p;
char c;
/* Allocate a buffer; it will have the default
   protection of PROT_READ|PROT_WRITE. */
p = malloc(1024+PAGESIZE-1);
if (!p) {
    perror("Couldn't malloc(1024)");
    exit(errno);
}
/* Align to a multiple of PAGESIZE, assumed to be a power of two */
p = (char *)(((int) p + PAGESIZE-1) & ~(PAGESIZE-1));
c = p[666];         /* Read; ok */
p[666] = 42;        /* Write; ok */
/* Mark the buffer read-only. */
if (mprotect(p, 1024, PROT_READ)) {
    perror("Couldn't mprotect");
    exit(errno);
}

就我的理解而言,我尝试使用PAGESIZE为16和0010作为p的地址。
由于(((int) p + PAGESIZE-1) & ~(PAGESIZE-1))的结果,我最终得到0001。

您能否阐明整个“调整”是如何进行的?

谢谢,

最佳答案

假设PAGESIZE是2的幂(要求),则整数值x可以四舍五入为PAGESIZE(x & ~(PAGESIZE-1))的倍数。同样,((x + PAGESIZE-1) & ~(PAGESIZE-1))将导致x向上舍入为PAGESIZE的倍数。

例如,如果PAGESIZE为16,则使用32位字的二进制格式:00000000000000000000000000010000 PAGESIZE00000000000000000000000000001111 PAGESIZE-111111111111111111111111111110000 ~(PAGESIZE-1)具有上述值的按位与(&)将清除该值的低4位,使其为16的倍数。

就是说,描述中引用的代码来自手册页的旧版本,因此效果不佳,因为它浪费内存并且无法在64位系统上运行。最好使用 posix_memalign() or memalign() 获得已经正确对齐的内存。当前版本 mprotect() 手册页上的示例使用memalign()posix_memalign()的优点是它是POSIX标准的一部分,并且在不同的系统(如较旧的非标准memalign())上没有不同的行为。

关于linux - mprotect-如何与多个页面大小对齐?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2601121/

10-11 19:41