skip to content

Sound Safe Abstractions

A safe function that wraps unsafe code must be sound for every input a safe caller can pass. Interviewers ask how to encapsulate unsafe behind a safe API and prove it.

on this pageshow

questions

6

In Rust, what does it mean for a safe function that wraps `unsafe` code to be sound, and how is that different from correct?

level: middleimportance: must knowfreq 55%

answer

  1. a promise about safe callers
  2. every input, every call order
  3. undefined behaviour vs wrong answer
  4. BTreeMap and a broken Ord

basics

~20 s

A safe function is sound when no input or call sequence available to safe code can make it cause undefined behaviour. Correctness means returning the right result; a sound function may still be buggy, but its bugs stay defined.

solid answer

~40 s

Safe Rust promises that safe code can never cause undefined behaviour, so a safe `fn` containing an `unsafe` block inherits that promise for every argument and every state its type can reach. That is **soundness**. **Correctness** is separate: whether the function returns what its docs say. std's `BTreeMap` may panic or return wrong results when a key's ordering changes while it is in the map, yet it never causes undefined behaviour, so it stays sound. The reverse also happens: a stack vector whose `get(i)` checks `i` against the capacity instead of `len` compiles, passes tests that only read pushed slots, and is unsound because `get(2)` reads an uninitialised slot. A wrapper that cannot check its precondition must become an `unsafe fn` with a `# Safety` section.

code

rust · 35 lines
rust
use std::mem::MaybeUninit;

pub struct StackVec<T, const N: usize> {
    buf: [MaybeUninit<T>; N],
    len: usize, // invariant: buf[..len] is initialised
}

impl<T, const N: usize> StackVec<T, N> {
    pub fn new() -> Self {
        StackVec { buf: [const { MaybeUninit::uninit() }; N], len: 0 }
    }

    pub fn push(&mut self, value: T) -> Result<(), T> {
        if self.len == N {
            return Err(value);
        }
        self.buf[self.len].write(value);
        self.len += 1;
        Ok(())
    }

    // Compiles, and is unsound: the index is checked against N, not len.
    pub fn get(&self, i: usize) -> Option<&T> {
        let slot = self.buf.get(i)?;
        // SAFETY: wrong - slots at or above len are uninitialised.
        Some(unsafe { slot.assume_init_ref() })
    }
}

fn main() {
    let mut v: StackVec<u32, 4> = StackVec::new();
    v.push(7).unwrap();
    println!("{:?}", v.get(0));
    println!("{:?}", v.get(2)); // safe call, undefined behaviour
}

go deeper

for a junior

Recall the one-line rule: safe Rust code must never be able to cause undefined behaviour, and anyone who writes unsafe inside a safe function takes on that promise.

for a middle

Separate the two properties with an example each: BTreeMap with a key whose ordering changes is wrong but sound, and a get that checks capacity instead of length is unsound. Explain why a panic does not break soundness.

for a senior

Show the review method: list each assumption an unsafe block makes and find the safe input that falsifies it. Name the three fixes: check at run time, make the bad state unrepresentable, or move the obligation into an unsafe fn.

for a principal

Frame soundness as a property of the whole API surface, not of one block, and argue why a team should treat a soundness bug as a security issue while a correctness bug follows the normal bug process.

