Home / Learn Chip Programming / Writing a Bootloader: Concept and Memory Layout
Writing a Bootloader: Concept and Memory Layout
A tiny program at the start of flash that can start, verify or replace the application.
Theory in plain words
What it is
A bootloader runs first after reset, decides what to do (start the app, enter update mode), optionally verifies the app, and jumps to it. The app lives at a higher flash address.
Why we use it
Field updates over UART/USB/OTA, safe rollback and firmware signing all need a bootloader.
How it works
Layout: [bootloader 16 KB][app 200 KB][config]. The bootloader reads the app's vector table, sets MSP, reloads VTOR and jumps to its reset handler. The app is linked at its own origin.
Where it is used
- STM32 custom bootloader project
- USB DFU / UART update
- Secure boot
Boot decision
A bootloader must never leave the user with a dead device: if the application is invalid it must fall back to update mode.
#define APP_BASE 0x08004100u
typedef void (*app_t)(void);
void jump_to_app(void) {
uint32_t sp = *(volatile uint32_t *)APP_BASE; // word 0: initial stack pointer
uint32_t pc = *(volatile uint32_t *)(APP_BASE + 4); // word 1: reset handler
if ((sp & 0x2FFE0000) != 0x20000000) return; // sanity: SP must point into RAM
__disable_irq();
SysTick->CTRL = 0; NVIC->ICER[0] = 0xFFFFFFFF; // de-initialise what the bootloader used
SCB->VTOR = APP_BASE; // application has its own vector table
__set_MSP(sp);
((app_t)pc)();
}- Link the app with
FLASH ORIGIN = 0x08004100and setVECT_TAB_OFFSET. - Always de-initialise peripherals before jumping, so the app starts from a clean state.
- Protect the bootloader pages with write protection.
- Keep it small and heavily tested: it is the one piece that must never fail.
Quick quiz
1. What must a bootloader set before jumping to the app?
App vector table and stack pointer.
2. If the app CRC fails...
The device must stay recoverable.