How do you make a firmware image position independent or relocatable?
Short answer: Compile with position-independent options (-fPIC/-fpie, or on Cortex-M -fropi/-frwpi with Arm Compiler, or GCC's -msingle-pic-base -mpic-register=r9 -mno-pic-data-is-text-relative for separate data), so code uses PC-relative addressing and data is reached through a base register or a global offset table (GOT) that is fixed up at load time. In practice most MCU firmware is linked at a fixed address, and bootloaders support multiple images with fixed slots or by swapping images rather than relocating them.
Why it is hard on MCUs
- Function pointers, the vector table and any initialised pointer in
.datacontain absolute addresses that must be patched if the image moves. - Without an MMU there is no virtual address trick to make the image appear at its link address.
- Position-independent code is slightly larger and slower (extra indirections through the GOT).
Common strategies for firmware updates
| Strategy | How | Trade-off |
|---|---|---|
| Fixed single slot + recovery bootloader | bootloader overwrites the app in place | no rollback if the update fails mid-way, unless the bootloader can always re-download |
| Two slots, image linked for slot A only, swap | MCUboot copies/swaps the new image from slot B into slot A (using a scratch area), with revert support | needs time and flash wear for the swap |
| Two slots, two builds | build the same firmware twice, linked for each slot; the bootloader runs whichever is valid | the update server must deliver the right build for the inactive slot |
| Execute-in-place from external flash with address remapping | some MCUs (e.g. with OTFDEC/remap registers, or nRF/ESP32 flash mapping/MMU) map either slot to the same execution address | needs hardware support |
| Real PIC | -fpie + loader fix-ups (as in Zephyr's LLEXT, or loadable modules) |
complexity and size |
What the bootloader must do for any non-default location: set SCB->VTOR to the application's vector table, which must be suitably aligned, before jumping (next question).