Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map two virtual adresses on the same physical memory on linux?

I'm facing a quite tricky problem. I'm trying to get 2 virtual memory areas pointing to the same physical memory. The point is to have different page protection parameters on different memory areas.

On this forum, the user seems to have a solution, but it seems kinda hacky and it's pretty clear that something better can be done performance-wise : http://www.linuxforums.org/forum/programming-scripting/19491-map-two-virtual-memory-addres-same-physical-page.html

As I'm facing the same problem, I want to give a shot here to know if somebody has a better idea. Don't be afraid to mention the dirty details behind the hood, this is what this question is about.

Thank by advance.

like image 873
deadalnix Avatar asked Sep 07 '11 13:09

deadalnix


Video Answer


2 Answers

Since Linux kernel 3.17 (released in October 2014) you can use memfd_create system call to create a file descriptor backed by anonymous memory. Then mmap the same region several times, as mentioned in the above answers.

Note that glibc wrapper for the memfd_create system call was added in glibc 2.27 (released in February 2018). The glibc manual also describes how the descriptor returned can be used to create multiple mappings to the same underlying memory.

like image 51
Ivan Avatar answered Sep 20 '22 21:09

Ivan


I'm trying to get 2 virtual memory area pointing on the same physical memory.

mmap the same region in the same file, twice, or use System V shared memory (which does not require mapping a file in memory).

like image 38
Fred Foo Avatar answered Sep 17 '22 21:09

Fred Foo