13. Userland
Why this layer exists
An operating system is proven by the programs it runs, and until now every program ember ran was baked into the kernel’s .rodata at build time and launched by the boot stage. That is a test harness, not an OS. This chapter closes the loop: programs are files on the disk of chapter 12, loaded by the kernel when a running program asks, given a console and an argument, waited for, and reclaimed. At the end there is an init, a shell, and a cat, and a reader who types cat hello.txt at the shell is running a program the kernel found by name, checked, and mapped — the whole of Part II in one keystroke.
The second reason is Part VI’s. A unikernel is an image with the userland cut off and the rest inlined; to cut a userland off there has to be one worth cutting, with a syscall boundary that can be seen and deleted. This chapter’s image is that: an S-mode kernel, U-mode programs, nine syscalls between them, IPC, a device, a file system, a shell. hearth will be allowed to run this same image, stripped, as a guest — something the reader wrote, not bought.
Mechanism
spawn is proc_create fed from a file
Chapter 7’s proc_create took a blob and an address and produced a process: pages, a fabricated frame, a kernel stack. spawn is the same call with the blob read from a file:
struct proc *spawn_path(const char *name, const char *argstr)
{
const struct elf64_phdr *ph;
struct proc *p;
unsigned int size;
int ino;
ino = fs_open(name, O_RDONLY);
if (ino < 0)
return 0;
size = fs_size((unsigned int)ino);
if (size > sizeof img)
return (struct proc *)reject("file larger than the loader's buffer");
fs_read((unsigned int)ino, 0, img, (long)size);
ph = elf_check(size);
if (!ph)
return 0;
/* Chapter 7's shape: the segment's file bytes become the code page
* at p_vaddr, and the page beyond p_filesz — the .bss the ELF
* promised in p_memsz — is zero because kalloc zeroed it. Then a
* stack page, a kernel stack, a fabricated frame at e_entry. */
p = launch(img + ph->p_offset, ph->p_filesz, ph->p_vaddr, 0);
console_attach(p);
p->parent = curproc; /* 0 for init, spawned by the boot stage */
/* One argument, as a string at the bottom of the stack page; the
* child finds its address in a2. Not argv — named, not built. */
if (argstr) {
unsigned long *slot = walk(ph->p_vaddr + PAGE_SIZE);
unsigned char *dst = (unsigned char *)(((*slot >> 10) << PAGE_SHIFT));
unsigned int i;
for (i = 0; i < 63 && argstr[i]; i++)
dst[i] = (unsigned char)argstr[i];
dst[i] = 0;
p->tf.a2 = ph->p_vaddr + PAGE_SIZE;
}
uart_puts("S: spawn ");
uart_puts(name);
uart_puts(" pid ");
uart_puthex((unsigned long)p->pid);
uart_puts(" entry ");
uart_puthex(ph->p_vaddr);
uart_puts("\r\n");
return p;
}
long spawn_impl(long path_uva, long arg_uva)
{
char name[FS_NAMELEN + 2];
char argbuf[64];
struct proc *p;
unsigned int i;
for (i = 0; i < sizeof name; i++)
name[i] = 0;
for (i = 0; i < sizeof argbuf; i++)
argbuf[i] = 0;
if (fs_copy_name(curproc, (unsigned long)path_uva, name, sizeof name) < 0)
return -1;
if (arg_uva &&
fs_copy_name(curproc, (unsigned long)arg_uva, argbuf, sizeof argbuf) < 0)
return -1;
p = spawn_path(name, arg_uva ? argbuf : 0);
return p ? p->pid : -1;
}
The name goes to chapter 12’s fs_open, the bytes to fs_read, and the result to launch — chapter 8’s create-and-fabricate — with the segment’s file bytes as the blob and the segment’s virtual address as the base. The child gets a console (console_attach, fds 0–2), a parent (whoever called), and, if the caller passed one, a single argument string copied to the bottom of the child’s stack page with its address in a2. That is not argv; it is one string, and the chapter says so rather than pretending. The kernel prints what it launched, and the child’s first instruction is the libc stub’s _start.
Why spawn and not fork and exec? Because fork needs a second copy of an address space, and this kernel has one page table. fork on ember would mean either copying every U page of the parent into fresh pages at different virtual addresses (which the program was not linked for) or per-process page tables with copy-on-write, which is a chapter of its own and the design every production kernel has. exec without fork replaces the caller, and a shell that replaced itself with cat would not be there to prompt again. spawn — create a new process from a file, in one call — is what POSIX offers as posix_spawn, for exactly the cases where fork’s copy is the wrong price; xv6, which has per-process tables, does fork and exec, and Part III’s chapter 16 reads it. ember keeps the one table, and one consequence follows: each program is linked at its own base — init at 0x10000, sh at 0x20000, cat at 0x30000 — and a second sh at once would collide with the first. Named, not fixed.
The kernel is the loader now
Chapter 2 read ELF headers to learn what QEMU loads and where. This chapter does what QEMU did:
struct elf64_ehdr {
unsigned char e_ident[16];
unsigned short e_type, e_machine;
unsigned int e_version;
unsigned long e_entry, e_phoff, e_shoff;
unsigned int e_flags;
unsigned short e_ehsize, e_phentsize, e_phnum;
unsigned short e_shentsize, e_shnum, e_shstrndx;
};
struct elf64_phdr {
unsigned int p_type, p_flags;
unsigned long p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_align;
};
#define ET_EXEC 2
#define EM_RISCV 243
#define ELFCLASS64 2
#define ELFDATA2LSB 1
#define PT_LOAD 1
static unsigned char img[4096]; /* a file is at most 3 KiB (fs.h) */
static const char *reject(const char *why)
{
uart_puts("S: spawn: ");
uart_puts(why);
uart_puts("\r\n");
return 0;
}
/* Validate the file in img[] and return its one PT_LOAD, or 0. Every
* check names what a malformed file would have made the kernel do. */
static const struct elf64_phdr *elf_check(unsigned int size)
{
const struct elf64_ehdr *eh = (const struct elf64_ehdr *)img;
const struct elf64_phdr *ph;
unsigned int i;
if (size < sizeof *eh)
return (const struct elf64_phdr *)reject("file shorter than a header");
if (eh->e_ident[0] != 0x7f || eh->e_ident[1] != 'E' ||
eh->e_ident[2] != 'L' || eh->e_ident[3] != 'F')
return (const struct elf64_phdr *)reject("bad magic");
if (eh->e_ident[4] != ELFCLASS64 || eh->e_ident[5] != ELFDATA2LSB)
return (const struct elf64_phdr *)reject("not ELF64 little-endian");
if (eh->e_type != ET_EXEC || eh->e_machine != EM_RISCV)
return (const struct elf64_phdr *)reject("not a RISC-V executable");
if (eh->e_phentsize != sizeof *ph || eh->e_phnum == 0 ||
eh->e_phoff + (unsigned long)eh->e_phnum * sizeof *ph > size)
return (const struct elf64_phdr *)reject("program headers out of range");
for (i = 0; i < eh->e_phnum; i++) {
ph = (const struct elf64_phdr *)(img + eh->e_phoff) + i;
if (ph->p_type != PT_LOAD)
continue;
if (ph->p_vaddr & (PAGE_SIZE - 1))
return (const struct elf64_phdr *)reject("segment not page-aligned");
if (ph->p_offset + ph->p_filesz > size || ph->p_filesz > ph->p_memsz)
return (const struct elf64_phdr *)reject("segment out of range");
if (ph->p_memsz > PAGE_SIZE)
return (const struct elf64_phdr *)reject("segment larger than a page");
if (eh->e_entry != ph->p_vaddr)
return (const struct elf64_phdr *)reject("entry is not the segment start");
return ph; /* the first PT_LOAD is the program */
}
return (const struct elf64_phdr *)reject("no loadable segment");
}
The fields are the System V gABI’s: the four magic bytes, the class and data bytes in e_ident (64-bit, little-endian), e_type = 2 for an executable, e_machine = 243 for RISC-V — the psABI’s number, and the f3 00 at byte 18 of every binary this toolchain makes — e_entry, and the program header table’s offset, entry size and count. Then the program headers, of which one matters: the first PT_LOAD says where in the file the program’s bytes are (p_offset, p_filesz), where in memory they go (p_vaddr), and how much memory the program expects (p_memsz). Every check names what a malformed file would have done to the kernel: a segment past the end of the file is a read past the loader’s buffer; a segment larger than a page is a copy over the stack page; an entry that is not the segment’s start is a jump into the middle of something. Exercise (a) feeds the loader a text file.
p_memsz is larger than p_filesz when the program has a .bss: bytes that are zero at start and take no space in the file. The loader does nothing for them, and that is correct, because proc_create copies the file bytes into a page that kalloc_page zeroed — the .bss is zero for free, and the stub’s _start zeroes it again anyway. Exercise (b) puts numbers on it.
The user build makes ELFs the loader can take, which is not what this toolchain does on its own. It links position-independent executables by default, with .interp, .dynamic, a GOT and an unwind table, and a load segment that starts below the program’s base; the flat blobs of chapters 7–12 never noticed, because objcopy -O binary discarded all of it. As files they would be 6 KiB, over chapter 12’s 3 KiB limit. -fno-pie -no-pie, no unwind tables, no build ID, and -N so the load segment is not padded to a page in the file: the shell is 1304 bytes on disk. That is chapter 2’s lesson from the other side — the ELF is a container, and what the linker puts in it is a choice.
The stub is the ABI
void _start(void) __attribute__((section(".text.start"), noreturn));
void _start(void)
{
extern char __bss_start[], __bss_end[], stack_top[];
char *p;
register long a1r __asm__("a1");
register long a2r __asm__("a2");
__asm__ volatile("" : "+r"(a1r), "+r"(a2r)); /* before .bss is wiped */
for (p = __bss_start; p < __bss_end; p++)
*p = 0;
pid = a1r;
arg = (const char *)a2r;
__asm__ volatile(
"mv sp, %0\n"
"call main\n"
"li a7, 1\n" /* exit(main()) — a0 already holds the value */
"ecall\n"
:: "r"(stack_top) : "memory");
__builtin_unreachable();
}
static long syscall3(long n, long a0, long a1, long a2)
{
register long a0r __asm__("a0") = a0;
register long a1r __asm__("a1") = a1;
register long a2r __asm__("a2") = a2;
register long a7r __asm__("a7") = n;
__asm__ volatile("ecall"
: "+r"(a0r)
: "r"(a1r), "r"(a2r), "r"(a7r)
: "memory");
return a0r;
}
lib.c is the whole syscall interface as a user program sees it: _start, which captures the two registers the kernel set (the pid in a1, the argument in a2), zeroes .bss, sets sp, calls main, and turns main’s return into exit; and nine wrappers, one ecall each, with the numbers the kernel’s table froze in the order the chapters added them: exit 1, write 2, yield 3, sbrk 4, read 5, close 6, open 7, spawn 8, wait 9. A stub, not a library — nothing here formats, allocates or buffers, and the three programs are written against that. _start sits in .text.start so it is the first byte of the segment, which is the byte e_entry names; exercise (c) is what happens if either of its duties is skipped.
wait, and the leak closes
/* The child's pages come back: every U page from its base to its
* break, unmapped and freed; its kernel stack; its slot. Chapter 9
* named this leak; a parent that waits is who closes it. */
static void reap(struct proc *c)
{
unsigned long va;
for (va = c->base; va < c->brk; va += PAGE_SIZE) {
unsigned long *slot = walk(va);
if (slot && (*slot & PTE_V)) {
kfree_page((*slot >> 10) << PAGE_SHIFT);
*slot = 0;
}
}
__asm__ volatile("sfence.vma" ::: "memory");
kfree_page(c->kstack_top - PAGE_SIZE);
c->state = UNUSED;
c->parent = 0;
uart_puts("S: reap proc ");
uart_putc((char)('0' + c->pid));
uart_puts("\r\n");
}
long wait_impl(long pid)
{
struct proc *c;
if (pid < 1 || pid > NPROC)
return -1;
c = &proc_tab[pid - 1];
if (c->state == UNUSED || c->parent != curproc)
return -1; /* not a child of the caller */
while (c->state != DEAD)
sleep_on(c, "child"); /* exit wakes on the child's own address */
reap(c);
return pid;
}
wait(pid) is chapter 10’s sleep_on with the child’s own address as the channel; exit calls wakeup on that address after marking the child DEAD. When the parent wakes it reaps: every user page from the child’s base to its break, unmapped through the frozen walk and returned to the freelist; the child’s kernel stack; the slot. Chapter 9 named this leak — a process that exits leaves its pages mapped in a DEAD slot — and said that a parent that waits is who closes it. Only a parent may wait, and only for its own child; the kernel says S: reap proc N when it does.
The programs
int main(void)
{
long sh;
puts_("init: up\r\n");
sh = spawn("sh", 0);
if (sh < 0) {
puts_("init: no sh\r\n");
return 1;
}
wait(sh);
return 0;
}
int main(void)
{
char line[64];
puts_("sh: up\r\n");
for (;;) {
long n = read(0, line, sizeof line - 1);
char *a = 0;
long i, child;
if (n <= 0)
return 0; /* EOF on the console */
if (line[n - 1] == '\n')
n--;
line[n] = 0;
puts_("$ ");
puts_(line);
puts_("\r\n");
for (i = 0; i < n; i++)
if (line[i] == ' ') {
line[i] = 0;
a = &line[i + 1];
break;
}
if (line[0] == 0)
continue;
if (streq(line, "exit"))
return 0;
child = spawn(line, a);
if (child < 0) {
puts_("sh: cannot spawn ");
puts_(line);
puts_("\r\n");
continue;
}
wait(child);
}
}
init spawns the shell and waits for it; when the shell exits, init exits, the table is empty, and the boot stage’s scheduler() returns — to a wait on init itself, since the boot stage is init’s parent, and then to PASS. The shell is the userland’s scheduler of one: read a line from fd 0, print it after a prompt, split it at the first space into a command and an argument, spawn the command, wait for it, loop. exit is the one built-in. cat opens its argument, copies it to fd 1 in 64-byte reads until read returns 0, and returns — a program that would work unchanged on a pipe end, which is exercise (d).
mem_init();
trap_init();
uart_puts("S: kernel up\r\n");
kalloc_init();
blk_init();
fs_init();
uart_irq_on(); /* the console: chapter 5's path, chapter 10's buffer */
console_wait_line(2); /* the lab's script is two lines; see console.c */
if (!spawn_path("init", 0))
halt(1); /* no init on the disk: nothing to run */
scheduler(); /* returns when init has exited */
wait_impl(1); /* init's parent is the boot stage: reap it too */
{
int i;
for (i = 0; i < NPROC; i++)
if (proc_tab[i].state == WAITING) {
uart_puts("S: deadlock: proc ");
uart_putc((char)('0' + proc_tab[i].pid));
uart_puts(" still waiting\r\n");
halt(1);
}
}
uart_puts("PASS\r\n");
halt(0);
The boot stage mounts the disk, brings up the console, and spawns init by name through the same spawn_path a program would use. Nothing is embedded; the kernel image carries no user code from this chapter on. The console wait is two lines because the lab’s script is two lines — the same determinism argument as chapter 10, and the same admission that a human at the console would block in the shell’s read instead.
Walkthrough
ch13-main (mount, console, init by name, the loop, the deadlock check), ch13-spawn (file to process: fs_open, fs_read, the check, launch, the argument, the parent), ch13-elf-load (the fields and every rejection), ch13-wait (sleep on the child, reap), ch13-libc-start (the two registers, .bss, sp, main, exit), ch13-init, ch13-sh.
Exercises
(a) Type hello.txt at the shell — spawn a text file. Predict which check rejects it, then run it.
Answer
The first one that can. hello.txt is 20 bytes, an ELF header is 64, and the loader checks the size before it looks at a single byte of the header: S: spawn: file shorter than a header, then the shell’s sh: cannot spawn hello.txt. Observed. A longer text file would fall to bad magic; a real ELF for the wrong machine to not a RISC-V executable; a file whose program-header offset points past its end to program headers out of range. Each rejection is a read or a copy the kernel would otherwise have done on the file’s say-so, and the order of the checks is the order of the damage they prevent.
(b) readelf -l on the shell shows FileSiz 0x30a and MemSiz 0x320. Derive what the 22 bytes are and who makes them zero.
Answer
They are the shell’s .bss — pid and arg from the stub, eight bytes each, plus alignment — variables that must start at zero and therefore need no bytes in the file. The gABI says the loader supplies p_memsz − p_filesz zero bytes after the file’s bytes. This loader does not, explicitly: it copies p_filesz bytes into a page that kalloc_page zeroed, and the remaining 22 bytes of that page are zero because every byte of it was. Then _start zeroes __bss_start to __bss_end a second time, which on this kernel is redundant and on a kernel that reused pages without zeroing would be the only thing standing between the program and someone else’s old data. Two mechanisms, either of which suffices; the one in the program is the one the program can rely on.
(c) What must the stub’s _start do before it calls anything, and what fails if it skips either?
Answer
Two things, in this order: capture what is in the registers the kernel set, and set up the world C expects. The frame’s a1 and a2 exist only until the first instruction that clobbers them, so _start reads them into registers the compiler is told to keep (register long a1r asm("a1")) before anything else. Then it zeroes .bss — but not before the captures, because pid and arg are in .bss and would be wiped — and sets sp to stack_top, because the fabricated frame’s sp is the kernel’s guess and the link script’s symbol is the program’s. Skip the captures and the shell has no pid to print and cat has no argument. Skip the .bss zeroing and on this kernel nothing changes, which is exercise (b)’s point. Skip sp and the first call pushes onto whatever the frame said, which here happens to be the same page top — chapter 7 chose them to agree — and on any other kernel would be a fault at the first push.
(d) cat reads a descriptor from open and writes to fd 1. What would change if the descriptor were a pipe end instead of a file?
Answer
Nothing in cat. It calls read until it returns 0 and writes what it got; a pipe’s read returns bytes while a writer is open and 0 when none is, which is the same contract a file’s read keeps at end of file, and close on either drops a reference. The only thing this kernel lacks is a way to hand a pipe end to a spawned process — spawn attaches the console and nothing else, so sh | cat would need spawn to install a caller’s descriptor in the child, the way posix_spawn’s file actions do. The uniformity is chapter 10’s descriptor table earning its keep: three kinds behind three calls, and a program that cannot tell them apart.
(e) Strip the userland: on paper, what does the Part VI cut keep and what does it delete?
Answer
Deleted: the three programs as separate address spaces, the stub, the ecall and everything on its path — user_vec, the frame save, the syscall table, copy_in_user and copy_out_user — and the U bit as a boundary, since there is one privilege level left. spawn, wait, the per-process kernel stacks and the scheduler go with them, or shrink to threads. Kept: the allocator, the file system and its cache, the block driver and the ring, the console’s interrupt path, the page table as a map of the machine rather than as a wall between programs, and the M-mode shim underneath it all. What was cat hello.txt becomes a function that calls fs_open and fs_read directly and prints through uart_putc. The image is smaller and every bug in the application is now a bug in the kernel; chapter 32 fixes what such an image may assume of its host, and chapter 40 is the list of what it refuses.
(f) Count the syscalls in this ABI and set the number beside Linux’s.
Answer
Nine: exit, write, yield, sbrk, read, close, open, spawn, wait. The riscv64 Linux table, which uses the generic numbering, declares __NR_syscalls as 472 in this host’s asm-generic/unistd.h. The contrast is named and not surveyed: the gap is not nine things done badly against 472 done well, it is nine things a shell and a cat need against everything thirty years of programs have asked for, and the ABI is the part of a kernel that can never be taken back. A unikernel’s answer to the 472 is to have none — which is why chapter 32’s contract is a boot-info block and not a syscall table, and why an image with a syscall table is wick, not hearth.
Lab
make lab CH=13
make lab CH=13 IMPL=mine
input.txt is the shell session: cat hello.txt, then exit. extra.mk builds the disk from the reference init, sh and cat — stripped ELFs from ember/user/build/fs — and files/hello.txt, regenerated before every run.
After the mount: the two lines echoed as they arrive; S: console 0x2 lines ready; S: fs: open init inode 0x2 size 0x3f0 and S: spawn init pid 0x1 entry 0x10000, the boot stage loading the first program by name; init: up; the same pair for sh at 0x20000; S: proc 1 blocks on child, init in wait; sh: up; $ cat hello.txt, the shell showing what it parsed; cat opened, checked, spawned at 0x30000, the shell blocking on it; S: fs: open hello.txt inode 0x5 size 0x14, cat’s own open; the file’s bytes; S: proc 3 exited, S: wake proc 2, S: reap proc 3; $ exit; the shell exits, init wakes and reaps it, init exits; S: reap proc 1 — init has no parent process, so the boot stage, which spawned it, is the one that waits for it and gives its pages back; PASS. The three file sizes are the stripped binaries’ sizes on this toolchain; the reader’s mine/ runs the same binaries, so its transcript has the same numbers.
One ordering rule in this stage is load-bearing. The block device is brought up before the console, and blk_init enables sstatus.SIE; a console drain that merely ordered “drain, then unmask” would then run with the UART’s line live, the handler would nest inside the drain loop, and both loops would echo and buffer the same bytes. Chapter 5’s drain clears sstatus.SIE itself for exactly this reason. Interrupt enable is global, and a driver that turns it on changes every later assumption about it.
IMPL=mine copies exactly the objects chapter 13 links and stubs spawn_path to print MINE: spawn_path stub for init and halt: the mount succeeds and the first program never loads.
Further reading
- System V Application Binary Interface — ELF Header and Program Header (gABI 4.1+, Linux Foundation referenced specifications) —
Elf64_Ehdr,Elf64_Phdr,ET_EXEC,PT_LOAD, the magic bytes; every field the loader reads. - xv6-riscv (MIT PDOS) —
kernel/exec.cis the sibling that replaces: the same header checks, then a new page table swapped for the old, which is what per-process tables buy andemberdoes without. - pipe(2) — Linux manual page (man-pages project) — for exercise (d), the contract a pipe end keeps that lets
catnot care.