Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

Version History: Unsafe Rust Features

Reference for rust-unsafe-block-auditor · 67 lines

Programming / Rustv1.0.0Updated OCT 21 20266 references8 scripts

Unsafe-related stabilisations by Rust version and the edition 2024 changes, so a safe alternative or a fix matches the project's MSRV (rust-version in Cargo.toml).

Contents

Stabilisations

RustFeatureReplaces
1.25std::ptr::NonNull<T>*mut T with manual null checks
1.36MaybeUninit<T>mem::uninitialized (deprecated in 1.39)
1.51ptr::addr_of! / addr_of_mut!&x as *const _ (creates a reference first)
1.52unsafe_op_in_unsafe_fn lintimplicit unsafe bodies
1.59inline assembly asm! / global_asm!llvm_asm! (nightly)
1.71extern "C-unwind" and the other -unwind ABIsUB when a panic crossed extern "C"
1.76ptr::from_ref, ptr::from_mutx as *const T casts
1.79unchecked integer arithmetic (unchecked_add, ...)checked_add(..).unwrap_unchecked()
1.81panics unwinding out of extern "C" functions abort the processUB
1.82&raw const / &raw mut; unsafe extern blocks with safe items; unsafe attributes #[unsafe(no_mangle)]addr_of!; plain extern blocks; #[no_mangle]
1.84strict provenance APIs: addr, with_addr, map_addr, ptr::without_provenance, expose_provenance, with_exposed_provenanceas usize / as *const T round trips
1.85edition 2024 (see below)
1.88naked functions: #[unsafe(naked)] with naked_asm!nightly only

&raw const/&raw mut and addr_of! produce raw pointers without creating an intermediate reference, which matters for packed fields, uninitialised memory and static mut.

Edition 2024 unsafe changes

ChangeLint (migration)Script rule
unsafe_op_in_unsafe_fn warns by default: unsafe operations inside an unsafe fn need their own unsafe {} blockunsafe_op_in_unsafe_fnUS027
References to static mut are denied (&X, &mut X, method calls)static_mut_refsUS009
extern blocks must be written unsafe extern; items inside may be marked safemissing_unsafe_on_externUS019
#[no_mangle], #[export_name], #[link_section] must be written #[unsafe(..)]unsafe_attr_outside_unsafeUS020
std::env::set_var, remove_var and std::os::unix::process::CommandExt::before_exec are unsafe fndeprecated_safe_2024US021

The new syntax (unsafe extern, #[unsafe(..)], &raw) works on Rust 1.82+ in every edition, so you can adopt it before switching editions.

Migrating a crate to edition 2024

  1. Update the toolchain to 1.85+ and run cargo fix --edition on edition 2021: it rewrites extern blocks and attributes and wraps unsafe operations inside unsafe fns.
  2. Review every generated unsafe {} block inside unsafe fns: give each its own // SAFETY: comment (it now discharges part of the fn's # Safety contract).
  3. Replace static mut with atomics, Mutex, OnceLock/LazyLock or thread_local! (see the undefined-behaviour catalog); where it must stay, use &raw mut X.
  4. Audit env::set_var calls: move them before any thread starts, or pass configuration explicitly.
  5. Set edition = "2024" and run the scanners: US019-US021 and US009 should now be empty.

Before-and-after for older MSRVs

Need1.82+Older
Raw pointer to a field without a reference&raw const s.fieldptr::addr_of!(s.field) (1.51)
Raw pointer to a static mut&raw mut COUNTERptr::addr_of_mut!(COUNTER) (1.51)
Change pointer address, keep provenance`p.map_addr(a
Pointer from an MMIO addressptr::with_exposed_provenance::<u32>(0x4000_0000) (1.84)0x4000_0000 as *const u32
Unwind across FFI on purposeextern "C-unwind" (1.71)not possible soundly
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-tokio-async-service-builder

Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.

rust-trait-design-reviewer

Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.