Skip to content
systemcoding.dev
Embedded

Jump From a Custom Bootloader to an Application on Cortex-M

Hand control from a bootloader to a Cortex-M application safely: validate the vector table, quiesce peripherals, set VTOR and MSP, and avoid the usual crashes.

8 min read
Summarize in AI
Flat illustration of a boot chain of stages, each handing over to the next, with the Arm, C and Linux logos.

The jump is the shortest part of a bootloader and the part that fails most often. Four assignments and a function call look trivial, yet a missing clean-up step produces a hard fault at the first interrupt, a clock that refuses to reconfigure, or an application that works from a programmer and crashes when started by the bootloader. This post walks through the jump on Cortex-M3, M4 and M7 in detail: what to check before leaving, what to undo in the bootloader, the exact register writes, the special cases for Cortex-M0, M7 caches and an RTOS, and how to find out what went wrong when the application dies. The examples target an STM32F407 with arm-none-eabi-gcc 14 and the CMSIS headers.

Validate the vector table first

The application's first two words are the stack pointer and the reset handler. If the slot is empty or corrupt, jumping through them is a crash, so check them before anything else.

jump_check.cc
#include <stdint.h>
#include <stdbool.h>

#define RAM_BASE   0x20000000u
#define RAM_TOP    0x20020000u         /* 128 KB of main SRAM */
#define APP_BASE   0x08010000u
#define FLASH_END  0x08100000u

bool app_vectors_plausible(uint32_t vectors)
{
    uint32_t sp    = *(const volatile uint32_t *)(vectors + 0u);
    uint32_t reset = *(const volatile uint32_t *)(vectors + 4u);

    if (sp < RAM_BASE || sp > RAM_TOP)          return false;
    if (sp & 3u)                                return false;   /* word aligned */
    if (!(reset & 1u))                          return false;   /* Thumb bit */
    if (reset < vectors || reset >= FLASH_END)  return false;
    return true;
}

Each test excludes a failure mode. Erased flash reads 0xFFFFFFFF, which is outside RAM. A reset address with the low bit clear would make the core attempt Arm-state execution, which Cortex-M does not support, and fault at once. An address outside the application's flash means the table is from some other image. This check is not authentication. It only stops obvious accidents, and a CRC or signature check on the whole image belongs before it, as the guide in this cluster explains.

Stop what the bootloader started

At reset the hardware is in a known state: peripherals idle, interrupts disabled, the clock on the internal oscillator. The application's start-up code assumes that state. A bootloader that has been running for a while has changed it, and the changes survive the jump.

Make a list of everything the bootloader touched. The usual suspects:

ItemWhy it mattersHow to undo it
SysTickA pending or running tick interrupt fires into the application's vector table at an unexpected momentWrite 0 to SysTick->CTRL, LOAD and VAL
NVIC enables and pending bitsAn interrupt enabled by the bootloader fires as soon as the application enables interruptsWrite 0xFFFFFFFF to every NVIC->ICER and ICPR word
Peripheral clocks and resetsThe application's init may assume a peripheral is idleHAL_DeInit(), or toggle the RCC reset registers for used peripherals
System clockPLL in use cannot be reconfigured without switching away firstHAL_RCC_DeInit() returns to the internal oscillator
DMA streamsA running transfer writes to memory the application now ownsDisable the streams and clear their flags
MPUA region the bootloader set may block the applicationDisable it with MPU->CTRL = 0
Caches (Cortex-M7)Stale lines for the old image survive in cacheClean, then disable instruction and data caches

With the STM32 HAL, the simplest reliable approach is to call HAL_DeInit() and HAL_RCC_DeInit() first, then handle the core-level items by hand. If you wrote the bootloader against registers instead of the HAL, reset each peripheral you used through its RCC_xxxRSTR bit.

The jump itself

jump.cc
#include "stm32f4xx.h"
#include "stm32f4xx_hal.h"

typedef void (*entry_fn)(void);

void jump_to_application(uint32_t vectors)
{
    uint32_t sp    = *(const volatile uint32_t *)(vectors + 0u);
    uint32_t reset = *(const volatile uint32_t *)(vectors + 4u);

    HAL_RCC_DeInit();
    HAL_DeInit();

    __disable_irq();

    SysTick->CTRL = 0;
    SysTick->LOAD = 0;
    SysTick->VAL  = 0;

    for (unsigned i = 0; i < 8; i++) {          /* 82 IRQs on the F407 */
        NVIC->ICER[i] = 0xFFFFFFFFu;
        NVIC->ICPR[i] = 0xFFFFFFFFu;
    }

    SCB->VTOR = vectors;
    __DSB();
    __ISB();

    __set_MSP(sp);
    ((entry_fn)reset)();

    for (;;) { }                                 /* not reached */
}

The order matters in three places.

**Disable interrupts before changing VTOR.** If an interrupt fires between the write to VTOR and the switch of the stack, the core stacks an exception frame and fetches a handler from the new table, whose application code expects a freshly reset system.

**__DSB() and __ISB() after writing VTOR.** The data synchronization barrier makes sure the write has completed, and the instruction synchronization barrier flushes the pipeline, so nothing already fetched runs under the old assumptions. Arm documents this as the architecturally required sequence after changing system control registers.

