The idea: the chip wakes up with only its flash

A PC program is loaded by an operating system (see what happens when you run a program). A microcontroller has no OS. When the power comes on, the only thing that holds the program is flash, and SRAM holds random bits. So before main() runs, a small piece of code called the startup code must build the C world: give every global its starting value and set up the clock. The page follows one STM32F103C8 (an Arm Cortex-M3 at up to 72 MHz, the chip on the "Blue Pill" board) from power-on to main(), and watches one global, int counter = 42;.

Left: the flash from 0x0800_0000 with .isr_vector (0x10C bytes), .text from 0x0800_010C, .rodata from 0x0800_0600 and the .data load image at 0x0800_0610 holding 42, 500 and 13. Right: the SRAM from 0x2000_0000 with .data (counter, period_ms, led_pin) at 0x2000_0000, .bss (5 words) at 0x2000_000C, the heap at 0x2000_0020, free space, and the stack from 0x2000_4C00 up to _estack 0x2000_5000. An arrow labelled copy at reset goes from the .data load image in flash to .data in SRAM; .bss is marked zeroed at reset.
.data lives twice: its starting values sit in flash (the load address) and the startup code copies them to SRAM (the run address); .bss exists only in SRAM.

The STM32F103 memory map and its buses

All Arm Cortex-M chips split the 4 GB address space the same way. Code from 0x0000_0000, SRAM from 0x2000_0000, peripherals from 0x4000_0000 and the core's own devices (NVIC, SysTick) from 0xE000_0000. ST puts the STM32F103C8's 64 KB of flash at 0x0800_0000–0x0800_FFFF and its 20 KB of SRAM at 0x2000_0000–0x2000_4FFF. The reset and clock control block RCC is at 0x4002_1000 and the flash interface (FLASH_ACR) at 0x4002_2000. With the BOOT0 pin at 0, the chip also shows the flash at 0x0000_0000, the boot alias, so the word at 0x0000_0000 is the word at 0x0800_0000.

The core reaches memory over several buses at once. That is a Harvard design. The I-bus fetches instructions from flash, the D-bus reads constants from flash, and the S-bus (system bus) goes to SRAM and the peripherals. A von Neumann design has one bus for instructions and data, so they take turns. The page counts bus "slots" in a toy model: each bus moves one word per slot. The copy loop is 12 bytes of code (3 instruction words), one flash read and one SRAM write per word copied. With three buses the I-bus sets the pace, 3 slots per word. One bus needs 5. Demo: one bus vs Harvard buses: copying 3 words and zeroing 5 takes 19 slots with the three buses and 30 with one bus.

The linker script: sections, LMA and VMA

The compiler sorts everything into sections, and the linker script says where each one goes. Code goes in .text, constants in .rodata, and initialised globals in .data. Globals that start at zero go in .bss. A section has a VMA (virtual memory address: where the program uses it) and an LMA (load memory address: where its bytes are stored in the image). They are the same for everything in flash. For .data they differ: the line >RAM AT> FLASH says "run in RAM, store in flash".

sectionrun address (VMA)stored at (LMA)sizeholds
.isr_vector0x0800_0000same0x10Cinitial SP, then one address per exception
.text0x0800_010Csame0x4F4main, SystemInit, Reset_Handler
.rodata0x0800_0600same0x10const char msg[] = "blink";
.data0x2000_0000 (_sdata)0x0800_0610 (_sidata)0x0Ccounter = 42, period_ms = 500, led_pin = 13
.bss0x2000_000C (_sbss)none0x14hits, ticks, buf[3]
heap0x2000_0020 (_end)none0x200malloc
stackdown from 0x2000_5000 (_estack)none0x400locals, return addresses

The heap and stack sizes are _Min_Heap_Size = 0x200 and _Min_Stack_Size = 0x400. They are minimums: the linker fails if they do not fit, but the stack can grow further down. The image costs 0x61C = 1564 bytes of flash: the code plus 12 bytes for the .data values. .bss costs no flash at all; the linker only records where it starts and ends. Part of the linker script:

_estack = ORIGIN(RAM) + LENGTH(RAM);      /* 0x20005000 */
.data :
{
  _sdata = .;                /* 0x20000000 */
  *(.data*)
  _edata = .;                /* 0x2000000C */
} >RAM AT> FLASH
_sidata = LOADADDR(.data);   /* 0x08000610 */
.bss :
{
  _sbss = .;  *(.bss*)  *(COMMON)  _ebss = .;
} >RAM

Reset: SP and PC from the vector table

At power-on the chip runs from its internal 8 MHz RC oscillator, the HSI. Then the core does only two things by itself. It reads the word at 0x0000_0000 into SP: 0x2000_5000, the top of SRAM. It reads the word at 0x0000_0004 into PC: 0x0800_0531, the address of Reset_Handler with bit 0 set to mean Thumb code, so PC = 0x0800_0530. From then on it runs at the real flash addresses (Demo: reset loads SP and PC). The rest of the vector table, and what the core does when an interrupt comes, is on Cortex-M exceptions. That page uses a TI TM4C123 with 32 KB of SRAM and flash at address 0, so its first word is 0x2000_8000; the rule is the same.

Reset_Handler: copy .data, zero .bss

