Cortex-M Bootloader to Application Jump: What to Reset When the App Crashes Only Sometimes
Your bootloader validates the image, sets the stack pointer, calls the application's reset handler, and the application starts. Usually. Once in a while it hangs inside HAL_Delay(), lands in Default_Handler, or takes a HardFault a few milliseconds after main() starts, and a power cycle "fixes" it. The cause is almost never the three-line jump itself. It is state that the bootloader leaves behind and the application never expects. This article lists that state, explains why it makes the failure intermittent, and gives a jump routine that clears it.
The symptom
The patterns I see reported for custom bootloaders on STM32 (and on any Cortex-M part) are consistent:
- The application runs fine when flashed and started directly by the debugger or by reset, but crashes or stalls when started via the bootloader.
- The failure rate depends on timing: the length of the bootloader's last operation, whether a UART byte arrived during the jump, how long the application takes to reach its own clock and tick setup.
- The fault location varies:
Default_Handler(the endless loop in the ST startup file), an unexpected handler running before its peripheral is initialised, a HardFault with a NULL handle in the stacked PC region, orHAL_Delay()never returning because interrupts are still masked. - Stepping through the jump with a debugger makes it work, because the stepping delays change which interrupts become pending.
Root cause: the core is not in its reset state
A reset puts the core and the System Control Space into a known state. A branch from one image to another does not. The application's startup code (Reset_Handler, SystemInit, HAL_Init) was written assuming the reset state. These are the pieces of state that survive the jump:
| State | What goes wrong in the application |
|---|---|
SysTick enabled with its interrupt (SysTick->CTRL TICKINT/ENABLE) | SysTick fires between the jump and the application's own tick setup. With HAL it just increments a not-yet-initialised uwTick; with FreeRTOS, xPortSysTickHandler runs before the scheduler exists and crashes. |
NVIC enabled and pending bits (ISER, ISPR) | A UART, DMA or timer interrupt that the bootloader enabled fires as soon as the application re-enables interrupts, in a handler whose driver was never initialised. |
SysTick and PendSV pending flags (in SCB->ICSR, not in the NVIC) | Clearing NVIC->ICPR does not touch them. A pending PendSV runs as soon as it is unmasked. |
PRIMASK | If the bootloader executed __disable_irq() before the jump, the application starts with all configurable interrupts masked, because nothing in a normal startup file re-enables them. Symptom: HAL_Delay() hangs forever. |
VTOR | Still points at the bootloader's vector table. Every exception then runs a bootloader handler against application RAM. |
| Peripherals: UART/DMA/timers running, clocks switched to PLL | DMA keeps writing into RAM that the application's startup code is zeroing or reusing; HAL clock configuration may behave differently from a cold start. |
| Cortex-M7: MPU regions, caches | Bootloader MPU attributes apply to the application's memory map; caches the application expects to be off are on. |
The reason this is intermittent is that each item is a race. Whether a pending interrupt exists at the moment of the jump depends on what happened on the wire in the last microseconds. The failure only appears when an event lands inside the window between the jump and the application installing its own state.
The SysTick and PendSV trap
This one catches people who already "clear all pending interrupts". The NVIC pending registers cover external interrupts only. SysTick and PendSV are system exceptions, and their pending state is held in the Interrupt Control and State Register: PENDSTSET/PENDSTCLR and PENDSVSET/PENDSVCLR (CMSIS: SCB_ICSR_PENDSTCLR_Msk, SCB_ICSR_PENDSVCLR_Msk). Writing 1 to the CLR bit removes the pending state. Stopping the SysTick counter alone does not clear an already pending exception.
The VTOR alignment rule
If you set VTOR yourself, the address must be aligned to the vector table size rounded up to a power of two (with a minimum of 128 bytes on ARMv7-M). A table with 82 entries on an F4 is 328 bytes, so it needs 512-byte alignment; the ST system file comments say the vector table offset must be a multiple of 0x200 on those devices. Check the comment in your own system_stm32xxxx.c. A flash page or sector boundary satisfies every case.
The application must also agree
The bootloader can set VTOR, but the application has to be consistent with it, or it breaks the next time it is started without the bootloader or after a soft reset:
- The application is linked for its own flash origin (the
FLASHregion in the linker script starts at the application address, not at0x08000000). - The application's
SystemInit()setsVTORto its own base. The CubeMX/CMSIS template does this withVECT_TAB_OFFSET(orUSER_VECT_TAB_ADDRESSin newer templates). If this value stays 0, a reset (not a jump) boots with a vector table that is actually at the bootloader address. Setting it in the application is the robust choice; the bootloader setting it is only a convenience.
A jump routine that clears the state
The following targets an STM32F4 with HAL and a bootloader that does not use an RTOS, but nothing in it is family-specific except the RAM and flash limits and HAL_DeInit(). The vendor device header supplies the NVIC register array sizes, so the loops are portable across Cortex-M3/M4/M7.
#include "stm32f4xx.h"
#include <stdint.h>
#define APP_BASE 0x08020000UL /* start of application image */
#define APP_END 0x08100000UL /* end of flash (1 MB device) */
#define RAM_BASE 0x20000000UL
#define RAM_END (RAM_BASE + 128UL * 1024UL)
static int app_is_plausible(uint32_t base)
{
const uint32_t *vt = (const uint32_t *)base;
uint32_t sp = vt[0];
uint32_t pc = vt[1];
/* erased flash reads 0xFFFFFFFF, so this also rejects "no image" */
if (sp < RAM_BASE || sp > RAM_END) return 0; /* SP may equal RAM end */
if ((sp & 7U) != 0U) return 0; /* AAPCS: 8-byte aligned */
if ((pc & 1U) == 0U) return 0; /* Thumb bit must be set */
if (pc < APP_BASE || pc >= APP_END) return 0;
return 1;
}
__attribute__((noreturn))
void jump_to_app(uint32_t base)
{
const uint32_t *vt = (const uint32_t *)base;
uint32_t sp = vt[0];
uint32_t pc = vt[1];
/* 1. Stop what the bootloader started: DMA, UARTs, timers, clocks.
Do this first, with interrupts still working if the drivers need them. */
HAL_DeInit(); /* resets APBx/AHBx peripherals via RCC */
__disable_irq();
/* 2. SysTick: stop it and drop a pending exception */
SysTick->CTRL = 0U;
SysTick->LOAD = 0U;
SysTick->VAL = 0U;
SCB->ICSR = SCB_ICSR_PENDSTCLR_Msk | SCB_ICSR_PENDSVCLR_Msk;
/* 3. NVIC: disable and un-pend every external interrupt */
for (uint32_t i = 0U; i < (sizeof(NVIC->ICER) / sizeof(NVIC->ICER[0])); i++) {
NVIC->ICER[i] = 0xFFFFFFFFU;
NVIC->ICPR[i] = 0xFFFFFFFFU;
}
/* 4. Vector table of the application */
SCB->VTOR = base;
__DSB();
__ISB();
/* 5. Leave PRIMASK clear: the app expects the reset state. Every source
is already disabled and cleared, so nothing can fire in this window. */
__enable_irq();
/* 6. Load MSP and branch in one asm block, so the compiler cannot emit a
stack access between the two instructions. */
__asm volatile ("msr msp, %0\n\t"
"bx %1\n\t"
: : "r" (sp), "r" (pc) : );
for (;;) { }
}
Call it as if (app_is_plausible(APP_BASE)) jump_to_app(APP_BASE);. A few notes on the choices:
- MSP and branch in one asm block. The common pattern
__set_MSP(sp); ((void (*)(void))pc)();lets the compiler loadpcfrom a stack slot after MSP has changed. It often works because the value happens to be in a register; it is an optimisation-level-dependent bet. With the asm block both values are in registers beforemsr. - The reset vector already has bit 0 set. The linker emits the Thumb bit in the vector table entry, so
bxto it stays in Thumb state. That is why the plausibility check rejects an even value. - The RAM check is device specific. The initial SP of an STM32H7 application may be in DTCM (0x2000xxxx) or AXI SRAM (0x2400xxxx), so do not copy a mask like
0x2FFE0000from a forum post. Take the ranges from your own linker script. - The core must use MSP when this runs. If your bootloader switched thread mode to PSP (usually only when an RTOS is in use), shut the RTOS down and return to MSP first. The routine above does not change
CONTROL. - The clock.
HAL_DeInit()resets peripherals, but I would not assume it returns the clock tree to HSI. Some HAL versions'HAL_RCC_OscConfig()returnHAL_ERRORif the PLL is already the system clock source and the requested PLL configuration differs. Either callHAL_RCC_DeInit()where your HAL provides it, or switch back to HSI explicitly, and verify on your device.
Cortex-M7 additions
On M7 parts (STM32F7/H7), add these before the jump so the application sees the reset-like cache and MPU state it expects:
SCB_DisableDCache(); /* CMSIS: cleans and invalidates, then disables */
SCB_DisableICache();
HAL_MPU_Disable();
The application re-enables what it wants. Disabling the MPU is the part people forget: a bootloader region marked execute-never or device-type over the application's address range produces crashes that look like random code corruption. If the bootloader's MPU setup is needed for something the application never touches, the alternative is to have the application program all the regions it relies on, and not rely on the inherited map.
How to confirm the diagnosis
Before changing the jump, prove that state is leaking. Add this to the very start of the application, as the first thing SystemInit() or main() does, in debug builds:
static void assert_reset_like_state(void)
{
uint32_t leak = 0U;
for (uint32_t i = 0U; i < (sizeof(NVIC->ISER) / sizeof(NVIC->ISER[0])); i++) {
leak |= NVIC->ISER[i] | NVIC->ISPR[i];
}
leak |= SysTick->CTRL & (SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk);
leak |= SCB->ICSR & (SCB_ICSR_PENDSTSET_Msk | SCB_ICSR_PENDSVSET_Msk);
if (leak != 0U) {
__BKPT(0); /* or increment a retained counter / log it */
}
}
Start the application via the bootloader while the host streams data into the bootloader's UART, or while its timers run. If the breakpoint hits with an unmodified jump and never with the routine above, you have your root cause. Note that ISER and ISPR are read-only views here; reading them has no side effects.
Two things the jump cannot reset. A started independent watchdog (IWDG) cannot be stopped by software; the application must be able to refresh it from its first milliseconds, which includes the time spent in SystemInit and zeroing .bss. And if bootloader and application share a RAM region (boot flags, version info), that region must be excluded from the application's .bss clearing by placing it in a NOLOAD section in both linker scripts.
Guarding against regression
- Keep the
assert_reset_like_state()check in debug and in CI builds that run on hardware. Make it count violations in a retained RAM variable so field units can report them. - Add a soak test: reset the board, enter the bootloader, jump, wait for a heartbeat from the application, repeat a few thousand times while the host keeps traffic flowing on every bootloader interface. A race that fails one in a hundred jumps becomes visible in minutes.
- Build the test application with FreeRTOS as well as bare metal. The SysTick-before-scheduler crash is much louder there.
Practical checklist
- De-initialise every peripheral the bootloader used, including DMA streams and their interrupts, before clearing the NVIC.
- Stop SysTick (
CTRL,LOAD,VAL) and clearPENDSTSET/PENDSVSETthroughSCB->ICSR. - Write
0xFFFFFFFFto everyNVIC->ICER[n]andNVIC->ICPR[n]that exists on the device. - Set
VTORto a correctly aligned address, thenDSB+ISB. Also set it in the application's ownSystemInit(). - Leave
PRIMASKclear (or re-enable interrupts in the application startup). - Load MSP and branch without any compiler-generated stack access in between; make sure the reset vector has the Thumb bit set.
- Validate SP (inside the real RAM ranges, 8-byte aligned) and reset vector (inside the image) before jumping.
- Cortex-M7: disable caches and MPU, or make the application set up everything it needs.
- Check what cannot be undone: IWDG, option bytes, RAM shared between images.
- Run the leaked-state assertion and a repeated jump soak test.
How I would approach this on a client project
I treat the jump as an interface between two firmware images, with a written contract: "the application is entered with all external interrupts disabled and un-pended, SysTick stopped, PRIMASK clear, clocks and peripherals in reset state, VTOR unspecified." That contract lives in a header next to jump_to_app(), and the application's early-boot assertion enforces it. Then the intermittent crash stops being a mystery and becomes a failing assertion with a name.
I also keep the application independently bootable: its linker script, VTOR and startup code must work with and without the bootloader, so I can debug it on its own. For the update side of the problem, see the related articles on the system memory bootloader and on reading Cortex-M fault registers, which helps when the first fault does slip through.
Sources
- Arm, Armv7-M Architecture Reference Manual (DDI 0403), chapter B3 (System Address Map and System Control Space): VTOR, ICSR (PENDSTSET/PENDSTCLR, PENDSVSET/PENDSVCLR), NVIC ISER/ICER/ISPR/ICPR, SysTick registers, and the reset behaviour of these registers.
- ST, PM0214 STM32 Cortex-M4 MCUs and MPUs programming manual, system control block and NVIC sections (and PM0253 for Cortex-M7).
- Arm, CMSIS-Core documentation:
NVIC_Type,SCB_Type,SysTick_Type,__set_MSP,SCB_DisableDCache. - ST Community, "STM32H7 bootloader jumps as clean as possible to application": peripheral de-init, SysTick, and VTOR pitfalls.
- ST Community, "How to jump correctly to application on a bootloader": linking the application at its own address, VTOR in
SystemInit(), and interrupts left disabled.
Reply to this article by email — I read and respond to every message.