Skip to content
Advertisement

How can I find the size of a ELF file/image with Header information?

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.

Advertisement

Answer

You can use the stat functions family (stat(), lstat(), fstat()) to get the size of any file (using the st_size member of the stat 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:

typedef struct {
         unsigned char  e_ident[EI_NIDENT];
         uint16_t       e_type;
         uint16_t       e_machine;
         uint32_t       e_version;
         ElfN_Addr      e_entry;
         ElfN_Off       e_phoff;
         ElfN_Off       e_shoff;
         uint32_t       e_flags;
         uint16_t       e_ehsize;
         uint16_t       e_phentsize;
         uint16_t       e_phnum;
         uint16_t       e_shentsize;
         uint16_t       e_shnum;
         uint16_t       e_shstrndx;
 } Elf32_Ehdr;

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:

This answer is incorrect. e_ehsize is merely the size of the elf header, not the elf file.

Advertisement