Writing Your Own Bootloader for STM32.
In one of my previous articles I described how to flash an STM32 using the bootloader and explained how it works. For those who haven't read it, let me remind you that a bootloader is essentially a program that lives in the MCU and can rewrite its memory, i.e. update the firmware.
I think someone may wonder why write a bootloader yourself if you can use the built-in one.
The answer to this question is very simple: as long as you are the only one using your MCU gadgets, there's no need to write a bootloader; you can take the gadget at any time and flash new firmware into it. But if the device becomes commercial, the question arises of how users will update the firmware.
If you publish the firmware openly, there's a high chance someone will copy the device and start selling it. A developer would like to avoid that, but at the same time would like to delight users with new features and fixes for old bugs; a custom bootloader is what solves these problems.
With a custom bootloader, nothing prevents us from initializing some of the peripherals needed for the device to work in the bootloader and not initializing them in the firmware. This way, the firmware sent to the user is incomplete and won't work on an MCU without our bootloader. For more security the firmware can be encrypted, but none of these methods will help if someone really needs your firmware. Judging by information found on the internet, there are companies that will extract firmware from a locked MCU for a fee (around $1000).
That covers the theory; let's move on to practice. Roughly speaking, our bootloader will have the following structure
Depending on which medium or method we use for updating, the code inside the conditional statement will change; only the jump to the main program will stay the same, so let's start with that.
I'd like to note right away that our bootloader will be located in flash, and this is assumed by default in the discussion below.
When power is applied, the MCU always starts from the beginning of flash memory, namely from address 0x0800000. Next, the bootloader must jump to the main program, whose location depends on the size of the bootloader. To calculate the start address of the main program, add the size of the bootloader to 0x0800000.
In short, we face two questions:
Which address do we need to jump to?
How do we implement the jump?
The jump is implemented with a function pointer. As we know, a pointer is an address, and a function pointer stores the address where the function begins.
To answer the first question, we need to recall how the MCU boots.

When power is applied, the MCU reads the value at address 0x08000000 and writes it to SP (SP is the register that points to the top of the stack), then reads the value at address 0x08000004 and writes it to PC (PC is the register that points to the current instruction + 4 bytes).
So the jump address is stored in the Reset Handler vector. The function that implements the jump looks like this.
We've sorted out the jump to the main program; now we need to learn how to update the firmware. It's important to remember here that you can only write to blank pages, i.e. before updating the firmware, the pages allocated to it must be erased.
One more question remains open: how do we transfer the firmware?
At first I solved this problem head-on, sending a binary with the firmware size at its beginning, but later I realized this option is inconvenient and wrong. It's inconvenient because after generating the binary you have to remove everything unnecessary from it: if the main program starts at address 0x08008400, all the space before that address will be filled with FF.
The screenshot shows how much space the main program takes and how much junk it contains. It's wrong because the firmware is written to the MCU sequentially, but individual parts of it can be located anywhere; for example, an image may be stored at the end of flash, and then instead of writing the image at the right address we would have to sequentially fill the MCU memory with FF values until we reach the right address.
It's much easier to send a hex file, because it consists of records (there are actually 5 types; the structure of a data record is described here), and each record specifies the size of the data, the address where the data should be written, and the data itself, so everything is clear and simple.
It would be nice to end the article with a working example, but we haven't covered the record types or decided on the update method. So below I'll describe the structure of the bootloader taking into account what we've learned, and in the next article we'll deal with the record types and complete it.
I think someone may wonder why write a bootloader yourself if you can use the built-in one.
The answer to this question is very simple: as long as you are the only one using your MCU gadgets, there's no need to write a bootloader; you can take the gadget at any time and flash new firmware into it. But if the device becomes commercial, the question arises of how users will update the firmware.
If you publish the firmware openly, there's a high chance someone will copy the device and start selling it. A developer would like to avoid that, but at the same time would like to delight users with new features and fixes for old bugs; a custom bootloader is what solves these problems.
With a custom bootloader, nothing prevents us from initializing some of the peripherals needed for the device to work in the bootloader and not initializing them in the firmware. This way, the firmware sent to the user is incomplete and won't work on an MCU without our bootloader. For more security the firmware can be encrypted, but none of these methods will help if someone really needs your firmware. Judging by information found on the internet, there are companies that will extract firmware from a locked MCU for a fee (around $1000).
That covers the theory; let's move on to practice. Roughly speaking, our bootloader will have the following structure
//if new firmware is found
if(new_firmware)
{
//update
}
Go_To_Application();//jump to the main programDepending on which medium or method we use for updating, the code inside the conditional statement will change; only the jump to the main program will stay the same, so let's start with that.
I'd like to note right away that our bootloader will be located in flash, and this is assumed by default in the discussion below.
When power is applied, the MCU always starts from the beginning of flash memory, namely from address 0x0800000. Next, the bootloader must jump to the main program, whose location depends on the size of the bootloader. To calculate the start address of the main program, add the size of the bootloader to 0x0800000.
In short, we face two questions:
Which address do we need to jump to?
How do we implement the jump?
The jump is implemented with a function pointer. As we know, a pointer is an address, and a function pointer stores the address where the function begins.
To answer the first question, we need to recall how the MCU boots.

