Skip to content

Unsafe: soundness, unsafe_op_in_unsafe_fn, and Miri

Targets rust-1.99 edition-2024Last reviewed 2026-11-12Sources anssi-rust corrode matklad ralf-jung rust-blog rust-docs tweede-golf

Unresolved research. This topic is evidence that research-topic gathered, waiting on resolve-research. It isn't an opinion, and it can cite unvetted material. Follow the opinions instead.

Write no unsafe unless a crate needs it for FFI, hardware access, or a measured hot path. When it does, put the unsafe inside one module whose safe API no safe caller can misuse, and test that module under Miri:

  • Forbid unsafe_code in every crate that has no unsafe, with #![forbid(unsafe_code)] in its root, and justify each use in a crate that needs it. A manifest forbid can't be relaxed for a module, and a crate that inherits [lints] can't override one key, so the workspace setting is still open: see deny in the manifest.
  • Treat the module as the soundness boundary. Keep each invariant in a private field, and make the safe API sound for every safe caller, including a misbehaving Ord, Clone, or Drop implementation.
  • Explain every unsafe. Write a // SAFETY: comment on each block and unsafe impl, and a # Safety section on each public unsafe fn and unsafe trait. clippy::missing_safety_doc warns by default for a missing section.
  • Keep an unsafe fn body safe by default. Edition 2024 makes unsafe_op_in_unsafe_fn warn, so every unsafe operation inside an unsafe fn has to sit in an explicit unsafe {} block, with a // SAFETY: comment on the block. One block can hold several operations.
  • Prefer the 1.82 to 1.93 raw-pointer APIs: &raw const and &raw mut over &x as *const _, .cast() over pointer as, and the strict provenance methods over integer round trips.
  • Run cargo miri test in CI on a nightly toolchain. A pass means the tests hit no undefined behaviour, not that the code is sound.

Everything recommended here is stable in 1.99.1 (released 2026-10-15) except two tools: Miri, which ships only as a nightly component, and cargo-careful, which needs a nightly toolchain too. They're tools, not language features, and the code they test stays on stable. Coming next lists what's unstable as of 2026-10-19.

Six claims here are unsupported, and each is marked where it appears: the new-abstraction case, keeping the default aliasing model, the 0..16 seed range, turning on the three Clippy safety lints, leaving out multiple_unsafe_ops_per_block, and workspace deny over workspace forbid. They're choices or judgements that rest on the editor's reading or on a reference alone, so resolve-research can't promote them as they stand. The opening list leaves them out.

No opinion file covers this. opinions/rust.md mentions unsafe only in its edition 2024 migration table, for static_mut_refs, unsafe attributes, and set_var. This is the unsafe.md topic in PLAN.md: Phase 6.

What unsafe promises

The Reference defines the keyword in two directions. unsafe fn, unsafe trait, and unsafe static create an obligation that callers or implementers must meet. unsafe {}, unsafe impl, unsafe extern, and #[unsafe(attr)] assert that an obligation defined elsewhere is met (The Rust Reference: The unsafe keyword). An unsafe block states "that all relevant proof obligations of functions or operations called inside the block have been discharged".

unsafe doesn't permit undefined behaviour. Code that "can be misused by safe code to exhibit undefined behavior" is unsound, and the list of undefined behaviour "is not exhaustive": there's "no formal model of Rust's semantics" (The Rust Reference: Behavior considered undefined). The page asks readers to read the Rustonomicon before writing unsafe. On aliasing it gives only an outline, "The exact aliasing rules are not determined yet", and adopts neither Stacked Borrows nor Tree Borrows.

ralf-jung splits a type's invariants in two (Ralf Jung: Two Kinds of Invariants: Safety and Validity, 2018-08-22):

  • The validity invariant is what the compiler assumes for optimisation, such as a bool being 0 or 1. "Unsafe code must always uphold validity invariants."
  • The safety invariant is what safe code may assume, such as Vec's first len elements being initialised. "Unsafe code only has to uphold safety invariants at the boundaries to safe code."

