← Week 15 page
# exec and File Descriptors ## Week 15 talk · Tuesday, December 1 CS 326 · `49k_exec` and `50k_file_descriptors`: a 15-minute talk, then you work the exercises - Prep: [exec and File Descriptors](../prep/15-cs326-2026-12-01-prep-exec-and-file-descriptors/) - READMEs: [`49k_exec`](../assignments/exercises/49k_exec/) · [`50k_file_descriptors`](../assignments/exercises/50k_file_descriptors/) - Videos: [Week 15](../videos/week15/), four of them for today - Lecture: [Week 15 · Essentials](../lectures/15-cs326-2026-11-24-exec-and-file-descriptors/#essentials), given Nov 24 Notes: **0:00–0:30** (30 s) - Welcome back. Today is an exercise day: 15 minutes on the big ideas, then you work `49k_exec`, then `50k_file_descriptors`, here on the class network. Both READMEs are released now; this talk is drawn from them, and they say the rest. **Minute plan** (15 minutes) | Min | Slide | Topic | |---|---|---| | 0:00–0:30 | title | the day | | 0:30–2:30 | 49k-by-name | programs by name, flat at address 0 | | 2:30–4:30 | 49k-layout | loading, and the user address space | | 4:30–7:00 | 49k-argv | argv on the new stack | | 7:00–8:30 | 49k-write | `build_process`, and the four registers | | 8:30–10:30 | 50k-fd | an fd indexes the per-process table | | 10:30–12:00 | 50k-offset | the offset remembers | | 12:00–13:30 | 50k-open | `open` and its flags | | 13:30–15:00 | 50k-write | `fdalloc` and the `Inode` arm | **If behind:** give 49k-layout in one sentence ("image at 0, stack fixed above it, a gap between") and 50k-open in one ("flags are bits combined with `|`"). Never cut the two What-you-write slides. - **Q:** "Is today on the final?" Yes: the final, Tue Dec 8, covers all of the Nov 24 page's Essentials. --- ## `49k_exec` · programs by name **`exec`** throws away a process's memory and loads a *new* program in its place. - `run echo` finds `echo` in a table: `hello`, `args`, `echo`, `big` - Each is a **flat binary**: raw instruction bytes, no header (unlike **ELF**) - Small enough to always load at virtual address 0 - **Position-independent**: addresses computed from the `pc`, so it runs anywhere Notes: **0:30–2:30** (2 min) - `48k` ran one program, hard-coded onto one page. An OS keeps a collection of programs and starts whichever one you name, with whatever arguments you type. Three things are new: a table looked up by name, programs bigger than a page, and arguments. Starting a program on Unix is two steps: `fork` makes the copy (`51k`, Thursday), and `exec` replaces it. - There is no compiler for user programs yet (Friday's `53k` compiles your own commands for rv6), so each program is a short hand-written chunk of machine code, stored in the kernel image between two labels such as `prog_echo_start` and `prog_echo_end`. It sits at one address in the kernel and runs at user address 0, so it never hard-codes an address: `la` with `.option norelax` gives pc-relative math. The programs are given: read each one's one-line header and skip the assembly. - **Q:** "Is `exec` a system call yet?" Not today: the kernel shell's `run` calls it, and it builds a fresh process. On Thursday `52k` makes it a system call that replaces a running program and keeps the process. --- ## Loading, and the user address space `load_segment` (given) is `48k`'s one-page loader in a **loop**: allocate a page, copy one `PGSIZE` chunk, map it with `PTE_U`. A 5,000-byte image: ```text 0x3F_FFFF_F000 trampoline R X 0x3F_FFFF_E000 trapframe R W 0x0001_0000 USER_STACK: one page, top 0x1_1000 R W U 0x0000_2000 ... unmapped: running off the image faults none 0x0000_1000 image page 1: 904 bytes, rest zero-filled R X U 0x0000_0000 USER_CODE: image page 0, 4,096 bytes R X U ``` The stack sits at a fixed address above the largest possible image, `MAX_PROG_PAGES` = 16. Notes: **2:30–4:30** (2 min) - Read `load_segment` beside `map_user_stack`, right below it in `vm.rs`: the stack is the one-page version of the same recipe, minus the copy. `big` is padded past 4,096 bytes, so loading it runs the loop twice, and the harness checks that both pages end up mapped. - 16 pages of 4,096 bytes is `0x1_0000`, so the stack sits where a 17th image page would go. The image has no W, and the trampoline and trapframe have no U, so user mode cannot touch them. The zero fill matters because a fresh page holds whatever its last owner left: the prep's third question. - **Q:** "Why not put the stack right after the image?" One fixed address works for every image up to 16 pages, and the unmapped pages between them catch a program that runs off its end: an access past the image faults. --- ## `argv` on the new stack `run echo hello world`: **argc** = 3, the name counts. **argv** points at an array of pointers to NUL-terminated strings, laid out on the *user's* stack from the top down, with `copyout`: ```text 0x1_1000 top of the stack page 0x1_0FF8 "echo\0" 0x1_0FF0 "hello\0" 0x1_0FE8 "world\0" 0x1_0FE0 (8 bytes unused: the array rounds down to 16) 0x1_0FD8 argv[3] = 0 the NULL that ends the list 0x1_0FD0 argv[2] = 0x1_0FE8 0x1_0FC8 argv[1] = 0x1_0FF0 0x1_0FC0 argv[0] = 0x1_0FF8 <- sp ends here; this address IS argv ``` On entry: `a0 = argc`, `a1 = argv`, like C's `main(argc, argv)`. Notes: **4:30–7:00** (2.5 min) - The strings and the array must live in the user's memory, because the program cannot read the kernel's. The strings go first because the array holds their addresses, and every pointer in it is a **user virtual address**: where the string sits in the program's address space, not the kernel's. A NUL is the single zero byte that ends a C-style string, which carries no length; the array ends in NULL for the same reason. - Each string's address rounds down to a multiple of 8, and the array's to 16, the calling convention's rule for `sp`. `push_argv` is given: read it slowly, since it is the argv layout made real. It hands back `(argc, argv, sp)`, here `(3, 0x1_0FC0, 0x1_0FC0)`. - **Q:** "Why is `echo` at `0x1_0FF8` and not `0x1_0FFB`?" Five bytes below the top is `0x1_0FFB`; rounding down to a multiple of 8 gives `0x1_0FF8`, and the three bytes above the string go unused. --- ## What you write today · `49k` **`exec.rs` · `build_process`**: the six-step recipe, `?` on each step. Steps 1–5 call functions that already exist; step 6 fills in four trapframe fields, the registers the program starts with. ```text shell: exec("echo", ["hello","world"]) -> allocproc a blank process -> build_process: <- YOU lookup("echo") find the program proc_pagetable map trampoline+trapframe load_segment(image) copy the program in (given) map_user_stack give it a stack push_argv(name,args) lay out argv -> (argc,argv,sp) trapframe: epc=0, sp, a0=argc, a1=argv -> run(p) drop to user mode (exercise 48k) ``` If any step fails, `exec` frees the half-built process for you. Notes: **7:00–8:30** (1.5 min) - This is all of `49k`: one function. Each fallible step returns a `Result`, so you chain them with `?`, as in `40k`. The `// IMPLEMENT` comment gives the exact call for every line. - Step 6 is the four registers: a process that never ran has nothing to resume, so the saved program counter (0, the image's first instruction), `sp`, `a0` and `a1` are its whole start. `run` then drops to user mode through `48k`'s return path. - Check: `oslings run 49k_exec`, or `oslings watch`. The harness checks that arguments reach the program, the strings arrive intact, and a two-page program loads. Then `cd rv6 && cargo run`, type `progs`, and try `run echo hello world`; `run args a b c` exits with status 4, its argc. - **Q:** "Why write the trapframe instead of jumping to address 0?" The kernel never jumps into user code. The trampoline loads all 31 saved registers, and `sret` drops to user mode at the saved program counter. --- ## `50k_file_descriptors` · an fd is an index `open` hands back a small integer, a **file descriptor**. Each process owns an array of open files, `ofile`: fd 3 *is* `ofile[3]`. A new fd takes the **lowest free** entry. ```rust pub struct File { pub kind: FileKind, // None (free), Console, or Inode pub inum: usize, // which inode, when kind == Inode pub off: usize, // the read/write cursor <-- the interesting part pub readable: bool, pub writable: bool, } ``` Every process starts with 0, 1 and 2 open on the console: stdin, stdout, stderr. Notes: **8:30–10:30** (2 min) - Why a plain integer? It is cheap to pass in a register, cheap for the kernel to look up, since it is just an array index, and it hides *what* is behind it: a file on disk, the console, later a pipe. The program reads and writes all of them the same way. "Everything is a file" is one of Unix's oldest ideas, and the descriptor is what makes it work. - The table is per-process: fd 3 in one program has nothing to do with fd 3 in another, like the address space. The kernel rechecks every use, so a number never handed out names nothing: `read` on an empty slot 5 returns -1 (the prep's second question). `write(1, ...)` worked in `48k` and `49k` because fd 1 was the console all along; `allocproc` now opens 0, 1 and 2 for every process. - **Q:** "Why the lowest free slot, and not any free one?" Programs rely on it: close 1, then open a file, and the file gets fd 1, so it is now your standard output. That is redirection. --- ## The offset: a descriptor remembers its place Each `File` carries `off`, the byte position the next read or write starts at. Every `read` returns the next chunk, then advances `off` by the count: ```text file: [ h e l l o f i l e s . . . ] ^ read(fd, buf, 64) -> returns "hello files...", off jumps to 64 read(fd, buf, 64) -> returns the NEXT 64 bytes, off jumps to 128 read(fd, buf, 64) -> returns 0 (nothing left: end of file) ``` `cat` loops "read a chunk, write it out" until `read` returns 0.
Forget to advance the offset, and every read returns the same first chunk forever.
Notes: **10:30–12:00** (1.5 min) - In `47k` the shell's `cat` read a whole file in one call, always from the beginning. A descriptor **remembers where you are**: the offset lives in its entry, and it is the only state the kernel keeps between calls. - The count `read` returns says how far the offset moved. A short read is not the end: 10 bytes back when you asked for 64 means 10 were left. Only 0 is the end, and a loop that never sees it never ends. - **Q:** "If I open the same file twice, do the two share an offset?" No: each `open` makes its own entry, starting at offset 0, so each keeps its own place. --- ## `open`: a name becomes a descriptor `sys_open` is given; its doc comment is the spec. `flags` are bits, combined with `|`: ```text O_RDONLY 0x000 O_CREATE 0x200 O_WRONLY 0x001 O_TRUNC 0x400 O_RDWR 0x002 ``` `O_CREATE | O_WRONLY`: make the file if needed, open it for writing. - The path ends at its NUL: `copyinstr` is a `copyin` that stops at the zero byte - Last step: a `File` with `off: 0`, handed to **your** `fdalloc` Notes: **12:00–13:30** (1.5 min) - `open(path, flags)` is the one file call that takes a name. The lookup is `47k` filesystem work: `dirlookup`, `dircreate`, `truncate`. Every path resolves in the root directory for now. The only new step is the last, so until `fdalloc` works, every `open` fails. - `O_RDONLY` is 0, a bit you cannot test: a file opened with neither write bit set is read-only. `O_CREATE | O_RDWR` is `0x202`. - **Q:** "Why can't `open` just `copyin` the path?" `copyin` needs a length, and the kernel knows none in advance: it finds the end of the string only by reaching the zero byte. --- ## What you write today · `50k` Two pieces, both in `rv6/src/syscall.rs`: 1. **`fdalloc`**: find the lowest free slot (`FileKind::None`) in this process's `ofile`, store the given `File` there, return its index as the fd; -1 if the table is full 2. **`sys_read`, the `FileKind::Inode` arm**: mirror the given `sys_write`'s inode arm, and **advance the stored offset** by `n` ```text cat: open("notes.txt", O_RDONLY) -> sys_open: copyinstr the name, dirlookup, fdalloc -> fd (fdalloc is YOU) cat: loop { read(fd, buf, 64); write(1, buf, n) } until read == 0 -> sys_read: read_at(off) -> copyout -> off += n -> return n <- YOU -> sys_write: copyin -> emit to console (given) cat: close(fd); exit(0) ``` Notes: **13:30–15:00** (1.5 min) - Read in the README's order: all of `file.rs`; in `proc.rs`, only `ofile`, `allocproc` and `freeproc`; the offset-based primitives at the bottom of `fs.rs`; then `syscall.rs`, where `sys_open` is the spec and `sys_write` is your model. `read` and `write` do not care whether the fd is the console or a file: the kernel branches on `file.kind`, and `sys_read`'s lookup, `Console` arm and `None` arm are given. - Check: `oslings run 50k_file_descriptors`. The harness seeds a file, then runs `cat` and `create`: read a file, create and write a file, open a missing file. Then `cd rv6 && cargo run`, and `run create notes.txt`, then `run cat notes.txt`: unprivileged programs doing real file I/O through system calls. - Close: start `49k_exec` now (`oslings run 49k_exec`, or `oslings watch`), then `50k`. Stuck? `oslings hint`. Green, then `oslings submit` before you leave; not green, submit anyway. - **Q:** "Is that the shell's `cat`?" No: the built-in `cat`, given since `47k`, is still there for comparison; `run cat` launches the user-mode one.