Skip to content

21r · Raw Pointers, unsafe, and Leaving std

Released Fri Oct 2, in class

This is the README OSlings gives every student for 21r_unsafe_bridge (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. A kernel prints by storing one byte at a magic address. Today you write that store — the pointer, the unsafe, the volatile — on your laptop, where a mistake costs you a red test instead of a hung machine.

Learn

This is the last exercise of Module 1. Exercise 30k takes the standard library away — the step where OS courses lose people, because raw pointers, unsafe, and #![no_std] usually arrive at once. Today you meet the first two with cargo test catching your mistakes, so that in 30k only #![no_std] is new.

The problem: some memory is not yours to name

Everything you have written so far pointed at memory Rust created for you. A device driver cannot work that way: on QEMU's virt board the serial port's registers are wired into the physical address space at 0x1000_0000, and a byte stored there goes out the serial line to your terminal. Nothing allocated that address; the hardware answers to it. That is MMIO — memory-mapped I/O. A reference (&u8, from 03r) cannot name it, because a reference always borrows something Rust owns, and Rust does not own the UART. For an arbitrary address you need a raw pointer.

Raw pointers: *const T and *mut T

A raw pointer is an address with a claim attached about what lives there:

let uart: *mut u8 = 0x1000_0000 as *mut u8;

Read *mut u8 as "raw pointer to a u8 I may write through"; *const u8 is the read-only version, and a *mut T converts to a *const T wherever one is expected. as is Rust's cast — same bits, different type. Making a raw pointer is safe: nothing has happened yet. But it has none of a reference's guarantees: it may be null or dangle, the borrow checker never looks at it, two *mut pointers to the same byte are legal, and it is Copy.

Pointer arithmetic: .add(n)

A device is a small block of registers, so a driver names each one as base plus offset. p.add(n) is the address n elements past p — and every pointer here is a *const u8 or *mut u8, so one element is one byte:

let lsr = unsafe { uart.add(5) };   // address 0x1000_0005

.add is unsafe because the result must stay inside the allocation you started from — a wild address is undefined behavior even if you never load or store through it. Every .add in today's file already sits inside an unsafe fn or an unsafe block.

unsafe, and what it does not do

Dereferencing a raw pointer — *p, "the value at p" — is the part the compiler cannot check:

unsafe { *uart = b'A'; }

unsafe does not turn off the compiler's checks: the borrow checker still runs, types are still checked, indexing is still bounds-checked. It unlocks a few extra abilities — chiefly dereferencing a raw pointer and calling an unsafe fn — and it is a promise you make: I have checked by hand what the compiler cannot. An unsafe fn pushes that promise onto its caller: read_reg cannot know whether base is a real address, so whoever calls it must guarantee that (which is why kalloc and kfree in 32k are unsafe fn). The discipline: keep unsafe small, and wrap it in a safe function that checks what the unsafe code needs. You write one today.

volatile, and why device registers need it

The compiler optimizes memory accesses on one assumption: memory changes only when your program changes it. True of RAM, false of a device.

*uart = b'h';
*uart = b'i';

To the compiler that is a dead store followed by a live one — nobody read *uart in between, so the first write can be deleted, and on real hardware you just lost the h. A loop polling a status register has the mirror-image bug: the read gets hoisted out of the loop and the kernel spins forever. core::ptr::write_volatile and core::ptr::read_volatile mark the access observable: it happens exactly once, where it is written, never reordered against other volatile accesses. (Volatile is not synchronization; 37k's locks are.) The rule is mechanical: a device register gets read_volatile / write_volatile, ordinary memory gets a plain *p.

core versus std

This exercise spells out core::ptr::write_volatile in full: std::ptr::write_volatile is the same function (std re-exports it from core), and writing core:: shows that the line survives #![no_std] unchanged. Here is rv6/src/uart.rs, which you will read in exercise 31k:

use core::ptr::write_volatile;

const UART0: *mut u8 = 0x1000_0000 as *mut u8;

pub fn putc(c: u8) {
    unsafe { write_volatile(UART0, c); }
}

You write every piece of that today.

Understand

Open warmup/src/lib.rs — one file, as always.

Poking 0x1000_0000 on your laptop would get the process killed, so the tests build an ordinary [u8; 8] array and hand your functions its address with device.as_mut_ptr(). Your code cannot tell the difference — only the number changes. The array stands in for the NS16550A's register file, with the chip's real offsets:

Offset Constant What it is
0 THR Transmit Holding Register — a byte written here goes out the wire
5 LSR Line Status Register — read-only device state

LSR_TX_IDLE is 1 << 5, bit 5 of the LSR, which the chip sets when it is ready for another byte. The driver in exercise 45k spins on exactly that bit.

At the bottom is the #[cfg(test)] mod tests block: given, never edited, the exact contract. Read it first, and notice where the unsafe { } blocks sit — every call into your raw-pointer functions is one, because the test is the party making the promise.

Implement

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

  1. uart_pointer — turn the number UART0 into a *mut u8. No unsafe: making a pointer is safe, and this one is never dereferenced.
  2. write_reg — volatile-write one byte to base + offset.
  3. read_reg — volatile-read one byte from base + offset.
  4. write_reg_checked — the safe wrapper: bounds-check the offset against the slice, then call write_reg inside an unsafe block. Return false and write nothing when the offset is past the end, true otherwise.
  5. copy_bytes — the kernel's memcpy: copy len bytes with pointer arithmetic and plain dereferences, no volatile.

Check your work:

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

Green means you have written a device driver's inner loop and a kernel's memcpy. Exercise 30k takes std away; nothing on this page changes.

Stuck? oslings hint.