esp-hal icon indicating copy to clipboard operation
esp-hal copied to clipboard

#[ram(uninitialized)] statics are unsound

Open icewind1991 opened this issue 1 year ago • 6 comments

#[entry]
fn main() -> ! {
    ...
    print(&BOOL);
    ...
}

// usage of the static is done trough a function call to stop rustc from just inlining the constant
// release mode will inline things enough that it just prints the constant
// more complex code might still fail in release mode
fn print(val: &bool) {
    println!("{:?}", *val as u32);
}

#[ram(rtc_fast, uninitialized)]
static BOOL: bool = false;

will output a number that isn't a 0 or 1 which means that any use of the boolean is undefined behavior.

While in practice this is probably fine since the main use case for #[ram(uninitialized)] is through static mut where access is unsafe anyway this can still lead to unexpected issues when checking the static before writing it or when dealing with atomics.

Imo the best approach would be to have the macro require that the type of the statics are "plain old data" to ensure that all bit patterns are valid for the type.

icewind1991 avatar Jan 23 '24 22:01 icewind1991