liveBook · Manning

Unsafe block

As explained in Embedded Software with Rust

An unsafe block is a Rust construct in which operations requiring explicit programmer verification, such as raw-pointer dereferencing, are permitted.

An unsafe block marks operations whose safety requires programmer verification. It permits operations such as raw-pointer dereferencing, calling unsafe functions, and accessing mutable statics. It does not turn off the borrow checker, type system, or other checks. section 5.2.1 section 7.1.3

Treat each block as a promise that the required invariants hold. Audit it carefully, and isolate unsafe operations behind safe abstractions where possible. section 5.2.1

const GPIOA_ODR: *mut u32 = 0x4001_080C as *mut u32;

// More code
unsafe {
    *GPIOA_ODR = 0x0000_0001;
}

Creating the raw pointer is allowed outside the block; dereferencing it requires unsafe. The programmer must verify the register address, alignment, accessibility, and type. section 5.2.2

A plain pointer dereference is not guaranteed to perform a volatile memory-mapped I/O access: optimization may remove, merge, or reorder it. Use explicit volatile operations or a PAC/HAL API for registers. A full-register write can also overwrite unrelated bits. section 5.2.2

static mut SHARED: u32 = 0;

fn main() -> ! {
    loop {
        unsafe { SHARED += 1; } // Unsafe: may introduce race conditions
    }
}

#[interrupt]
fn SysTick() {
    unsafe { SHARED += 1; } // Unsafe: may introduce race conditions
}

Both the main loop and interrupt handler update the same mutable static. Unsafe permits the accesses but does not prevent a race; prefer safer sharing methods unless exclusive access can be guaranteed. section 4.6.1

extern crate alloc;

use alloc::alloc::{alloc, dealloc, Layout};

fn manual_heap_example() {
    // Describe what we want: size and alignment of a u32.
    let layout = Layout::new::<u32>();

    unsafe {
        let ptr = alloc(layout);
        if ptr.is_null() {
            // Allocation failed; bail out before dereferencing.
            return;
        }

        // Write, then read back.
        *(ptr as *mut u32) = 1986;
        assert_eq!(*(ptr as *mut u32), 1986);

        // Deallocate using the same layout we allocated with.
        dealloc(ptr, layout);
    }
}

Manual allocation requires a null check before dereferencing and the same layout for deallocation. Box::new provides an alternative that handles these details automatically. section 7.1.3

Calls to generated C bindings also require unsafe. A thin safe wrapper can keep those calls localized, provided it upholds their requirements. section 8.5.2

How Embedded Software with Rust covers it

How deep it goes
Explains permitted operations and remaining checks, then works through register, sharing, and allocation safety requirements.
Examples
Uses an STM32 GPIO register write, a SysTick shared-counter race, and manual heap allocation.
What you can do after
Evaluate unsafe operations by identifying their invariants, reviewing race risks, and choosing safer abstractions where available.
How it connects
Connects raw pointers and mutable statics to memory-mapped I/O, volatile operations, safe abstractions, and manual memory management.

Also explained in

Compare how 4 books explain unsafe block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.