Skip to content

52k · userland: exec, and a shell in user mode

Released Thu Dec 3, in class: posted here early

This is the README OSlings will give every student for 52k_userland (oslings lesson shows it) when the exercise is released on Thu Dec 3. The starter code is not published here: it reaches you through OSlings, in class on the class network. Back to All Exercises.

Learn -> Understand -> Implement. You can fork a process (exercise 51k) and wait for it. The missing piece is exec: make a running process become a different program. With it the trio is complete, and the shell itself can run in user mode - the capstone of the course: an operating system you built from nothing, booting to a user-mode shell.

Learn

What exec does

fork makes a copy of a process. But a copy of the shell is still the shell - useless on its own. To run ls, the copy has to become ls. That is exec:

exec throws away a process's current memory and loads a different program in its place, then starts that program from its first instruction. The process keeps its identity - same process id, same open files - but its code, data, and stack are all replaced.

Every Unix shell runs a command the same way:

    let pid = fork();          // 1. make a child (a copy of the shell)
    if pid == 0 {
        exec("ls", argv);      // 2. the child BECOMES `ls`
        // exec never returns on success: the child is `ls` now
    } else {
        wait(&status);         // 3. the shell waits for `ls` to finish
    }

fork answers "make another process"; exec answers "run this program in it"; wait answers "tell me when it is done". That is how every Unix program is launched - including the shell itself.

exec does not return (on success)

This is the strangest thing about exec, and the key to understanding it. When exec succeeds, there is no code to return to - the memory holding the instruction after the exec call was just thrown away. The process simply continues as the new program, at its first instruction. exec returns only if it fails (say, no such program): -1, so the caller - still its old self - can react.

   program A calls exec("B", ...)
        |
        |  success: A's memory is replaced by B; we resume in B at its start.
        |           A's next instruction is gone; exec does not return.
        v
   program B runs   ────────────▶   (A is gone; only B remains, same pid)

   ...OR, on failure (no such program B):
        exec returns -1, and A keeps running its own code.

The mechanism: swap the address space

An address space is everything a process can see through its page table: its code, its stack, its arguments. In rv6 each process owns a page table (the Sv39 tree from exercise 33k). So "replace the program" really means: build a brand-new page table holding the new program, and swap it in for the old one.

You built every piece of this in exercise 49k (load_segment, map_user_stack, push_argv, free_user_pagetable); this exercise gathers the first three into one given helper, build_addrspace. So exec is: build a new address space with it, then swap - point the process at the new page table, repoint its saved registers (the trapframe) at the new program's first instruction and stack, and free the old page table. That swap is the one function you write, exec_into.

Freeing the old memory out from under a running program is safe because a system call runs on the kernel's page table, not the user's: while exec_into runs, the old user page table is just data.

The shell becomes a user program

Until now rv6's shell has lived in the kernel (shell.rs, since exercise 46k), calling the filesystem directly because it was the kernel. In Unix the shell is an ordinary user program that can only ask the kernel for things through system calls - and now that exec is a system call, we can write it that way. This exercise adds sh, a small user-mode shell in the program table: print a prompt, read a line, split it into words, fork, the child execs the command, the parent waits - using nothing but read, write, fork, exec, wait, and exit. The block comments on sh in exec.rs walk through it. (The kernel shell is still there; run sh drops you into the user one.)

One new wrinkle: a blocking read needs interrupts

The user shell's read blocks until you press a key, and that key arrives as a UART interrupt (exercise 45k). But the CPU turns interrupts off on entry to the kernel, so simply waiting would hang forever. The fix (given, in sys_read): at the one system call that blocks on the console, turn supervisor interrupts back on. We do it there, not for every system call, so deeper calls like exec keep running on a quiet, shallow kernel stack.

Understand

Read these, in order (line numbers are approximate):

  1. rv6/src/exec.rs
    • The sh program (lines 341-466): its block comment and the # --- comments inside; do not trace the instructions. Then the header comments of execself, exectest, and execfail (lines 468-540).
    • Built and build_addrspace (lines 633-666): the helper and its result.
    • fill_addrspace (lines 668-687): exercise 49k's recipe, five calls.
    • build_process (lines 689-712): the model - the same swap, for a fresh process.
    • exec_into (lines 714-760): yours.
  2. rv6/src/syscall.rs
    • SYS_EXEC (line 25) and its arm in dispatch (lines 33-46).
    • ArgvStore/ARGV_STORE (lines 183-200): why the argv scratch is a static, not on the 4 KiB kernel stack.
    • fetch_argv and sys_exec (lines 202-272): copy the path and the argument strings out of user memory, then call your exec_into.
    • The interrupt comment in sys_read (lines 477-488).
  3. rv6/src/usermode.rs: usertrapret (lines 439-467). It sets sepc from the trapframe's epc, satp from (*p).pagetable, and restores the other registers (sp included) from the trapframe - which is why repointing those two is all it takes to make exec "jump" into the new program.
  4. rv6/src/main.rs: exec_self_check (lines 179-280), skim. Each [fail] line names what went wrong.

Control flow of run sh, then typing hello:

kernel shell: run sh  ──▶ exec("sh")  ──▶ the user shell starts
  sh: write "$ "
  sh: read a line  ──▶ blocks; a keypress interrupt wakes it ("hello", Enter)
  sh: fork()            ──▶ a child copy of the shell
      child: exec("hello", argv)   ──▶ sys_exec ──▶ exec_into      <- YOU
             the child's memory is REPLACED by the `hello` program
             child resumes as `hello`, prints, exits
      parent (sh): wait()  ──▶ reaps the child, loops, prints "$ " again

Implement

One function, in rv6/src/exec.rs: exec_into, the swap. The // IMPLEMENT comment walks through the six steps: build the new address space with the given build_addrspace (use ? so a failure leaves the old program untouched), remember the old page table, install the new one, point the trapframe at the new program (USER_CODE, the new sp, a0 = argc, a1 = argv), free the old page table, and return argc.

Check your work:

oslings run 52k_userland
# or
oslings watch

The harness runs execself (exec does not return), exectest (fork + exec + wait), and execfail (a failed exec returns -1 and the caller lives on).

Then the payoff:

cd rv6 && cargo run        # boots to the rv6$ kernel shell

At the rv6$ prompt, type run sh to drop into your user-mode shell. The prompt becomes $. Try:

hello
echo hi there
forktest
exit            (leaves sh, back to the rv6$ kernel shell)

Every one of those ran as a user program, launched by a shell that is itself a user program: the finish line of the course.

Stuck? oslings hint.