skip to content

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%

answer

  1. forbid by default, exceptions visible
  2. small modules with private invariants
  3. SAFETY comments, enforced by Clippy
  4. Miri and a second reviewer

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.

solid answer

~40 s

I would make safe Rust the default and every exception visible. Crates that never need `unsafe` get `#![forbid(unsafe_code)]`; crates that do get `deny` plus `#[allow(unsafe_code)]` on one small module, because `forbid` cannot be lowered: rustc rejects the inner allow with E0453. Inside those modules, invariants live in private fields and are documented once; every block carries a `// SAFETY:` comment, enforced with Clippy's `undocumented_unsafe_blocks`, which is in the restriction group and therefore off until enabled, alongside `missing_safety_doc` and `multiple_unsafe_ops_per_block`. CI runs the modules' tests under Miri. Changes need a reviewer who knows unsafe code well. The trade-off is speed versus audit cost, so I would ask for a benchmark or an FFI need before any new module appears.

code

rust · 14 lines
rust
#![forbid(unsafe_code)]

#[allow(unsafe_code)]
mod raw {
    pub fn first(v: &[u8]) -> u8 {
        assert!(!v.is_empty());
        // SAFETY: v is non-empty, checked above.
        unsafe { *v.get_unchecked(0) }
    }
}

fn main() {
    println!("{}", raw::first(&[1, 2]));
}

go deeper

for a junior

Recall that unsafe_code is a rustc lint you can deny or forbid, and that teams expect a SAFETY comment above every unsafe block.

for a middle

Explain forbid versus deny, why forbid rejects an inner allow with E0453, and which Clippy lints enforce SAFETY comments and Safety docs.

for a senior

Describe how unsafe modules are tested: edge-case tests, a panicking Clone or Ord, and Miri in CI, with Miri's limits on untested paths and foreign code.

for a principal

Own the trade-off: where exceptions may live, who reviews them, what evidence a new unsafe module needs, and how to keep the policy strict without driving people to unreviewed workarounds.

## The decision a lead owns Every Rust team eventually has to decide **where unsafe code may live and who may change it**. There is no single right answer: a crate of business logic should never need `unsafe`, a parser or allocator may need a little for speed, and a crate that wraps a C library needs it at every boundary. The policy's job is to keep the safe-by-default property true, make each exception visible, and spend review effort where unsoundness can actually happen. | Option | What it buys | What it costs | |---|---|---| | `#![forbid(unsafe_code)]` on the crate | A compiler guarantee that the crate has no unsafe code | No exceptions at all; FFI and hand-tuned code must move to another crate | | `deny(unsafe_code)` plus `#[allow(unsafe_code)]` on named modules | Exceptions you can grep for, each in a module you can audit | Discipline to keep those modules small | | No restriction, review only | Fastest to write | Unsafe code spreads, and audit scope becomes the whole crate | ## Mechanical enforcement rustc and Clippy cover most of the policy without any custom tooling. Every lint below was checked against the 1.99.1 lint lists: - **`unsafe_code`** (rustc, allow by default) flags `unsafe` blocks and other unsafe constructs. At `forbid`, an inner `#[allow(unsafe_code)]` fails with "error[E0453]: allow(unsafe_code) incompatible with previous forbid"; at `deny`, a module-level `allow` works, which is how exceptions are made explicit. - **`unsafe_op_in_unsafe_fn`** requires an `unsafe` block even inside an `unsafe fn`; the 2024 edition makes it warn, and a policy can raise it to `deny`. - **`clippy::undocumented_unsafe_blocks`** (restriction group, allow by default) reports "unsafe block missing a safety comment"; it has to be enabled explicitly. - **`clippy::multiple_unsafe_ops_per_block`** (restriction) keeps each block to one operation, so each SAFETY comment justifies one thing. - **`clippy::missing_safety_doc`** (style, warn by default) catches a `pub unsafe fn` without a `# Safety` section. - **`clippy::not_unsafe_ptr_arg_deref`** (correctness, deny by default) catches a public safe function that dereferences a raw-pointer argument. The levels can live in each crate's root attributes or in the manifest's `[lints]` table, which is covered with Cargo's lint configuration. ## Testing what review cannot see Review checks the argument; tests check behaviour. For unsafe modules: 1. Write tests that hit edge cases deliberately: full and empty containers, zero-sized types, a `Clone` or `Ord` that panics on the n-th call. 2. Run those tests under **Miri** in CI with `cargo +nightly miri test`. Miri interprets the program and reports undefined behaviour such as reading uninitialised memory or aliasing violations, but only on the paths the tests execute, and it cannot run foreign C code (the material on undefined behaviour covers its limits). 3. Keep the safe API's tests separate from the unsafe module's, so a refactor of the internals stays covered. ## Review and ownership - Each unsafe module documents its **invariants** next to the struct; each `// SAFETY:` comment names the invariant or the precondition it relies on. - Changes to those modules need a reviewer who has written sound unsafe code before; a code-ownership rule in the repository makes this automatic. - Before adding a new unsafe module, ask whether std or a well-reviewed crate already provides the abstraction, since the best unsafe code is the code someone else has already audited. - Remember the scope: `forbid(unsafe_code)` covers only the crate it is in. std and every dependency still contain unsafe code, so dependency review is a separate policy. ## Trade-offs to state out loud - `forbid` gives the strongest guarantee but pushes every exception into a separate crate, which can be the right shape for FFI bindings anyway. - SAFETY comments cost little and are only as good as the reviewer reading them; a comment is an argument, not a proof. - Miri slows CI down and runs only on nightly, so many teams run it on the unsafe modules' tests rather than the whole workspace. - A policy needs an owner and an exception process: who approves a new `allow`, and when the list of unsafe modules is re-audited, for example at each toolchain upgrade. - Being too strict drives people to unreviewed workarounds such as vendoring code; being too loose turns soundness into an audit of everything.

  • Should the crate root use `forbid(unsafe_code)` or `deny(unsafe_code)`?
    `forbid` when the crate should never contain unsafe code: no inner attribute can lower it, so rustc rejects `#[allow(unsafe_code)]` with E0453. `deny` when a crate needs a few exceptions: one module carries `#[allow(unsafe_code)]`, which is easy to find in review and in a search. Many teams forbid in application crates and deny in the one or two crates that hold low-level code.
  • What does a green Miri run in CI not tell you?
    That the code is free of undefined behaviour in general. Miri checks only the executions the tests perform, cannot interpret calls into foreign C code, and models aliasing with rules that are still experimental. It is strong evidence for the paths tested, so pair it with edge-case tests and review of the safety argument.
  • Does `#![forbid(unsafe_code)]` on every crate mean the binary runs no unsafe code?
    No. The lint covers only the crate it is applied to. std uses unsafe internally, and so do many dependencies. The policy reduces what your team must audit; trusting dependencies is a separate decision, made through dependency review and advisory scanning.

  • forbid(unsafe_code) at the root plus allow on one module gives a clean exception.
  • A SAFETY comment on every block proves the crate is sound.
  • Miri passing in CI means the unsafe code has no undefined behaviour.
  • Forbidding unsafe in our crates means the binary runs no unsafe code.
  • Clippy's undocumented_unsafe_blocks lint is on by default.