1. The magic of the Elf

 

Any sufficiently advanced technology is indistinguishable from magic.

 Arthur C. Clarke

This document tries to cover multiple platforms through conditional compilation. There is a configure.pl that determines the host type and sets up a Makefile. The Makefile uses individual sub-directories for each platform and exports the name of these directories (and some other platform specific values) as environment variables. Most of the shell scripts invoked by make(1) are shown here. The following table should help to understand them.

Table 1. Environment variables exported by Makefile

VariableValue on this platform
${ARCH}sparc
${CFLAGS}-Wall -O2
${ELF_ALIGN}10000
${ELF_ADDRSIZE}32
${ASM_STYLE}att
${ELF_BASE}00010000
${OBJDUMP}/usr/bin/objdump
${OUT}out/sparc-debian-linux
${READELF}/usr/bin/readelf
${TMP}tmp/sparc-debian-linux
${UNAME}Linux

1.1. In the language of mortals

For the first example I'll present the simplest piece of code that still gives sufficient feedback. Our aim is to implant it into /bin/sh. On practically every recent installation of Linux/sparc the following code will emit three magic letters instead of just dumping core.

It is not an error that a file called magic_elf.c is located in a directory called out/sparc-debian-linux. The Makefile building this document did trivial pre-processing on the original source file. ELF is used on many architectures. And each has a different magic value.

1.2. How it works

1.3. Strings and dumps

What would you do if you knew nothing about ELF and just asked yourself how that example works? How can you go sure that the executable file really contains those three letters?

1.4. The address of main

Looks good. The byte at address 0x10000 + 0 is equal to that at file offset 0. And 0x106a8 is a plausible address of function main.

1.5. Other roads to ELF

Notes

[1]

http://www.tuxedo.org/~esr/jargon/html/entry/RTFM.html