gpt4 book ai didi

c - mprotect - 如何对齐多个页面大小?

转载 作者:太空狗 更新时间:2023-10-29 11:24:58 25 4
gpt4 key购买 nike

我不理解 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);
}

根据我的理解,我尝试使用 16 的 PAGESIZE 和 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 PAGESIZE
00000000000000000000000000001111 PAGESIZE-1
11111111111111111111111111110000 ~(PAGESIZE-1)
与上述值的按位与 (&) 将清除值的低 4 位,使其成为 16 的倍数。

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com