Kristoffer
Kristoffer

Reputation: 486

How do I declare a static variable in a specific memory region in Rust?

I have static constant that I want to place in a specific memory region of my MCU, and the program is written in Rust for an ARM stm32m4 MCU.

In my test case I have defined the variable as such:

#[link_section = ".device_info"]
static DEVINFO: &'static str = "This is in the correct place no?";

In my memory.x file I have specified:

MEMORY
{
    FLASH           : org = 0x08000000, len = 15k
    DEVICE_INFO     : org = 0x08003C00, len = 1k
    EEPROM          : org = 0x08004000, len = 16k
    ..Others
}

SECTIONS {
     .device_info :  {
       *(.device_info);
       . = ALIGN(4);
     } > DEVICE_INFO
} INSERT AFTER .text;

This builds, but when I check my output file, I want to find the text "This is in the correct place no?" located at 0x8003c00, but instead when I search with this:

arm-none-eabi-objdump  target/thumbv7em-none-eabihf/debug/binaryfile -s | rg -C4 This

It gives this as output:

 8001b80 401b0008 2b000000 6b1b0008 15000000  @...+...k.......
 8001b90 59010000 15000000 00000000 00000000  Y...............
 8001ba0 696e6465 78206f75 74206f66 20626f75  index out of bou
 8001bb0 6e64733a 20746865 206c656e 20697320  nds: the len is
 8001bc0 54686973 20697320 696e2074 68652063  This is in the c
 8001bd0 6f727265 63742070 6c616365 206e6f3f  orrect place no?
 8001be0 4e6f2076 616c6964 20666972 6d776172  No valid firmwar
 8001bf0 65737372 632f6c69 622e7273 e01b0008  essrc/lib.rs....
 8001c00 12000000 f21b0008 0a000000 ac000000  ................

How do I get the string to be stored at 8003c00 when compiling? Or any value for that matter?

Basically, in the end, I want to store a larger structure at that specific position as this is my bootloader, and I want to read that structure's value from my application code later.

Upvotes: 4

Views: 1923

Answers (1)

Peter Hall
Peter Hall

Reputation: 58805

The value of &'static str is still just a pointer, so you are storing only an address in the .device_info section, not the data it is pointing to. To store the actual value there, you could use:

#[link_section = ".device_info"]
static DEVINFO: [u8; 32] = *b"This is in the correct place no?";

Upvotes: 3

Related Questions