Sub topic 1
What unsafe Rust lets you do, and what it still requires of you
Safe Rust makes a promise: if your program compiles without unsafe, it cannot cause undefined behavior. The unsafe keyword marks the places where you take over part of that promise. This chapter covers what unsafe unlocks, what it leaves switched on, and why the rest of this tutorial needs a tool like Miri.
Prerequisites
This chapter assumes you already know:
- Rust ownership, borrowing and lifetimes, including the difference between
&Tand&mut T. - Basic Cargo usage:
cargo runandcargo test. - What a raw pointer (
*const T,*mut T) is, and that dereferencing one needs anunsafeblock. - How to install toolchains and components with
rustup.
You do not need to know anything about Miri yet.
What `unsafe` actually unlocks
unsafe does not turn off the compiler. It gives you exactly five extra abilities:
- Dereference a raw pointer.
- Call an
unsafefunction or method, including foreign functions declared in anexternblock. - Access or modify a mutable
staticvariable. - Implement an
unsafetrait, such asSendorSync. - Read a field of a
union.
Everything else works as before. The borrow checker still checks references inside unsafe blocks, and type checking and lifetimes still apply. What changes is that for these five operations, the compiler can no longer prove the operation is valid. It trusts you.
Here is a small example that uses the first ability.
fn main() {
let mut value = 42;
let p = &mut value as *mut i32;
unsafe {
*p += 1;
println!("{}", *p);
}
println!("{value}");
}This program is correct. The pointer p was made from a live variable, value has not moved or been dropped, and nothing else touches value while p is in use. Each of those facts is something you had to check by reading the code. The compiler did not check them.
Two meanings of `unsafe`
The keyword appears in two roles, and it helps to keep them apart.
| Where it appears | What it means | Who carries the burden |
|---|---|---|
| `unsafe { ... }` block | "I have checked that the conditions for these operations hold." | The author of the block |
| `unsafe fn` or `unsafe trait` | "Callers must meet conditions the compiler cannot check." | The caller or implementor |
By convention, an unsafe fn documents its conditions in a # Safety section. A block that relies on them carries a // SAFETY: comment explaining why they hold. Both are written for human reviewers, and nothing enforces them.
/// Returns the element at `index` without a bounds check.
///
/// # Safety
///
/// `index` must be less than `data.len()`.
unsafe fn read_at(data: &[u32], index: usize) -> u32 {
// SAFETY: the caller guarantees `index < data.len()`.
unsafe { *data.as_ptr().add(index) }
}
fn main() {
let data = [10, 20, 30];
// SAFETY: 1 is less than 3.
let x = unsafe { read_at(&data, 1) };
println!("{x}");
}If a caller passes 3 here, the program compiles and may even print a plausible number. The function's contract was broken, and the caller is the one at fault.
What `unsafe` still requires of you
The compiler stops checking some things, but the rules those checks enforced are still in force. Breaking them is undefined behavior (UB), a term the next chapter defines precisely. For now, think of UB as "the program no longer has a meaning, so anything can happen."
These are the main obligations that stay with you inside unsafe code:
- Valid memory access. A pointer you read or write must point to memory that is allocated, in bounds, and still alive. It must also be properly aligned for its type.
- Valid values. Every value must be valid for its type. A
boolmust be 0 or 1, a reference must never be null or dangling, and an enum must hold a real variant. - Initialized memory. You cannot read bytes that were never written, except in a few cases such as padding that you copy as raw bytes.
- Aliasing rules. A
&mut Tmust be the only way to reach its target while it is in use. A&Tpromises that the target does not change while it is live, except throughUnsafeCell. - No data races. Two threads must not access the same memory at the same time if at least one access is a write, unless the accesses are synchronized or atomic.
The aliasing rule surprises many intermediate Rust programmers, because raw pointers feel free of rules. They are not. Creating a reference asserts something about all other pointers to the same memory. The next example shows the trap, but do not run it yet. You will see it again when we meet Miri.
fn main() {
let mut x = 10;
let raw = &mut x as *mut i32;
let r = &mut x;
unsafe { *raw = 20; }
*r += 1;
}This compiles and probably "works" on your machine. Creating r invalidated raw, so the write through raw breaks the aliasing rules. Later chapters on Stacked Borrows and Tree Borrows explain exactly why.
The safe-abstraction contract
The usual goal of unsafe code is not to expose unsafe operations to every caller. It is to build a safe API on top of an unsafe core. The standard library does this with Vec, Rc, split_at_mut and many other types.
For that to be valid, the safe function must be sound: no sequence of calls to it from safe code can cause UB. If any safe caller can trigger UB, the function is unsound, even if your own tests never do.
Here is a sound wrapper. It splits a slice into its first element and the rest, both mutable.
fn split_first_rest(slice: &mut [i32]) -> Option<(&mut i32, &mut [i32])> {
let len = slice.len();
if len == 0 {
return None;
}
let ptr = slice.as_mut_ptr();
// SAFETY: len >= 1, so index 0 is in bounds and the range
// 1..len is in bounds. The two regions do not overlap, so
// the two `&mut` borrows do not alias.
unsafe {
Some((
&mut *ptr,
std::slice::from_raw_parts_mut(ptr.add(1), len - 1),
))
}
}
fn main() {
let mut data = [1, 2, 3, 4];
if let Some((first, rest)) = split_first_rest(&mut data) {
*first = 100;
rest[0] = 200;
}
println!("{data:?}");
}The empty-slice check is what makes the function sound. If you removed it, ptr.add(1) and len - 1 would be wrong for an empty slice, and safe callers could trigger UB with split_first_rest(&mut []). The unsafe block is the same either way, and only the surrounding checks decide whether the function is sound.
The boundary also extends beyond the unsafe block. Safe code in the same module can break an invariant that unsafe code relies on, for example by changing a len field that an unsafe method trusts. For this reason, the unit of review is the whole module that maintains the invariant, not just the lines inside unsafe.
Why this matters for testing
Consider how the failures in this chapter look at run time.
| Mistake | What usually happens natively |
|---|---|
| Calling `read_at` with an out-of-range index | Reads a neighboring value and continues |
| Writing through an invalidated raw pointer | Works, because the compiler often does not exploit the violation |
| Reading a freed allocation | Often returns the old value |
In each case the program can pass its tests. Later, a compiler upgrade, a different optimization level or a different target can turn the same code into a crash or a silent wrong answer. Code review catches some of these problems, and a tool that executes the code and checks each operation catches more. That is the role of Miri, which the following chapters build up piece by piece.
Common mistakes
- Treating
unsafeas "turn off the borrow checker." The checker still runs. Raw pointers just step outside it, and the rules still apply to what you do with them. - Putting too much code in one
unsafeblock. A large block hides which operation relies on which condition. Keep blocks small and comment each one. - Assuming a passing test means a sound function. Tests only show that the inputs you tried did not misbehave.
- Forgetting that safe code can break unsafe invariants. Keep the fields that unsafe code relies on private.
Exercise
The function below is meant to be a safe wrapper that returns the last element of a slice. Is it sound? If not, say what input breaks it and how to fix it. fn last(data: &[u32]) -> u32 { unsafe { *data.as_ptr().add(data.len() - 1) } }
Show answer
It is not sound. For an empty slice, data.len() - 1 underflows (a panic in debug builds, a wrapped huge value in release builds). In release builds the pointer is then far outside the allocation, so the dereference is UB. Safe callers can reach this with last(&[]). A fix is to check first: if data.is_empty() { None } else { Some(...) }, returning Option<u32>. Better still, use data.last().copied() and avoid unsafe entirely.
Exercise
Name the five operations that unsafe permits, and name two rules that still apply inside an unsafe block.
Show answer
The five operations are dereferencing a raw pointer, calling an unsafe function, accessing or modifying a mutable static, implementing an unsafe trait, and reading a union field. Rules that still apply include the borrow checker on references, valid memory access (in bounds, alive, aligned), valid values for each type, the aliasing rules for & and &mut, and the ban on data races.