Computing the size of an ELF file based on the header information

Viewed 494

I understand it is possible to compute the size of an ELF file (i.e., where it ends) based on the information found in the header (i.e., e_shoff + (e_shentsize * e_shnum)), assuming that there is a section header table ("SHT"), and the SHT is the last part of the ELF.

However, SHT is not required to load the binary, and I was wondering wether it would be possible to compute the same information if the SHT was missing (e.g, an stripped binary). Can we leverage the program header or other offsets to compute the size programmatically?

1 Answers

Can we leverage the program header or other offsets?

The information that is required for the binary to start running is contained in program headers (use readelf -Wl a.out to see what's there).

You can compute the minimum required size of the binary by finding maximum value of phdr->p_offset + phdr->p_filesz. If you truncate the file at that size, it should continue to work (or at least load and reach main).

But the file may contain any number of additional non-loadable sections, so don't be surprised if the size you compute is smaller than the file size on disk.

Whether these additional sections are required or not depends entirely on the executable -- it may have code which opens argv[0], seeks to some offset, and reads data from there (in which case the application will stop working after truncation).

P.S.

assuming that ...the SHT is the last part of the ELF.

That assumption is not necessarily true, and is certainly not required for the file to be a proper ELF file.

Related