I’ve heard of lot of wrong information about the ELF format from people so I decided to write a post of my thoughts about it.

ELF: Executable and Linkable Format.

Before diving into how ELF is structured, we need to talk about what ELF is used to store and how these things are different from each other.

Stuff that ELF can store

(a) .data

.data corresponds to the memory region where explicity initialized global and local variables live. So something like the following would be on the .data segment.

   char str[] = "Hello World";

(b) .text

.text is where code lives. Something like the following:

   void foo(char input) {
        // do stuff.

Would be in the .text part of the ELF file.

(c) .bss

.bss is probably the most important out of them all and the most easiest. This is the place where unintialized stuff lives. So the following:

   char str[];

Would be on the .bss segment.

.bss can also be used to create a stack for higher level languages such as C. Consider the following:

section .bss:
align 4
    resb KERNEL_STACK_SIZE                      ; reserve a 4096 block for stack in .bss
    mov esp, kernel_stack + KERNEL_STACK_SIZE   ; point esp to the end of stack.

Point the esp register to the end, store the stuff inside .bss rather than .data as one might think of doing. Reasoning being that .bss doesn’t need to be taken care with initialization as by default everything is zeroed out. Also the stack benefits from this as garbage can’t be read. A write is needed before a read.

(d) .rodata

Read Only stuff like strings.

(e) .comment & .note

Self explainatory.