如何将同一文件的不同区域映射到不同的内存地址?

发布于 2025-01-09 15:35:47 字数 865 浏览 4 评论 0原文

如何将文件的不同部分映射到不同的内存区域?

我尝试使用此代码,但出现 File isn't 错误:

int fd = open(FN, O_RDONLY);
if (fd == -1) {
       perror("");
       exit(1);
}
void* retval;
retval = mmap((void*) 0x00401000, 0xb93, PROT_READ | PROT_EXEC, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x1000);
if (retval == MAP_FAILED) {
       perror("Error mmap 1");
       exit(1);
}
   
retval = mmap((void*) 0x00402000, 0x660, PROT_READ, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x2000);
if (retval == MAP_FAILED) {
       perror("Error mmap 2");
       exit(1);
}

第一个 mmap 工作正常;第二个失败,并显示文件存在。如果我注释掉第一个,第二个就可以了。

无论我执行 MMAP_PRIVATE 还是 MMAP_SHARED,我都会收到此错误。同样,如果我重用原始 fd,或打开同一文件的新 fd,我也会收到错误。

如何将同一文件的两个区域映射到不同的位置?为什么我不能直接执行此操作,因为 mmap 是只读的(没有 PROT_WRITE)并且也是写时复制(MMAP_PRIVATE)。

How can I mmap different parts of a file into different memory regions?

I tried with this code, but get File exists errors:

int fd = open(FN, O_RDONLY);
if (fd == -1) {
       perror("");
       exit(1);
}
void* retval;
retval = mmap((void*) 0x00401000, 0xb93, PROT_READ | PROT_EXEC, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x1000);
if (retval == MAP_FAILED) {
       perror("Error mmap 1");
       exit(1);
}
   
retval = mmap((void*) 0x00402000, 0x660, PROT_READ, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x2000);
if (retval == MAP_FAILED) {
       perror("Error mmap 2");
       exit(1);
}

The first mmap works fine; the second fails with File exists. If I comment out the first one, the second works.

I get this error whether I do MMAP_PRIVATE or MMAP_SHARED. Likewise, I get the error if I reuse the original fd, or open a new fd to the same file.

How can I mmap two regions of the same file to different places? Why can't I do this directly, given that the mmap is read only (no PROT_WRITE) and also copy-on-write (MMAP_PRIVATE).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫轩蝶泪 2025-01-16 15:35:47

问题在于 mmap 调用中的 length 字段,而不是它是同一个文件这一事实。请注意,长度为 0xb9320x660,但这些长度由 mmap 向上舍入为 0x1000。因此,页面最终会占用比预期更多的内存,从而导致冲突,由于 MAP_FIXED_NOREPLACE ,内核无法替换和修复。

The problem is the length field in the mmap calls, not the fact that it's the same file. Note the length is 0xb932, 0x660, but these are rounded up by mmap to 0x1000. Thus, the pages end up taking more memory than expected, causing collisions, which, due to MAP_FIXED_NOREPLACE, the kernel is unable to replace and fix.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文