08r · Errors as Values: Option, Result, and ?¶
Released Fri Sep 18, in class
This is the README OSlings gives every student for 08r_errors (oslings
lesson shows it). 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. Things go wrong, and a kernel has nowhere to throw an exception. Today you learn Rust's answer: failure is an ordinary value, returned like any other, that the compiler will not let you ignore.
Learn¶
Open a file that is not there. Ask for a page of memory when there is none left. Look up a process ID that no longer exists. None of these is a bug — they are ordinary events a correct kernel must survive, and each has to be reported from the code that noticed to the code that can do something about it.
Most languages report failure by throwing an exception: control leaves the
function without returning, unwinds the stack, and lands in a catch up the
call chain. A kernel cannot work that way, for two reasons.
There is nowhere to throw to. When a user program calls read, the CPU is
in the middle of a trap: it has switched stacks, and the "caller" is a program
in a different address space that has never heard of Rust. There is no stack to
unwind into and no handler to land in. The kernel must get back to that trap
handler by ordinary means, carrying its answer with it.
Stopping is not an option. In an application an unhandled exception kills
the process and the operating system cleans up; in an operating system it kills
the machine. Rust's panic! — what unwrap does when it fails, what
indexing past the end of an array does — halts our kernel and never returns.
That is right for "the kernel's own invariants are broken" and wrong for "the
user asked for a file that does not exist".
So failure travels the same way any other answer does: as a return value. C
does this too, with the famous -1 and a global errno, and the famous
problem that nothing makes you look. Rust does it with two types.
Two standard-library enums¶
T and E stand for any types you choose, and all four variant names are in
scope everywhere without a prefix. You met Option in 05r: it is for
absence, a question whose honest answer may be "nothing". Which slot holds
pid 7? Possibly none of them, and nothing has gone wrong.
Result is for failure: an operation that was supposed to produce a T
and could not, so it produces an E explaining itself instead. That E is the
whole difference. None says nothing happened; Err(FsError::NameTooLong)
says what went wrong, which is what lets the caller decide whether to give up,
retry, or tell the user.
Result is marked #[must_use], so ignoring one is a compiler warning — the
-1-you-forgot-to-check bug, caught at compile time.
Writing your own error type¶
E is whatever type you like, and in kernel code it is an enum you wrote:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FsError {
NotFound,
NameTooLong,
IsADirectory,
}
One variant per way this subsystem can fail. A caller can match on the
specific failure instead of guessing at an integer, and exhaustiveness (05r)
runs in reverse when you grow the type: add AlreadyExists in exercise 40k and
the compiler hands you every match that now needs a new decision. The
derive line is the usual four from 05r — Debug to print an error in a
failed assertion, Clone/Copy to pass it around cheaply, PartialEq/Eq so
the tests can say assert_eq!(fs.lookup("nope"), Err(FsError::NotFound)).
Getting the value out¶
To produce a failure you just return it: return Err(FsError::NotFound);.
To consume one, you have to open the enum, and match is the honest way:
match fs.lookup(name) {
Ok(inode) => println!("inode {}", inode.inum),
Err(FsError::NotFound) => println!("no such file"),
Err(e) => println!("failed: {e:?}"),
}
There is also unwrap() — the Ok value, or a panic on Err — and
expect("message"), the same with a better message. Both are fine in tests,
where a panic is one failed test, and close to banned in kernel code, where a
panic is a dead machine.
?: the whole point¶
Most kernel functions are a chain of fallible steps, each of which should abandon the rest of the work and report upward. Written out longhand, one step is five lines:
A function with four such steps is unreadable, so Rust has an operator for
exactly this shape — let inode = self.lookup(name)?;.
? means: if this is Err(e), return Err(e) from the function I am in,
right now; otherwise unwrap the Ok and carry on with the value. It works only
inside a function that itself returns Result (or Option), because that is
where the early return has to go. This is why every filesystem function in
exercise 40k returns Result: one ? per step, and an error raised four calls
deep arrives at the system-call boundary unchanged.
.ok_or(): from absence to failure¶
The two types meet constantly, because a search returns Option and its caller
wants Result. .ok_or(e) converts: Some(x) becomes Ok(x), and None
becomes Err(e).
The directory scan reports what it saw; this line is where the policy lives —
in this filesystem, a name that is not there means the call failed with
NotFound. Keeping the two apart is deliberate: find is a fact, lookup is
a decision.
Where a Result turns back into a number¶
A user program cannot receive a Result; it gets one integer in a register. So
at the very edge of the kernel every rich error collapses into a number. The
Unix convention, which we adopt from exercise 50k on, is that a value >= 0 is
success and a negative value is minus an error code, using the numbers from
errno.h: 2 is ENOENT (no such file), 21 is EISDIR, 36 is ENAMETOOLONG.
That collapse belongs in exactly one place — the boundary. Everything behind it
speaks in FsError.
Understand¶
Open warmup/src/lib.rs — that one file is your whole workspace. You are given
a small filesystem, deliberately shaped like the real one you build in exercise
40k:
Inode— the record of one file: an inode numberinum, akind(FileorDir), and asize. It does not hold the name.DirEnt— one directory entry: a name and the inode it points at.FileSystem— aVec<DirEnt>(the directory) plus aVec<Vec<u8>>(the contents, indexed by inode number).FileSystem::new()andadd, both given, build this filesystem:
| name | inum | kind | contents |
|---|---|---|---|
README |
0 | File | hello, world\n (13 bytes) |
init |
1 | File | first user process (18 bytes) |
dev |
2 | Dir | — |
NAME_MAX is 14, which is xv6's DIRSIZ: a directory entry on disk is a
fixed-size record, so a longer name does not fit and cannot be stored.
find and read are given. find is the 06r loop over a Vec — walk
self.entries, return Some(entry.inode) on a match, None off the end —
and it returns Option because absence is not an error. read is the
early-Err shape you repeat in lookup: one if that returns an
Err(...), then the Ok value as the last expression.
At the bottom of the file is the #[cfg(test)] mod tests block: given to you,
never edited by you, and the exact contract your code must satisfy. Read it
first. It uses two names that are not in the directory — one of exactly 14
characters and one of 15 — to pin down which failure each must produce.
Implement¶
Fill in the three IMPLEMENT markers in warmup/src/lib.rs:
lookup— reject an over-long name withNameTooLong, then turnfind'sOptioninto aResultwith.ok_or(FsError::NotFound).read_file— chainlookupandreadwith?.sys_read—matchtheResultdown to one integer: a byte count, or a negative error code.
The given find and marker 1 ask the same question twice, once as absence and
once as failure — that is the distinction this exercise exists to teach. Marker
2 is two lines, and it is the shape dirlookup (exercise 40k) and exec
(exercise 49k) are written in.
Check your work:
Stuck? oslings hint.