pythonic
pythonic

Reputation: 21665

Manage virtual memory from userspace

What I actually want to do is to redirect writes in a certain memory area to a separate memory area which is shared between two processes. Can this be done at user level? For example, for some page X. What I want to do is to change its (virtual to physical) mapping to some shared mapping when it's written. Is this achievable? I need to do it transparently too, that is the program still uses the variables in page X by their names or pointers, but behind the scenes, we are using a different page.

Upvotes: 0

Views: 350

Answers (2)

Hristo Iliev
Hristo Iliev

Reputation: 74485

Yes, it is possible to replace memory mappings in Linux, though it is not advisable to do it since it is highly non-portable.

First, you should find out in what page the X variable is located by taking its address and masking out the last several bits - query the system page size with sysconf(_SC_PAGE_SIZE) in order to know how many bits to mask out. Then you can create a shared memory mapping that overlaps this page using the MAP_FIXED | MAP_SHARED flag to mmap(2) or mmap2(2). You should copy the initial content of the page and restore it after the new mapping. Since other variables may reside in the same page, you should be very careful about memory layout and better use a dedicated shared memory object.

Upvotes: 1

user149341
user149341

Reputation:

What you're trying to do isn't entirely possible, because, at least on x86, memory cannot be remapped on that fine-grained of a scale. The smallest quantum that you can remap memory on is a 4k page, and the page containing any given variable (e.g, X) is likely to contain other variables or program data.

That being said, you can share memory between processes using the mmap() system call.

Upvotes: 1

Related Questions