Reputation: 490
I have an elf file, and when I use readelf -h filename I get the entry point. Now, lets say I want to calculate this address by myself [Using assembly, but the language isn't important].
How can I do that?
I know the the entry point is 4 bytes starting from offset 24 in the file, but I don't know how to translate this data into address.
Upvotes: 3
Views: 3710
Reputation: 213526
I know the the entry point is 4 bytes starting from offset 24 in the file, but I don't know how to translate this data into address.
There is no translation necessary when you run on the same target (x86
) as the one for which the executable has been built.
In pseudo-code, error checking omitted:
int fd = open(path, O_RDONLY);
lseek(fd, 24, SEEK_SET);
unsigned long entry_point;
read(fd, &entry_point, sizeof(entry_point));
printf("entry: 0x%lx\n", entry_point);
P.S. The 24 is only correct offset for Elf32
; it's much better to write this portably by reading entire Elf32_Ehdr
or Elf64_Ehdr
(depending on byte 5 being ELFCLASS32
or ELFCLASS64
) from offset 0, and then using .e_entry
member.
Upvotes: 2
Reputation: 4562
Your question is unclear. If you ask how to read this value from ELF
file, you should parse ELF file (likely using libelf
or another existing helper software). If you ask how to form it using some magic on knowledge of the binary program contents, this "magic" is solely calculated from offset of entry how it is compiled into the resulting binary.
The binary in Linux (provided you use standard toolchain, namely, gcc + GNU binutils) is formed as sum of a few input files as the main binary, relocation table for the latter, prolog modules (crtbegin.o
, crti.o
), epilog modules (crtend.o
, crtn.o
). Entry point is in the prolog but it could be placed by linker after the main binary contents (I see this on /bin/sh on my OpenSuSE) so is really at the end of the resulting binary file. This is linker's right to choose, unless explicitly regulated.
Upvotes: 0