Home ▸ STM32 Tutorials ▸ STM32 Custom Bootloader ▸ Flash Layout and Application Jump

STM32 Custom Bootloader: Set Up the Flash Layout and Jump to Your Application Safely

A bootloader is the first program that runs after a reset, and its job is to decide what runs next. This tutorial is Part 1 of the STM32 Custom Bootloader series, and it takes you from an empty CubeMX project to a bootloader that starts an application stored in a separate flash region.

You will create two projects, divide the flash of an STM32F103C8 into a bootloader area, an application header area and an application area, restrict each project to its own region with its linker script, relocate the vector table of the application and implement the jump. The result is checked with UART logs and LEDs. If you have not used CubeMX before, start with Getting Started with STM32. The next parts add application validation with a magic number and CRC based validation.

STM32 Bootloader Basics

A bootloader runs first after power-up or reset and decides whether to start the main application, run a firmware update or enter a recovery mode. A custom bootloader gives you more control than the built-in system bootloader of the device, because you decide how the firmware starts, how updates arrive and how errors are detected. If you only need to update firmware over USB, the USB DFU bootloader tutorial shows a ready-made route.

A custom bootloader brings several benefits to a product:

  • Firmware can be updated without a debugger, which is essential for OTA updates and devices in the field.
  • The bootloader can check the application before it runs, and it can refuse to jump when the application is missing or damaged.
  • Clear flash boundaries keep the bootloader and the application from overwriting each other.
  • Status LEDs and logs make it easier to see what the device does during startup.

This tutorial uses an STM32F103C8 board and two separate CubeIDE projects, one for the bootloader and one for the application. The flash layout is decided first, because both projects must agree on where each region starts.


STM32 Bootloader Flash Layout

The flash layout defines where the bootloader lives, where the application starts and which areas can be erased safely. It is kept in one header file that both projects include, so a change to the memory map has to be made in only one place.

RegionStart addressSizeEnd address
Bootloader0x0800000016 KB0x08003FFF
Application header0x080040001 KB0x080043FF
Application0x0800440047 KB0x0800FFFF

The three regions fill the 64 KB of the STM32F103C8 without overlapping. The application header is reserved for the information that the following parts of the series use to validate the application.

Flash memory distribution for the STM32F103C8 and STM32F446RE with bootloader, header and application regions

Defining the Bootloader and Application Addresses

Create a header file named flash_layout.h in the bootloader project and add the addresses.

#ifndef FLASH_LAYOUT_H
#define FLASH_LAYOUT_H

#define BL_START_ADDR      0x08000000UL   /* bootloader, 16 KB */
#define APP_HEADER_ADDR    0x08004000UL   /* application header, 1 KB */
#define APP_START_ADDR     0x08004400UL   /* application, 47 KB */

#endif /* FLASH_LAYOUT_H */

Named macros make the code easier to read than raw addresses. The same file is copied into the application project later, so the two copies must be kept identical.


Flash Alignment and Other STM32 Families

The STM32F103 erases flash in pages of 1 KB, and every region boundary above is a multiple of 1 KB, so each region can be erased without touching its neighbor. Devices that erase by sectors, such as the STM32F4 series, have sectors of different sizes, so the boundaries must be moved to sector edges and the application header should sit in its own sector. The start of the vector table also has to be aligned to a power of two that fits the number of interrupt vectors of the device, and 0x08004400 satisfies this for the STM32F103. Check the reference manual of your device before reusing the addresses.


STM32 Bootloader CubeMX Project

A bootloader should stay small, so only the peripherals needed for debugging, status indication and logging are enabled: SYS, GPIO and UART.

Enable Serial Wire Debug

Open the SYS settings and select Serial Wire as the debug mode. This lets you set breakpoints and inspect registers and memory in the bootloader.

STM32CubeMX SYS settings with Serial Wire debug enabled

Configure the Status LED

