FerrousPath

Level 3 · Systems· Lesson 7 of 11 · 35 min

Unsafe Rust

What unsafe actually unlocks, what undefined behaviour is, raw pointers, and how to wrap unsafety in a sound safe API.

Why unsafe exists

The safe subset of Rust is deliberately conservative: it rejects every program it cannot prove memory-safe, including many that are fine. Some things can never be proven by the compiler — talking to hardware, calling C, implementing Vec itself. unsafe is where you tell the compiler: I have checked this myself.

The contract of Rust is that this obligation stays local. unsafe code is wrapped in safe abstractions, and users of those abstractions can never cause memory errors. When something does go wrong, you audit the unsafe blocks and the module around them, not the whole program.

The five superpowers

Inside unsafe { } you may additionally:

  1. Dereference a raw pointer (*const T, *mut T).
  2. Call an unsafe function or method.
  3. Read or write a static mut.
  4. Implement an unsafe trait (such as Send or Sync).
  5. Access fields of a union.

That is all. The borrow checker, type checker and lifetime checker all keep running on everything else.

Raw pointers

fn main() {
    let mut value = 10;

    // Creating raw pointers is safe. Only dereferencing them is not.
    let r: *const i32 = &value;
    let w: *mut i32 = &raw mut value;

    unsafe {
        *w += 1;
        println!("{} {}", *r, *w);
    }

    let nowhere = 0x1234usize as *const i32; // creating this is fine…
    println!("{nowhere:?}");                 // …printing the address is fine…
    // unsafe { println!("{}", *nowhere); }  // …dereferencing it is undefined behaviour.
}

Raw pointers may be null, dangling, unaligned, or aliased. They have no lifetime and no automatic cleanup. &raw const x and &raw mut x create one without going through a reference — necessary for fields of packed structs and for uninitialised memory.

Undefined behaviour

Undefined behaviour (UB) is not “the program crashes”. It means the compiler was entitled to assume this never happens, and optimised accordingly; the result can be anything, including appearing to work until an unrelated change. The main sources:

  • Dereferencing a dangling, null or unaligned pointer; reading out of bounds.
  • A data race.
  • Producing an invalid value: a bool that is not 0 or 1, an invalid enum discriminant, a char outside the Unicode scalar range, a null or dangling reference, an uninitialised integer.
  • Violating the aliasing rules: mutating through a &T (without UnsafeCell), or having a &mut T that is not unique.
  • Calling a function with the wrong ABI or signature; unwinding across an ABI that does not permit it.
  • Breaking a library precondition documented under # Safety.

Note what is not UB: integer overflow (panics or wraps), leaking memory, deadlock, panicking.

Building a safe abstraction

The standard library’s split_at_mut returns two non-overlapping mutable slices of one slice. The borrow checker cannot see that the halves are disjoint, so safe code cannot express it:

fn split_at_mut<T>(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) {
    let len = slice.len();
    let ptr = slice.as_mut_ptr();
    assert!(mid <= len, "mid out of bounds"); // the check that makes the API sound

    // SAFETY: `mid <= len`, so both ranges lie within the original slice.
    // [0, mid) and [mid, len) do not overlap, so the two &mut are unique.
    unsafe {
        (
            std::slice::from_raw_parts_mut(ptr, mid),
            std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut data = [1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut data, 2);
    left[0] = 100;
    right[0] = 300;
    println!("{data:?}");
}

The function is safe to call with any arguments: a bad mid panics before any unsafe code runs. That is the standard: a safe function must be impossible to misuse into UB. Delete the assert! and the function becomes unsound — still compiling, still usually working, and wrong.

unsafe fn and safety comments

  • An unsafe fn has preconditions the compiler cannot check. Document them under # Safety.
  • Every unsafe { } block should carry a // SAFETY: comment explaining why the preconditions hold.
/// Returns the element at `index` without bounds checking.
///
/// # Safety
/// `index` must be less than `slice.len()`.
unsafe fn get_fast(slice: &[u32], index: usize) -> u32 {
    // SAFETY: the caller guarantees index < len.
    unsafe { *slice.get_unchecked(index) }
}

fn main() {
    let data = [10, 20, 30];
    // SAFETY: 1 < 3.
    let x = unsafe { get_fast(&data, 1) };
    println!("{x}");
}

Since the 2024 edition the body of an unsafe fn is no longer an implicit unsafe block: each unsafe operation inside needs its own unsafe { }.

Unsafe traits

A trait is unsafe when implementing it makes a promise other unsafe code relies on.

use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;

/// A minimal spin lock, to show where `unsafe impl Sync` comes from.
struct SpinLock<T> {
    locked: AtomicBool,
    value: UnsafeCell<T>,
}

// SAFETY: access to `value` is serialised by `locked`, so sharing &SpinLock<T>
// across threads only ever gives one thread access to the T at a time.
unsafe impl<T: Send> Sync for SpinLock<T> {}

impl<T> SpinLock<T> {
    fn new(value: T) -> Self {
        SpinLock { locked: AtomicBool::new(false), value: UnsafeCell::new(value) }
    }

    fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        while self.locked.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
            std::hint::spin_loop();
        }
        // SAFETY: we hold the lock, so no other &mut T exists.
        let result = f(unsafe { &mut *self.value.get() });
        self.locked.store(false, Ordering::Release);
        result
    }
}

