3 ms·
You don't need userfaultfd for that. Just mmap the same file twice, at different addresses: int mem_fd = memfd_create("", 0); ftruncate(fd, 4096);
by 10000truths 5y ago
You don't need userfaultfd for that. Just mmap the same file twice, at different addresses:
int mem_fd = memfd_create("", 0);
ftruncate(fd, 4096);
void* mem = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd, 0);
void* alias = mmap((void*) 0x4000, 4096, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, mem_fd, 0);
close(mem_fd);
// alias now points to the same physical memory as mem
This is commonly used to create ring buffers that wrap around transparently.
- tsavola 5y agoDo you have a link or can you suggest search terms for an example? I can't imagine that being useful, as you have to wrap around at some point anyway.
- toast0 5y agoI could see it being useful to map the same area twice, adjacently; not specifically at 0x4000 though. You'd still wrap pointers at some point, but as long as sizes are limited to fit into your buffer, you could do memcpy and what not without having to check boundaries. If you were mapped at 0x4000 and aliased at 0x5000, you could memcpy something to 0x4FFF -> 0x5003, and not have to do a split write of 0x4fff and then 0x4000 -> 0x4003. (If your buffer is bigger than a page, this will still work, just use bigger addresses, etc. if your buffer is smaller than a page, you're stuck)