Reading ELF Header in C

I am currently writing a small program that reads the header of an elf file and prints some information

I have an unsigned char pointer called buf that points to where the elf file is in memory (I used mmap to map it to memory), then I cast it to the correct elf header pointer

Elf32_Ehdr *ehdr = (Elf32_Ehdr *)buf; 

After that I want to get the address of the program header table, I do it like this:

 Elf32_Phdr *ptbl = (Elf32_Phdr *) (buf + ehdr->e_phoff) 

As I noticed, the value of the ptbl pointer does not change, and when I try to print the value of the e_phoff element, like this

 fprintf( stdout , "Offset of program headers : %d\n", ehdr->e_phoff); 

I get zero. The same thing happens when I try to print the number of program headers and the number of section headers - I always get zero. If I use linux readelf, it prints the correct values ​​Has anyone experienced the same problem?

+7
source share
1 answer

When parsing an ELF object, you need to keep in mind that:

  • The size, file alignment, and internal layout of in-structure structures (for example, the ELF executable header) depend on the size of the ELF object word.
  • The specificity of an ELF object may differ from the "native" purpose of the program viewing the object.
  • ELF objects that contain a large number of program sections or segments can use an alternative "extended numbering" scheme.

Instead of handling these cases manually, it may be easier to use the ELF (3) access API implementation to parse the ELF object (see BSD libelf , or GNU libelf ).

The tutorial `` libelf by Example '' provides a readable introduction to the ELF API (3).

+5
source

All Articles