Diving into ELF

Abstract
For the first time, I did some stuff regarding ELF.

While it was very fun, here are some things I didn’t like:

Getting the filepath

I had a instruction pointer, and I wanted to open the corresponding ELF file on disk. If the corresponding ELF-file is some shared library, both dl_iterate_phdr and dladdr can be used to do that. But if the corresponding ELF-file is the main program (i.e. /proc/self/exe), there is a problem:

This left me with three choices:

  1. Use dl_iterate_phdr and fallback to /proc/self/exe if dlpi_name is an empty string.
  2. Use dladdr and fallback to /proc/self/exe if dlpi_name is not an absolute path.
  3. Use /proc/self/maps.

I chose the latter because I don’t like fallbacks. But unfortunately there was no way around writing a parser for the text-format of /proc/self/maps.

Reading elf files

Coherent naming is important in software. Unfortunately, the elf manpage uses both section name string table section and section header string table section to refer to the same thing.

The bigger problem is that there are 3 address spaces that are relevant:

  1. Virtual Addresses (i.e. what printf("%p\n", ptr) will print)
  2. Positions in the elf file (i.e. what xxd libfoo.so shows)
  3. Virtual Adresses minus info->dlpi_addr (i.e. what objdump -d libfoo.so shows)

I absolutely do not like the fact that there seems to be no proper term for the third address space. The elf manpage is calling it vaddr, virtual address and the dladdr1 manpage is calling it address in the ELF file.