Set PA4 as a GPIO output. The LED shows that the bootloader is running and signals a failed jump, which is useful when no UART is connected.

STM32CubeMX pin PA4 configured as a GPIO output for the bootloader status LED

Enable UART for Bootloader Logs

Enable USART1 in Asynchronous mode and confirm that its TX pin matches the pin wired on your board. The bootloader prints log messages through this UART, and the transmit function is explained in the STM32 UART transmit tutorial.

STM32CubeMX USART1 enabled in asynchronous mode for bootloader logs

Generate the Bootloader Project

Open the Project Manager tab, enter a project name, select STM32CubeIDE as the toolchain and click Generate Code. Then import the project into CubeIDE.

STM32CubeMX Project Manager tab with the bootloader project name and the STM32CubeIDE toolchain

STM32 Bootloader Linker Script

By default the linker can use the whole flash of the device, so the bootloader could grow into the application area without any warning. Restricting the flash region in the linker script prevents this, because the build fails when the code does not fit.

Open the linker script of the bootloader project, which has the extension .ld, and find the FLASH entry in the MEMORY section.

STM32F103C8 linker script with the FLASH length changed to 16K for the bootloader
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 16K

The linker now reports an overflow error if the bootloader grows beyond 16 KB. That error is the intended safety check, and it tells you to either shrink the bootloader or move the application start address.


STM32 Bootloader Jump to Application

The main task of the bootloader is to hand control to the application, which is called the bootloader jump. The jump code goes into two new files in the bootloader project, bl_jump.c and bl_jump.h.

How the Jump Works

Every Cortex-M application starts with its vector table. The first word holds the initial stack pointer and the second word holds the address of the reset handler. The bootloader reads both words from the start of the application region, loads the stack pointer into MSP and branches to the reset handler, so the application starts as if the device had just been reset.

Before the branch, the bootloader cleans up its own runtime state. Interrupts are disabled, the SysTick timer is stopped and its pending flag is cleared, the NVIC is cleared and the UART used for logging is released. The bootloader in this tutorial runs from the default internal oscillator, so it does not change the system clock. A bootloader that configures the PLL should also call HAL_RCC_DeInit before the jump.


JumpToApplication Function

The code below is the original jump logic with three changes. It returns without jumping when the stack pointer does not point into RAM, it clears the NVIC and the pending SysTick flag, and it switches the stack pointer and branches in one assembly block. The last change matters because the original version kept the reset handler address in a local variable. After __set_MSP the compiler could read that variable from the new stack, which belongs to the application, and the CPU could then jump to a wrong address. A reader reported exactly this behavior while debugging.

#include "bl_jump.h"
#include "main.h"
#include "usart.h"
#include "flash_layout.h"

/* Load MSP and branch in one step, so no stack access happens in between */
static void __attribute__((noreturn)) StartApplication(uint32_t sp, uint32_t pc)
{
  __asm volatile (
    "msr msp, %0 \n"
    "bx  %1      \n"
    :
    : "r" (sp), "r" (pc)
  );
  __builtin_unreachable();
}

void JumpToApplication(void)
{
  uint32_t appStack = *(volatile uint32_t *)APP_START_ADDR;          /* initial stack pointer */
  uint32_t appReset = *(volatile uint32_t *)(APP_START_ADDR + 4U);   /* reset handler address */

  /* Basic check: the stack pointer must point into RAM, so an empty flash is rejected.
     Parts 2 and 3 of the series add proper validation. */
  if ((appStack & 0x2FFE0000U) != 0x20000000U)
  {
    return;   /* no valid application, stay in the bootloader */
  }

  HAL_UART_DeInit(&huart1);   /* release the peripheral used for logging */

  __disable_irq();

  /* Stop SysTick and clear a pending SysTick interrupt */
  SysTick->CTRL = 0;
  SysTick->LOAD = 0;
  SysTick->VAL  = 0;
  SCB->ICSR = SCB_ICSR_PENDSTCLR_Msk;

  /* Disable and clear every NVIC interrupt */
  for (uint32_t i = 0; i < 8U; i++)
  {
    NVIC->ICER[i] = 0xFFFFFFFFU;
    NVIC->ICPR[i] = 0xFFFFFFFFU;
  }

  StartApplication(appStack, appReset);
}

