mprotect - 如何对齐多个pagesize有效?

Cha*_*nya 2 linux memory-management

我不理解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);
}
Run Code Online (Sandbox Code Playgroud)

据我所知,我尝试使用PAGESIZE为16,而0010为p的地址.我最终得到了0001作为结果(((int) p + PAGESIZE-1) & ~(PAGESIZE-1)).

你能澄清一下这整个'对齐'是如何工作的吗?

谢谢,

mar*_*k4o 11

假设这PAGESIZE是2的幂(一个要求),则可以将整数值x向下舍入到PAGESIZEwith 的倍数(x & ~(PAGESIZE-1)).同样,((x + PAGESIZE-1) & ~(PAGESIZE-1))将导致x向上舍入到的倍数PAGESIZE.

例如,如果PAGESIZE是16,则使用32位字进行二进制:
00000000000000000000000000010000 PAGESIZE
00000000000000000000000000001111 PAGESIZE-1
11111111111111111111111111110000 ~(PAGESIZE-1)
按位 - 和(&)使用上述值将清除该值的低4位,使其成为16的倍数.

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