Linux 将虚拟内存范围映射到现有虚拟内存范围?
在Linux中,有没有一种方法(在用户空间中)将虚拟地址范围映射到支持现有虚拟地址范围的物理页面? mmap() 函数只允许映射文件或“新”物理页。我需要能够做这样的事情:
int* addr1 = malloc(SIZE);
int* addr2 = 0x60000; // Assume nothing is allocated here
fancy_map_function(addr1, addr2, SIZE);
assert(*addr1 == *addr2); // Should succeed
assert(addr1 != addr2); // Should succeed
In Linux, is there a way (in user space) to map a virtual address range to the physical pages that back an existing virtual address range? The mmap() function only allows one to map files or "new" physical pages. I need to be able to do something like this:
int* addr1 = malloc(SIZE);
int* addr2 = 0x60000; // Assume nothing is allocated here
fancy_map_function(addr1, addr2, SIZE);
assert(*addr1 == *addr2); // Should succeed
assert(addr1 != addr2); // Should succeed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我很好奇,所以我测试了问题评论中建议的共享内存想法,它似乎有效:(
显然真实的代码会想要检查系统调用的返回值是否有错误并自行清理)
I was curious so I tested the shared memory idea suggested in question comments, and it seems to work:
(Obviously real code will want to check the return value of the syscalls for errors and clean up after itself)
如果您有映射到
addr1
的文件的 fd,则只需mmap
再次在addr2
处。否则,特定于 Linux 的
remap_file_pages< /code>
可以在单个 VMA 内以页面大小的粒度修改虚拟地址⇆文件偏移量转换,包括将相同的文件偏移量映射到多个地址。
If you have the fd for the file mapped at
addr1
, you can simplymmap
it again ataddr2
.Otherwise, the Linux-specific
remap_file_pages
can modify the virtual address ⇆ file offset translation within a single VMA, with page-sized granularity, including mapping the same file offset to multiple addresses.打开
/proc/self/mem
并从中mmap
您需要的虚拟地址范围。Open
/proc/self/mem
andmmap
the range of virtual addresses you need from it.