Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

25.5 Unsafe Attributes in Rust 2024

Certain attributes influence the symbol names and linking behavior of items. Because the set of symbols across all linked libraries is a global namespace, symbol name collisions can cause issues, typically leading to undefined behavior. While Rust’s name mangling usually ensures uniqueness, attributes like #[no_mangle], #[export_name], and #[link_section] can override this.

Starting with the Rust 2024 Edition, these attributes must now be explicitly marked as unsafe(...) to highlight that the programmer is responsible for upholding soundness requirements. For example, #[no_mangle] becomes #[unsafe(no_mangle)].

// Example from the Edition Guide:
// SAFETY: There should only be a single definition of the loop symbol.
#[unsafe(export_name="loop")]
pub fn arduino_loop() {
    // ... code that might be called from Arduino firmware or C
    println!("Arduino loop running!");
}

fn main() {
    // The `arduino_loop` function can now be called from C code,
    // where it will appear as the symbol "loop".
    // We cannot directly call `arduino_loop` from safe Rust here due to
    // `export_name` making it not accessible via its Rust name.
    // This example is illustrative of the safety requirement.
    arduino_loop();
    // Call the function as normal from Rust, after marking its export unsafe
}

Marking these attributes unsafe emphasizes that the programmer must ensure the correct usage of symbols to prevent collisions or other linking-related undefined behavior.