**Set MSP last.** After __set_MSP(sp) the stack is the application's. The function does not use the stack between that instruction and the jump, but a compiler is free to add spills or a frame in a function it considers needs them. If you see inexplicable crashes right at the jump, move the last three lines into a naked function written in assembly:

jump_naked.cc
__attribute__((naked, noreturn))
static void jump_asm(uint32_t sp, uint32_t reset)
{
    __asm volatile (
        "msr msp, r0 \n"       /* new main stack pointer */
        "bx  r1      \n"       /* branch to the reset handler */
    );
}

A naked function has no prologue, so r0 and r1 still hold the arguments when the first instruction runs.

What the application must do

The jump only works if the application cooperates, and the two halves have to agree.

The linker script must put the application at the address you jump to, with the vector table at the start of the region. In the GNU linker script this means FLASH origin 0x08010000 (or past a header, as the guide describes).

The vector table offset must be set by the application too, since a later reset of the core by software or a watchdog reloads VTOR to zero and starts the bootloader, but SystemInit() in the application runs after a bootloader jump and must match. Define VECT_TAB_OFFSET in system_stm32f4xx.c to the application's offset (0x10000 for 0x08010000). Without it the application's own interrupts fetch handlers from the bootloader's table.

The table alignment has a rule: VTOR requires the table to be aligned to a power of two at least as large as the table. On the F407 the 98-entry table needs 512-byte alignment, so an application at 0x08010000 is fine and one at 0x08010100 is not.

You can prove the hand-over is right from inside the application. Print SCB->VTOR and the stack pointer on start:

app_check.cc
#include <stdio.h>
#include "stm32f4xx.h"

void app_report(void)
{
    printf("VTOR=0x%08lX MSP=0x%08lX\r\n",
           (unsigned long)SCB->VTOR, (unsigned long)__get_MSP());
}

Right after the start-up code, with the application's first stack frame near the top of the stack, this prints something like:

Text
VTOR=0x08010000 MSP=0x2001FFE8

VTOR shows the application's table. The stack pointer is a few words below the top of RAM (0x20020000), which depends on the call depth at that point.

Special cases

Cortex-M0 and M0+

The Cortex-M0 has no VTOR register. Its vector table is fixed at address zero, and the M0+ has VTOR only as an option. A bootloader on an M0 part gets around this in one of two ways. Some chips, such as STM32F0, can remap the first words of RAM to address zero through a SYSCFG register, so the bootloader copies the application's vector table into RAM and remaps it. Others, such as many NXP LPC parts, provide a vector remap register of their own. Either way the application must be built to cooperate, and the interrupt handler addresses live in RAM, which costs RAM and a copy step.

Cortex-M7 caches

On an STM32F7 or H7 the instruction and data caches may hold lines for the bootloader's addresses and, more importantly, any flash writes the bootloader did to the application region. Before the jump, clean and disable the data cache with SCB_CleanDCache() and SCB_DisableDCache(), and disable and invalidate the instruction cache with SCB_DisableICache(). Without that, the CPU can execute stale instructions from the old contents of the slot, a bug that only shows on the second update.

An RTOS in the bootloader

If the bootloader used FreeRTOS, the scheduler has taken over SVC, PendSV and SysTick. A jump from inside a task leaves the scheduler's state behind, with PRIMASK and exception priorities set in ways the application does not expect. A bootloader that needs an RTOS is usually trying to do too much. If you must, stop the scheduler, disable the tick, and leave from the highest-priority context with all interrupts off. Leave BASEPRI at zero and clear FAULTMASK too, since __disable_irq() sets PRIMASK and the application must start with it cleared (its start-up code enables interrupts as part of its own setup).

TrustZone parts

On Cortex-M33 devices with TrustZone, such as the STM32L5 and U5, the jump may cross a security boundary, and the application starts in a state defined by the secure bootloader's configuration. Use the vendor's secure boot package for those.

Debugging a jump that fails

When the application dies right after the hand-over, find out which kind of failure it is.

  1. Attach with GDB before the jump. Set a breakpoint at the ((entry_fn)reset)() line and print sp and reset to confirm they are what you expect.

  2. Single-step into the application. stepi once after the jump should land on the first instruction of the application's reset handler. If it lands somewhere else, the reset value was wrong.

  3. Check the fault status. If the core takes a hard fault, read SCB->CFSR, SCB->HFSR and the stacked PC. The fault escalation post in this cluster explains how. A VECTTBL bit in HFSR means the table address was bad.

  4. **Compare VTOR and the application's expectations.** An application whose SystemInit() resets VTOR to 0x08000000 runs fine until its first interrupt.

  5. Test the application without the bootloader. Flash it alone at its address and start it by setting PC and MSP in the debugger. If that works, the fault is in the hand-over, not the application.

A last piece of advice. Leave the jump function simple, review it as carefully as security-sensitive code, and keep a test that runs the whole path on real hardware in your continuous integration. The hand-over is rarely changed, which is exactly why a quiet regression there goes unnoticed until a device in the field reboots into a hard fault.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.