1

I have code that needs to mmap an external file into a particular memory range. How can I tell the linker to map my host code into a different range? That is, how can I tell the linker "avoid putting any section at vaddr 0x40000"?

I am doing mmap with MAP_FIXED_NOREPLACE, and want to ensure that this doesn't fail; e.g. no collision.

Linux, gcc (for C and for linking), nasm (for asm), 64 bit

SRobertJames
  • 8,210
  • 14
  • 60
  • 107
  • 1
    Easiest way is to make a PIE executable, `gcc -fPIE -pie`. That gets ASLRed to somewhere near the lower 1/3rd of the user-space virtual-address range, far from `0x40000`, although it's possible to customize the default load address. But if you're making a non-PIE executable, the image base address is fixed by the linker (*not* relocatable at run-time), usually at `0x400000`. (one more zero than your target address). You can set BSS, text, rodata, and data segment bases explicitly with `-Tbss=0x500000` and so on, but you have to know how much room to leave between each one; not recommended. – Peter Cordes Feb 23 '22 at 10:29
  • PIE is great. Is there a way to explicitly specify (I guess to the runtime loader): Do not load this PIE into region X, because I will want to mmap something into X? – SRobertJames Feb 23 '22 at 10:35
  • Not that I know of. See [How is the address of the text section of a PIE executable determined in Linux?](https://stackoverflow.com/q/51343596) - the ASLR base address is hard-coded as `ELF_ET_DYN_BASE (2 * TASK_SIZE_64 / 3)`. (At least before support for PML5 57-bit virt addrs was added.) So I was mis-remembering, there isn't a sysctl for this; you'd have to recompile the kernel to change the load address. ASLR doesn't use a huge number of bits, so it's always around `0x000055...` (Run `cat /proc/self/maps` a few times) – Peter Cordes Feb 23 '22 at 10:39
  • 1
    The only surefire way is to use a custom linker script that places a dummy section at the desired memory range, preventing anything else from being loaded there. But that's kind of fragile to get right. – fuz Feb 23 '22 at 10:48

0 Answers0