Wrapping code in unsafe leaves the borrow checker and the type checker in place. Two mutable borrows of the same value inside the block give E0499, just as they do outside it. What unsafe adds is a few operations the compiler cannot prove safe, such as dereferencing a raw pointer, and the person writing the code has to supply the reason each one is safe. In backend code that builds its own data structures for performance, or pulls in crates that do, you need to know where that boundary sits to read those crates. So I wanted to pin down what unsafe allows and what the author answers for inside it.
Every example below was compiled directly with rustc 1.94.1, edition 2021, and run on aarch64-apple-darwin (Apple M4 Pro, macOS 15.1). Miri needs a nightly toolchain and this machine only has stable, so I did not run it; that section quotes the official documentation.
Raw pointers
Raw pointers come as *const T and *mut T. The Rust Book lists how they differ from references: they may ignore the borrowing rules, are not guaranteed to point to valid memory, may be null, and do no automatic cleanup. Creating a raw pointer is fine in safe code. Only dereferencing it needs an unsafe block.
fn main() {
let mut count = 10;
let ptr = &mut count as *mut i32;
let nothing: *const i32 = std::ptr::null();
let anywhere = 0x1234usize as *const i32;
println!("nothing.is_null() = {}", nothing.is_null());
println!("anywhere = {anywhere:?}");
unsafe {
*ptr += 1;
println!("*ptr = {}", *ptr);
}
println!("count = {count}");
}
nothing.is_null() = true
anywhere = 0x1234
*ptr = 11
count = 11
A null pointer and a pointer made from an arbitrary number can both be created and printed. The program treats the address as a value and never reads from it. Dereference outside unsafe, and the compiler refuses.
fn main() {
let count = 10;
let shared = &count as *const i32;
println!("{}", *shared);
}
error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block
--> raw_err.rs:4:20
|
4 | println!("{}", *shared);
| ^^^^^^^ dereference of raw pointer
|
= note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior
The note lists what can go wrong. The address may be null, already freed (dangling), or misaligned, and the access may break aliasing rules or race with another thread. The compiler cannot check any of this for a raw pointer, so it confines dereferencing to unsafe and hands the check to the author.
Five things unsafe allows
The Rust Book names five things you can do in unsafe Rust but not in safe Rust: dereference a raw pointer, call an unsafe function or method, access or modify a mutable static, implement an unsafe trait, and access fields of a union. The Rust Reference’s list adds items such as declaring an extern block, applying unsafe attributes, and calling target_feature functions. This post sticks to the Book’s five. Dereferencing a raw pointer came up in the previous section, so the program below covers the other four.
static mut REQUESTS: u64 = 0;
/// # Safety
/// `index` must be less than `ids.len()`.
unsafe fn id_at(ids: &[u64], index: usize) -> u64 {
// SAFETY: the caller guarantees index < ids.len().
unsafe { *ids.get_unchecked(index) }
}
#[repr(C)]
union Bits {
float: f32,
int: u32,
}
/// # Safety
/// A value whose bytes are all zero must be a valid value of the type.
unsafe trait Zeroable {}
// SAFETY: eight zero bytes are the u64 value 0.
unsafe impl Zeroable for u64 {}
fn zeroed<T: Zeroable>() -> T {
// SAFETY: T: Zeroable promises that all-zero bytes are valid.
unsafe { std::mem::zeroed() }
}
fn main() {
let ids = [7, 8, 9];
let first = unsafe { id_at(&ids, 0) };
unsafe {
REQUESTS += 1;
}
let requests = unsafe { REQUESTS };
let bits = Bits { float: 1.0 };
let raw = unsafe { bits.int };
let empty: u64 = zeroed();
println!("first id = {first}, requests = {requests}");
println!("1.0f32 bits = {raw:#x}, zeroed u64 = {empty}");
}
first id = 7, requests = 1
1.0f32 bits = 0x3f800000, zeroed u64 = 0
Each of the four rests on a condition the compiler cannot check.
id_atreads an element without a bounds check. Keepingindexbelow the length is up to the caller, so the function itself is anunsafe fn- A
static mutis reachable from any thread, and concurrent writes are a data race - A union’s fields share the same bytes. Only the code that wrote them knows whether those bytes are a valid value of the field being read. Writing
1.0asf32and reading it asu32gave the IEEE 754 bit pattern0x3f800000 Zeroableasks each implementor to promise that zero bytes form a valid value. Trusting that promise is what letszeroedbe a safe function. Implementing the trait for a type where zero is not a valid value, such as&u64orNonZeroU32, would break the promise
A /// # Safety doc section states what callers of an unsafe fn, or implementors of an unsafe trait, must uphold. A // SAFETY: comment states why that condition holds at this spot. The Rust Book lists # Safety among the sections doc comments commonly include, and calls it idiomatic to put a comment starting with SAFETY on unsafe functions and unsafe operations.
Everything outside those five is still checked inside unsafe. Here a raw-pointer dereference makes the unsafe block necessary, and the same block takes two mutable borrows of count.
fn main() {
let mut count = 10;
let mut hits = 0;
let hits_ptr = &mut hits as *mut i32;
let first = &mut count;
unsafe {
*hits_ptr += 1;
let second = &mut count;
*first += 1;
*second += 1;
}
}
error[E0499]: cannot borrow `count` as mutable more than once at a time
--> still_checked.rs:8:22
|
5 | let first = &mut count;
| ---------- first mutable borrow occurs here
...
8 | let second = &mut count;
| ^^^^^^^^^^ second mutable borrow occurs here
9 | *first += 1;
| ----------- first borrow later used here
It is the same E0499 from the post on references and borrowing. The Rust Book says the same thing: unsafe does not turn off the borrow checker or any other safety check, and references used in unsafe code are still checked.
Undefined behavior
Breaking the promise behind an unsafe operation is undefined behavior (UB). The Rust Reference says Rust code that exhibits UB is incorrect, and that this includes code inside unsafe blocks and unsafe functions. Its list includes data races, accessing dangling or misaligned places, breaking the pointer aliasing rules, and producing invalid values such as a bool holding 2. It adds that unsafe only means avoiding UB is on the programmer; Rust programs must still never cause it.
UB does not show up as a compile error. The code below makes two mutable references from one raw pointer. The borrow checker does not track references that come out of a raw pointer, so it compiles.
fn main() {
let mut count = 0;
let ptr = &mut count as *mut i32;
let first = unsafe { &mut *ptr };
let second = unsafe { &mut *ptr };
*first += 1;
*second += 1;
println!("count = {count}");
}
count = 2
Both the debug and --release builds printed count = 2. The code is still wrong. second is created and used while first is alive. The Reference says the exact aliasing rules are not settled yet and gives an outline; this breaks that outline’s principle that mutable references do not overlap, so I read it as UB. The compiler optimizes on the assumption that the rule holds, so the same code can behave differently under another compiler version or with different surrounding code. The expected output is not evidence that there is no UB.
Wrapping split_at_mut in a safe API
Code that uses unsafe is often exposed to callers as a safe function. The standard library’s slice::split_at_mut is one example: it splits one slice into two mutable slices that do not overlap. Written in safe code, it does not compile.
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = values.len();
assert!(mid <= len);
(&mut values[..mid], &mut values[mid..])
}
fn main() {
let mut values = [1, 2, 3, 4];
let (left, right) = split_at_mut(&mut values, 2);
left[0] = 10;
right[0] = 30;
}
error[E0499]: cannot borrow `*values` as mutable more than once at a time
--> split_err.rs:4:31
|
1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
| - let's call the lifetime of this reference `'1`
...
4 | (&mut values[..mid], &mut values[mid..])
| --------------------------^^^^^^--------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*values` is borrowed for `'1`
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices
[..mid] and [mid..] do not overlap, but the borrow checker only sees the same slice borrowed mutably twice. The Rust Book also says this function cannot be implemented in safe Rust alone. I built the two slices from a raw pointer instead.
use std::slice;
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = values.len();
let ptr = values.as_mut_ptr();
assert!(mid <= len, "mid {mid} > len {len}");
// SAFETY: mid <= len, so [0, mid) and [mid, len) lie inside values and do not overlap.
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
fn main() {
let mut values = [1, 2, 3, 4];
let (left, right) = split_at_mut(&mut values, 2);
left[0] = 10;
right[0] = 30;
println!("{values:?}");
let (_, _) = split_at_mut(&mut values, 5);
}
[10, 2, 30, 4]
thread 'main' (61634524) panicked at split.rs:6:5:
mid 5 > len 4
The Safety section of slice::from_raw_parts_mut lists conditions; the main ones are these. The pointer must be non-null, aligned, and valid for reads and writes of len elements inside a single allocation, and while the returned slice is alive the memory must not be accessed through any other pointer. ptr comes from values, so values already meets the first group. The assert! keeps the ranges in bounds, and splitting into [0, mid) and [mid, len) keeps them apart.
With mid set to 5 the assert! panics, and a panic is not UB. Delete that assert! and the function still compiles. Nothing then stops a call with mid past the length, the conditions of from_raw_parts_mut break, and safe code calling a safe function can cause UB. I did not run that version.
Invariants and who answers for them
A function signature without unsafe promises that no argument can lead to UB. The Rust Reference calls unsafe code that meets this for any safe caller sound, and unsafe code that safe code can misuse into UB unsound. In split_at_mut, the compiler checks the argument and return types, the borrow rules, and the lifetimes of the returned references. That the ranges sit inside the slice and do not overlap is outside what it checks. The assert! checks that, and the SAFETY comment records why it holds.
The scope grows when the condition unsafe relies on lives in a struct field. The Rustonomicon’s Working with Unsafe chapter uses unsafe code that trusts the capacity (cap) field of a Vec. Adding one safe method that sets that field wrongly makes the program unsound, and the chapter says such unsafe code pollutes a whole module, not one function. It concludes that, generally, the only bullet-proof way to limit the scope of unsafe code is the module boundary with privacy. With the field private, only code in the defining module (and its submodules) can change it, and that is what needs reviewing.
Implementing Send and Sync by hand
Send marks a value as safe to move to another thread, and Sync marks it as safe for several threads to hold &T at once. Both are auto traits; as the Rustonomicon puts it, a type made entirely of Send (or Sync) types is Send (Sync) too. Raw pointers have no safety guards and are neither, so a single raw-pointer field keeps the whole type on one thread. I moved RawBuf, which manages a heap buffer through a raw pointer, into a thread.
use std::thread;
struct RawBuf {
ptr: *mut u64,
len: usize,
}
impl RawBuf {
fn new(len: usize) -> Self {
let boxed = vec![0u64; len].into_boxed_slice();
let ptr = Box::into_raw(boxed) as *mut u64;
RawBuf { ptr, len }
}
fn set(&mut self, index: usize, value: u64) {
assert!(index < self.len);
// SAFETY: index < len and ptr points to an allocation of len slots.
unsafe { *self.ptr.add(index) = value }
}
fn sum(&self) -> u64 {
// SAFETY: ptr points to len initialized slots and nothing writes during &self.
unsafe { std::slice::from_raw_parts(self.ptr, self.len).iter().sum() }
}
}
impl Drop for RawBuf {
fn drop(&mut self) {
// SAFETY: ptr and len come from Box::into_raw in new, and are freed once.
unsafe { drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(self.ptr, self.len))) }
}
}
fn main() {
let mut buf = RawBuf::new(4);
buf.set(0, 5);
let handle = thread::spawn(move || {
buf.set(1, 7);
buf.sum()
});
println!("sum = {}", handle.join().unwrap());
}
error[E0277]: `*mut u64` cannot be sent between threads safely
--> send_err.rs:37:32
|
37 | let handle = thread::spawn(move || {
| ------------- ^------
| | |
| __________________|_____________within this `{closure@send_err.rs:37:32: 37:39}`
| | |
| | required by a bound introduced by this call
38 | | buf.set(1, 7);
39 | | buf.sum()
40 | | });
| |_____^ `*mut u64` cannot be sent between threads safely
|
= help: within `{closure@send_err.rs:37:32: 37:39}`, the trait `Send` is not implemented for `*mut u64`
note: required because it appears within the type `RawBuf`
--> send_err.rs:3:8
|
3 | struct RawBuf {
| ^^^^^^
note: required because it's used within this closure
--> send_err.rs:37:32
|
37 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> …/library/std/src/thread/functions.rs:128:8
|
125 | pub fn spawn<F, T>(f: F) -> JoinHandle<T>
| ----- required by a bound in this function
...
128 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
The standard library path is shortened. The notes trace the chain from *mut u64 through RawBuf and the closure to the Send bound on spawn. But RawBuf owns its buffer alone and never hands the pointer out. That is the same situation as holding a Box<[u64]>, which is Send. I wrote that judgment down as an unsafe impl.
// SAFETY: RawBuf owns its buffer alone and never hands the pointer out.
unsafe impl Send for RawBuf {}
sum = 12
Only these two lines were added; the rest is unchanged. The compiler does not verify the judgment. A struct holding an Rc<i32>, whose count is shared without synchronization, also compiles and runs with the same unsafe impl Send.
use std::rc::Rc;
struct Shared {
count: Rc<i32>,
}
unsafe impl Send for Shared {}
fn main() {
let shared = Shared { count: Rc::new(1) };
let handle = std::thread::spawn(move || {
let shared = shared;
*shared.count
});
println!("{}", handle.join().unwrap());
}
1
That judgment is wrong. Clone the Rc and let two threads change the count, and it is a data race. The Rustonomicon explains that Send and Sync are unsafe traits, so other unsafe code may assume they are implemented correctly, and that implementing them incorrectly can cause UB. RawBuf::sum only reads through &self, so Sync looks possible too, but I did not make a promise the code does not need.
Miri
Miri is a widely used tool for finding UB the compiler misses by running the code. As noted at the top, I did not run it; what follows comes from the Miri README.
The Miri README introduces Miri as an undefined behavior detection tool that runs the binaries and test suites of cargo projects and detects unsafe code that fails to uphold its safety requirements. It is installed and run on a nightly toolchain.
rustup +nightly component add miri
cargo +nightly miri test
cargo +nightly miri run
The README’s examples of what it detects are out-of-bounds accesses and use-after-free, invalid use of uninitialized data, violated intrinsic preconditions, misaligned accesses and references, broken basic type invariants such as a bool that is not 0 or 1, and data races. Aliasing violations for references are checked with the Stacked Borrows rules, or the alternative Tree Borrows rules, and both are marked experimental. I read the first/second code from the UB section as an aliasing violation that falls under that item. I did not check what Miri actually prints for it.
The README also lists limits. Miri tests one of the many possible executions of a program, so it misses bugs that only show up in a different one. It does not catch every violation of the Rust specification, and it cannot prove that code is sound. Run the split_at_mut version without the assert! under Miri, and if no test passes a mid past the length, the problem stays hidden.
Wrapping up
E0499 still fired inside the unsafe block. unsafe does not switch off the borrow checker; it allows operations such as dereferencing a raw pointer, five in the Book’s list, and makes the author uphold what those operations assume. In split_at_mut that was the assert! and the range arithmetic, and in RawBuf it was the judgment that the type owns its buffer alone. The compiler does not check those assumptions, and Miri only sees the paths it runs. So unsafe code writes its assumptions down in SAFETY comments and keeps the code that could break them inside the same module. The next post looks at how an async Future becomes a state machine and how Pin handles values that point to themselves.
References
- Rust async and the tokio Scheduler: how
Pinkeeps self-referential state machines in place, and the tokio scheduler - Rust Memory Layout and Allocation: the pointer, length, and capacity of a
Vec, and alignment - Rust Smart Pointers:
RcandArc, andthread::spawnblocked bySendandSync - Rust References and Borrowing: the rule that mutable references cannot overlap, and E0499
- Rust Lifetimes: lifetimes of returned references
- The Rust Programming Language: Unsafe Rust
- The Rust Reference: Unsafety
- The Rust Reference: Behavior considered undefined
- The Rustonomicon: Working with Unsafe
- The Rustonomicon: Send and Sync
std::slice::from_raw_parts_mut- Miri