When power is applied, the MCU reads the value at address 0x08000000 and writes it to SP (SP is the register that points to the top of the stack), then reads the value at address 0x08000004 and writes it to PC (PC is the register that points to the current instruction + 4 bytes).
So the jump address is stored in the Reset Handler vector. The function that implements the jump looks like this.
#define APPLICATION_ADDRESS 0x08008400//program start address
void Go_To_User_App(void)
{
uint32_t app_jump_address;
typedef void(*pFunction)(void);//declare a user type
pFunction Jump_To_Application;//and create a variable of this type
__disable_irq();//disable interrupts
app_jump_address = *( uint32_t*) (APPLICATION_ADDRESS + 4); //get the jump address from the Reset vector
Jump_To_Application = (pFunction)app_jump_address; //cast it to the user type
__set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS); //set the application SP
Jump_To_Application(); //start the application
}
We've sorted out the jump to the main program; now we need to learn how to update the firmware. It's important to remember here that you can only write to blank pages, i.e. before updating the firmware, the pages allocated to it must be erased.
One more question remains open: how do we transfer the firmware?
At first I solved this problem head-on, sending a binary with the firmware size at its beginning, but later I realized this option is inconvenient and wrong. It's inconvenient because after generating the binary you have to remove everything unnecessary from it: if the main program starts at address 0x08008400, all the space before that address will be filled with FF.
The screenshot shows how much space the main program takes and how much junk it contains. It's wrong because the firmware is written to the MCU sequentially, but individual parts of it can be located anywhere; for example, an image may be stored at the end of flash, and then instead of writing the image at the right address we would have to sequentially fill the MCU memory with FF values until we reach the right address.
It's much easier to send a hex file, because it consists of records (there are actually 5 types; the structure of a data record is described here), and each record specifies the size of the data, the address where the data should be written, and the data itself, so everything is clear and simple.
It would be nice to end the article with a working example, but we haven't covered the record types or decided on the update method. So below I'll describe the structure of the bootloader taking into account what we've learned, and in the next article we'll deal with the record types and complete it.
#include "stm32f10x.h"
#define APPLICATION_ADDRESS 0x08008400//program start address
//choose the page size depending on the MCU model
#if defined (STM32F10X_HD) || defined (STM32F10X_HD_VL) || defined (STM32F10X_CL) || defined (STM32F10X_XL)
#define FLASH_PAGE_SIZE ((uint16_t)0x800)
#else
#define FLASH_PAGE_SIZE ((uint16_t)0x400)
#endif
void Go_To_User_App(void)
{
uint32_t app_jump_address;
typedef void(*pFunction)(void);//declare a user type
pFunction Jump_To_Application;//and create a variable of this type
__disable_irq();//disable interrupts
app_jump_address = *( uint32_t*) (APPLICATION_ADDRESS + 4); //get the jump address from the Reset vector
Jump_To_Application = (pFunction)app_jump_address; //cast it to the user type
__set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS); //set the application SP
Jump_To_Application(); //start the application
}
int main(void)
{
uint16_t count_page = 20;//number of pages to erase
uint16_t erase_counter = 0x00;//counter
volatile FLASH_Status FLASHStatus = FLASH_COMPLETE;//status of flash memory operations
//if new firmware is found
if(new_firmware)
{
// we use StdPeriph to work with flash, don't forget to include it
//unlock the flash,
FLASH_Unlock();
//clear the flags
FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
//erase the pages
for(erase_counter = 0; (erase_counter <= count_page) && (FLASHStatus == FLASH_COMPLETE); erase_counter++)
{
FLASHStatus = FLASH_ErasePage(APPLICATION_ADDRESS + (FLASH_PAGE_SIZE * erase_counter));
}
/*update*/
//lock the flash
FLASH_Lock();
}
Go_To_User_App();//jump to the main program
}