The header file only needs the prototype.

#ifndef BL_JUMP_H
#define BL_JUMP_H

void JumpToApplication(void);   /* returns only when no valid application is found */

#endif /* BL_JUMP_H */

Calling the Jump from main

The original post does not show the bootloader main code, so the following version is a minimal example. It prints a log line, switches on the LED on PA4 and calls the jump. If the function returns, the application was rejected and the LED blinks quickly.

/* USER CODE BEGIN Includes */
#include <string.h>
#include "bl_jump.h"
/* USER CODE END Includes */

/* USER CODE BEGIN 2 */
static const char blMsg[] = "Bootloader started, jumping to application\r\n";

HAL_UART_Transmit(&huart1, (uint8_t *)blMsg, strlen(blMsg), 100);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);   /* LED on while the bootloader runs */
HAL_Delay(500);

JumpToApplication();
/* USER CODE END 2 */

while (1)
{
  HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_4);   /* fast blink means the jump failed */
  HAL_Delay(100);
}

STM32 Bootloader Binary File

The bootloader is flashed as a binary file, so enable the binary output in CubeIDE. Right-click the project, open Properties, go to C/C++ Build, Settings, Post-build outputs, and enable the option that converts the output to a binary file. Then build the project again.

STM32CubeIDE post-build output settings with the binary file option enabled

After a successful build the .bin file appears in the Debug folder of the bootloader project.

Bootloader binary file inside the Debug folder of the STM32CubeIDE project

Compare the size of the file with the flash usage in the Memory Regions table of the build output. Both values should match, and the size must stay below 16 KB.

Build analyzer memory regions table showing the bootloader flash usage equal to the binary size

STM32 Application CubeMX Project

The application is a normal firmware project that can use many peripherals. In this tutorial it only needs the clock, SWD, an LED and the UART.

Configure the System Clock

Open the Clock Configuration tab, enable the external crystal (HSE) and set the system clock to 72 MHz, which is the maximum frequency of the STM32F103.

STM32CubeMX clock configuration with the HSE crystal enabled and the system clock set to 72 MHz

Enable SWD, the LED and the UART

Enable Serial Wire in the SYS settings as in the bootloader project and enable USART1 in Asynchronous mode.

Enable Serial Wire Debug in STM32.
Enable USART1 in STM32CubeMX for logging the data on serial console.

Then set PA1 as a GPIO output, which shows that the application is running.

STM32CubeMX pin PA1 configured as a GPIO output for the application LED

Generate the Application Project

Enter a project name in the Project Manager tab, select STM32CubeIDE and generate the code.

STM32CubeMX Project Manager tab with the application project name and the STM32CubeIDE toolchain

STM32 Application Linker Script and VTOR

The application does not start at the beginning of flash, so both its linker script and its vector table must be moved.

Set the Application Flash Start Address

Open the linker script of the application project and change the FLASH entry so that the region starts at the application address and covers 47 KB.

Application linker script with the FLASH origin changed to 0x08004400 and the length set to 47K
FLASH (rx) : ORIGIN = 0x08004400, LENGTH = 47K

Relocate the Vector Table

Copy flash_layout.h from the bootloader project into the application project.

flash_layout.h copied into the application project folder in STM32CubeIDE

The vector table is now at APP_START_ADDR, so the VTOR register must point to it. The bootloader also disabled all interrupts before the jump, and the PRIMASK setting stays in effect after the jump, so the application has to enable interrupts again. Without this step HAL_Delay never returns, because the SysTick interrupt cannot fire. Add the two lines in the Init user section of main, after HAL_Init and before the clock configuration.

  HAL_Init();

  /* USER CODE BEGIN Init */
  SCB->VTOR = APP_START_ADDR;   /* use the vector table of the application */
  __enable_irq();               /* the bootloader left interrupts disabled */
  /* USER CODE END Init */

  SystemClock_Config();

