Sub topic 2
Unsafe functions and writing safety contracts
Assume you know ownership, borrowing, lifetimes, slices, structs, traits, and Cargo. This chapter focuses on how to make unsafe code understandable and safe to call.
Unsafe functions and safety contracts
An unsafe fn is a function whose caller must guarantee conditions that the compiler cannot prove. The function should document those conditions in a # Safety section.
/// Reads one `u32` from a raw pointer.
///
/// # Safety
///
/// `ptr` must be non-null, aligned for `u32`, and point to an
/// initialized `u32` that is valid to read.
unsafe fn read_u32(ptr: *const u32) -> u32 {
unsafe { ptr.read() }
}
fn main() {
let value = 7u32;
// SAFETY: `&value` is aligned, initialized, and valid to read.
let result = unsafe { read_u32(&value) };
println!("{result}");
}An unsafe block does not turn off ownership, borrowing, or type checking. It permits operations whose correctness depends on facts outside the compiler's analysis. The caller owns the responsibility for the documented contract.
Validity, alignment, and aliasing
A pointer must point to a valid value of its type. It must also have the required alignment. For example, a *const u32 must point to an address suitable for a u32.
Aliasing means having multiple ways to access the same memory. Rust allows many shared references or one exclusive mutable reference, but not both at the same time. Violating these rules can cause undefined behavior, even if the program appears to work.
flowchart TD
A[Unsafe function] --> B[Document preconditions]
B --> C[Caller proves preconditions]
C --> D[Unsafe operation]
D --> E[Safe result]Wrapping unsafe code in a safe API
A safe abstraction checks its preconditions before entering an unsafe block. For example, this function safely returns the first byte because it checks that the slice is non-empty.
fn first_byte(bytes: &[u8]) -> u8 {
assert!(!bytes.is_empty());
// SAFETY: the slice is non-empty, so its pointer is valid to read.
unsafe { *bytes.as_ptr() }
}
fn main() {
println!("{}", first_byte(b"Rust"));
}Keep the unsafe portion small. Put the proof beside the operation in a SAFETY comment.
Mutable statics are risky
A static mut can be accessed from many parts of a program, including different threads. Unsynchronized access can create a data race. Prefer an atomic type or a synchronization primitive such as Mutex.
Exercise
What must an unsafe function's caller prove?
Show answer
The caller must prove every condition listed in the function's safety contract, including validity, alignment, initialization, and non-aliasing where applicable.