Impact of Static Variables on API Soundness
Rust Internals [Unofficial]
February 26, 2026
I have a question regarding the policy for declaring API safety when it depends on the value of static variables. In the example below, the module FooSys contains a static variable PTR with internal mutability and two public APIs. Can the API do_critical_task be declared safe?
The function do_critical_task requires that PTR is either null or points to CONFIG. In the current module, this is guaranteed because PTR can only have these two states. However, future modifications to the module could introduce additional states or allow PTR to be changed, which could break this guarantee.
My specific questions are as follows:
- In the current implementation, I believe
do_critical_taskcan be declared safe. Is this correct? - If
PTRremains private, but additional invalid states become possible, thendo_critical_taskcannot be declared safe, correct? - If
PTRis made public (but not to other crates), meaning that additional invalid states could be introduced from outside the module, cando_critical_taskstill be declared safe?
mod FooSys {
use std::{ptr, sync::atomic::{AtomicPtr, Ordering}};
/// Static atomic pointer pointing to system configuration
static PTR: AtomicPtr<u32> = AtomicPtr::new(ptr::null_mut());
/// Initialize the system and set PTR to point to a valid static resource
pub fn initialize_system() {
static CONFIG: u32 = 42;
PTR.store(&CONFIG as *const u32 as *mut u32, Ordering::SeqCst);
}
pub fn do_critical_task() {
let ptr = PTR.load(Ordering::SeqCst);
if !ptr.is_null() {
unsafe { read_config(ptr); }
}
}
// Safety: `ptr` must point to a valid configuration.
unsafe fn read_config(ptr: *mut u32) {
...
}
}
Discussion in the ATmosphere