STM32 Application Binary File

Enable the same post-build binary option in the application project and build it. The .bin file is created in the Debug folder of the application project.

Application binary file inside the Debug folder of the STM32CubeIDE project

The size of the binary should again match the flash usage in the Memory Regions table, and it must stay below 47 KB.

Build analyzer memory regions table showing the application flash usage equal to the binary size

STM32 Bootloader Flashing with CubeProgrammer

Flash the bootloader first and the application second, so the bootloader is already in control when the application is added. Both binaries are written with STM32CubeProgrammer.

Flash the Bootloader Binary

  1. Connect the ST-Link to the board and open STM32CubeProgrammer.
  2. Open the Download section and set the address to 0x08000000.
  3. Select the bootloader binary file.
  4. Check the address and click Start Programming.
STM32CubeProgrammer download settings for the bootloader binary at address 0x08000000
STM32CubeProgrammer message confirming that the bootloader binary was programmed

Flash the Application Binary

Select the application binary, set the address to 0x08004400 and click Start Programming. A wrong address here is the most common reason why the jump fails.

STM32CubeProgrammer download settings for the application binary at address 0x08004400

STM32 Bootloader Output and Verification

The board is connected to a USB to UART adapter for the logs, and one LED is wired to PA4 for the bootloader and one to PA1 for the application.

STM32 board wired to two LEDs and a USB to UART adapter for the bootloader test

After a reset the bootloader runs first and prints its log line on the serial console. It then jumps to the application, which prints its own log line, and the application LED starts to blink every 500 ms. This blinking confirms that the jump, the vector table relocation and the interrupts work, because the delay depends on SysTick.

Gif showing the control first enters the bootloader and then inside the application. The LED is blinking every 500ms confirms the application is running fine.

Conclusion

In this tutorial you created a bootloader and an application as two separate projects, divided the flash into a bootloader, a header and an application region, and limited each project to its own region with its linker script. You then implemented the jump, relocated the vector table of the application, generated both binary files and flashed them with STM32CubeProgrammer. The UART logs and the blinking LED confirmed that the bootloader starts first and hands control to the application.

The jump in this part checks only the stack pointer, so a damaged application with a plausible first word would still be started. Part 2 adds validation with a magic number in the application header, and Part 3 extends it with a CRC and a size check. After that, the series continues with the OTA flag mechanism and the OTA update.


Download Project Here

Download the CubeMX project files and HAL source code — all tested on real hardware.

If you find this useful, you can support us with a Donation as well.

STM32 Custom Bootloader Tutorials

About the Author
Arun Rawat
Arun Rawat
Embedded Systems Engineer · Founder, ControllersTech

Arun is an embedded systems engineer with 10+ years of experience in STM32, ESP32, and AVR microcontrollers. He created ControllersTech to share practical tutorials on embedded software, HAL drivers, RTOS, and hardware design — grounded in real industrial automation experience.

Subscribe
Notify of

1 Comment
Newest
Oldest Most Voted
Cap
5 months ago

Thank you for the tutorial. It was very helpful and gave me a good starting point for learning more about bootloaders.
I would like to point out an issue I encountered.
Inside the JumpToApplication() function, three variables are declared locally. While debugging, I noticed three accesses to stack memory between __set_msp() and appEntry(). Since the stack pointer has already been changed by __set_msp(), appEntry() may be fetched from the new stack location rather than the original one. In my case, this caused execution to jump to an unexpected address.
To avoid this problem, I explored a few alternatives and ultimately used assembly instructions to perform the handoff safely.

×

Don’t Miss Future STM32 Tutorials

Join thousands of developers getting free guides, code examples, and updates.