## Two promises, not one Rust's **soundness property** fits in one line: no matter what, safe Rust code cannot cause **undefined behaviour** (UB). The compiler enforces it for code without `unsafe`. Once a safe function contains an `unsafe` block, its author takes that promise over: the function is **sound** only if no argument, no sequence of calls and no state that safe code can reach makes the unsafe operations inside it misbehave. **Correctness** is a different question: does the function return what its documentation says? The two properties are independent: - A function can be **correct and sound**: a bounds check followed by `get_unchecked`, the Rustonomicon's own example. - A function can be **incorrect but sound**: std's `BTreeMap` documents that a key whose ordering changes while it sits in the map leads to unspecified behaviour (panics, incorrect results, aborts, memory leaks or non-termination), but never undefined behaviour. - A function can be **right on every input you tried and still unsound**: one reachable input is enough. ## An unsound function that compiles The stack vector below keeps up to `N` values in `[MaybeUninit<T>; N]` and records how many are initialised in `len`. Its `get` checks `i` against the array, not against `len`: ```rust pub fn get(&self, i: usize) -> Option<&T> { let slot = self.buf.get(i)?; // checks i < N, not i < len // SAFETY: wrong - slots at or above len are uninitialised Some(unsafe { slot.assume_init_ref() }) } ``` rustc 1.99.1 accepts it without a warning: calling the unsafe `assume_init_ref` inside an `unsafe` block satisfies the compiler, which has no idea which slots hold values. A test that pushes one value and reads index 0 passes. A safe call `v.get(2)` on that vector hands out a reference to uninitialised memory; a native run printed a garbage number, and Miri stopped with "Undefined Behavior: reading memory ... but memory is uninitialized". Because a safe caller reached UB, the bug belongs to `get`, never to the caller. ## Where the burden of proof sits Trust between safe and unsafe Rust is **asymmetric**, and interviewers usually want all of it: - **Safe callers trust the safe API completely.** They do not read your SAFETY comments; the signature is the contract. - **Unsafe code may trust safe code it chose**, such as std's slices and integers or a concrete dependency the crate decided to depend on. - **Unsafe code must not trust generic safe code supplied by callers**: a caller's `Ord`, `Hash`, `Clone`, closure or iterator may be wrong or may panic, and the unsafe code has to stay memory-safe anyway. - **Unsafe traits shift the burden**: when an implementation needs `unsafe impl` (as `Send`, `Sync` and `GlobalAlloc` do), the implementer carries the proof, not the code that relies on it. ## Repairing an unsound wrapper When review finds a safe function that can reach UB, the honest fixes are few: 1. **Check the precondition at run time** and return `None`, return an `Err` or panic; here, `if i >= self.len { return None; }` before touching the slot. 2. **Make the precondition impossible to violate** through the type: private fields, constructors that establish the invariant, newtypes that carry a proof. 3. **Move the obligation to the caller** by declaring `pub unsafe fn get_unchecked(&self, i: usize) -> &T` with a `# Safety` section; Clippy's `missing_safety_doc` lint warns on a `pub unsafe fn` without one. A panic is not a soundness bug. Indexing a `Vec` out of range panics, and that is defined, safe behaviour; choosing between a panic and an `Option` is an API decision, not a safety one. A related Clippy lint, `not_unsafe_ptr_arg_deref`, sits in the deny-by-default correctness group: a public safe function that dereferences a raw-pointer argument is unsound by construction, since any caller can pass a dangling pointer. ## Telling the two apart in review | Question | Soundness bug | Correctness bug | |---|---|---| | Who can trigger it? | Some safe caller, with some input | Callers who reach the faulty logic | | What happens? | Undefined behaviour: anything, including silent corruption | A wrong value, a panic or a hang | | Do passing tests prove absence? | No; they cover only the inputs they tried | They reduce it | | Typical fix | Check, restrict the type, or make the fn `unsafe` | Fix the logic | The working method: when reading a safe function that contains `unsafe`, write down every assumption the block makes, then ask whether some input or call order from safe code can falsify each one. If one can, the function is unsound however rarely that input occurs in practice.

  • Is a safe Rust function unsound if some input makes it panic?
    No. A panic is defined behaviour: the stack unwinds or the process aborts, and no memory is misused. Indexing a `Vec` out of range panics and is perfectly sound. Soundness forbids undefined behaviour only; whether to panic, return `None` or return an `Err` is an API and correctness decision. A panic does matter for soundness in one place: unsafe code must leave its invariants intact if a panic unwinds through it.
  • May the unsafe code inside a generic safe function trust the caller's `Ord` or closure to behave?
    No. Generic safe code chosen by the caller can be wrong or can panic, and writing it is safe, so the unsafe code must stay memory-safe whatever it does. `BTreeMap` relies on `Ord` for ordering, not for memory safety. Unsafe code may trust specific code it chose, such as std or a concrete dependency. When a guarantee from caller code is genuinely needed, the tool is an unsafe trait, which moves the proof to the implementer.
  • When should a wrapper be an `unsafe fn` rather than a safe one?
    When it relies on a precondition it cannot or will not check, such as an index already validated elsewhere in a hot loop. Mark it `unsafe fn`, document the exact precondition under `# Safety`, and usually also offer a checked safe version, as `get` and `get_unchecked` do. Clippy's `missing_safety_doc` warns on a `pub unsafe fn` without that section.

  • It compiles without warnings, so the safe wrapper must be sound.
  • Sound means bug-free; a sound function always returns the right answer.
  • A safe function is unsound if any input can make it panic.
  • If every test passes under a normal run, there is no undefined behaviour.
  • Unsafe code may assume a caller's Ord or Clone implementation is correct.
open as a page

In Rust, why does making the `len` field of a `MaybeUninit`-backed stack vector `pub` break soundness when no `unsafe` code changed?

level: middleimportance: should knowfreq 40%

basics

~20 s

The unsafe code in as_slice and Drop trusts that buf[..len] is initialised. A pub len lets safe code in any module set it to any value, so safe code can cause undefined behaviour. Privacy is what keeps a safety invariant trustworthy.

open as a page

How does Rust's standard library implement the safe `<[T]>::split_at_mut`, and which checks keep its `unsafe` body sound?

level: seniorimportance: should knowfreq 45%

basics

~20 s

It checks mid <= len, panicking with "mid > len" otherwise, takes one raw pointer from as_mut_ptr, and builds from_raw_parts_mut(ptr, mid) and from_raw_parts_mut(ptr.add(mid), len - mid). The ranges cannot overlap and both borrow from the input.

open as a page

In Rust, a type owning a heap value through `NonNull<T>` needs `unsafe impl Send` — which bounds on `T` make that impl sound, and why?

level: seniorimportance: should knowfreq 38%

basics

~20 s

NonNull<T> makes the type neither Send nor Sync. For a uniquely owning type, write unsafe impl<T: Send> Send and unsafe impl<T: Sync> Sync; leaving out T: Send lets an Rc cross threads, and that is unsound.

open as a page

As the lead of a Rust codebase, what policy would you set for `unsafe` code, and how would you enforce it with rustc lints, Clippy and Miri?

level: principalimportance: should knowfreq 25%

basics

~20 s

Ban unsafe by default with the unsafe_code lint, allow it only in small named modules with private invariants, require // SAFETY: comments through Clippy's undocumented_unsafe_blocks, run Miri over those modules' tests in CI, and require an experienced second reviewer.

open as a page

In Rust, why is a stack vector's `extend_from_slice` unsound if it raises `len` before cloning each item into `MaybeUninit` slots, and how do you fix it?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

T::clone may panic. If len already counts unwritten slots, unwinding drops the vector and Drop calls assume_init_drop on uninitialised memory. Raise len only after each write, or use a guard, so every state a panic can leave is safe.

open as a page