Memory layout and startup code
From reset to main: copying .data, zeroing .bss and the C runtime.
main is not the first code to run
C makes promises before main starts: globals with initialisers hold their values, globals without them are zero, and there is a stack. On a desktop the operating system's loader keeps those promises. On a microcontroller nobody does, so a small piece of startup code must, every time the chip resets.
The memory map
A typical Cortex-M part has flash starting at 0x08000000 (STM32) or 0x00000000 and SRAM at 0x20000000.
VMA and LMA
.data is the interesting section: its variables must live in RAM (they change), but their initial values must survive power-off, so they are stored in flash. The section therefore has two addresses:
- VMA (virtual memory address): where the code expects the variable to be while running, in RAM.
- LMA (load memory address): where the initial bytes are stored in the image, in flash.
The linker script records both, and exports symbols marking them:
.data : {
_sdata = .;
*(.data*)
_edata = .;
} > RAM AT> FLASH /* VMA in RAM, LMA in flash */
_sidata = LOADADDR(.data);
.bss : {
_sbss = .;
*(.bss*)
*(COMMON)
_ebss = .;
} > RAM
For most sections VMA equals LMA. objdump -h shows both columns.
The reset handler
The CPU reads two words from the vector table at reset: the initial stack pointer, then the address of Reset_Handler. From there:
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;
extern void __libc_init_array(void);
extern int main(void);
void Reset_Handler(void) {
/* 1. Copy .data initial values from flash to RAM */
uint32_t *src = &_sidata;
for (uint32_t *dst = &_sdata; dst < &_edata; ) *dst++ = *src++;
/* 2. Zero .bss */
for (uint32_t *dst = &_sbss; dst < &_ebss; ) *dst++ = 0;
/* 3. Clocks, FPU enable, vector table relocation */
SystemInit();
/* 4. C++ constructors and functions marked __attribute__((constructor)) */
__libc_init_array();
/* 5. Run the program */
main();
for (;;) { } /* main should never return */
}
The symbols are addresses defined by the linker, not variables; &_sdata is the start of the region. Vendor startup files do exactly this, often in assembly.
The simulation below plays both roles, with arrays standing in for flash and RAM:
#include <stdio.h>
#include <stdint.h>
/* "Flash" holds the initial values of two initialised globals; "RAM" starts as garbage. */
static const uint32_t flash_data_image[2] = { 115200, 42 };
static uint32_t ram[5] = { 0xDEAD, 0xBEEF, 0xFEED, 0xF00D, 0xCAFE };
/* Layout chosen by the "linker": .data is ram[0..1], .bss is ram[2..4]. */
#define SDATA 0
#define EDATA 2
#define SBSS 2
#define EBSS 5
int main(void) {
for (int i = SDATA; i < EDATA; i++) ram[i] = flash_data_image[i - SDATA]; /* copy .data */
for (int i = SBSS; i < EBSS; i++) ram[i] = 0; /* zero .bss */
printf("baud (initialised global) = %u\n", ram[0]);
printf("answer (initialised global) = %u\n", ram[1]);
printf("counters (zeroed globals) = %u %u %u\n", ram[2], ram[3], ram[4]);
return 0;
}
Things that go wrong
- Globals have garbage values. The startup code is missing the copy or the zeroing, or the linker script symbols do not match what it expects. Common when hand-writing a startup file.
- Code runs before the copy. Anything called before step 1, including
SystemInitin some vendor files, must not rely on initialised globals. - Stack overflows into .bss. The stack grows down towards the heap and the globals; nothing stops it. Fill the stack with a pattern at boot and check how much was overwritten (stack painting), or place the stack at the bottom of RAM so an overflow faults immediately.
- Watchdog resets during start-up. Zeroing a large
.bsson a slow clock can take long enough to trigger a watchdog left running by a bootloader.
Code in RAM
Some code must run from RAM: flash-programming routines (flash cannot be read while it is being written), or a fast interrupt handler on a part with slow flash. It gets its own section with VMA in RAM and LMA in flash, and the startup code copies it just like .data:
__attribute__((section(".ramfunc"))) void flash_write_word(uint32_t addr, uint32_t value);
Keeping data across a reset
A .noinit section placed in RAM but neither copied nor zeroed keeps its contents across a warm reset. Fault handlers write a crash record there; after the reset, the application finds it and reports it. Protect it with a magic number and a checksum, because after a power cycle it holds random data.
Interview question: What happens between reset and main on a Cortex-M?
Answer: The core loads the initial stack pointer from address 0 of the vector table and the reset handler address from the next word, then jumps there. The reset handler copies .data from its load address in flash to RAM, zeroes .bss, calls SystemInit to set up clocks (and enable the FPU and relocate VTOR if needed), runs static constructors via __libc_init_array, and calls main. If main returns it loops forever.
Interview question: What is the difference between the VMA and LMA of a section?
Answer: The VMA is the address where the section lives while the program runs; the LMA is where its bytes are stored in the image. They differ for .data and RAM functions: stored in flash (LMA) so they survive power-off, but used from RAM (VMA). The linker script expresses this with "> RAM AT> FLASH", and startup code copies from the LMA to the VMA using linker-defined symbols.
Build it: the code that runs before main
This is step 3 of the module project. A meter in the field occasionally starts with its tariff set to garbage. The cause is in the startup code: before main(), it must copy every initialised global from flash into RAM and set every zero-initialised global to 0, and this one gets the boundaries wrong. Write it correctly.
Lab: Copy .data and zero .bss in the reset handler
The memory is simulated by two byte arrays, flash_image and ram, and the linker's symbols are offsets into them, as in the provided code:
.data's starting values are stored in flash from_sidata; in RAM it runs from_sdataup to (not including)_edata..bssruns in RAM from_sbssup to (not including)_ebss.
Write reset_handler():
- copy the bytes of
.datafrom flash to RAM, word by word (4 bytes at a time: the linker aligns these sections to 4 bytes, and word copies are 4 times faster); - fill
.bsswith zeros, word by word; - touch nothing else: RAM outside the two sections (such as the stack's guard bytes) must keep its contents;
- then call
main_app().
Use memcpy to move each 4-byte word between the byte arrays and uint32_t values.
Going deeper
Interview question: A motor controller's global variables have wrong values at start-up. Where do you look?
Answer: The startup code: is .data copied from flash to RAM and .bss zeroed before main, using the linker script's symbols, and does the linker script place sections where the startup code expects? Also check the clock and stack set-up, and that no code (such as a constructor or an early interrupt) runs before the initialisation.
Interview question: How can firmware detect a stack overflow on a Cortex-M without an MPU?
Answer: Fill the stack area with a known pattern at start-up and periodically check how much of it remains untouched (stack painting), or check a canary word at the stack's limit. Place the stack at the bottom of RAM so overflowing it runs off the start of RAM and faults immediately instead of corrupting globals. Cortex-M33 and other Armv8-M cores also have stack limit registers (MSPLIM, PSPLIM) that fault on overflow.
Interview question: Why must the startup code avoid using initialised globals before copying .data?
Answer: Until the copy runs, .data in RAM holds whatever was there at power-up, not the initial values, and .bss is not zeroed. Any code that runs before that point, including some vendor SystemInit implementations or C++ constructors if run too early, sees garbage. Such early code must use only local variables, constants and registers.
Explain it: In your own words, explain what the reset handler does before calling main.
Answer: When the chip resets, the hardware loads the stack pointer and the reset handler's address from the vector table and starts running the reset handler. The handler copies the initial values of initialised global variables from flash into their RAM locations, fills the zero-initialised globals with zeros, sets up the clocks and other early hardware in SystemInit, runs C++ constructors and similar initialisation, and only then calls main. If main ever returns, it loops forever.