Search code examples
c++armstm32mbed

ARM, how the content of the specified section name is not overwritten?


I am working on a fw written in C++ with mbed-os for a STM32F4 series MCU. There is a portion of code that should be executed only at the first boot. To achieve this goal, the developer uses a memory section named mysection for storing a flag, named MAGIC_INIT_CODE. mysection is defined in the ARM_GCC compiler linker file under text memory. The content of mysection is written by below lines at the very beginning, just after including the headers:

extern uint32_t __mysection_start__;
extern uint32_t __mysection_end__;
#define MAGIC_INIT_CODE 0xBDDBBDDBBDDBBDDB
static uint64_t magicCode __attribute__((__section__(".mysection"),used)) = MAGIC_INIT_CODE;

Then in main() function block it is overwritten by below lines:

if(magicCode == MAGIC_INIT_CODE){
    uint64_t voidMagicCode = 0;
    FW_Manager_Interface.MicroFlash.ProgramFlash(reinterpret_cast<uint32_t>(&__mysection_start__), reinterpret_cast<uint8_t*>(&voidMagicCode) , 8, false);
    #ifdef BOOTLOADER_MODE
    err = FW_Manager_Interface.FW_Checker.updateExternalBackup(Bootloader);
    appSettings.boot_outcome = BOOT_OUTCOME_UNKNOWN;
    appSettings.store();
    #else
    err = FW_Manager_Interface.FW_Checker.updateExternalBackup(Application);
    #endif
}

So if the content of mysection is equal to the MAGIC_INIT_CODE, the logic becomes true, the content of mysection is overwritten and the backup function takes the backup. During the program execution MicroFlash.ProgramFlash writes the specified value to the corresponding memory address starting from __mysection_start__. This is clear. But what I do not understand is how the content of mysection is not changing after the first boot? In particular I do not understand what does below line do.

 static uint64_t magicCode __attribute__((__section__(".mysection"),used)) = MAGIC_INIT_CODE;

What is the meaning of equalizing mysection to the MAGIC_INIT_CODE. Is this like assigning a value to a variable name or does it write MAGIC_INIT_CODE to the specified memory address? How this line does not modify the content of mysection after the first boot? As far as I know the program counter starts execution from the first line. Then, it always reaches at this point after each reset. But why the content of mysection does not change to MAGIC_INIT_CODE again?


Solution

  • this line place uint64_t object into .mysection section and initialize it to MAGIC_INIT_CODE. If .mysection is placed in flash it will be permanently there. It is being programmed when you upload your program to your micro. Ihis value will be the permanently (it cannot be changed by the standard C operations. You can only change its value by erasing the flash and programming the new value)