Reset_Handler is normal code from the startup file (startup_stm32f103xb.s). It sets SP to _estack again, then runs two loops. The first copies .data word by word from _sidata in flash to _sdata…_edata in SRAM. The second writes 0 to every word from _sbss to _ebss. Only then does it call SystemInit and main. Demo: copy .data, zero .bss shows the three copies and five zero writes.

A time-down sequence of the boot with the value of counter at 0x2000_0000 next to each step. Power-on, HSI 8 MHz: counter is garbage 0xC49ECC56. SP and PC loaded from the vector table: still garbage. Copy .data: counter = 42. Zero .bss: 42, and hits = 0. SystemInit, 72 MHz: 42. main, counter++: 43. The flash word at 0x0800_0610 stays 42 throughout.
The global is garbage until the copy loop runs; the 42 in flash never changes, only the SRAM copy does.

Demo: power-on all the way to main() ends with counter = 43 (main does counter++), hits = 1, SP = 0x2000_4FF8 after main pushes r7 and LR, and the board's LED on PC13 blinking every 500 ms. The flash word at 0x0800_0610 still says 42, so the next reset starts from 42 again.

SystemInit: from HSI to 72 MHz

After reset the chip runs at 8 MHz. SystemInit (ST's system_stm32f10x.c) moves it to 72 MHz using the 8 MHz crystal (HSE) and the PLL (Demo: SystemInit, HSI 8 MHz to PLL 72 MHz):

stepregister writewhy
1RCC_CR.HSEON = 1, wait for HSERDYstart the crystal; it takes time to settle
2FLASH_ACR = 0x32 (LATENCY = 2, prefetch on)flash needs 2 wait states above 48 MHz; set it before the clock goes up
3RCC_CFGR: PLLSRC = HSE, PLLMUL = ×9, APB1 /28 × 9 = 72 MHz; APB1 may not run above 36 MHz
4RCC_CR.PLLON = 1, wait for PLLRDYthe PLL must lock first
5RCC_CFGR.SW = PLL, wait for SWS = PLLswitch SYSCLK; RCC_CFGR = 0x001D040A
The clock tree after SystemInit. HSI 8 MHz RC oscillator, used at reset, goes into the SW switch. HSE 8 MHz crystal goes into the PLL times 9, giving 72 MHz, also into SW. SW selects PLL, so SYSCLK is 72 MHz. SYSCLK feeds AHB divide by 1 giving HCLK 72 MHz, APB1 divide by 2 giving 36 MHz, and APB2 divide by 1 giving 72 MHz. FLASH_ACR LATENCY = 2.
At reset SW picks the HSI (8 MHz); SystemInit starts the crystal and the PLL and then switches SW to the PLL (72 MHz).

Newer ST startup files call SystemInit before the copy loops, and CubeMX projects do the 72 MHz switch in SystemClock_Config() at the top of main. Either way, code that runs before the copy must not use any global.

When the startup code is wrong

A hand-written or edited startup file sometimes loses one of the loops. What happens depends on how the chip was reset. After power-on SRAM holds random bits. After a warm reset (the NRST pin, or a watchdog reset) SRAM keeps what the last run left there.

left outafter power-onafter a warm reset
.data copycounter = 0xC49ECC56, so main makes it 0xC49ECC57; period_ms = 0x91803807 ms, about 28 days between blinkscounter = 43 from the last run, so main makes it 44; period_ms = 500 and led_pin = 13 still look right
.bss zeroinghits = 0xAA614AB9, so main makes it 0xAA614ABAhits = 1 from the last run, so 2

The garbage values are the page's stand-in for random power-on SRAM. Demo: skip the .data copy after power-on shows the obvious failure. Demo: skip the copy, a warm reset hides it shows why the bug can survive testing: when the board is only reset and not powered off, the old values are still in SRAM, so the LED blinks normally and only counter is off by one. Demo: skip zeroing .bss breaks the C rule that globals without a value start at 0.

Once main runs, the program's shape (a super loop, interrupts, an RTOS) is on embedded software architectures, and how interrupts preempt each other is on interrupt priorities and nesting. Why flash keeps its bits without power and SRAM does not is on memory arrays.

See also driving loads from an MCU pin, which uses the same STM32F103 to drive an LED, a relay, a button and a sensor.

What the page leaves out

The real startup also calls __libc_init_array (C++ constructors and init functions) before main, and SystemInit also sets VTOR to 0x0800_0000. The page shows only 8 of the SRAM words and 2 of the 67 vectors. The bus-slot count is a toy: the real Cortex-M3 has a flash prefetch buffer, wait states and a bus matrix shared with DMA. Real SRAM after power-on is not uniformly random, and a brown-out can corrupt part of it. Left out as well: the other boot modes (BOOT0 = 1 boots ST's system-memory bootloader, or SRAM), code that runs from SRAM (.ramfunc), a stack that grows into the heap, and the HSE failing to start (the clock security system).

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlPID ControlI removes error; clamp stops windupOpen the Computer Architecture mind mapComputer Architecturesmall fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlPID ControlI removes error; clamp stops windup
This page on the Computer Architecture mind map · 79 pages in 7 branches · open it to see the whole map and test yourself in recall mode.