</>EmbeddedInterview

What happens before main() runs on a microcontroller?

MediumEmbedded C

Short answer: On reset, the Cortex-M core reads the initial stack pointer from the first word of the vector table and the reset handler's address from the second word, then starts executing the reset handler. The reset handler (start-up code) typically configures clocks and the FPU (SystemInit), copies the .data section's initial values from flash to RAM, zeroes .bss, runs C/C++ constructors, and finally calls main().

Step by step

  1. Hardware reset sequence: the core loads MSP from address VTOR + 0 (usually 0x00000000, aliased to flash at 0x08000000 on STM32) and PC from VTOR + 4. Thumb mode, privileged, all interrupts enabled but no peripheral interrupts enabled yet.
  2. Reset_Handler (in startup_<device>.s or a C file): - SystemInit(): set up clocks/PLL (or leave that to main), flash wait states, enable the FPU (SCB->CPACR), set VTOR if the image is not at the default address. - Copy .data: from its load address in flash (_sidata) to its run address in RAM (_sdata.._edata). - Zero .bss: _sbss.._ebss. - Optionally copy code into RAM/ITCM (.ramfunc) and initialise other memories (e.g. external SDRAM must be set up before any data placed there is initialised). - __libc_init_array(): runs C++ static constructors and functions marked __attribute__((constructor)). - Call main(); if it returns, loop forever.
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;
extern int main(void);
void SystemInit(void);
void __libc_init_array(void);

void Reset_Handler(void)
{
    SystemInit();
    for (uint32_t *s = &_sidata, *d = &_sdata; d < &_edata; ) *d++ = *s++;
    for (uint32_t *d = &_sbss; d < &_ebss; ) *d++ = 0;
    __libc_init_array();
    main();
    for (;;) { }
}

Things that commonly go wrong

  • Writing the reset handler in C is fine, but it must not rely on initialised globals before they are copied, and the compiler may turn the copy loops into memcpy/memset calls (fine if those do not depend on .data either).
  • A watchdog enabled by option bytes can reset the chip during a long .bss clear on large-RAM parts.
  • Variables meant to survive a reset must be in a .noinit section, or the zeroing wipes them.
  • Clock configuration done too late can make the copy loops slow on big images.

Follow-up: "What runs before the reset handler?" On many MCUs a boot ROM (system memory bootloader) runs first, reads boot pins/option bytes and decides whether to start user flash, the built-in UART/USB DFU bootloader, or SRAM.