我试图编写一个程序,在其中分配一个内存块,然后有选择地更改对该块的页面大小和页面对齐子集的保护。但是,当我尝试在内存中超过8页的部分上调用mprotect
时,mprotect
失败,并显示错误“无法分配内存”。
这是一个重现此问题的最小,完整且可验证的示例:
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <cerrno>
#include <cstring>
#include <iostream>
int main() {
const int n_pages = 12;
const int page_size = sysconf(_SC_PAGE_SIZE); // 4096
const int block_size = n_pages * page_size; // 65536
char* block_addr = (char*)aligned_alloc(page_size, block_size);
char* chunks[n_pages];
char* pointer = block_addr;
for (int n = 0; n < n_pages; n++) {
pointer = pointer + (n * page_size);
chunks[n] = pointer;
}
std::cout << "Set chunks read-only.\n";
for (int n = 0; n < n_pages; n++) {
if (mprotect(chunks[n], page_size, PROT_READ) != 0) {
std::cerr << n+1 << '/' << n_pages << ' '
<< "mprotect failed: " << std::strerror(errno) << '\n';
}
}
std::cout << "Set chunks read/write.\n";
for (int n = 0; n < n_pages; n++) {
if (mprotect(chunks[n], page_size, PROT_READ|PROT_WRITE) != 0) {
std::cerr << n+1 << '/' << n_pages << ' '
<< "mprotect failed: " << std::strerror(errno) << '\n';
}
}
free(block_addr);
}
对于n> 8的块,这始终失败,并给出以下消息:
Set chunks read-only.
9/12 mprotect failed: Cannot allocate memory
10/12 mprotect failed: Cannot allocate memory
11/12 mprotect failed: Cannot allocate memory
12/12 mprotect failed: Cannot allocate memory
Set chunks read/write.
9/12 mprotect failed: Cannot allocate memory
10/12 mprotect failed: Cannot allocate memory
11/12 mprotect failed: Cannot allocate memory
12/12 mprotect failed: Cannot allocate memory
我发现了question,其中OP似乎遇到了与我相同的错误,其中David Hammen有用地为问题的根源提供了一些提示,但我并不真正理解他在说什么。不幸的是,OP没有提供他们的代码,因此我们无法确切知道他们在做什么或如何解决它。
所以基本上我的问题是:为什么
mprotect
会产生该错误,我该如何解决? 最佳答案
pointer = pointer + (n * page_size);
这条线看起来非常可疑。应该是
pointer = block_addr + (n * page_size);
要么
chunks[n] = pointer; // need to assign to chunks[n] first
pointer = pointer + page_size;
否则,
pointer
将会以0、1(= 0 + 1),3(= 0 +1 + 2),6(= 0 +1 + 2 + 3)等步入内存,不属于您的进程,因为您没有分配它(即它是“未映射的”)。这可以解释为什么mprotect
在最后两个块中失败。