Skip to content

01r · Control Flow and Overflow

Released Fri Aug 28, in class

This is the README OSlings gives every student for 01r_control_flow (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. Branches, loops, and the arithmetic that decides where a page begins. By the end you'll know why addr + 4095 is a real bug in a kernel, and what to write instead.

Learn

In 00r your functions computed one thing and handed it back. Real code has to decide and to repeat, and today is about both — plus the way Rust handles arithmetic that runs off the end of a number, which is the difference between a kernel that catches its own bug and one that quietly corrupts memory.

Exercise 31k, the first kernel exercise, ends its boot code with a loop that never exits — not a placeholder, but what a kernel does when it has nothing left to do. Exercise 32k's page allocator walks physical memory a page at a time, rounding addresses up to page boundaries as it goes. You write that arithmetic today, on your laptop, where a mistake costs a red test instead of a hung machine.

if is an expression

In many languages if is a statement: it runs code, it doesn't produce a value. In Rust it is an expression, so it has a value and you can assign it:

let bigger = if a > b { a } else { b };

No parentheses around the condition, and the braces are never optional. The condition must be a real bool — there is no truthiness in Rust, so if 1 { } does not compile. Every branch must produce the same type, and if you want a value out you need an else ("what would it be if the condition were false?"). The value of a branch is its last expression, with no semicolon — the same rule as a function body, and the same trap.

Chain them with else if. There is no ? : ternary operator in Rust, because if already does that job. And an if can be a function's entire body:

fn floor_to_ram(addr: usize) -> usize {
    if addr < KERNEL_BASE { KERNEL_BASE } else { addr }
}

Three ways to loop

loop { }                                         // forever, until you `break`
while p + PAGE_SIZE <= stop { p += PAGE_SIZE; }  // re-checks first, each pass
for i in 0..4 { }                                // i = 0, 1, 2, 3

loop repeats until something inside it says break; the kernel's idle path really is loop { } with no break at all. for walks a range: 0..4 is half-open, including 0 and excluding 4 — the same convention as "RAM is KERNEL_BASE..PHYS_TOP". Write 0..=4 to include the endpoint. Inside any loop, break leaves it and continue skips to the next pass. Anything you change across passes must be declared mutable (let mut pages = 0;), as in 00r.

break with a value

A loop can hand a value back, by putting it after break:

let pages = loop {
    if addr + PAGE_SIZE > end {
        break count;      // this value becomes the value of the loop
    }
    addr += PAGE_SIZE;
    count += 1;
};

Only loop can do this: while and for can end without ever reaching a break, so there would be no value to produce.

Integer overflow, and why a kernel cares

A u8 holds 0 through 255. What is 255u8 + 1? In C the answer is 0, silently, and you find out weeks later. Rust's answer depends on how you built the code:

  • Debug build (what cargo test and oslings run use): the program panics with attempt to add with overflow. The bug stops the program at the line that caused it.
  • Release build (--release): the check is removed for speed and the value wraps to 0.

Two behaviors for the same source is a strange bargain; it exists because the check costs a branch on every arithmetic operation. The lesson is simple: never rely on wrapping by accident. If overflow is possible, say what you want to happen.

Why this matters concretely: pgroundup adds 4095 to an address. Give it an address in the last page of the address space and that addition wraps to a tiny number, so a function whose job is "round up" returns something below where it started, and the allocator hands out a page at address 0. In debug you get a panic naming the line. In release you get a kernel that works for a while and then doesn't.

Every integer type carries an explicit version of each operation:

Method Behavior on overflow Use it when
a.wrapping_add(b) wraps around wrapping is the intent, e.g. a tick counter
a.checked_add(b) gives you None overflow is a real possibility you must handle
a.saturating_add(b) sticks at the maximum clamping is a sane answer

There is a wrapping_sub, a checked_mul, a saturating_sub, and so on for every operator and every integer type. A type's largest value is usize::MAX, u64::MAX, u8::MAX.

Option, just enough of it

checked_add cannot return a plain number, because sometimes there isn't one. It returns an Option<usize>: either Some(n) — here is your number — or None — there is no answer. Rust has no null, so this is how "maybe nothing" is spelled, and the compiler will not let you touch the number without dealing with None first.

You take an Option apart with match, which tests a value against a list of shapes and must cover all of them:

match addr.checked_add(PAGE_SIZE) {
    Some(next) => next,
    None => PHYS_TOP,
}

Each arm is pattern => value, and Some(next) both matches and names the inner number next. match is an expression too, so that whole block is a usize. You'll meet enums and pattern matching properly later; this one shape is all you need today.

Rounding an address up

Here is the formula you are about to write, and why it works:

(addr + PAGE_SIZE - 1) / PAGE_SIZE * PAGE_SIZE

Integer division discards the remainder (00r), so addr / PAGE_SIZE * PAGE_SIZE snaps an address down to the page it is in: 0x8000_1234 becomes 0x8000_1000. Adding PAGE_SIZE - 1 first — 4095, one byte short of a page — is exactly enough to push an address with a nonzero offset over the next boundary, and never enough to push an aligned one past its own. By hand:

  • 0x8000_1234 + 0xfff = 0x8000_2233, which snaps down to 0x8000_2000. ✓
  • 0x8000_1000 + 0xfff = 0x8000_1fff, which snaps down to 0x8000_1000. ✓

Exercise 32k's kalloc.rs writes the same operation with bit masks, (addr + PGSIZE - 1) & !(PGSIZE - 1) — identical arithmetic, faster, obvious once we've done bit manipulation.

Understand

Open warmup/src/lib.rs. As in 00r it is your whole workspace, and this exercise replaces it wholesale — nothing you wrote last time is needed here. Three constants are given at the top: KERNEL_BASE, PAGE_SIZE, and PHYS_TOP, the first address past the end of RAM. Together they say our board has 128 MiB of memory in the half-open range 0x8000_0000..0x8800_0000. The kernel calls them KERNBASE, PGSIZE, and PHYSTOP; you'll see all three again in exercise 32k.

At the bottom is the #[cfg(test)] mod tests block — given, never edited, the exact contract your code has to satisfy. Read it first; the assertions say more precisely than prose what "round up" and "count pages" mean at the edges.

One function builds on another: count_pages should call your pgroundup rather than repeating the formula. That is not a style preference — it is what the real free_range in kalloc.rs does.

Implement

Fill in the five IMPLEMENT markers in warmup/src/lib.rs:

  1. pgroundup — round an address up to the next page boundary.
  2. clamp_to_ram — return KERNEL_BASE for an address below RAM and PHYS_TOP for one above it; anything in between, and both edges themselves, comes back unchanged. One if/else if/else expression.
  3. count_pages — count the whole pages in a range, with a loop.
  4. checked_pgroundup — the same rounding, but None rather than an overflow at the top of the address space.
  5. wrapping_tick — add 1 to a tick counter that is allowed to wrap.

Check your work:

oslings run 01r_control_flow
# or leave it watching and it re-runs every time you save:
oslings watch

If a test panics with attempt to add with overflow, that is not a mysterious failure — it is the debug build telling you which line did arithmetic it could not do.

Stuck? oslings hint.