54k · The ELF Loader¶
Released Fri Dec 4, in class: posted here early
This is the README OSlings will give every student for 54k_elf_loader (oslings
lesson shows it) when the exercise is released on Fri Dec 4. The starter code
is not published here: it reaches you through OSlings, in class on the
class network. It is extra credit, +1.0: see
Extra Credit. Back to All Exercises.
Extra credit. No session of its own: it is released with a core exercise and worked once that day's core exercise passes, in class or in office hours. Prerequisites: 52k_userland (do 53k first if you want your own commands to keep working). Nothing later depends on the code you write here.
Learn → Understand → Implement. Teach the kernel to read a real executable file format, and remove the last piece of hand-waving in
exec.
Learn¶
Every program exec has run so far is a flat image: a bare sequence of
bytes that the kernel copies to virtual address 0 and jumps into at the first
one. That is the simplest thing that can possibly work, and it has been fine
because every program until now was hand-written to suit it.
It is also a lie of convenience, and the cost is real:
- There is no entry point. The first byte of the image is the entry
point, so
_startmust be physically first in the file. Add a function above it and the program silently jumps into the wrong code. - There are no permissions. With one undifferentiated blob, every page gets the same mapping. rv6 maps them read-execute, which means a program's constants are executable and its variables cannot be written at all.
- There is no
.bss. A flat image has exactly the bytes in the file. A program with an uninitialized global has nowhere to put it, so it cannot have one — and both C and Rust assume.bssexists and arrives zeroed.
An ELF file — Executable and Linkable Format, what your compiler has been emitting all along — answers all three, and it does so with about eighty lines of kernel code.
What an ELF file actually is¶
Two structures matter to a loader. Everything else in the format is for linkers and debuggers, and you can ignore it.
The header, at the very start of the file:
| Offset | Size | Field | What you use it for |
|---|---|---|---|
| 0 | 4 | magic | Must be 7F 45 4C 46 — \x7f then "ELF" |
| 4 | 1 | class | 2 = 64-bit |
| 5 | 1 | data | 1 = little-endian |
| 16 | 2 | e_type |
2 = ET_EXEC, a linked executable |
| 18 | 2 | e_machine |
243 = EM_RISCV |
| 24 | 8 | e_entry |
Where to start executing |
| 32 | 8 | e_phoff |
File offset of the program header table |
| 54 | 2 | e_phentsize |
Size of one program header (56) |
| 56 | 2 | e_phnum |
How many there are |
The program headers, an array of e_phnum entries of e_phentsize bytes
each, starting at e_phoff. Each one describes a chunk of the file and where
it wants to live:
| Offset | Size | Field | Meaning |
|---|---|---|---|
| 0 | 4 | p_type |
1 = PT_LOAD, "map this". Skip everything else |
| 4 | 4 | p_flags |
4 = R, 2 = W, 1 = X |
| 8 | 8 | p_offset |
Where the bytes are in the file |
| 16 | 8 | p_vaddr |
Where they go in the address space |
| 32 | 8 | p_filesz |
How many bytes are in the file |
| 40 | 8 | p_memsz |
How many bytes to occupy in memory |
The last two are the interesting pair. When p_memsz is larger than
p_filesz, the difference is .bss — memory the program wants but which is
not stored in the file, because it is all zeros. Your loader must supply those
zeros. Forgetting is the single most common ELF-loader bug, and the symptom is
maddening: a program that works when the memory happens to be zero already and
fails mysteriously later.
Here is the probe program you will load, as its own headers describe it:
entry 0x1080 <- not the first byte!
PT_LOAD vaddr 0x1000 filesz 382 memsz 382 R+X .text
PT_LOAD vaddr 0x2000 filesz 89 memsz 89 R .rodata
PT_LOAD vaddr 0x3000 filesz 8 memsz 16 R+W .data + 8 bytes of .bss
Three segments, three different permission sets, a non-zero entry point, and
eight bytes of .bss. A flat loader cannot express any of it.
Reading a byte layout, not a struct¶
You might expect to cast the image to a #[repr(C)] struct Elf64Ehdr and read
fields. Do not. include_bytes! produces a byte slice with alignment 1,
and casting an under-aligned pointer to a struct is undefined behavior in
Rust — it may work today and break under a different optimization level.
Read each field out of the slice instead. The helpers are given:
fn u16le(b: &[u8], off: usize) -> u16
fn u32le(b: &[u8], off: usize) -> u32
fn u64le(b: &[u8], off: usize) -> u64
This is not merely a workaround. A file format is a byte layout, and writing it out that way says so.
Understand¶
Open and read, in order:
rv6/src/elf.rs— the constants, the field offsets, the little-endian helpers,pgrounddown, andpermsare all given. OnlyloadhasIMPLEMENTmarkers — three of them.rv6/src/exec.rs— findfill_addrspace. It now chooses a loader by looking at the first four bytes: an ELF file goes toelf::load, anything else to the oldvm::load_segment. Note that it returns an entry point now, which flows intoBuilt::entryand then into the trapframe'sepc.lookupis 53k's finished version — the built-in table, then the commands you shipped — with one special case ahead of both: the probe.rv6/src/probe.rs— the probe's image, embedded withinclude_bytes!.
Control flow:
run probe → exec::lookup → fill_addrspace
→ sees \x7fELF → elf::load(pt, image)
→ validate header → read e_entry, e_phoff, e_phnum
→ for each PT_LOAD: allocate, ZERO, copy p_filesz bytes, map with p_flags
→ return e_entry
→ epc = entry → sret → the probe runs
Implement¶
In rv6/src/elf.rs, fill in the three IMPLEMENT markers:
-
Validate the header and read
e_entry,e_phoff,e_phentsize, ande_phnum. Reject anything that is not a 64-bit little-endian RISC-V executable. A kernel that trusts a file it was handed is a kernel with a security hole. -
Map every
PT_LOADsegment where its header says, one page at a time, with the permissionsp_flagsasks for. Zero each page before copying, so thep_memsz-beyond-p_filesztail arrives as zeros. -
Return
e_entry, not a fixed address.
Check your work:
The harness runs the probe and checks four separate things, and tells you which one broke:
| If you see | It means |
|---|---|
the decoy ran |
You jumped to the first byte instead of e_entry |
found its .bss non-zero |
You copied before zeroing, or skipped the tail |
could not write to its own global |
You mapped everything R+X instead of reading p_flags |
probe faulted |
A segment is missing, or mapped at the wrong p_vaddr |
It also checks that a file with no ELF magic is rejected rather than
faulted on, and that flat programs still run — both the kernel's built-in demos
and your own shipped commands, which oslings run ships again before building,
as it does for 53k. This exercise adds a format, it does not replace one.
Stuck? oslings hint.