06r · Arrays, Slices, and Vec¶
Released Thu Sep 17, in class
This is the README OSlings gives every student for 06r_collections (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. The kernel's process table is eight fixed slots in a row, and it stays eight forever. Today you build one, and you find out why it is an array and not a
Vec.
Learn¶
An operating system has to remember every process it is running: which ones exist, what their process IDs are, whose turn it is next. Ours — like xv6's — keeps that bookkeeping in a plain fixed-size array:
Exactly NPROC slots, fixed when the kernel is compiled. Today you build a
miniature of that table — each slot holds just a process ID — so the real one
in exercise 34k is already familiar.
Arrays: [T; N]¶
An array is N values of the same type, laid out end to end in memory:
The length is part of the type. [u32; 4] and [u32; 5] are different
types, and no array ever changes length. In application code that is usually a
limitation; in a kernel it is the feature. Because N is fixed at compile time,
the compiler reserves the table's exact size in the kernel image itself, so
nothing has to run before the table exists — and at boot there is no allocator
to run.
Two ways to build one:
The second form, [value; N], is how new_table makes an empty table of
NPROC slots.
Indexing is slots[0], the length is slots.len(), and slots[9] panics:
Rust checks every index at runtime and stops the program rather than read past
the end. (C does not check — hence a large share of the world's security
bugs.) In a kernel, though, a panic is not "one test failed", it is a machine
that stops, so an index from somewhere you do not control — a system-call
argument, say — gets tested first:
The given free_slot does exactly that, and sys_close does it again in
exercise 50k with a file-descriptor number the kernel must not trust.
Slices: a borrowed view of a run of elements¶
A slice, written &[T] (read-only) or &mut [T] (writable), is a borrowed
window onto elements someone else owns: a pointer plus a length, no ownership,
no copy of the data.
The length is not in the type, and that is the point: one function can work
on a table of 8, a table of 64, or a growable Vec, because all of them hand
out a slice.
fn count_free(table: &[Option<u32>]) -> usize { ... }
count_free(&[None; 8]); // an array becomes a slice automatically
That conversion is why every function in today's file takes a slice though the
tests pass arrays. The borrowing rules from 03r still apply: &mut [T] is
exclusive, &[T] is shared.
Iterating¶
for slot in table.iter() { ... } // slot: &Option<u32> (read)
for slot in table.iter_mut() { ... } // slot: &mut Option<u32> (write)
iter_mut hands you a mutable borrow of each element, and you assign through
it with *slot = Some(pid);. The signature decides which you may use: a
function that took &[T] cannot call iter_mut, because it borrowed the data
for reading only.
When you also need to know where you are, .enumerate() pairs each item with
its index, counting from 0 — for (index, slot) in table.iter().enumerate().
The given find_pid is exactly that loop.
Vec<T>: the growable one¶
A Vec<T> is an array that can grow. It owns a block of memory on the heap
— memory a program asks for while it runs — and asks for a bigger block when it
fills up.
let mut pids = Vec::new(); // empty; owns nothing yet
pids.push(10); // now [10]
pids.push(20); // now [10, 20]
vec![10, 20] is shorthand for the same thing, and a Vec acts like a
slice — len, indexing, iter, passing &v where a &[T] is wanted — so
everything above carries over.
Why the kernel does not use Vec¶
Vec is the obvious choice in ordinary Rust and the wrong one here. push
calls the global allocator, and the kernel has none when the process table is
first needed: the table must exist before any allocator does. Worse, this table
is touched while the kernel handles a trap, where an allocation could fail or
stall with nowhere to report it, so the rule is absolute: no allocation on that
path. And a hard limit is honest: fork fails cleanly at the eighth slot,
where a Vec fails "when memory runs out", far from the cause. So: Vec on
your laptop, fixed arrays in the kernel.
Understand¶
Open warmup/src/lib.rs — that one file is your whole workspace. The table
is [Option<u32>; NPROC] with NPROC = 8, and each slot is an Option<u32>
(05r): Some(pid) when a process owns the slot, None when it is free. Keep
the two numbers straight — the slot index is a position in the table, 0
through 7; the pid is a process's identity. They are unrelated, and
different functions here return each.
Three of the five functions are given. new_table is one expression,
[None; NPROC]. find_pid is given — read it beside alloc_slot: the same
enumerate loop, but iter where alloc_slot needs iter_mut, because a
&[T] only lets it read. free_slot is given — note the bounds check before
the index, which is what keeps free_slot(&mut table, 10_000) from panicking.
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. One test, the_table_is_one_fixed_lump_of_memory, is green before you
start: it asserts a property of [T; N] itself rather than of your code, to
make the point that the table's size in bytes is settled at compile time.
Implement¶
Fill in the two IMPLEMENT markers in warmup/src/lib.rs:
alloc_slot— put a pid in the lowest free slot and return that index, orNoneif every slot is taken.live_pids— collect the live pids into aVec, in table order.
"Lowest free slot" is not an arbitrary rule. In exercise 50k this same search
runs over a process's file-descriptor table, and the index it returns is the
file descriptor that open gives back to the user program — which is why every
Unix, ours included, hands out the lowest free one.
Check your work:
oslings run 06r_collections
# or leave it watching and it re-runs every time you save:
oslings watch
Stuck? oslings hint.