I need to find the size of an elf image for some computation. I have tried with the readelf utility on linux which gives the informations about the headers and section. I need to have the exact file size of the elf(on the whole).
How do I find the size of the ELF from the header information or Is there any other means to find the size of an elf without reading the full image.
Example:
This assumes that the section header table (SHT) is the last part of the ELF. This is usually the case but it could also be that the last section is the last part of the ELF. This should be checked for, but is not in this example.
Here is a working implementation in C, compile with
gcc elfsize.c -o elfsize
:You can use the
stat
functions family (stat()
,lstat()
,fstat()
) to get the size of any file (using thest_size
member of thestat
member). Do you need something more specific?If you really want to use the ELF structure, use the elf.h header which contains that structure:
It's the header of an ELF32 file (replace 32 with 64 for a 64-bit file).
e_ehsize
is the size of the file in bytes.I'll copy verbatim the comment that was posted as an edit suggestion:
The answer to the specific question is a little tricky for ELF files.
The following will compute the size of the "descriptive" information in an ELF file using the header: e_ehsize + (e_phnum * e_phentsize) + (e_shnum * e_shentsize)
The above is based on the ELF documentation.
The next piece to add to the above sum is the size in the file of the section entries. Intuitively we would like to compute this using sh_size for each of the sections in the file -- e_shnum of them. HOWEVER, this doesn't yield the correct answer due to alignment issues. If you use an ordered list of sh_offset values you can compute the exact number of bytes that the section entry occupies (I found some strange alignments where using sh_addralign isn't as useful as you would like); for the last section entry use the file header's e_shoff since the section header table is last. This worked for the couple I checked.
update.c in libelf has the details it uses when updating an elf file.
Have you tried using the gnu "readelf" utility?
http://sourceware.org/binutils/docs/binutils/readelf.html
Perhaps gelf could be useful.
specifically these functions:
All you have to do is to sum the last section's file offset and its size.
elfHeader used values:
sectionHeader used values: