tags:

views:

148

answers:

3

I have a program. I want it to be able to mmap a particular region of memory over different runs.

  1. I have the source code of the program. C/C++
  2. I control how the program is compiled. gcc
  3. I control how the program is linked. gcc
  4. I control how the program is run (Linux).

I just want to have this particular region of memory, say 0xabcdabcd to 0xdeadbeef that I mmap to a particular file. Is there anyway to guarantee this? (I have to somehow make sure that other things aren't loaded into this particular region).

EDIT:

How do I make sure that nothing else takes this particular region in memory?

+1  A: 

Pass the address to map in addr. Try to get it on a 8KB boundary. You could try mlock() instead though.

Ignacio Vazquez-Abrams
+6  A: 

You need to do two things:

  1. Specify the starting address as the first argument to mmap.
  2. Include the MAP_FIXED flag.

For the starting address, you need to make sure it's a multiple of the pagesize. To get the pagesize, use the call sysconf(_SC_PAGESIZE) (that's the appropriate call on Linux, other platforms may be different).

R Samuel Klatchko
In short, don't depend on MAP_FIXED working. It can (and therefore will) fail.
Yann Ramin
@theatrus - which platform are you referring to. On Linux, addr is only interpreted as a hint if MAP_FIXED is not specified (http://www.kernel.org/doc/man-pages/online/pages/man2/mmap.2.html).
R Samuel Klatchko
MAP_FIXED is not guaranteed to succeed - of course it will inform you of the inability to map, but if your program is depending on this behavior then there will be issues :)
Yann Ramin
But without MAP_FIXED, mmap can return a different address then what you requested. If your code is dependent on getting the address you asked for, there is not much difference between mmap failing and mmap returning a different address. Ideally, your code is not dependent on getting a specific address, but in that case, it's best just to pass 0 for the address.
R Samuel Klatchko
I think he's just saying "don't assume it works every time". One can use it, but gracefully handle its failure.
jdizzle
A: 

You cannot make sure that nothing else takes that area of memory - first come, first served. However, as you need a particular part of the memory, I'm guessing that you have a pretty specialized environment, so you simply need to make sure that you are first (using start scripts)

e8johan
Address space is per-process, so it doesn't matter what else is running on the system. What matters is what else has been done in the current process, before making the mmap() call, that might have allocated something in that region of the process's address space.
Wyzard
Yes, of course, you are right. I'm for the embedded space and directly thought "map a specific physical region"... but you are probably right.
e8johan