That split is why a &mut T to a half-built value can be fine inside a module and unsound once it escapes.

Encapsulation: the module is the boundary

The Rustonomicon's Working with Unsafe shows that an unsafe block's soundness can depend on state that safe code in the same module can change: setting Vec's len in safe code breaks the unsafe code that reads it. Its conclusion is that unsafe "pollutes a whole module", and that privacy at the module boundary contains it. matklad reaches the same conclusion from code review: reasoning about one block is local, but "correctness of two unsafe blocks in isolation does not guarantee that they together are correct!", and "the boundary for unsafe code is a module" (Alex Kladov: Unsafe as a Human-Assisted Type System, 2019-07-25).

Unsafe code also can't trust safe code it doesn't control. BTreeMap must stay sound when an Ord implementation misbehaves, because a safe trait implementation can't be relied on for memory safety (The Rustonomicon: How Safe and Unsafe Interact). The same applies to Clone, Drop, Deref, and any closure the module calls.

anssi-rust makes encapsulation a rule. LANG-UNSAFE-ENCP requires that a component either expose only safe behaviour, "in which no safe interaction can result in UB", or mark its unsafe features with "exhaustively documented" usage conditions (ANSSI: General information on unsafe, changed 2026-03-25). Its note in AWESOME-HUMANS.md asks for a rust-docs cross-check before an opinion rests on a rule. The Reference's soundness rule and the Rustonomicon make the same point.

The editor's example, a fragment of a library crate:

//! A non-empty vector whose invariant lives in one module.

pub use non_empty::NonEmpty;

#[expect(unsafe_code, reason = "`first` skips a bounds check that the invariant makes redundant")]
mod non_empty {
    /// A vector with at least one element.
    pub struct NonEmpty<T> {
        // Invariant: `items` is never empty. Only this module can touch the field.
        items: Vec<T>,
    }

    impl<T> NonEmpty<T> {
        /// Creates a vector holding `first`.
        pub fn new(first: T) -> Self {
            Self { items: vec![first] }
        }

        /// Appends an element.
        pub fn push(&mut self, item: T) {
            self.items.push(item);
        }