fn main() {
    let lock = SpinLock::new(0u64);
    thread::scope(|s| {
        for _ in 0..4 {
            s.spawn(|| for _ in 0..10_000 { lock.with(|v| *v += 1) });
        }
    });
    println!("{}", lock.with(|v| *v));
}

UnsafeCell<T> is the single primitive that makes mutation through & legal. Cell, RefCell, Mutex and the atomics are all built on it. (This lock is not panic-safe — if f panics the lock stays held. A real implementation uses a guard with Drop.)

Miri

Miri is an interpreter for Rust’s mid-level IR that detects most UB at runtime: out-of-bounds access, use-after-free, invalid values, aliasing violations, uninitialised reads, and some data races.

rustup +nightly component add miri
cargo +nightly miri test

On the Playground page, load the “Undefined behaviour” example and press Miri. A normal run prints a plausible answer; Miri reports the exact violation. Run your unsafe code’s tests under Miri as a matter of routine. It only checks the paths your tests execute, so it complements review rather than replacing it.

Discipline

  • Keep unsafe blocks small and the surrounding module’s invariants explicit. Soundness often depends on private fields: any safe code in the module that can modify len of your vector is part of the trusted base.
  • Prefer existing safe abstractions (split_at_mut, chunks_exact, bytemuck, zerocopy) to writing your own.
  • Prove performance claims before reaching for get_unchecked. The optimiser removes most bounds checks already.
  • Enable #![deny(unsafe_op_in_unsafe_fn)] on older editions and clippy::undocumented_unsafe_blocks.

Level 4 goes much deeper: layout, variance, drop check, and implementing Vec from raw allocation.

Exercises

  1. Implement fn swap_elements<T>(slice: &mut [T], i: usize, j: usize) using ptr::swap. What must you check, and what happens when i == j?
  2. Write a safe fn as_bytes(x: &u32) -> &[u8] with slice::from_raw_parts. Why is the reverse direction, &[u8] to &u32, not always sound?
  3. The following is unsound. Find a safe caller that triggers UB, then fix the API: pub fn first<T>(v: &Vec<T>) -> &T { unsafe { &*v.as_ptr() } }
  4. Add an RAII guard to SpinLock so it unlocks on panic.
Answers to 2 and 3

2. u8 has alignment 1 and no invalid bit patterns, so any memory can be viewed as bytes. A &u32 must be 4-byte aligned; an arbitrary byte slice may not be. (Its length may also be less than 4.)

3. first(&Vec::<i32>::new()) returns a reference to a dangling pointer. Return Option<&T> or assert non-emptiness before the unsafe block.

Check your understanding

Pick an answer to see the explanation.

  1. 1.Which of these does an unsafe block allow?

  2. 2.What does it mean for a safe API built on unsafe code to be *sound*?

  3. 3.Is creating a &mut T that aliases a live &T to the same data undefined behaviour, even if neither is ever used to write?

Key terms in this lesson

Finished the lesson and the exercises?