Code

View on GitHub

Simple program compilation #

make hello
./hello

hello.c main.c

4 compilation phases #

gcc -E -o hello.i hello.c  # Stop after pre-processing
gcc -S -o hello.s hello.i  # Stop after compiler
gcc -c hello.s  # Stop after assembler
gcc -o hello hello.o  # Stop after linker

Typical buildsystem behavior #

#gcc -c main.c -o main.o
#gcc -c hello.c -o hello.o
#gcc -o hello main.o hello.o
make -B hello

hello.c main.c

Inspect file types #

file hello.c
file hello.o
file hello

ELF Object Files #

readelf --file-header hello.o
readelf --sections hello.o
readelf --symbols hello.o
readelf -x .data hello.o
readelf -x .rodata hello.o
readelf -p .rodata hello.o
readelf --symbols hello.o
objdump --disassemble=f_defined hello.o
readelf --relocs hello.o

ELF Executables #

readelf -h hello
readelf --sections hello
readelf --symbols hello
objdump --disassemble=f_defined hello
objdump --disassemble=f_static hello
objdump --disassemble=f_external hello

Dynamic symbol resolution #

objdump --disassemble=main hello

Note the call to printf@plt. Target address is in .plt section.

objdump -dj .plt hello

.plt contains short linker-generated trampoline to the value in .got.plt section:

readelf -x .got.plt hello
readelf --relocs hello

Loader view #

readelf --segments hello
./hello block
cat /proc/$(pidof hello)/maps | grep hello
readelf --segments hello | grep LOAD -A1

Dynamic loader operation #

readelf -p .interp hello
readelf --dynamic hello
LD_SHOW_AUXV=1 ./hello block
cat /proc/$(pidof hello)/maps | grep ld-linux
LD_DEBUG=all ./hello

Dynamic library development #

#gcc -Wall -Wextra -c hello.c -o hello.o
#gcc -Wall -Wextra -c main_shared.c -o main_shared.o
#gcc shared_utils.c -o libshared_utils.so -shared -fPIC
#gcc hello.o main_shared.o -o hello_shared -L. -lshared_utils
make -B hello_shared
file libshared_utils.so
readelf -h libshared_utils.so
readelf --dynamic hello_shared
readelf --relocs hello_shared
LD_LIBRARY_PATH=. ./hello_shared block
cat /proc/$(pidof hello_shared)/maps | grep libshared_utils.so
LD_DEBUG=all LD_LIBRARY_PATH=. ./hello_shared block

Statically linked executable #

#gcc -Wall -Wextra -c hello.c -o hello.o
#gcc -Wall -Wextra -c main.c -o main.o
#gcc -static hello.o main.o -o hello_static
make hello_static
hello_static
file hello_static
readelf -h hello_static
objdump --disassemble=f_defined hello_static