Search code examples
linuxlinkerldelf

PT_INTERP segment order in executable ELF


ELF specification http://www.skyfree.org/linux/references/ELF_Format.pdf at page 2-3 says ad Program Header entry with p_type=PT_INTERP that it must precede any loadable segment entry.

I would like to know if this rule concerns

1) the order of this entry in Program Header Table,

or 2) position of the raw contents (string with path to the actual interpreter) in file layout,

or 3) both.

GNU linker ld seems to follow 3). Program Header produced by ld generates PT_PHDR, then PT_INTERP, then PT_LOAD, and the actual interpreter string is generated right after program header, before any code and data contents. It also (unnecessarily?) generates special section entry .interp in Section Headers with sh_type=SHT_PROGBITS, which duplicates program header entry PT_INTERP.

In my linker I would like to concatenate INTERP path string with .strtab and .shstrtab contents somewhere near the end of file, because all those three sections are byte-aligned and that'll spare alignment stuff and reduce size of the output file. However, I'm not sure whether this doesn't violate ELF specification as I grasp it.


Solution

  • I believe that:

    1. The answer is 1) -- PT_INTERP must precede PT_LOADs in the program header table.
    2. This requirement is very likely obsolete (at least on Linux) -- the kernel iterates over all program headers in fs/binfmt_elf.c looking for PT_INTERP, and doesn't appear to care where in the table this entry appears.

    In my linker I would like to concatenate INTERP path string with .strtab and .shstrtab contents somewhere near the end of file

    That should work just fine (but I haven't tried it).