7
votes

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?

1
I think I found the problem, I'm using 64 bit machine, so I just changed Elf32_Phdr to Elf64_Phdr and it workedRustam Issabekov
Go ahead an answer your own question. It is a valid thing to do, if you find the answer first. Obviously, you used the wrong struct pointer type, so you were referencing memory upstream of what intended.Edwin Buck
I suggest to use libelf.jørgensen
Can you share your codes?Ursa Major

1 Answers

5
votes

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

  1. 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.
  2. The endianness of the ELF object could differ from the 'native' endianness of the program reading the object.
  3. 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.