        /// Returns the first element, without an `Option`.
        #[must_use]
        pub fn first(&self) -> &T {
            // SAFETY: `items` is never empty, so index 0 is in bounds.
            unsafe { self.items.get_unchecked(0) }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::NonEmpty;

    #[test]
    fn first_survives_push() {
        let mut v = NonEmpty::new(String::from("a"));
        v.push(String::from("b"));
        assert_eq!(v.first(), "a");
    }
}

Compiled as src/lib.rs of a library crate with unsafe_code = "deny", clippy::pedantic, and the three Clippy lints below: it passes CARGO_BUILD_WARNINGS=deny cargo check --all-targets and CARGO_BUILD_WARNINGS=deny cargo clippy --all-targets on 1.99.1, and cargo +nightly miri test runs the test and passes (nightly 2026-10-18, miri 0.1.0), all on 2026-11-14. It uses only std. The test gives Miri an execution to check: without one, cargo miri test passes having checked nothing.

The proposal sets unsafe_code = "deny" in [lints.rust]. The example compiles without it, but under deny, removing the expect is an error (editor's probe on 1.99.1, 2026-11-12). A pub field, or a pub fn that removes elements, would make first unsound without changing the unsafe line.

When to write unsafe at all

anssi-rust LANG-UNSAFE says unsafe blocks "SHOULD be avoided, or MUST be justified" by FFI, hardware access at fixed addresses, or "a performance wall on a small portion of code". Otherwise #![forbid(unsafe_code)] "must appear in the crate root". The Book says to "keep unsafe blocks small" and to wrap them in a safe abstraction (The Rust Programming Language: Unsafe Rust).

Unsupported: a new abstraction as a fourth case. The opening rule leaves it out, because LANG-UNSAFE lists only the three cases above. Only watch-list ms-rust-guidelines M-UNSAFE allows unsafe for "novel abstractions", and a watch-list source can't be cited in an opinion.

Use deny in the manifest, and forbid in the root of a crate with no unsafe. LANG-UNSAFE exempts a crate whose unsafe is justified, and requires the attribute in every other crate root. The manifest can't use forbid, as the editor's probe on 1.99.1 (2026-10-19) found:

  • unsafe_code = "forbid" in a manifest turns a module's #[expect(unsafe_code, …)] into error E0453. With deny, the expect compiles cleanly, and it warns if the module stops needing unsafe.
  • A crate with [lints] workspace = true can't add a [lints.rust] key of its own: Cargo refuses to load the manifest.

So a workspace forbid would force a crate that needs one unsafe module to drop the workspace lints entirely. Workspace deny, plus expect on one module, gives that crate the audit trail ANSSI asks for: the reason string records the justification. Every other crate adds #![forbid(unsafe_code)] to its root, which compiles beside the inherited deny (editor's probe on 1.99.1, 2026-11-12).

Unsupported: workspace deny over workspace forbid. What Cargo and rustc accept is from the probes. Choosing deny for the workspace is the editor's judgement, and no roster source weighs the two. security.md proposes the opposite, a workspace forbid and a crate that needs unsafe dropping workspace = true, so resolve-research settles one design for both opinions.

Documenting unsafe

The Book calls it idiomatic to write a comment "starting with SAFETY" on every unsafe function, saying what the caller must do, and on every unsafe operation, saying how the rules are upheld. Clippy enforces each half. The lint groups are from --explain and a probe on 1.99.1 (2026-10-19):

Lint Group Default Requires
missing_safety_doc style warn A # Safety section on every public unsafe fn and unsafe trait
undocumented_unsafe_blocks restriction allow A // SAFETY: comment on every unsafe block and unsafe impl
unnecessary_safety_comment restriction allow No // SAFETY: comment on safe code, so comments don't outlive the unsafe they explained
unnecessary_safety_doc restriction allow No # Safety section on a safe public function
multiple_unsafe_ops_per_block restriction allow One unsafe operation per block. The probe counted (*p, *p.add(1)) as three, so it's noisy
borrow_as_ptr pedantic allow &raw const x and &raw mut x, not &x as *const _
ptr_as_ptr pedantic allow .cast::<U>(), not as *const U

unsafe_op_in_unsafe_fn is a rustc lint, not a Clippy one. The Edition Guide says it "now warns by default" on edition 2024, because an unsafe fn keyword that also unlocked its whole body was "too risky without explicit unsafe blocks" (Rust Edition Guide: unsafe_op_in_unsafe_fn warning). Under CI's -D warnings it's an error, so an edition 2024 crate needs no configuration for it.

Unsupported: turning on undocumented_unsafe_blocks, unnecessary_safety_comment, and unnecessary_safety_doc. The Book supports the comments, and what each lint reports is a reference fact. Turning on an optional lint is a choice, and only watch-list ms-rust-guidelines makes it, so the opening list leaves it out.

Leave out multiple_unsafe_ops_per_block. The Book's "keep unsafe blocks small" is the goal. The lint turns it into one block per dereference and pointer offset, so a two-field read needs three blocks and three comments. Unsupported: this is the editor's judgement from the probe, and no roster source comments on the lint.

Raw pointers, provenance, and uninitialized memory

Each row is a stable replacement for an older idiom, from the release notes on rust-blog and rust-docs, and the std documentation:

Use Release Instead of
&raw const x and &raw mut x 1.82 addr_of!, or &x as *const _, which creates a reference first
unsafe extern "C" { … }, with safe fn items 1.82 A bare extern block, now an error on edition 2024
#[unsafe(no_mangle)] and #[unsafe(export_name)] 1.82 The unmarked attributes, now an error on edition 2024
ptr.with_addr, map_addr, and addr 1.84 ptr as usize and back, which loses provenance
ptr::without_provenance and ptr::dangling 1.84 addr as *const T for a sentinel or a dangling pointer
[MaybeUninit<T>]::assume_init_ref and write_copy_of_slice 1.93 Casting a &[MaybeUninit<T>] to &[T] by hand

MaybeUninit itself replaced mem::uninitialized in 1.36, which predates the releases in this table. Sources: Rust Blog: Announcing Rust 1.82.0, Announcing Rust 1.84.0, and Rust Release Notes: Version 1.93.0. The std::ptr documentation calls strict provenance "a set of APIs designed to make working with provenance more explicit", "intended as substitutes for casting a pointer to an integer and back", and says "most code needs no changes to conform" (std::ptr: Strict Provenance). Code that must turn an integer into a pointer uses expose_provenance and with_exposed_provenance. Miri can't fully check the way back, an integer-to-pointer cast or with_exposed_provenance: it "will necessarily miss some bugs as those operations are not efficiently and accurately implementable in a sanitizer" (rust-lang/miri: README, a reference, read 2026-11-14).

The compiler now catches some of these mistakes itself. dangerous_implicit_autorefs (warn in 1.88, deny in 1.89) rejects an implicit reference through a raw-pointer dereference, integer_to_ptr_transmutes (warn in 1.91) flags transmute::<usize, *const T>, and static_mut_refs denies a reference to a static mut on edition 2024. 1.98 makes unsafe_code fire on every unsafe attribute. These come from the Rust Release Notes, the published page on rust-docs. opinions/rust.md's migration table already covers static_mut_refs and unsafe attributes, but not unsafe extern blocks or unsafe_op_in_unsafe_fn, so the opinion here has to.

FFI

anssi-rust has the roster's only FFI rules, in ANSSI: Foreign Function Interface. Its roster note scopes it as citable for security.md, and asks for a rust-docs cross-check before an opinion rests on a rule. This topic cross-checks only LANG-UNSAFE-ENCP, so these rules, LANG-UNSAFE's cases, and its crate-root forbid need that check, or a ruling that the scope covers unsafe.md, before resolve-research promotes them. The ones an opinion can apply mechanically:

Rule Says
FFI-SAFEWRAPPING (recommendation) Wrap the foreign library in a safe API
FFI-AUTOMATE (recommendation) Generate bindings with a tool such as bindgen or cbindgen
FFI-CTYPE and FFI-PFTYPE Use only #[repr(C)] types and the core::ffi::c_* aliases
FFI-CKNONROBUST and FFI-CK-PTR-VALID Check foreign values and pointers before using them as Rust values
FFI-NOENUM Don't accept a Rust enum from foreign code, whose discriminant could be invalid
FFI-MEM-OWNER and FFI-MEM-NODROP Make ownership explicit, and pass no Drop type across the boundary
FFI-NOPANIC (recommendation) Don't let a panic cross the boundary

Since 1.81, a panic that unwinds out of an extern "C" function aborts the process instead of being undefined behaviour (Rust Release Notes: Version 1.81.0). FFI-NOPANIC still applies, because an abort is rarely what the caller wants. tweede-golf's bzip2 port shows the gain from safe types: c2rust output is "full of unsafe", and changing a pointer argument to a slice removed every unsafe from one function (Tweede golf: Translating bzip2 with c2rust, 2025-03-11).

Testing unsafe code

Miri. "Miri is an Undefined Behavior testing tool for Rust", and it aims to "find all de-facto Undefined Behavior in deterministic Rust programs" (Ralf Jung: What's "new" in Miri, 2025-12-22, written with the POPL 2026 Miri paper). The Book recommends it and installs it with rustup +nightly component add miri. corrode recommends it for production hardening, with the same CI job (Matthias Endler: Hardening Rust Code For Production, 2026-07-23). tweede-golf found it "extremely helpful to confirm the correctness of our code" in the bzip2 port.

The Miri README is a reference for how to run it. Its CI example installs a nightly toolchain with the miri component, then runs the tests (rust-lang/miri: README):

rustup toolchain install nightly --component miri
rustup override set nightly
cargo miri setup
cargo miri test

This topic owns the Miri job, as the ci.md and testing.md topics both say. The README's example checks out the repository with actions/checkout@v4, a tag. Write the job under the workflow rules that ci.md settles instead: how to pin an action, the token's permissions, and caching.

  • Add MIRIFLAGS="-Zmiri-many-seeds=0..16" for concurrent code, to explore more thread interleavings and allocation addresses. ralf-jung says the flag makes Miri "randomly explore multiple possible executions" (2025-12-22, above). The range is unsupported: 0..16 is the README's example, the default is 0..64, and the editor chose the smaller range for speed.
  • A pass isn't a proof of soundness. Miri checks the executions the tests reach, and "there might always be more executions that Miri did not find yet" (ralf-jung, 2025-12-22, above). The README agrees: "Miri fundamentally cannot ensure that your code is sound." When it finds undefined behaviour, the code is unsound. When it doesn't, you might need more inputs.
  • Unsupported: keep the default aliasing model, Stacked Borrows. It's a choice that rests on the README alone. The README says Tree Borrows "is even more experimental", and that "it is likely that the eventual final aliasing model of Rust will be stricter than Tree Borrows", so code that passes only under -Zmiri-tree-borrows "might be declared UB in the future". The editor's probe on nightly 2026-10-18 confirmed Stacked Borrows is still the default, which is a reference fact. Choosing to stay on it isn't.
  • Mark tests Miri can't run with #[cfg_attr(miri, ignore)]. Miri can't run networking or most FFI, and it interprets slowly. The README shows the attribute, "to ignore test cases that fail under Miri because they do things Miri does not support" (read 2026-11-14). That's what the tool asks of a project that uses it, a reference fact, so it needs no roster source.

cargo-careful runs tests against a std built with debug assertions. It's "much faster than executing your program in Miri", "fully FFI-compatible", and misses much of what Miri catches (Ralf Jung: cargo careful, 2022-09-26). Use it for unsafe code that calls C and so can't run under Miri. It also needs nightly.

Sanitizers (-Zsanitizer=address) are still nightly-only: 1.99.1 rejects the flag with "the option Z is only accepted on the nightly compiler". See Coming next.

Where the roster disagrees

  • Leaking memory. anssi-rust MEM-FORGET and MEM-LEAK forbid mem::forget and Box::leak in secure code (ANSSI: Memory management). In std, both are safe functions, because Rust's safety guarantees don't include running destructors (std::mem::forget). The ANSSI rules are about resource exhaustion in security-critical software, not soundness, so they belong in security.md, not unsafe.md.

Coming next

Unstable on nightly as of 2026-10-19, not yet an opinion. Statuses are from the tracking issues, which are references, and from Rust Project Goals: 2026, which is unvetted: the goals site isn't on the roster or among its named references. Each "goal" link in the table is unvetted too.

Feature Status, 2026-10-19
Unsafe fields (RFC 3458) RFC accepted, partly implemented behind unsafe_fields, and a 2026 goal to stabilise (rust-lang/rust#132922, goal). It would let NonEmpty's invariant live on the field
A normative aliasing model Not decided. Tree Borrows was published at PLDI 2025 (Ralf Jung: The Tree Borrows paper is finally published, 2025-07-07), but neither the Reference nor Miri's default has adopted it. A 2026 goal works on normative documentation for sound unsafe Rust
MemorySanitizer and ThreadSanitizer Nightly-only, with a 2026 goal to stabilise both (goal, rust-lang/rust#123615)
BorrowSanitizer A 2026 goal for an aliasing checker faster than Miri that also covers C and C++ (goal)
Unsafe binders Experimental (rust-lang/rust#130516)
Miri on stable No plan found. Miri remains a nightly component

None is in 1.100.0, released 2026-11-12 (Rust Blog: Announcing Rust 1.100.0, read 2026-11-14). The statuses themselves weren't rechecked after 2026-10-19. Unsafe fields affects this topic most: once it's stable, the # Safety and // SAFETY: rules extend to unsafe field access, and Clippy's missing_safety_doc already supports them (rust-lang/rust-clippy#16767).

Watch-list and unvetted material

Kept apart from the roster findings above. None of it supports a claim. M-UNSAFE is the only source that allows the new-abstraction case, which is why that case is unsupported.

  • Watch-list ms-rust-guidelines: M-UNSAFE allows unsafe only for "novel abstractions", performance, or FFI, and requires "plain-text reasoning" and a Miri pass. M-UNSAFE-IMPLIES-UB says unsafe "must not be used to mark functions that are dangerous to call for other reasons". M-STATIC-VERIFICATION enables undocumented_unsafe_blocks, unnecessary_safety_comment, unnecessary_safety_doc, and unsafe_op_in_unsafe_fn (Microsoft: Pragmatic Rust Guidelines, Correctness and Universal). It agrees with every recommendation here, and picks the same three Clippy lints.
  • Watch-list effective-rust: Item 16, "Avoid writing unsafe code", says to check std and crates first, keep a wrapper layer, write safety comments, and "consider running Miri" (David Drysdale: Effective Rust). It agrees.
  • Not scanned: jon-gjengset (Rust for Rustaceans, chapter 9), mara-bos, and the unvetted candidates the plan listed: the Rust for Linux safety standard, Android's and Chromium's unsafe guidance, the Rust Foundation's study of unsafe in published crates, cargo-geiger, and Kani. The worker scan stopped on a usage limit, and the editor didn't need them: every recommendation cites a roster source, or a reference for a reference fact, except the six marked unsupported.

What this means for the repository

  • No opinion covers the topic. Run resolve-research to create opinions/unsafe.md. Its first sentence is the opening list here, which leaves out the unsupported claims. It needs sections for when to write unsafe, encapsulation and the module boundary, documentation and the lint table, raw pointers and provenance, FFI, and Miri. List it under README.md's Scope and in the layout tree.
  • templates/Cargo.toml would gain four lints, once they're supported: unsafe_code = "deny" in a new [workspace.lints.rust], and undocumented_unsafe_blocks, unnecessary_safety_comment, and unnecessary_safety_doc in [workspace.lints.clippy]. All four are unsupported choices, so they wait for a roster source, and unsafe_code = "deny" also waits for the ruling against security.md's workspace forbid. undocumented_unsafe_blocks reports nothing in a crate without unsafe. The two unnecessary_safety_* lints do: they report a // SAFETY: comment or a # Safety section on safe code in any crate (editor's probe on 1.99.1, 2026-11-14), so check the workspace under -D warnings before adding them. No template holds a crate root, so the #![forbid(unsafe_code)] rule goes in the opinion only. borrow_as_ptr and ptr_as_ptr are in clippy::pedantic, if a later topic turns the group on.
  • Miri runs on nightly. That's a tool, and the repository's freshness rule is about features the code uses, but resolve-research should confirm the opinion may recommend a nightly-only tool, for Miri and for cargo-careful. The Book, corrode, and the Miri README all recommend Miri, and ralf-jung recommends cargo-careful. This topic owns the Miri job, and ci.md sets the workflow rules the job follows.
  • ANSSI's leak rules go to security.md, with the disagreement above.
  • Six claims are unsupported: the new-abstraction case, keeping the default aliasing model, the 0..16 seed range, turning on the three Clippy safety lints, leaving out multiple_unsafe_ops_per_block, and workspace deny over workspace forbid. resolve-research needs a citable source for each, or leaves it out.
  • anssi-rust needs a scope ruling or a cross-check. The FFI table, LANG-UNSAFE, and the crate-root forbid rest on it alone, and its roster note scopes it to security.md.
  • One vet-source candidate: Rust Project Goals. Only the Coming next statuses cite it. Admit it, or name it as a reference, before an opinion's Coming next note cites it. Apart from it and the unsupported claims, every claim cites a roster source, or a reference for a reference fact: ralf-jung and rust-docs cover the semantics, anssi-rust the rules, and corrode, matklad, and tweede-golf the practice.