Files
PX4-Autopilot/Tools/prepend_bootloader.py
Jacob Dahl de52c98eff feat(cannode): bootloader update from the app and combined flash image (#28293)
* feat(bl_update): pet the watchdog during erase and program

CAN nodes start the IWDG in the bootloader, and nothing else pets it
while bl_update holds the scheduler lock.

Assisted-by: Claude:claude-opus-5-5

* feat(nuttx): emit canbootloader to board extras and build bootloader+app image

canbootloader builds now write extras/<vendor>_<board>_bootloader.bin
like FMU bootloader builds do, which plugs CAN nodes into the existing
ROMFS / rc.board_bootloader_upgrade / jlink wiring. CAN node app builds
with that file also emit <config>_with_bootloader.bin (bootloader padded
to the app's ELF load address, followed by the CRC'd image) so a bare
board is flashed in one SWD step instead of two.

Assisted-by: Claude:claude-opus-5-5

* feat(cannode): run rc.board_bootloader_upgrade at startup

The hook was only wired into the FMU rcS, so SYS_BL_UPDATE did nothing
on CAN nodes even with bl_update built in.

* feat(ark): enable bootloader update on CAN nodes

Ships the CAN bootloader in the app ROMFS so a node can rewrite it via
SYS_BL_UPDATE without SWD.

Assisted-by: Claude:claude-opus-5-5

* docs(dronecan): bootloader update and combined image for CAN nodes

Assisted-by: Claude:claude-opus-5-5

* build(ark): rebuild CAN node bootloaders from current main

The committed binaries predated the F412 chip-selection and linker fixes
and the NuttX 12.12 upgrade, so they no longer matched the source.

Assisted-by: Claude:claude-opus-5-5

* feat(uavcannode): update the bootloader as soon as SYS_BL_UPDATE is set

Same approach as AP_Periph. Running the update on the next boot needed
two reboots and reported nothing over CAN: it ran before uavcannode
started, and the boot script printed "done" even when bl_update failed.
The node now flashes while running, skips an identical bootloader, and
the result reaches the flight controller through the existing log
message forwarding. A value left set from before boot is cleared rather
than acted on.

The flash routine moves into a library so uavcannode can call it.

Assisted-by: Claude:claude-opus-5-5

* docs(dronecan): note that the combined CAN node image resets parameters

Found on the bench: the padding between bootloader and app covers the
parameter sectors, so every SWD flash of the combined image erases them.

Assisted-by: Claude:claude-opus-5-5

* fix(nuttx): limit CAN bootloader extras and combined image to STM32

Every canbootloader build wrote its binary to the board's extras, so a
later nxp_ucans32k146 default or cyphal configure picked it up and failed
in prepend_bootloader.py: the S32K application loads at 0x6000, below
the 0x08000000 base the script and bl_update assume. CI only passed
because the canbootloader was built after both had configured.

Assisted-by: Claude:claude-fable-5-1

* fix(bl_update): pad the image before erasing and warn on every flash failure

The STM32F4 up_progmem_write() returns -EINVAL for an odd byte count,
which was only found out after sector 0 had been erased. An erase or
program failure also leaves the board without a bootloader, but only a
verify failure told the user to retry before rebooting.

Assisted-by: Claude:claude-fable-5-1

* fix(romfs): pack rc.board_bootloader_upgrade only where rcS runs it

CAN nodes with bl_update carried the script in their ROMFS although the
cannode rcS never sources it: uavcannode flashes the bootloader itself.

Assisted-by: Claude:claude-fable-5-1

* refactor(bl_update): move the flash routine to src/lib

The library lived under systemcmds, which is configured after drivers,
so uavcannode could only link it through a forward reference. The
watchdog is now selected by chip because the platform targets do not
exist yet when src/lib is configured.

Assisted-by: Claude:claude-fable-5-1

* docs(dronecan): the CAN bootloader is written to extras on STM32 only

Assisted-by: Claude:claude-fable-5-1
2026-10-06 15:42:33 -06:00

113 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
############################################################################
#
# Copyright (C) 2026 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# 3. Neither the name PX4 nor the names of its contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
############################################################################
"""
Prepend a bootloader to an application image so the pair can be flashed in
one step at the start of flash (e.g. st-flash write out.bin 0x8000000).
The bootloader is padded with 0xff up to the application's load address,
which is taken from the lowest PT_LOAD segment of the application ELF.
"""
import argparse
import struct
import sys
PT_LOAD = 1
def elf_load_address(path):
with open(path, "rb") as f:
data = f.read()
if data[:4] != b"\x7fELF" or data[4] != 1:
sys.exit(f"{path}: not an ELF32 file")
little = data[5] == 1
e = "<" if little else ">"
(e_phoff,) = struct.unpack_from(e + "I", data, 0x1c)
(e_phentsize, e_phnum) = struct.unpack_from(e + "HH", data, 0x2a)
lowest = None
for i in range(e_phnum):
(p_type, p_offset, p_vaddr, p_paddr, p_filesz) = struct.unpack_from(
e + "IIIII", data, e_phoff + i * e_phentsize)
if p_type == PT_LOAD and p_filesz > 0:
lowest = p_paddr if lowest is None else min(lowest, p_paddr)
if lowest is None:
sys.exit(f"{path}: no loadable segments")
return lowest
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--bootloader", required=True, help="bootloader .bin, placed at --base")
parser.add_argument("--app", required=True, help="application .bin, placed at its ELF load address")
parser.add_argument("--elf", required=True, help="application ELF, used for the load address")
parser.add_argument("--base", type=lambda x: int(x, 0), default=0x08000000,
help="flash address the output is flashed to (default 0x08000000)")
parser.add_argument("--output", required=True)
args = parser.parse_args()
app_address = elf_load_address(args.elf)
app_offset = app_address - args.base
with open(args.bootloader, "rb") as f:
bootloader = f.read()
with open(args.app, "rb") as f:
app = f.read()
if app_offset < 0:
sys.exit(f"application load address 0x{app_address:08x} is below --base 0x{args.base:08x}")
if len(bootloader) > app_offset:
sys.exit(f"bootloader ({len(bootloader)} bytes) overlaps the application at offset 0x{app_offset:x}")
with open(args.output, "wb") as f:
f.write(bootloader)
f.write(b"\xff" * (app_offset - len(bootloader)))
f.write(app)
print(f"{args.output}: bootloader {len(bootloader)} bytes @ 0x{args.base:08x}, "
f"application {len(app)} bytes @ 0x{app_address:08x}")
if __name__ == "__main__":
main()