Reading ELF header in C

c, elf, linker

Solution

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

- The size, file alignment and internal layout for in-file structures (such as the ELF Executable Header) depends on the ELF object's word size.

- The endianness of the ELF object could differ from the 'native' endianness of the program reading the object.

- ELF objects containing a large number of sections or program segments may use an alternate "extended numbering" scheme.

Rather than handle these cases by hand, it may be easier to use an implementation of the ELF(3) access API to parse the ELF object (see: BSD libelf, or GNU libelf).

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

Problem

currently I'm writing little program that reads elf file header and prints some information I have an unsigned char pointer called buf which points to the location where elf file is located in memory(I used mmap to map it to memory), then I typecast it to a proper elf header pointer ``` Elf32_Ehdr *ehdr = (Elf32_Ehdr *)buf; ``` After this I want to get an 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 ptbl pointer doesn't change and when I try to print the value of the e_phoff member like this ``` fprintf( stdout , "Offset of program headers : %d\n", ehdr->e_phoff); ``` I get zero Same stuff happens when I try to print number of program headers and number of section headers - always get zero If I use linux readelf, it prints proper values Does anyone experienced the same problem?

Original source