xv6, line by line
kernel/elf.h

kernel/elf.h

C header · 42 lines · annotated 100% · kernel · upstream

Included by 2 fileskernel/exec.c, kernel/vm.c
About this file

C structures that mirror the start of an ELF file, the format of every xv6 user program (user/_cat, user/_sh, …). kexec in kernel/exec.c reads these structures straight from the file with readi and uses them to decide what to load where.

An executable ELF file starts with a fixed 64-byte file header (elfhdr). The header says where in the file to find the program header table, an array of proghdr entries, one per segment. Each segment is a range of bytes in the file together with the virtual address it should occupy in memory and its permissions. The rest of the file (section headers, symbol tables, debug information) is for tools such as the debugger and is ignored by the kernel.

The structures follow the 64-bit ELF layout exactly, field for field, so that the bytes on disk can be read directly into them. You can see the same fields, decoded, by running ${TOOLPREFIX}readelf -h -l user/_cat (TOOLPREFIX is your RISC-V toolchain’s prefix; see Tour 1: From make qemu to a disk image and a kernel).

Only a few fields are used by xv6: magic, entry, phoff and phnum in the file header, and type, flags, off, vaddr, filesz and memsz in a program header. The rest are present to keep the layout right.

Read next: kernel/exec.c.

1// Format of an ELF executable file
3#define ELF_MAGIC 0x464C457FU // "\x7FELF" in little endian
5// File header
6struct elfhdr {
7 uint magic; // must equal ELF_MAGIC
8 uchar elf[12];
22};
24// Program section header
25struct proghdr {
34};
36// Values for Proghdr type
37#define ELF_PROG_LOAD 1
39// Flag bits for Proghdr flags