03r · Borrowing, References, and Lifetimes¶
Released Fri Sep 4, in class
This is the README OSlings gives every student for 03r_borrowing (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. How to hand a value to a function without giving it away — and how the compiler proves that nobody is reading a page while somebody else scribbles on it.
Learn¶
You already know that every value in Rust has exactly one owner, and that
passing a value to a function hands ownership over: the value moves and
the old name is dead. That rule alone would make a kernel unwritable —
checksum(page) would swallow the page, fill(page, 0) would swallow it
again, and nothing could ever look at the same buffer twice. So Rust has a
second way to pass a value: instead of giving it away, you lend it.
References¶
&page creates a reference: a value that points at page without owning
it. Making one is called borrowing, and when the borrow ends, the owner
still has the thing. The function says the same from its side:
At run time a reference is nothing but an address — the same machine word a C pointer would be, no overhead. At compile time it is far more, because the compiler tracks how long every borrow lives and what else may touch the borrowed value meanwhile. That bookkeeping is the borrow checker.
Slices¶
&[u8] is read "shared reference to a run of u8". A slice is a
reference to a contiguous run of elements: a pointer and a length, two machine
words, no copy of the data. &page where page is a [u8; 4096] becomes a
&[u8] automatically, and &page[100..200] is a hundred-byte window starting
at offset 100.
A slice is the safe-code shape of the things a kernel moves around: a page the
allocator handed you, a 512-byte disk block, the part of a console buffer that
has been typed so far. Exercise 32k works below this layer, with raw pointers
and unsafe, because those addresses come from hardware. Everywhere above it,
slices.
Two kinds of borrow¶
&T— a shared borrow. You may read. You may have as many at once as you like.&mut T— an exclusive borrow. You may read and write. While it exists it is the only way to reach the value.
Most people meet &mut as "mutable reference", and the name misleads. What
matters is not that you can write through it; it is that nobody else can even
look. Read &mut as exclusive and the rest of this page follows.
Aliasing XOR mutation¶
Here is the whole rule. At any moment, for any one value:
Either any number of
&borrows, or exactly one&mutborrow. Never both.
Aliasing means more than one path leads to the same data; mutation means somebody is changing it. Rust allows either, never both at once: many readers, or one writer. That is why this does not compile:
let mut page = [0u8; 16];
let a = &mut page; // exclusive borrow #1
let b = &mut page; // exclusive borrow #2 ← rejected here
fill(a, 0xFF);
Mixing the two kinds fails the same way: take a & to read from, then a
&mut to write through while the first is still alive, and you get
error[E0502]: cannot borrow ... as mutable because it is also borrowed as
immutable. Don't type these in — nothing in the exercise asks you to make the
compiler angry. You only need to recognize the errors when you cause them by
accident, which you will.
The rule is not bureaucracy. Two writers to the same bytes, or a reader and a
writer at the same time, is precisely the bug that corrupts a kernel's process
table when two CPUs touch it at once — and on real hardware the only cure is a
lock, taken by hand, correctly, every time. Rust turns the single-threaded
version of that bug into a compile error, and makes you say so out loud with a
SpinLock (exercise 37k) when you genuinely need shared mutable state.
Borrows end¶
A borrow lasts from where it is made until its last use — not to the end of the enclosing block:
let mut buf = [0u8; 4];
let view = &buf; // shared borrow starts
let n = checksum(view); // ...and ends here, its last use
fill(&mut buf, 1); // fine: nothing is borrowing buf any more
Most "why is this rejected?" moments are a borrow you thought had finished but which gets used again further down.
Lifetimes¶
Every reference is valid for some span of the program, and that span is its lifetime. Usually the compiler works it out silently. Sometimes it cannot:
The returned reference borrows from something, and the compiler has to know what, so it can stop you keeping the result after that something is gone. Here there are two candidates and the signature does not say which. You settle it by naming the span:
'a (say "tick A") is a lifetime parameter, declared in the angle brackets
like a name you are about to use three times. Read it as: "for some span 'a,
give me two references that live at least that long, and I hand back one that
also lives that long." You are not choosing how long anything lives — the
caller's values already decided that. You are stating a relationship, and the
compiler checks it at every call site.
A struct that stores a reference has to be annotated the same way:
Guard<'a> means "a Guard that may not outlive the u64 it points at".
That struct is a preview. In exercise 37k you build SpinLock<T>, whose
lock() returns a guard holding a &mut T to the protected data: holding the
guard is holding the lock, and dropping it unlocks. Because the &mut
cannot outlive the guard and the guard cannot outlive the lock, "only touch
this data while you hold the lock" stops being a rule people remember and
becomes one the compiler enforces. Today's Guard is that idea minus the
atomics.
Understand¶
Open warmup/src/lib.rs. One file, as always in the Rust exercises, and it replaces
whatever was there before — this unit is not cumulative. Read the
#[cfg(test)] mod tests block at the bottom before you write anything. It is
given to you, you never edit it, and it is the exact contract your code has to
satisfy. Three of the tests are as much about borrowing as about your code:
many_readers_may_share_one_sliceholds two&borrows of the same array at once, and reads the array itself as well. All legal.the_buffer_is_readable_again_once_the_write_borrow_endstakes a&mutand then a&on the same array — fine, because the first is over before the second begins.the_borrow_ends_when_the_guard_goes_out_of_scopebuilds aGuardinside an inner{ }block and reads the counter after that block closes. Move that last line up inside the braces and the file no longer compiles.
Implement¶
Fill in the five IMPLEMENT markers in warmup/src/lib.rs:
checksum— add up every byte of a&[u8]into au32.fill— write one byte value over every element of a&mut [u8].longest— return the longer of two slices; on a tie, return the first.Guard::get— read the counter the guard borrows.Guard::set— write the counter the guard borrows.
Each is one to five lines. Take them in order and re-run after each.
Check your work:
Plain cargo test on your laptop — no QEMU, no kernel. Green tests, done.
Stuck? oslings hint.