Sub topic 1
What unsafe Rust lets you do, and what it still requires of you
Prerequisites
This chapter assumes you know Rust ownership, borrowing and lifetimes. You should also be comfortable with cargo run and cargo test, and have seen raw pointers and the unsafe keyword at a basic level. Later chapters install tools with rustup, but this chapter needs no installation.
What unsafe unlocks
Safe Rust guarantees that a program cannot cause undefined behavior (UB). The compiler checks this for you. The unsafe keyword marks code where the compiler cannot check it, so you must.
An unsafe block or function gives you five extra abilities:
- Dereference a raw pointer.
- Call an
unsafefunction, including foreign functions. - Access or modify a mutable
static. - Implement an
unsafetrait, such asSendorSync. - Access fields of a
union.
Nothing else changes. Inside unsafe, the borrow checker, type checker and lifetime rules still run. The keyword does not turn checking off. It lets you perform five operations whose safety the compiler cannot prove.
What you still owe
Each unsafe operation has conditions that must hold. If you break one, the program has undefined behavior, even if it appears to work. Common conditions are:
| Operation | What you must guarantee |
|---|---|
| Dereference a raw pointer | It points to live, properly aligned memory that holds a valid value of the type |
| Create a reference from a pointer | The reference obeys the aliasing rules: no mutable reference may overlap another reference |
| Read a `static mut` | No other thread writes it at the same time |
| Produce a value, for example with `transmute` | The bits are valid for the type, so a `bool` must be 0 or 1 |
| Call an `unsafe fn` | You meet the preconditions in its documentation |
These conditions are called safety invariants and validity rules. Some are written down in the standard library docs. Others, like the exact aliasing rules, are still being refined. Later chapters cover them.
A small example
This program has a mistake in an unsafe block:
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) };
println!("{x}");
}The vector holds three elements, at offsets 0, 1 and 2. Offset 3 is past the end of the allocation. The compiler accepts the code because dereferencing a raw pointer is allowed in unsafe. Nothing in the language stops the read. The condition "the pointer must point into live memory that you own" is broken, and only you can notice that.
The safe wrapper pattern
Good unsafe code keeps the danger small. You write a safe function whose body contains a short unsafe block, and you make sure no caller can reach the unsafe conditions with safe code. If a safe function can cause UB, the function is unsound, and the bug is in that function, not in its caller.
This is why unsafe code needs careful review and testing. A mistake can hide behind an interface that looks safe.
Why this matters for Miri
The out-of-bounds read above may print a number and exit normally on your machine. The compiler gave no warning, and a test might pass. The next chapter explains why, and why that makes UB hard to find. Miri exists to fill this gap by checking your unsafe code while it runs.
Exercise
Name two things the unsafe keyword allows, and one thing it does not turn off.
Show answer
It allows dereferencing a raw pointer and calling an unsafe function (also: accessing a mutable static, implementing an unsafe trait, accessing union fields). It does not turn off the borrow checker. References inside an unsafe block are still checked for ownership and lifetimes.
Exercise
A safe function contains an unsafe block, and some safe caller can make it read freed memory. Where is the bug?
Show answer
In the function itself. A safe function must not allow UB from any safe call, so the function is unsound and must be fixed, for example by validating its inputs or by making it an unsafe fn with documented preconditions.