Rust’s #[unsafe(link_section = "name")] attribute places a static or function in a named object-file section. It does not choose an address: a linker script maps that section into a physical memory region. This separation is useful when firmware must put a vector table or buffer in a particular place. section 5.4.4 section 5.4.5
In the Rust 2024 edition, the attribute is unsafe because the compiler cannot verify that the chosen placement is valid. For example, mutable data could land in read-only Flash, or code in a region without execute permission. The programmer must ensure the section and linker mapping satisfy the item’s requirements. section 5.4.4
// Safety: this buffer is only accessed from a single context. // In practice, use a mutex or critical section for shared access. #[unsafe(link_section = ".tcm_data")] static mut CRITICAL_BUFFER: [u32; 128] = [0; 128];
This static buffer is tagged for the .tcm_data section. The tag alone does not place it in DTCM; the linker script must map the section there. Access to the mutable static also needs appropriate synchronization and raw-pointer handling. section 5.4.4
MEMORY {
ITCM : ORIGIN = 0x00000000, LENGTH = 64K
DTCM : ORIGIN = 0x20000000, LENGTH = 64K
FLASH : ORIGIN = 0x08000000, LENGTH = 1M
}
SECTIONS {
.tcm_data (NOLOAD) : ALIGN(4) {
KEEP(*(.tcm_data*))
} > DTCM
}
The linker script names memory regions in MEMORY and maps .tcm_data into DTCM in SECTIONS. KEEP retains matching sections, while NOLOAD is part of this example’s output-section declaration. The region addresses and sizes must match the target device. section 5.4.4
DTCM provides predictable data access on devices that have it. The STM32F103 does not have TCM; the example instead applies to Cortex-M7 devices such as the STM32F746 or STM32H743. section 5.4.4
#[unsafe(no_mangle)]
pub unsafe extern "C" fn reset() -> ! {
// Initialization routines here
crate::main()
}
// Define the reset vector to point to the reset handler
#[unsafe(link_section = ".vector_table.reset_vector")]
#[unsafe(no_mangle)]
pub static RESET_VECTOR: unsafe extern "C" fn() -> ! = reset;
For startup, the reset-vector static is tagged with .vector_table.reset_vector. The linker script places that entry at the required Flash location so the processor can fetch the reset-handler address. The separate no_mangle attribute preserves the symbol name for linkage. section 4.3.1
The same pattern can place an exception-handler array in .vector_table.exceptions. The linker script collects the reset vector and exception entries in the required order; the attribute names the sections, while the script determines their final layout. section 4.2.3 section 5.4.5
