2

I'm contemplating a project where I would use a memory mapped file that is shared between multiple processes, and in order to be able to use pointer values in the mapped region in all those processes*, I need to ensure that it is mapped to the same base address in every process. Doing that is easy in itself, of course, using the MAP_FIXED flag to mmap(), but the question is what address I should choose.

When my code starts running, I would be in a situation where my executable and the shared libraries it uses are already mapped somewhere in memory. Is it possible to know the general ranges of these addresses in advance? The question is particularly pertinent these days with ASLR turned on by default on many kernels. I've seen empirically that there appears to be some loose range of addresses that are used for the main executable, and another such range that seem to be used for the shared libraries, but are these actually somewhat well-defined? A standards document would be nice, of course, but as the project in question will really only be run by myself, a loose design philosophy is also quite alright.

If there really exists no way to know in advance where pre-existing mappings might end up, is there at least a way to fail gracefully in case my guess at a useful address range turns out wrong? Normally, mmap will silently override preexisting mappings with the newly requested one. I guess I'd like a flag similar to O_EXCL that would make mmap fail if it would override anything, but I can't find anything to that effect or anything similar. I guess I could parse /proc/self/maps and see if anything overlaps my intended mapping, but eeww.

* Yes, I'm aware I could use relative pointers in the mapped area, but I don't want to, for several reasons.

  • I would ask why? But you have already shown that you have considered all of this. But out of curiosity why not relative addresses? Also I think I did see in the manual, that you can make mmap fail, if the virtual-range is in use (can't remember where). – ctrl-alt-delor Dec 24 '18 at 11:07
  • @ctrl-alt-delor: There are a couple of reasons, but the main one would be that I have functions that I want to have operating both on the memory-mapped region, and on memory local to the individual processes, and doing that otherwise would involve the complexity of using base/offset pair structures for every pointer, which I'd rather avoid. – Dolda2000 Dec 24 '18 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.