02r · Ownership and Moves¶
Released Thu Sep 3, in class
This is the README OSlings gives every student for 02r_ownership (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. Rust's one big idea: every value has exactly one owner. By the end you'll have hand-modeled a page allocator and seen why a page that has been handed out can no longer be considered free.
Learn¶
In exercise 32k you will write the kernel's physical page allocator. It keeps a
list of free pages; kalloc hands one out, kfree takes one back. The bug that
ruins that allocator — and every allocator ever written — is handing the same
page to two callers, who then both write to the same memory, each convinced it
owns it. Rust is the language it is because of that bug.
The problem, in two other languages¶
In C you call malloc to get memory and free to give it back. Nothing checks
that you free it exactly once, or that you stop using it afterwards. Free it
twice and the allocator's own bookkeeping is corrupted (a double free); use it
after freeing and you are reading memory that now belongs to somebody else (a
use-after-free). These are the two most common serious bugs in systems code.
In Java or Python you never free anything. A garbage collector — part of the language runtime, which periodically scans for values nothing can reach any more — cleans up behind you. That works, but it costs you a runtime: a thread that stops your program, allocates memory of its own, and needs an operating system underneath it to do any of that. We are writing the operating system; there is nothing underneath us. A garbage collector is not available, and a kernel could not afford one pausing it at an arbitrary moment anyway.
Rust takes a third road. There is no garbage collector and no free(), and
yet memory is still released, exactly once, at a moment you can point to in the
source. The compiler works it out at compile time from a single rule.
The rule¶
- Every value has exactly one owner — a binding that is responsible for it.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped: its memory is released, right there.
{
let label = String::from("kernel"); // `label` owns this text
// ... use label ...
} // scope ends: dropped here
A String is text whose characters live in a buffer on the heap — the pool
of memory a program allocates from at runtime, as opposed to the stack, which is
just the current function's local storage. Somebody has to release that buffer.
In Rust it happens at the closing brace, because that is where the owner stops
existing. No free, no collector, and the release point is visible in the code.
Moves¶
Now the interesting part. What happens here?
In most languages this makes a second name for the same text — and then two
names are responsible for one heap buffer, which means two drops, which is a
double free. So in Rust assignment moves ownership: b is now the owner and
a is no longer usable. Touch it and the compiler stops you:
error[E0382]: borrow of moved value: `a`
| let b = a;
| - value moved here
| println!("{}", a);
| ^ value borrowed here after move
That error is not the compiler being difficult. It is the compiler catching a use-after-free before the program has ever run. Read "moved" as "given away".
Passing a value to a function is a move too — the parameter becomes the new owner:
fn consume(text: String) { } // `text` owns it now, and drops it at the `}`
let a = String::from("kernel");
consume(a);
// `a` is gone. Using it here is a compile error.
If the caller still needs the value, the function has to hand it back by
returning it. That is genuinely clumsy, and it is what most of today's exercise
looks like. Rust has a better answer — borrowing, with & — but that is 03r,
and it is much easier to understand once you have felt why it exists.
Copy types¶
Not everything moves. Numbers do not:
A usize is 8 bytes with no heap buffer attached, so duplicating it is as cheap
as moving it and there is nothing to double-free. Types like this are Copy:
assigning or passing one copies the bits and leaves the original alone. The
integer types, bool, and char are Copy; String and Vec<T> are not.
So: page numbers are copied freely; the list of them is moved.
Vec, and the syntax you need today¶
A Vec<T> ("vector") is a growable list of values of type T, stored in a heap
buffer that the Vec owns. Everything you need:
let mut free = Vec::new(); // empty; `mut` because we are about to change it
free.push(3); // append 3 to the end
free.len(); // how many elements (3 -> 1)
free.is_empty(); // true when len() == 0
let page = free.remove(0); // take element 0 out and hand it to us
Tuples. A tuple is a fixed group of values written in parentheses, and it is
how a function returns more than one thing. (Vec<usize>, usize) is the type of
"a list and a number". Take one apart by matching its shape:
That single line moves the list back out of the tuple into a new binding also
called free — reusing the name is normal Rust and is called shadowing.
mut on a parameter. If a function needs to modify a value it was given, it
says so in the parameter list:
The mut is not part of the type and the caller never sees it. It only says
"inside this function, I may change my copy of this binding". Leave it off and
free.push(...) will not compile.
Understand¶
Open warmup/src/lib.rs. You are building a page allocator by hand, out of
nothing but a Vec<usize> of free page numbers — page 0, page 1, and so on,
each standing for one 4096-byte page of RAM.
new_free_list(count)builds the starting list, the way the kernel'sinitfrees every page at boot.take_page(free)iskalloc: it moves one page number out of the list.give_back(free, page)iskfree: it moves one in.
Because there is no borrowing yet, each of these takes the whole list by value
and hands it back. Notice what that buys you: while take_page runs it is the
only owner of the free list, and the page number it hands out is no longer in
the list it returns. There is no way to write this code such that a page is
both allocated and free — the property the test
the_same_page_is_never_handed_out_twice checks, and the one the real allocator
needs.
When the free list runs out, take_page returns the constant NO_PAGE, which
is usize::MAX — a page number so large it can never be real. Exercise 32k's
kalloc returns a null pointer for the same reason and to the same effect.
At the bottom of the file is the #[cfg(test)] mod tests block. It is given to
you, you never edit it, and it is the exact contract your code must satisfy.
Read it before you write anything.
Implement¶
Fill in the four IMPLEMENT markers in warmup/src/lib.rs:
new_free_list— return aVec<usize>holding0throughcount - 1.take_page— remove the last page number and return it with the list; returnNO_PAGEwhen the list is empty.give_back— push the page onto the list and return the list.measure_label— return the label's length in bytes and the label, because the caller gave it away to call you.
Two of these need mut added to a parameter. The compiler will say so.
Check your work:
Stuck? oslings hint.