EEVblog® Electronics Community Forum
Electronics => Microcontrollers => Topic started by: EVblog1 on August 28, 2026, 09:41:56 am
-
I know UART bootloader flashes application HEX data into ROM/Flash but I don't understand how it flash application into ROM memory
Imagine an MCU with ROM/Flash, RAM, and a UART. Normally, I can write a C program that receives data from a serial terminal. The compiler converts the C code into a HEX file, and I use a programmer to load that HEX file into the MCU's ROM/Flash. That part is clear to me.
Now suppose I have another C program that simply blinks an LED. I have its HEX file, and I want my UART program to receive that HEX file through the serial terminal and store the application program into the MCU's ROM/Flash. In this case, the UART program is basically acting as the bootloader, and the LED-blink program is the application.
My confusion is about what happens after the UART receives the data. In a normal UART program, I understand that the received data can be stored in RAM. But in the bootloader case, the UART is also receiving the HEX data from the serial terminal. So how does the bootloader take that received HEX data and actually program the application into the MCU's ROM/Flash?
In other words, what is the actual mechanism that allows the bootloader to receive the application data through UART and then write that data into Flash/ROM?
-
By following the process described in the datasheet: writing the right flash access registers to erase pages and write any data. That varies between manufacturers and product families, but the general pattern is the same: unlock the flash with some special magic number write, command page erasure and enable write access by writing to a control register in the FLASH peripheral, then write to the flash (special commands through registers, or just memory mapped).
How the bootloader deals with UART communication, buffering it, integrity checking etc. is up to the bootloader designer. The tool that produces the data for the bootloader (e.g., writes it to the UART) must be designed in tandem with the bootloader itself.
-
One fun part is that if the bootloader it itself in flash with XIP, you generally need to turn that off in order to write the flash, which means you first need to copy the important bits of program into SRAM and run them from there.
Doesn't apply to very low end Harvard architecture CPUs such as PIC, AVR, or 8051 which can not run program code from RAM.
-
So I made a high-level flowchart to explain my understanding of the process. flowchart is self-explanatory and shows how the bootloader receives the application data through UART and then writes it into Flash.
[attachimg=1]
-
No. RAM is usually many times smaller than flash.
On my HiFive1 FE310 dev board it's 16k RAM and 16 MB flash, but that's probably an extreme case. This used almost the entire flash:
https://www.youtube.com/watch?v=RxPvWCQY5iA (https://www.youtube.com/watch?v=RxPvWCQY5iA)
-
No. RAM is usually many times smaller than flash.
My point is that when the UART receives data from the serial terminal, the received data has to be stored somewhere for the software to process it. As I understand it, this is normally handled through RAM, not directly stored in ROM/Flash ( PIC, or 8051)
-
I have done flashers that copy the whole thing in RAM and write it in one go after verification, but that's a special case more than a rule. Usually you would receive a piece, write and verify the piece, receive another piece and so on, because the firmware image is larger than the RAM. The piece could be as small as the smallest allowed flash write size - depends on the microcontroller, but any sensible design would do a larger chunk (maybe a few hundred bytes) and calculate and verify a checksum over it before writing.
Bootloader being fixed means that if the write fails, app does not boot but you can retry the update later. That's a relatively safe design, although it doesn't allow automatic over-the-air updates, but rather needs a UART cable, special update software, and booting the device at the right instant to start the update.
-
No. RAM is usually many times smaller than flash.
My point is that when the UART receives data from the serial terminal, the received data has to be stored somewhere for the software to process it. As I understand it, this is normally handled through RAM, not directly stored in ROM/Flash ( PIC, or 8051)
Yes but you don't loop back to "Bootloader start" or "Firmware update request"!
-
No. RAM is usually many times smaller than flash.
My point is that when the UART receives data from the serial terminal, the received data has to be stored somewhere for the software to process it. As I understand it, this is normally handled through RAM, not directly stored in ROM/Flash ( PIC, or 8051)
Bootloader will certainly use RAM, but since there won't be enough to store the whole app image, the bootloader will have to erase the old app in the process. If something goes wrong in this process, there will be no working app, so the bootloader must recognize such situations and avoid running the app if it is not fully programmed.
To avoid this situation, it is possible to have two (or more) different places where the app can live, often called partitions. At boot, it is decided which of the partitions should run. If there are two partitions A and B, the working app may be in A, while the bootloader programs new application into B. Once it verifies that everything is written ok, it marks B as active - it will now run when the chip boots. Next time, the active app will be in B, and bootloader will re-write A, then swap them again.
By using position independent code, you can have multiple apps written in flash, and the startup logic will decide which one to run depending on circumstances. Thus, you can revert to an older version, or run an entirely different app.
-
often called partitions.
So, we actually partition the Flash memory into different regions for the bootloader, Application by modifying the linker script
-
often called partitions.
So, we actually partition the Flash memory into different regions for the bootloader, Application by modifying the linker script
That's not what I meant. But yes, you can do that. You would need to take care of interrupt vectors and such.
You can also embed a bootloader into the app. This way, your bootloader gets updated when you update the app, giving you opportunities to add new features to the bootloader too.
-
Two-partition approach also means you don't need to program the flash from the bootloader; you can program from the other app. It is 100% bulletproof and easy to prove as such. The working app never erases itself, so it's always bootable.
My implementation on this is: clear the other partition, write it at any pace you wish, as the last thing write checksum and a "boot counter" which is currently running partition's counter plus 1. After that is done, reset. Then the bootloader logic is simply, "boot the app whose checksum matches the content, and if both are bootable, boot the one with higher counter".
In this approach, bootloader is tiny and trivial, but there are two full set of applications, so available flash effectively halves. This makes sense when the update process is not small or trivial; e.g. it contains full TLS networking stack, which the application uses anyway, so on the app side, the flashing is trivially simple; in the bootloader, it should replicate the whole networking stack. You could do that, and let the application use bootloader's networking stack (you can share the flash, why not), but then you need a way to upgrade that (because it is complex enough it cannot be proven 100% future-proof before the first release), and this just pushes the problem elsewhere: the only 100% reliable way is to duplicate it anyway.
The erase cycle in flashing is relatively long and power consuming. You can't realistically protect it against power loss. And if the whole firmware doesn't fit in RAM at once (as it usually doesn't), you are at the mercy of the upstream system feeding the firmware into your product - that can stall indefinitely or stop working altogether. If you cleared your only working app, any "I have a li-ion battery" doesn't help. So, if you care about product not getting bricked, dual apps or a fully independent bootloader which can do the retry.
Sometimes you will see magical thinking happening: claims of easy wins without duplicating everything, but usually there is a hole somewhere, or some amount of risk. Full duplication of the the whole app is the only obviously 100% bullet-proof when the flashing stack is large. Some people find that adding a physically separate flash chip is somehow easier for them to understand, but I find that weird. Partitioning the internal flash is always the simplest, and external chip makes sense when the otherwise good-fit MCU is already maxed out, and a larger-flash model series is significantly more expensive, complicated or weird than adding the external chip. Rarely so, unless the application is huge (e.g., high resolution graphics for UI).
-
Northguy and Siwastaja, have you guys actually developed a bootloader yourself, or did you use a ready-made one?
If you developed one yourself, could you share what platform you used, MCU, compiler, and communication interface and how it was working?
-
Northguy and Siwastaja, have you guys actually developed a bootloader yourself,
The bootloader I describe in my above post, yes, "developed" it myself. The whole thing is 248 lines of code and that contains comments, commented-out UART debug prints, delay functions to blink a LED, some small extra application-specific features.
Calculating a CRC, comparing it, looking at a counter, and "starting the app" - the full simple bootloader which doesn't flash but only boots, as I describe above, is 30 lines of code.
I'll give you the hard part here because really, that's something everyone copypastes anyway.
static void __attribute__((naked)) start_app(uint32_t pc, uint32_t sp)
{
__asm(
"msr msp, r1\n\
bx r0\n");
}
static void __attribute__((noreturn)) boot(void* addr)
{
SCB->VTOR = (uint32_t)addr;
uint32_t sp = ((uint32_t*)addr)[0];
uint32_t pc = ((uint32_t*)addr)[1];
start_app(pc, sp);
while(1);
}
-
Northguy and Siwastaja, have you guys actually developed a bootloader yourself, or did you use a ready-made one?
If you developed one yourself, could you share what platform you used, MCU, compiler, and communication interface and how it was working?
I developed one for the NXP Kinetis M0+ processors. It has two versions, one that uses a serial port, and one that uses a wiznet SPI ethernet chip as the primary communication device. The work essentially identically, it's just a question of whether read() reads from a TCP socket or a UART.
I used two partitions set up by the linker script. The bootloader and the main program are completely separate projects.
The bootloader is designed to never be updated. It won't write to it's own partition and the main program has no flash write code at all. So you have to get out a SWD probe if you want to modify it. At power up, the bootloader checks for a hardware button being pressed, a magic command on the serial port within the first 2 seconds, or a corrupt first block (the interrupt table) for the application partition, and if finding any of them enters bootloader mode, otherwise it chains to the main proram.
The bootloader update process is:
1) erase the first page of the application program.
2) Writes the application code in blocks of 1024 bytes, in reverse order from the end of the flast to the beginning.
3) The final block written is block 0, the interrupt vector block
4) reset
The idea is that after step 1 is complete, if the process is interrupted, it will be detected at power up and automatically sit in firmware update mode. This was just a lazier way to avoid implementing firmware signing or checksums.
The main program project itself has a stub loader at flash address zero that unconditionally chains to the main program. The idea here is that if I flash the main program from the SWD dongle (say for debugging) it overwrites the bootloader and runs as a stand-alone process. But since this stub is in the bootloader partition, it gets dropped from the firmware update.
The bootloader code itself is a couple hundred lines of code, but in my case I also included a bunch of code from the main project that does hardware diagnostics, and for the ethernet version device discovery. So the bootloader is actually fairly large in terms of flash usage, but that wasn't a constraint for my project.
I have a small python script that merges the IntelHex files from the bootloader and the application targets to create the initial factory programming image. That way I get a default version of the application immediately.
-
Northguy and Siwastaja, have you guys actually developed a bootloader yourself, or did you use a ready-made one?
Long time ago. I remember the last one was very simple, much simpler than Siwastaja describes. It simply executed read/erase/write commands from the controlling app and had some basic safety (like it woudn't overwrite the working app or the bootloader itself). The controlling app was run on PC, was doing all the work, and sending commands to the bootloader. But then I thought that instead of using a converter chip, I could use a small MCU, such as PIC16, which would re-program the target chip and then I wouldn't need a bootloader any more ...
-
To add:
In my application, it was deemed acceptable for a corrupt flash write to leave the device non-functional as long as it can be recovered. So we didn't store two full copies of the application image like Siwastaja describes. If a flash fails, we don't have a known good image to fall back to, we just sit in the bootloader loop until we can recover by re-running the flash update process.
The bootloader could have bugs in it, since it is considerably more complicated and includes the communication and flash logic. However, realistically, once it's tested to be able to program an application image and chain to it, I'm pretty confident that there are no show stoppers. Since we have complete control over the flash update client, the fix for any bugs is going to be to document "don't do that".
The A/B image Siwastaja described is definitely a more elegant solution. It's just wasn't needed for my application.
-
The A/B image Siwastaja described is definitely a more elegant solution. It's just wasn't needed for my application.
And it requires you to spec chips with twice as much flash as you'd otherwise need.
-
Northguy and Siwastaja, have you guys actually developed a bootloader yourself, or did you use a ready-made one?
If you developed one yourself, could you share what platform you used, MCU, compiler, and communication interface and how it was working?
I wrote an assembler program for a GPSDO using a PIC16F1455 as the microprocessor. Because the GPSDO was intended to be in an enclosure, it was a pain to update the firmware via the programming interface. The enclosure had to be opened up etc.
So I wrote a bootloader to update via the UART user interface. It is triggered by requesting an update by <TAB>u. The PC programming interface is Tera Term which is also used as the user interface, so no need to swap programs to update. The update is sent using Tera Term's implementation of XMODEM. It sends the .hex file and the bootloader interprets that. Because the update is requested from the user interface which gets overwritten by the update, it is desirable to know the update is not corrupt. So the update is done in two passes - a dummy run that does everything except write to flash, and if that succeeds a second pass to do the writing. It is all very slow but has worked reliably for a few years now.
The assembler source for the GPSDO can be found at https://sourceforge.net/projects/minimal-gpsdo/ (https://sourceforge.net/projects/minimal-gpsdo/), browse the files, look in the latest releases directory for source and hex. The assembler source is monolithic, the boot loader is at the end of the source file.
-
Protocols like XMODEM indeed have the advantage that many good old programs people use on PCs to do UART communications support them directly, i.e., you can initiate a "file transfer" function within such existing program and your firmware can detect that as firmware update. But I think this niche is shrinking - nowadays I bet many users would be more willing to install your custom application, than to use some modem-era software they have never heard about. A custom application can have a big "update firmware" button - it can also show a version number, verify the image before sending it, or even have an online autoupdate fetch feature.
-
Another thing to keep in mind is that CE compliance may require to encrypt and sign firmware files. So they can't be intercepted / modified by third parties.
-
Another thing to keep in mind is that CE compliance may require to encrypt and sign firmware files. So they can't be intercepted / modified by third parties.
Do you have a specific standard / field in mind where this is a requirement?
-
Another thing to keep in mind is that CE compliance may require to encrypt and sign firmware files. So they can't be intercepted / modified by third parties.
Do you have a specific standard / field in mind where this is a requirement?
The EU Cyber Resillience Act which has a broad scope (including industrial IoT). From December 2027 it is part of CE compliance.
-
Some mcus poll gpios at boot to see which state they are in prior to moving on. Bootloader or run program are two generally used settings.
-
Protocols like XMODEM indeed have the advantage that many good old programs people use on PCs to do UART communications support them directly, i.e., you can initiate a "file transfer" function within such existing program and your firmware can detect that as firmware update. But I think this niche is shrinking - nowadays I bet many users would be more willing to install your custom application, than to use some modem-era software they have never heard about. A custom application can have a big "update firmware" button - it can also show a version number, verify the image before sending it, or even have an online autoupdate fetch feature.
The user already has to "use some modem-era software they have never heard about" to interface with the GPSDO because the user interface is serial. The PIC has support for USB but it requires a 48MHz clock. For this application, the clock has to be 40MHz so the USB function won't work. And the loader isn't a true boot loader, it is initiated by the user. It could be a boot loader with a tiny bit of programming as the whole loader is a piece of standalone code. It works without interrupts, it uses polling for the serial interface. This works well with XMODEM, get a packet, process the packet, write to flash, then send an ACK ready for the next packet.
I take the point about a custom app, but one doesn't know what system is at the terminal end. Simpler for me to use an existing standard like XMODEM and hope the user can find a program for their system. The loader was in fact written by me, for me, to speed up development. I left it in the source in case an update was needed but so far I don't think anyone else has used the loader, just used a programmer to update via the ISP header. I mentioned it here because the OP wondered if people wrote loaders.
I hadn't thought about verification, encryption, signing etc. The whole source (GPSDO and loader) is on sourceforge, uses no external libraries. So anyone can compile from source if they don't trust the .hex. You just have to hope sourceforge is secure.
-
I bet many users would be more willing to install your custom application, than to use some modem-era software they have never heard about
That custom application can just as easily deal with the mcu that is using an xmodem bootloader, so one can have both- custom application for those that need/want it and can also use xmodem transfer (and any other needed interaction) via a terminal app like tera term for any others that can handle that.
I have a bootloader in the online compiler, for a modern avr (xmodem-crc)-
https://godbolt.org/z/YMWczGTrx
I have written various bootloaders starting with early pic's, and the above was simply so I could use sx on a linux pc and also tera term on a Windows pc. I previously wrote avr bootloaders that could take in a hex file, where I could drag/drop the hex file on tera term but that required adding a line delay as there is no flow control when doing something like that. With the above xmodem-crc bootloader I do convert to binary in the build so I do not need translation in the mcu.
Normally I have little need for bootloaders anymore, but for a current project I have a single wire coming out of a box for uart debug info and if I need to reprogram I would rather not open the box to get at the programming pins (although in this avr there is a single updi programming pin which I can tie to the one-wire uart pin and make it work, just not willing to tie the updi pin to the uart pin even though the probability of inadvertently entering programming is pretty slim). With this setup I can remain in tera term while watching debug info and do any reprogramming if needed.
I also have a bootloader for the newer avr where the bootloader has a simple protocol and very little brains (basically read n bytes from addr, or write n bytes to addr). The pc software does all the work, including writing to the appropriate nvm registers to do the flash write. So you basically have read/write access to the ram/peripherals from the pc. Its simple on the mcu side, but you just moved the work to the pc side and probably end up with more work in the end.
-
Another kind of bootloader (not for true Harvard CPUs like PIC/AVR/8051): just two commands - “write to RAM” and “jump to RAM”. The real job is performed by the external code loaded to RAM. This allows to define the actual functionality later. I.e. you can decide to do things like reformatting some settings area to a newer structure together with app update, or read something out for fault analysis, or perform some kind of init/test/calibration, or any combination of these things by loading a specific “RAM loader”, performing the function, rebooting/returning back to bootloader, loading another one.
-
I also have a bootloader for the newer avr where the bootloader has a simple protocol and very little brains (basically read n bytes from addr, or write n bytes to addr). The pc software does all the work, including writing to the appropriate nvm registers to do the flash write. So you basically have read/write access to the ram/peripherals from the pc. Its simple on the mcu side, but you just moved the work to the pc side and probably end up with more work in the end.
This is what SWD can do on ARM32 directly, along with nearly anything else, Doesn't require any bootloader at all.
-
Do you have a specific standard / field in mind where this is a requirement?
The EU Cyber Resillience Act which has a broad scope (including industrial IoT). From December 2027 it is part of CE compliance.
You might be interested in a webinar hosted by Memfault named "Shipping Firmware Under the CRA: Nicolas Schieli on the Questions Everyone’s Asking, and the Ones They Should Be"
https://memfault.com/resources/coredump-024-shipping-firmware-under-the-cra-nicolas-schieli/
It starts in 25 minutes, sorry for the late link, I just happen to come across new comments in this topic.
-
This is what SWD can do on ARM32 directly, along with nearly anything else, Doesn't require any bootloader at all.
The newer avr has updi which is similar with a single wire using uart half-duplex protocol. Certainly no need for a bootloader if you can make use of native programming.
-
Certainly no need for a bootloader if you can make use of native programming.
UPDI, and some other built-in programming capabilities, tend to be on pins that are NOT the same as a product might use to communicate under normal circumstances (eg USB or UART.) So you frequently see (for example) UDPI-capable AVRs with an added UART bootloader, or STM32F103 boards ("Blue Pill") with a USB bootloader...
-
You might be interested in a webinar hosted by Memfault named "Shipping Firmware Under the CRA: Nicolas Schieli on the Questions Everyone’s Asking, and the Ones They Should Be"
For anyone interested in the effects of CRA coming into force in September 2026, here is the webinar recording:
https://www.youtube.com/watch?v=c_8sudnteC8&list=PLx_tBuQ_KSqFBQzZ2uQLfaDnjU3nec3xJ (https://www.youtube.com/watch?v=c_8sudnteC8&list=PLx_tBuQ_KSqFBQzZ2uQLfaDnjU3nec3xJ)
-
I started a thread here on the EU security thing. I don't think many people have time to watch a 1hr video ;)
https://www.eevblog.com/forum/microcontrollers/eu-cyber-regulation-and-secure-firmware-updates-mandatory/ (https://www.eevblog.com/forum/microcontrollers/eu-cyber-regulation-and-secure-firmware-updates-mandatory/)
Re boot loaders, lots of ways to do it and with a lot of history.
One of the oldest formats is intex hex. You have a line of about 5 bytes, in ascii-hex, 2 bytes per binary byte, and each line starts with the load address. So you receive this line into RAM, check the checksum on it, and program it into FLASH. It usually relies on FLASH being much faster to program than the data is arriving, which is usuall ok.
The boot loaders in STM arm32 chips just receive data and program each byte into flash. Not sure there is any addressing. The loader code runs in a different address space to the flash being programmed; this is obviously important since you cannot normally execute from the same flash bank (there are exceptions to this and e.g. the 32F4 can, in certain ways). I wrote a RAM-resident loader to do it properly - see threads on eevblog on loaders, relocatable code, etc.
-
I started a thread here on the EU security thing. I don't think many people have time to watch a 1hr video ;)
https://www.eevblog.com/forum/microcontrollers/eu-cyber-regulation-and-secure-firmware-updates-mandatory/ (https://www.eevblog.com/forum/microcontrollers/eu-cyber-regulation-and-secure-firmware-updates-mandatory/)
You are right. TL:DR (well not Read but Watch - I felt sleepy after a minute). So I looked up EU CRA and there's a Wikipedia article. It seems open source is exempt so I am in the clear. I'm happy for people to hack anything I make public.
Re boot loaders, lots of ways to do it and with a lot of history.
Every computer has to have a boot loader. Historically it was in a ROM, the CPU would fetch its first instruction from a fixed address and proceed from there. The instructions may initiate a primitive user interface allowing the user to select a device from which to load a program. Many recent microprocessors have a programming state (for example raise a pin to a specific voltage) which activates something in the processor which allows it to be programmed. So the examples in this thread are really secondary loaders, originally loaded into the processor by the hardware loader. In the PC world the primary loader is the BIOS. For early machines it usually loads IIRC 128 bytes from a selected device, for a disk or USB drive this was from sector 0. The second 128 bytes had a partition table. The 128 bytes was a secondary loader that started loading another loader from the disk (sectors 1-?) which was a tertiary loader that was responsible for loading the operating system. I'm not up to date on the latest PC load system.
One of the oldest formats is intex hex. You have a line of about 5 bytes, in ascii-hex, 2 bytes per binary byte, and each line starts with the load address. So you receive this line into RAM, check the checksum on it, and program it into FLASH. It usually relies on FLASH being much faster to program than the data is arriving, which is usuall ok.
Intel hex is a little more complex than that. The loader I wrote for the PIC reads Intel format, as that is the output of the tool chain. A record starts with : followed by a byte count and ends with a checksum. The data in between can be a few different things. There can be padding bits between a checksum and the next : to allow time for programming to take place. I didn't need that because XMODEM implementation programs the flash before sending an ACK.
-
Yes of course. Typo: I meant 50 bytes. Probably 64 mostly. But the key point is that each intel hex line is standalone and gets programmed at the stated address. There can be gaps...
I wrote intel hex loaders in the old days.
-
each intel hex line is standalone and gets programmed at the stated address.
They're not standalone. There is a current base address to which the address in each line needs to be added. Original HEX was 16 bit addresses, then they extended it for segmented 20 bit, and later 32 bit. There is no standard 64 bit extension.
I wrote intel hex loaders in the old days.
I wrote a simple and overly-permissive one a couple of years ago.
https://github.com/brucehoult/trv/blob/main/trv.c#L55
-
I guess for under 64K payload the base address is 0 (assumed for mcu fw) and you can read each line stand-alone.
-
I guess for under 64K payload the base address is 0 (assumed for mcu fw) and you can read each line stand-alone.
Lots of MCUs have more than 64k of flash. Even the 8 bit 16 MHz ATmega2560 from 2007 has 256k.
-
Yes, of course they do these days. I was just pointing out that Peter wasn't wrong, just an outdated strategy.
-
Two-partition approach also means you don't need to program the flash from the bootloader; you can program from the other app. It is 100% bulletproof and easy to prove as such. The working app never erases itself, so it's always bootable.
My implementation on this is: clear the other partition, write it at any pace you wish, as the last thing write checksum and a "boot counter" which is currently running partition's counter plus 1. After that is done, reset. Then the bootloader logic is simply, "boot the app whose checksum matches the content, and if both are bootable, boot the one with higher counter".
In this approach, bootloader is tiny and trivial, but there are two full set of applications, so available flash effectively halves. This makes sense when the update process is not small or trivial; e.g. it contains full TLS networking stack, which the application uses anyway, so on the app side, the flashing is trivially simple; in the bootloader, it should replicate the whole networking stack. You could do that, and let the application use bootloader's networking stack (you can share the flash, why not), but then you need a way to upgrade that (because it is complex enough it cannot be proven 100% future-proof before the first release), and this just pushes the problem elsewhere: the only 100% reliable way is to duplicate it anyway.
The erase cycle in flashing is relatively long and power consuming. You can't realistically protect it against power loss. And if the whole firmware doesn't fit in RAM at once (as it usually doesn't), you are at the mercy of the upstream system feeding the firmware into your product - that can stall indefinitely or stop working altogether. If you cleared your only working app, any "I have a li-ion battery" doesn't help. So, if you care about product not getting bricked, dual apps or a fully independent bootloader which can do the retry.
Sometimes you will see magical thinking happening: claims of easy wins without duplicating everything, but usually there is a hole somewhere, or some amount of risk. Full duplication of the the whole app is the only obviously 100% bullet-proof when the flashing stack is large. Some people find that adding a physically separate flash chip is somehow easier for them to understand, but I find that weird. Partitioning the internal flash is always the simplest, and external chip makes sense when the otherwise good-fit MCU is already maxed out, and a larger-flash model series is significantly more expensive, complicated or weird than adding the external chip. Rarely so, unless the application is huge (e.g., high resolution graphics for UI).
I wrote a quite similar one, except that the bootloader always checks the second partition first, and if there's a valid image, it always copies that to the first partition and then erase the second partition. So you get atomic and consistent updates, while the program always executes from the same position (easier to build/debug).
-
Two-partition approach also means you don't need to program the flash from the bootloader; you can program from the other app. It is 100% bulletproof and easy to prove as such. The working app never erases itself, so it's always bootable.
My implementation on this is: clear the other partition, write it at any pace you wish, as the last thing write checksum and a "boot counter" which is currently running partition's counter plus 1. After that is done, reset. Then the bootloader logic is simply, "boot the app whose checksum matches the content, and if both are bootable, boot the one with higher counter".
In this approach, bootloader is tiny and trivial, but there are two full set of applications, so available flash effectively halves. This makes sense when the update process is not small or trivial; e.g. it contains full TLS networking stack, which the application uses anyway, so on the app side, the flashing is trivially simple; in the bootloader, it should replicate the whole networking stack. You could do that, and let the application use bootloader's networking stack (you can share the flash, why not), but then you need a way to upgrade that (because it is complex enough it cannot be proven 100% future-proof before the first release), and this just pushes the problem elsewhere: the only 100% reliable way is to duplicate it anyway.
The erase cycle in flashing is relatively long and power consuming. You can't realistically protect it against power loss. And if the whole firmware doesn't fit in RAM at once (as it usually doesn't), you are at the mercy of the upstream system feeding the firmware into your product - that can stall indefinitely or stop working altogether. If you cleared your only working app, any "I have a li-ion battery" doesn't help. So, if you care about product not getting bricked, dual apps or a fully independent bootloader which can do the retry.
Sometimes you will see magical thinking happening: claims of easy wins without duplicating everything, but usually there is a hole somewhere, or some amount of risk. Full duplication of the the whole app is the only obviously 100% bullet-proof when the flashing stack is large. Some people find that adding a physically separate flash chip is somehow easier for them to understand, but I find that weird. Partitioning the internal flash is always the simplest, and external chip makes sense when the otherwise good-fit MCU is already maxed out, and a larger-flash model series is significantly more expensive, complicated or weird than adding the external chip. Rarely so, unless the application is huge (e.g., high resolution graphics for UI).
I wrote a quite similar one, except that the bootloader always checks the second partition first, and if there's a valid image, it always copies that to the first partition and then erase the second partition. So you get atomic and consistent updates, while the program always executes from the same position (easier to build/debug).
Updates are as "consistent" and "atomic" either way, so really the only difference is, you don't have to link two copies of the application, and either supply them both during update (and have the firmware ignore one of them), or communicate which version is desired (this is what we do - there is continuous data flow from the device anyway, so whether it's now running "A" or "B" image is a single bit, so server can choose whether to send B or A for the update). And linking two versions is just two linker scripts and two calls to the linker. Another option would be position-independent code but that would have some downsides (slightly bigger code for example).
Your way has a downside that the boot-after-update is slower, but usually that would not matter. Also flash endurance is halved compared to my solution since every update involves two erases and writes. Doesn't matter either, so really either way is fine and it's up to preference / whichever you happened to choose originally.
-
One guy I've met (not on here AFAIK) did a design with a 2nd (simple) CPU which programs the FLASH in the main CPU, saying that this was the only way to provably make the product brick-safe.
I doubt that is actually correct, so there may have been something else...
Surely a product is brick-safe if there is a "boot block" which is never reprogrammed. That is how I've done my 32f4xx stuff. Bottom 32k is not touched (except, in general, when working with a debugger, when the entire ELF file gets written, obviously). There is a way to OTA write the whole lot and then you have a "brick window" which is just the programming time of that 32k (actually two 16k blocks but since the code is close to 16k I used 32k), which IIRC is around 300ms. The running code is in RAM and will retry a few times. You would need to be extraordinarily unlucky.
-
One guy I've met (not on here AFAIK) did a design with a 2nd (simple) CPU which programs the FLASH in the main CPU, saying that this was the only way to provably make the product brick-safe.
Of course not. Both my and gspeed's solutions are provably brick safe. They are very simple to reason about and prove: the application never ever writes over itself, or over its boot metadata, or the bootloader. As such, the running application always remains bootable: all parts that participate in booting the app, and the app itself, are untouched. Q.E.D., end of story. The cost is needing flash for two copies. That is what buys the non-brickage. The advantage in what I described is the absurdly simple bootloader which is so small that it's easy to reason about and prove good.
A multi-MCU solution for something which doesn't need it is a surefire way to increase complexity, and generally adding unnecessary complexity in something where you want to prove reliability isn't a very good idea.
-
Two-partition approach also means you don't need to program the flash from the bootloader; you can program from the other app. It is 100% bulletproof and easy to prove as such. The working app never erases itself, so it's always bootable.
My implementation on this is: clear the other partition, write it at any pace you wish, as the last thing write checksum and a "boot counter" which is currently running partition's counter plus 1. After that is done, reset. Then the bootloader logic is simply, "boot the app whose checksum matches the content, and if both are bootable, boot the one with higher counter".
In this approach, bootloader is tiny and trivial, but there are two full set of applications, so available flash effectively halves. This makes sense when the update process is not small or trivial; e.g. it contains full TLS networking stack, which the application uses anyway, so on the app side, the flashing is trivially simple; in the bootloader, it should replicate the whole networking stack. You could do that, and let the application use bootloader's networking stack (you can share the flash, why not), but then you need a way to upgrade that (because it is complex enough it cannot be proven 100% future-proof before the first release), and this just pushes the problem elsewhere: the only 100% reliable way is to duplicate it anyway.
The erase cycle in flashing is relatively long and power consuming. You can't realistically protect it against power loss. And if the whole firmware doesn't fit in RAM at once (as it usually doesn't), you are at the mercy of the upstream system feeding the firmware into your product - that can stall indefinitely or stop working altogether. If you cleared your only working app, any "I have a li-ion battery" doesn't help. So, if you care about product not getting bricked, dual apps or a fully independent bootloader which can do the retry.
I wrote a quite similar one, except that the bootloader always checks the second partition first, and if there's a valid image, it always copies that to the first partition and then erase the second partition. So you get atomic and consistent updates, while the program always executes from the same position (easier to build/debug).
Typically I implement something similar. The uploaded firmware image goes into the 2nd half of the flash. The bootloader can then verify the image for integrity and suitability and if those check out, the image is unpacked (decrypted) and programmed into the application flash area. For a more complex system I implemented a central file server style unit (with external flash) which can distribute firmware images to various modules while supporting different hardware types and versions as well. For this the firmware images not only contain a version but also a hardware ID and version.
-
Two-partition approach also means you don't need to program the flash from the bootloader; you can program from the other app. It is 100% bulletproof and easy to prove as such. The working app never erases itself, so it's always bootable.
My implementation on this is: clear the other partition, write it at any pace you wish, as the last thing write checksum and a "boot counter" which is currently running partition's counter plus 1. After that is done, reset. Then the bootloader logic is simply, "boot the app whose checksum matches the content, and if both are bootable, boot the one with higher counter".
In this approach, bootloader is tiny and trivial, but there are two full set of applications, so available flash effectively halves. This makes sense when the update process is not small or trivial; e.g. it contains full TLS networking stack, which the application uses anyway, so on the app side, the flashing is trivially simple; in the bootloader, it should replicate the whole networking stack. You could do that, and let the application use bootloader's networking stack (you can share the flash, why not), but then you need a way to upgrade that (because it is complex enough it cannot be proven 100% future-proof before the first release), and this just pushes the problem elsewhere: the only 100% reliable way is to duplicate it anyway.
The erase cycle in flashing is relatively long and power consuming. You can't realistically protect it against power loss. And if the whole firmware doesn't fit in RAM at once (as it usually doesn't), you are at the mercy of the upstream system feeding the firmware into your product - that can stall indefinitely or stop working altogether. If you cleared your only working app, any "I have a li-ion battery" doesn't help. So, if you care about product not getting bricked, dual apps or a fully independent bootloader which can do the retry.
I wrote a quite similar one, except that the bootloader always checks the second partition first, and if there's a valid image, it always copies that to the first partition and then erase the second partition. So you get atomic and consistent updates, while the program always executes from the same position (easier to build/debug).
Typically I implement something similar. The uploaded firmware image goes into the 2nd half of the flash. The bootloader can then verify the image for integrity and suitability and if those check out, the image is unpacked (decrypted) and programmed into the application flash area. For a more complex system I implemented a central file server style unit (with external flash) which can distribute firmware images to various modules while supporting different hardware types and versions as well. For this the firmware images not only contain a version but also a hardware ID and version.
The safety against brickage here comes from the fact that the validity checks are simple enough to prove obviously deterministic. If the flashing fails e.g. due to power interruption, then it simply restarts again, until it succeeds and application boots. The bootloader is slightly more complex than in my example, but still very simple and obvious.
In other words:
Anything invalid in input data -> erase never starts, old app always intact
Input data considered valid -> erase starts, but input data itself is never touched
If erase/write fails -> same input data, same outcome, retry guaranteed.
-
The bootloader can then verify the image for integrity and suitability and if those check out, the image is unpacked (decrypted) and programmed into the application flash area.
How the hell a bootloader can verify stability of a packed image?
-
The bootloader can then verify the image for integrity and suitability and if those check out, the image is unpacked (decrypted) and programmed into the application flash area.
How the hell a bootloader can verify stability of a packed image?
By reading or unpacking the headers (which are signed as well) and checking if the image is suitable for use. Keep in mind that cyphers used for encrypting data are typically block cyphers so you can do a partial decryption and read data into RAM.
-
Not doing block chaining does reduce security but it's a pointless argument in practice for this type of application.
-
Not doing block chaining does reduce security but it's a pointless argument in practice for this type of application.
No, you really need to use a block chain based cypher like AES-CBC to encrypt firmware (or any other data). Otherwise the encryption is pretty much useless.
-
Not sure about useless, but the same plaintext block produces the same ciphertext block, so you can pretty much tell the size of the image, but with AES there is no known attack even if not using CBC.
-
Not sure about useless, but the same plaintext block produces the same ciphertext block, so you can pretty much tell the size of the image, but with AES there is no known attack even if not using CBC.
You think there is no known attack... I've been digging a bit deeper a while ago and there are some concepts floating around about doing so called plaintext attacks to AES. Using CBC adds an extra unknown to the equation.
-
There is no published attack for the full-round AES.
Also with CBC the first block still looks the same, and since there is likely to be the jump table there, you have a bit of plausible known plaintext to work on.
One could add some "salt" into it to make it harder but I really think that in the context of boot loaders, firmware OTA, etc, and that EU regulation (actual or the intent) this is way off reality.
It will be easier to break the RDP security. I reckon it is breakable on nearly all MCUs already, and anyway there are firms which will decapsulate the package and read out the FLASH directly. But again the EU reg cannot be aimed at this because every "industrial grade" chip is vulnerable. Only specialised smartcard type chips have any hope.
-
There is no known attack for AES because detecting similarity of repeated messages and figuring out what they mean is not considered a cipher weakness, even if it means revealing the plaintext and as such it's still a very real shortcoming. This is exactly why counter mode or CBC have been invented - simply put, the message is modified before encryption so that similar repeated messages appear different every time. Same concept applies to any cipher with any amount of strength. So AES is good, but AES alone doesn't mean secure transport of the messages.
I don't know how relevant this is for firmware signing or firmware leakage protection. Some wiser than me could tell.
-
You think there is no known attack... I've been digging a bit deeper a while ago and there are some concepts floating around about doing so called plaintext attacks to AES. Using CBC adds an extra unknown to the equation.
Every little thing you do increases the attack surface. CBC, for example, may open up a way for oracle attacks. Xilinx 7-series bitstream AES encryption has been broken that way - because they used CBC in a wrong way:
https://www.usenix.org/system/files/sec20fall_ender_prepub.pdf (https://www.usenix.org/system/files/sec20fall_ender_prepub.pdf)
-
You think there is no known attack... I've been digging a bit deeper a while ago and there are some concepts floating around about doing so called plaintext attacks to AES. Using CBC adds an extra unknown to the equation.
Every little thing you do increases the attack surface. CBC, for example, may open up a way for oracle attacks. Xilinx 7-series bitstream AES encryption has been broken that way - because they used CBC in a wrong way:
https://www.usenix.org/system/files/sec20fall_ender_prepub.pdf (https://www.usenix.org/system/files/sec20fall_ender_prepub.pdf)
To be fair, if I read that correctly, the failed CBC means a failed CBC, no more - having no CBC wouldn't have been any better, but even worse (easier attack). So it's not like adding a necessary feature added any surface area for attacks, just that there was a hole in it, so it didn't protect what it was designed to protect.
But it does demonstrate that security is hard, as we all know.
-
Security is hard to do right but also any scheme to prevent malicious firmware loading will fail if the RDP security of the CPU can be broken. Which pretty much means that the vast majority of CPU/MCU chips in common use are useless.
Unless the EU reg discussed just requires "due diligence" and carries no strict liability on the mfg if a 3rd party breaks RDP.
Since this is well off topic for the OP's question, I started a thread here:
https://www.eevblog.com/forum/microcontrollers/eu-cyber-regulation-and-secure-firmware-updates-mandatory/ (https://www.eevblog.com/forum/microcontrollers/eu-cyber-regulation-and-secure-firmware-updates-mandatory/)
-
There is no published attack for the full-round AES.
Also with CBC the first block still looks the same, and since there is likely to be the jump table there, you have a bit of plausible known plaintext to work on.
No. Because with CBC the first block is random garbage. And this random garbage is then used to obscure the first block of the payload and this ripples through all the way to the end. If you encrypt a file with all zeros usin plain AES, you'll get a repeating pattern every 16 bytes. With AESCBC you get an extra 16 random bytes at the start and the rest are non-repeating 16 bytes blocks. In theory AES is designed so you can't extract the key if you know the original data. But every theory lasts until proven otherwise... Quantum computing and/or AI may help come up with something clever. Where CBC gets it's strength from is that the encrypted data is obscured by random data. So even if you know the original data, you don't know the random data. To know the random data, you need the key. This creates a much harder to crack chicken & egg problem compared to reverting encrypted known data into a key.
-
You think there is no known attack... I've been digging a bit deeper a while ago and there are some concepts floating around about doing so called plaintext attacks to AES. Using CBC adds an extra unknown to the equation.
Every little thing you do increases the attack surface. CBC, for example, may open up a way for oracle attacks. Xilinx 7-series bitstream AES encryption has been broken that way - because they used CBC in a wrong way:
https://www.usenix.org/system/files/sec20fall_ender_prepub.pdf (https://www.usenix.org/system/files/sec20fall_ender_prepub.pdf)
To be fair, if I read that correctly, the failed CBC means a failed CBC, no more - having no CBC wouldn't have been any better, but even worse (easier attack). So it's not like adding a necessary feature added any surface area for attacks, just that there was a hole in it, so it didn't protect what it was designed to protect.
But it does demonstrate that security is hard, as we all know.
In this particular case, the attack wouldn't be possible if Xilinx didn't use CBC.
Of course, it is also possible that other circumstances may exist where there would be a successful attack on non-CBC AES. It is also entirely possible that such an attack may have been prevented with using CBC.
Security is about identifying possible attacks and making them impossible, not about using prescribed allegedly "secured" methods.
-
Both my and gspeed's solutions are provably brick safe
I guess this assumes the latest firmware update contains a flawless app, and although the bootloader is choosing the latest valid version like is should, if that firmware for example had a flaw which prevented loading the next firmware update then you are stuck running that version and there is now no way to update firmware.
If I understand this update process correctly.
I would probably not consider something brick safe if I could write the app in a way which would prevent further updates. If you can intentionally write the app in such a way to cause a problem, you can do so unintentionally also. Giving the bootloader the ability to also do firmware updates if needed would at least allow for a way to recover from this type of problem.
-
I would argue that it should be possible to replace the entire firmware including the boot block, but the distributed firmware should not touch the boot block.
That way you protect the large business risk, while also protecting the hopefully much smaller (but much more expensive if triggered) business risk of having a crippled boot block.
It's mainly about risk management, not "technology". For example you may choose to not offer upgrades to a large customer, because a mistake could sink your business. The place to roll out updates, at least initially, is to a small customer in the Peoples' Republic of Upper Volta ;)
-
For example you may choose to not offer upgrades to a large customer, because a mistake could sink your business. The place to roll out updates, at least initially, is to a small customer in the Peoples' Republic of Upper Volta ;)
Or you may decide not to offer upgrades at all, which in itself offers lots of benefits.
-
Both my and gspeed's solutions are provably brick safe
I guess this assumes the latest firmware update contains a flawless app, and although the bootloader is choosing the latest valid version like is should, if that firmware for example had a flaw which prevented loading the next firmware update then you are stuck running that version and there is now no way to update firmware.
You are right, I was fixated on the safety of the update process itself, e.g. against power loss at any timing, corruption while writing. That is easy to prove. Old app always stays bootable, but if new app also becomes bootable and prevents entering the update process, the the device is effectively bricked, even if it technically runs a valid application.
To protect from this, some sort of "boot the old app" signal to the bootloader helps, but doesn't guarantee anything - a more subtle flaw that allows one update more to succeed would wipe the old, working app. So would a new update operation which starts (erases) but never finishes.
The only flawless version is that bootloader itself is the one which receives and does the update, which doesn't happen in either mine or gpseed's or nctnico's examples. If the update interface is simple, say, UART, then it's obvious to do it like this. But if it's like in our case, that the firmware connects to the production server through TLS authentication&encryption, and updates are served through the same path, then that would mean bootloader needs to do all of that. Fair enough, it could do it, and the app would reuse the same networking code to avoid wasting flash in duplicated code. But then the question of updating the bootloader arises. Sooner or later the TLS / networking code needs an update, and that means the bootloader needs to be updateable, which means same A/B concept for the bootloader, which means the same risk of putting technically correct but functionally broken code in place we just discussed. We just changed names of parts (app -> bootloader), not the actual structure.
There is silver lining through: this risk of "broken update" can be mitigated by good testing. Test well before releasing. Release in waves with canaries. This is what we do. Final simple test that after update and wait of a few days, another new update passes, in different device configurations.
Testing doesn't help if the flashing process physically is sensitive to power loss or data corruption, though. Which makes these two failure modes different. It's inexcusable to have an update process which bricks the device on power loss in 2026, in my mind.
-
Or you may decide not to offer upgrades at all, which in itself offers lots of benefits.
Indeed, although the capability to do so, even if not publicised, gives you a lot of business risk insurance. The cost of scrapping a lot of units could be astronomical, and the cost of the same at a customer's is even higher :)
We have numerous OTA threads e.g.
https://www.eevblog.com/forum/microcontrollers/stm-32f4xx-what-hacks-are-known-around-level-2-security/msg5605715/#msg5605715 (https://www.eevblog.com/forum/microcontrollers/stm-32f4xx-what-hacks-are-known-around-level-2-security/msg5605715/#msg5605715)
Unless you are selling phones or similar, OTA is largely a business risk limitation exercise. You are not some crook so you won't be knowingly selling non-working junk, so updating is largely about critical bug fixing.