pureboot v9: seal every command, and stop guarding what the seal covers

'W' handed the loader a whole page with no ack inside it and sp_spm handed any
wire byte to SPMCSR, so a dropped byte re-aligned the stream and page data
arrived where commands belong. That is how a page-address byte became
BLBSET|SELFPRGEN on the tempmon board and programmed its lock bits.

The first answer was to refuse that one command. It was the wrong shape twice
over: it forbade a lock-bit write the owner may want, and it left every other
command decided by bytes nobody checked. v9 checks them instead. One header for
every command — opcode, selector, address, count, seal — folded and compared
before the command is decoded, and *answered* before any payload moves: '+'
accepts, 0xd4 (the ack inverted) refuses and nothing happened. An ack cannot do
this job; it reports a command that has already run.

It is smaller than v8 everywhere: 1284P 506→480, m8 498→480, 328P 484→468,
t13A 474→460. The seal costs 14 bytes; bit opcodes in place of the letters pay
for it twice over, since a letter costs a compare and a branch where a bit costs
a skip. Both guards go — the lock-bit refusal because the seal covers it, the
running-slot write guard because what it defended against was a wire fault
naming an address and a wire fault can no longer name one. That one is a real
trade: a host bug aimed at the running slot now lands. It buys a resident copy
that can write its own slot, which is the only self-update route on a chip whose
boot section *is* the slot.

Two things the tests caught, both introduced here. Removing the invalid-opcode
arm made every byte a command, so the knock stopped being harmless against a
loader already in session and ate the five bytes behind it — identify moves to
bit 5, which both 'p' and 'b' carry, so the knock is inert again and version
discovery still works before the version is known. And the SPM value rides the
count field because a data byte would arrive after the seal was checked.

pbselfwrite and pbglitch are the new gates, both red-green: the same erase of
the running page refused unsealed and performed sealed, and every header byte
damaged after sealing refused where the identical damage before sealing is
obeyed. Both judge by the simulator's flash, not the loader's opinion of it.
pbreloc and pbrehome lose their write-guard probes, which is what those two
gates replace. Defeating the seal in the loader turns seven tests red.

37 of 37 chips green with the exhaustive size matrix; README protocol section
and every size row rewritten. pbhw gains an adversarial --seal-rounds sweep for
the bench.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-01 18:38:41 +02:00
parent eb213e1025
commit 546b1589a3
10 changed files with 761 additions and 213 deletions

View File

@@ -245,6 +245,28 @@ if(PROJECT_IS_TOP_LEVEL)
set_tests_properties(pureboot.reloc PROPERTIES TIMEOUT 180
ENVIRONMENT "PB_OBJCOPY=${CMAKE_OBJCOPY}")
# The seal against the one command that proves it: erasing the page the
# loader runs from, refused unsealed and honoured sealed. Destroys the
# loader by design, so it gets a device of its own.
add_test(NAME pureboot.selfwrite
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/pbselfwrite.py
${PB_DEVICE} $<TARGET_FILE:pureboot> ${PUREBOOT_SIM_MCU} ${_pb_stock_hz}
${PUREBOOT_BASE_HEX} ${PUREBOOT_PAGE} ${_pb_stock_baud}
${CMAKE_CURRENT_SOURCE_DIR}/pureboot/pureboot.py
${CMAKE_BINARY_DIR}/pbselfwrite-work)
set_tests_properties(pureboot.selfwrite PROPERTIES TIMEOUT 180)
# The seal against a link that damages bytes on purpose: every header
# field flipped after sealing must be refused, and the identical flip
# applied before sealing must be obeyed.
add_test(NAME pureboot.glitch
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/pbglitch.py
${PB_DEVICE} $<TARGET_FILE:pureboot> ${PUREBOOT_SIM_MCU} ${_pb_stock_hz}
${PUREBOOT_BASE_HEX} ${PUREBOOT_PAGE} ${_pb_stock_baud}
${CMAKE_CURRENT_SOURCE_DIR}/pureboot/pureboot.py
${CMAKE_BINARY_DIR}/pbglitch-work)
set_tests_properties(pureboot.glitch PROPERTIES TIMEOUT 180)
# Entering the loader from a running application with no reset
# between, over a page buffer the application dirtied — the case the
# loader declines to guard and the host repairs. Hardware forbids the

View File

@@ -8,10 +8,10 @@ erase, reset-vector surgery, updating the loader itself — lives in the host
tool (`pureboot.py`).
The image is **position-independent**: control flow is PC-relative, the
transfer paths take wire addresses, the write guard protects the slot the code
is *running* in (from the runtime return address), nothing else is
flash-resident to address at all, and the application jump is an indirect call
to an absolute entry. The identical binary therefore runs from any slot with
transfer paths take wire addresses, nothing is flash-resident to address at
all, and the application jump is an indirect call to an absolute entry. It does
not know which slot it occupies and does not need to. The identical binary
therefore runs from any slot with
every command intact, which makes pureboot **its own staging loader**: the host
installs the same binary one slot below the resident, jumps into it, and lets
it rewrite the resident. The lint holds it to that literally — the image must
@@ -33,26 +33,26 @@ loaders run 410 B smaller.
| Chip | Flash | Loader at | Link | Stock | Autobaud |
|---|---|---|---|---|---|
| ATtiny13, ATtiny13A † | 1 KiB | 0x0200 | software | 384 B | 474 B |
| ATtiny25 † | 2 KiB | 0x0600 | software | 388 B | 466 B |
| ATtiny45 † | 4 KiB | 0x0e00 | software | 388 B | 466 B |
| ATtiny85 † | 8 KiB | 0x1e00 | software | 388 B | 466 B |
| ATmega8, 8A | 8 KiB | 0x1e00 | USART0 | 362 B | 494 B |
| ATmega16, 16A | 16 KiB | 0x3e00 | USART0 | 364 B | 496 B |
| ATmega32, 32A | 32 KiB | 0x7e00 | USART0 | 364 B | 496 B |
| ATmega48, 48A, 48P, 48PA † | 4 KiB | 0x0e00 | USART0 | 378 B | 468 B |
| ATmega88, 88A, 88P, 88PA | 8 KiB | 0x1e00 | USART0 | 388 B | 478 B |
| ATmega168, 168A, 168P, 168PA | 16 KiB | 0x3e00 | USART0 | 390 B | 480 B |
| ATmega328, 328P | 32 KiB | 0x7e00 | USART0 | 390 B | 480 B |
| ATmega164A, 164P, 164PA | 16 KiB | 0x3e00 | USART0 | 390 B | 480 B |
| ATmega324A, 324P, 324PA | 32 KiB | 0x7e00 | USART0 | 390 B | 480 B |
| ATmega644, 644A, 644P, 644PA | 64 KiB | 0xfe00 | USART0 | 384 B | 474 B |
| ATmega1284, 1284P | 128 KiB | 0x1fe00 | USART0 | 410 B | 502 B |
| ATtiny13, ATtiny13A † | 1 KiB | 0x0200 | software | 372 B | 460 B |
| ATtiny25 † | 2 KiB | 0x0600 | software | 376 B | 452 B |
| ATtiny45 † | 4 KiB | 0x0e00 | software | 376 B | 452 B |
| ATtiny85 † | 8 KiB | 0x1e00 | software | 376 B | 452 B |
| ATmega8, 8A | 8 KiB | 0x1e00 | USART0 | 350 B | 480 B |
| ATmega16, 16A | 16 KiB | 0x3e00 | USART0 | 352 B | 484 B |
| ATmega32, 32A | 32 KiB | 0x7e00 | USART0 | 352 B | 484 B |
| ATmega48, 48A, 48P, 48PA † | 4 KiB | 0x0e00 | USART0 | 366 B | 454 B |
| ATmega88, 88A, 88P, 88PA | 8 KiB | 0x1e00 | USART0 | 376 B | 464 B |
| ATmega168, 168A, 168P, 168PA | 16 KiB | 0x3e00 | USART0 | 378 B | 468 B |
| ATmega328, 328P | 32 KiB | 0x7e00 | USART0 | 378 B | 468 B |
| ATmega164A, 164P, 164PA | 16 KiB | 0x3e00 | USART0 | 378 B | 468 B |
| ATmega324A, 324P, 324PA | 32 KiB | 0x7e00 | USART0 | 378 B | 468 B |
| ATmega644, 644A, 644P, 644PA | 64 KiB | 0xfe00 | USART0 | 372 B | 462 B |
| ATmega1284, 1284P | 128 KiB | 0x1fe00 | USART0 | 390 B | 480 B |
† No hardware boot section: the host patches the reset vector, and the budget
is 510 bytes, since the slot's last word is the trampoline.
The tightest fit in the whole space is therefore the 1284s' 502 of their
The tightest fit in the whole space is therefore the 1284s' 480 of their
512: they alone carry the far-flash machinery (ELPM reads, RAMPZ page
commands) on top of everything the column already stacks. The flash bank
riding in a transfer's selector byte keeps even those chips' addressing the
@@ -223,15 +223,21 @@ no clock to turn into seconds.
## Session
After the knock the loader stays in its command loop until `J` jumps away or
the chip resets. Before reading each command it waits for any pending EEPROM
After the knock the loader stays in its command loop until a jump takes it away
or the chip resets. Before reading each command it waits for any pending EEPROM
write and sends the prompt `+` (0x2b), which is therefore also the previous
command's completion ack. A session is: await `+`, send a command, read its
reply, repeat.
verdict, then its reply, repeat.
There is no invalid opcode: every byte begins a command, and it is the seal
rather than a table of known letters that rejects noise. The knock is the one
thing that must survive being sent into a loader already in session, which is
why both its bytes — `p` and `b` — carry the identify bit: they answer the
identity and consume nothing else.
Addresses are **byte addresses within a 64 KiB bank**, and the bank rides in
the command's selector byte, so no command has to speak word addresses. `J` is
the exception: its address is a word address, because that is what the
the command's selector byte, so no command has to speak word addresses. The jump
is the exception: its address is a word address, because that is what the
hardware's own jump takes — it still carries a selector byte (reserved,
ignored) so its decode is the same three reads as every other command's.
EEPROM and data-space addresses and all counts are bytes.
@@ -243,22 +249,38 @@ low EEPROM and the write silently overwrites it. Keeping transfers within the
real sizes is the host's job (the shipped tool does); the flash budget is
better spent on features than on re-checking a bound the host already holds.
| Cmd | Arguments | Reply |
|---|---|---|
| `b` | — | 4 bytes: the pureboot version, then the three signature bytes |
| `G` | sel8, addr16, n8 | n bytes from the selected space (n = 0 means 256) |
| `g` | sel8, addr16, n8, then n data bytes | `+` per byte, sent once its write has begun |
| `W` | sel8, addr16, then one page of data | — (completion = next prompt) |
| `J` | sel8 (reserved), word address (16-bit) | `+`, then execution continues there |
| other | — | ignored; the loop re-prompts (send a junk byte, await `+`, to resync) |
Every command but the identity has **one header shape** — six bytes, the last
of them a seal over the other five:
`G` and `g` are one letter in two cases, which is the whole command set for
every memory: the **selector** byte's low nibble names the space and its high
nibble carries the flash bank.
```text
op8 sel8 addr_lo8 addr_hi8 n8 seal8
seal = op ^ sel ^ addr_lo ^ addr_hi ^ n ^ 0x5A
```
The loader folds those fields and compares before it decodes what the command
is, then **answers the seal**: `+` accepts, `0xD4` refuses and nothing has
happened. The verdict comes before any payload, which is what keeps a refusal
local — a fill or a write burst sends its data only once the header is in, so
a rejected header never leaves the host pushing bytes into a loader that has
gone back to reading commands.
The opcode is bits, not a letter. A transfer is the absence of the other three,
and its direction is the low bit.
| Opcode | | Arguments after the header | Reply |
|---|---|---|---|
| 0x00 | read | none | verdict, then n bytes from the selected space (n = 0 means 256), then `+` |
| 0x01 | write | n data bytes | verdict, then `+` per byte once its write has begun, then `+` |
| 0x04 | fill | one page of data | verdict, then `+` when the page is in |
| 0x08 | jump | none | verdict, then execution continues at the word address |
| 0x20 | identify | *unsealed, one byte on its own* | 4 bytes: the version, then the three signature bytes, then `+` |
The **selector** byte's low nibble names the space and its high nibble carries
the flash bank.
| Space | | |
|---|---|---|
| 0 | flash | read-only here; it is written through `W` and the SPM space |
| 0 | flash | read-only here; it is written through the fill and the SPM command |
| 1 | EEPROM | |
| 2 | data | SRAM — and with it the register file and every I/O register, which share the data address space on AVR |
| 3 | fuse and lock | index 0..3 in the hardware's own Z order: low, lock, extended, high |
@@ -267,18 +289,26 @@ nibble carries the flash bank.
The data space is worth more than it looks. pureboot keeps **zero static RAM**
and pushes no register, so at loader entry an application's SRAM is still
whatever the application left there, bar the handful of bytes of return-address
stack — which makes `G` over space 2 a post-mortem of a running application,
stack — which makes a read over space 2 a post-mortem of a running application,
not just a poke hole. The same address space carries the register file and the
I/O registers, so peripheral state is readable too; reading some of those has
side effects (reading UDR clears its flags), which is the host's business to
know.
Programming a page is therefore `W` to fill the buffer, then a `g` to the SPM
space for the erase, another for the write, and on a boot-sectioned chip a
third to re-enable the RWW section — `0x03`, `0x05` and `0x11`, the SPMCSR
encodings every part pureboot targets shares. The loader carries no page-commit
logic of its own, and the same primitive reaches every other SPM operation,
lock bits included.
Programming a page is therefore a fill to load the buffer, then an SPM command
for the erase, another for the write, and on a boot-sectioned chip a third to
re-enable the RWW section — `0x03`, `0x05` and `0x11`, the SPMCSR encodings
every part pureboot targets shares. The loader carries no page-commit logic of
its own, and the same primitive reaches every other SPM operation, lock bits
included.
An SPM command has **no data phase**: its SPMCSR byte rides the header's count
field, where the seal covers it. That is the whole reason the field is
overloaded — a byte arriving behind the header would arrive after the seal had
been checked, and the one command that cannot be taken back is exactly the one
that must not be decided by an unchecked byte. Setting the lock bits is
therefore an ordinary sealed command (`0x09`) rather than something the loader
refuses: deliberate is expressible, accidental is not reachable.
The SPM store and the SPM instruction must issue within four cycles of each
other (§26.2), which no host can hit across a serial link — so this one
@@ -286,11 +316,21 @@ primitive is *fused* rather than being a poke of SPMCSR followed by a poke of
something else. That four-cycle window is the floor on how low-level a
bootloader's primitives can go; it is not a byte-count decision.
An SPM command aimed at the 512-byte slot the loader is **running in** is
dropped, so a broken host cannot brick the running copy, while a staged copy
one slot lower may rewrite the resident — which is what a self-update is.
Nothing refuses an address, the loader's own slot included. Through pureboot 8
a running-slot write was dropped; the seal replaced that guard, because what
the guard defended against was a wire fault naming an address, and a wire fault
can no longer name one. What it costs is that a host bug aimed at the running
slot now lands. What it buys is that a resident copy can write its own slot —
which is the only route a self-update has on a chip whose boot section *is* the
512-byte slot, where no staged copy can run SPM at all: the resident plants a
primitive in its own spare space and an application-side installer drives it.
A copy that erases the page it is executing from does not come back, so which
page matters; erasing any other page of its own slot it survives. That needs a
page the image does not reach into, which the stock builds have and the biggest
do not: a 378 B loader on a 128-byte-page mega leaves 384..511 entirely free,
while the 480 B autobaud build reaches into it and has none.
The loader never clears the SPM buffer before a fill, so **one `W` may program
The loader never clears the SPM buffer before a fill, so **one fill may program
the wrong bytes, and the host is what fixes it**. The buffer is write-once per
word until cleared, and two things leave words in it: a refused page, and —
where SPM runs from anywhere, the tinies and the m48s — an application that
@@ -300,15 +340,15 @@ the tinies), so repeating it programs correctly. The host therefore verifies
every page it writes and rewrites what comes back wrong (three retries, then it
stops).
`g` is host-paced: send the next byte only after the previous byte's `+`. Fuse
A write is host-paced: send the next byte only after the previous byte's `+`. Fuse
*writing* does not exist — SPM reaches flash and boot lock bits only.
`J` is the one control-transfer primitive: it runs the application (word 0 or
The jump is the one control-transfer primitive: it runs the application (word 0 or
the trampoline word, both derived from the chip) and moves between loader
copies during a self-update. A jump to a slot's base re-enters that copy's own
startup, which must then be knocked afresh.
`b` answers with the loader's identity — its version and the chip's signature —
Identify answers with the loader's identity — its version and the chip's signature —
and nothing else. Everything else the host needs (page size, loader base,
EEPROM size, whether the reset vector must be patched, how many flash banks)
follows from the signature, and the host holds that table; the loader derived
@@ -323,7 +363,7 @@ to install a mismatch against.
## Version
`b`'s first byte is the **pureboot version** — the loader's one identity
The identity's first byte is the **pureboot version** — the loader's one identity
number, and the only way to tell what a deployed loader is. Nothing else is
numbered: the wire protocol has no version, a pureboot version implies it, and
the host tool holds that map. The tool states the window of loader versions it
@@ -347,7 +387,14 @@ nothing on the wire either: it marks the builds whose deployment may be
one-wire (*One-wire* above) — the hardware USART's half-duplex turn-around,
or a software link folded onto a single pin. The host-side trace is
`--one-wire`, the echo discard a shared line requires of any tool driving
it.
it. **9** is the third wire change and the largest: bit opcodes in place of
the letters, one sealed header shape for every command, and a verdict on that
seal before the command runs (*Session* above). It also drops the
running-slot write guard, which the seal makes redundant and which was the
only thing standing between a resident copy and its own slot. Identify is
answered by both knock bytes so version discovery works before the version is
known, which is what keeps a deployed pureboot 8 drivable and self-updatable
to 9.
Every closed generation is tagged in this repo at its era's last commit — the
commit just before the next version bump, so a tag holds everything its
@@ -464,7 +511,7 @@ are interchangeable — as the silicon is.
the host composes the slot's last word as a jump to the resident base, so
even an abandoned staging copy times out into a loader. A loader already
sitting whole in the staging slot is left as the staging copy instead —
rewriting it would only meet its own running-slot guard.
rewriting it in place would be a copy overwriting itself as it runs.
3. `J` enters the staging copy, which rewrites the resident slot. Where a
patched reset vector routes through the resident, the host first re-aims
word 0 at the staging copy, so a power loss mid-rewrite still resets into a
@@ -502,7 +549,7 @@ update, flash (erase / program / read / verify), EEPROM (the same), then
`--peek`/`--poke` — then the loader hands over to the application. `--stay` keeps the session alive
instead, and a later invocation reconnects into it. `--flash` and `--eeprom`
verify by read-back unless `--no-verify`, and a flash page that reads back
wrong is rewritten up to three times before the run stops (see `W` above).
wrong is rewritten up to three times before the run stops (see the fill above).
`--verify-flash` only reports. Images are raw binary, or Intel HEX by
extension. `--force` overrides the refusable safety checks — today, flashing
application data into a mega's reset walk region.

View File

@@ -4,11 +4,12 @@
// reset-vector surgery, self-update) lives in the host tool. Protocol,
// deployment and configuration: README.md next to this file.
//
// The image is position-independent — PC-relative control flow, wire
// addresses in, the write guard and the info block both anchored on the
// runtime return address — so the identical binary runs from any slot. That
// is what makes a copy one slot below able to rewrite the resident one, and
// every change here has to keep it (test/check_pi.py).
// The image is position-independent — PC-relative control flow and wire
// addresses in, no absolute address formed anywhere — so the identical binary
// runs from any slot. That is what makes a copy one slot below able to rewrite
// the resident one, and every change here has to keep it (test/check_pi.py).
// It does not need to know *which* slot it is in: nothing here refuses an
// address, so there is no running-slot comparison to anchor.
#include <chrono>
@@ -26,6 +27,37 @@ constexpr auto off = avr::irq::guard_policy::unused;
constexpr std::uint8_t ack = '+';
// The refusal, which is the ack inverted: on a link whose whole problem is
// flipped bits, the byte saying "nothing happened" should be as far as a byte
// can be from the one saying "it did", and the complement is all eight bits.
// It is also the only spelling that needs no justifying — every other value
// would be a choice.
constexpr std::uint8_t nak = static_cast<std::uint8_t>(~ack);
// What a command's fields must fold to. Any non-zero constant does: zero is
// what a run of one repeated byte folds to, and a repeated byte is the shape of
// both a line stuck at a level and a page of erased flash arriving where a
// header belongs.
constexpr std::uint8_t seal = 0x5a;
// The opcode, as bits rather than letters. Each is a one-instruction skip,
// where a set of arbitrary values costs a compare and a branch apiece — and
// with the seal deciding what is a command at all, there is nothing left for a
// readable spelling to buy. A transfer is the absence of the other three, and
// its direction is the low bit.
//
// Identify is bit 5 for one reason: 'p' and 'b' both carry it, and those are
// the knock. Two things follow that no other assignment gives. A host cannot
// know which generation it is talking to until something has answered, so the
// command reporting the version has to mean the same thing before the version
// is known — 'b' still asks it. And a knock aimed at a loader that is
// *already* in session has to stay harmless: with no opcode reserved as
// invalid, every byte now starts a command, so a knock that meant nothing to
// earlier generations would otherwise consume the five header bytes behind it
// and put the stream out of step. Answering both knock bytes with the identity
// keeps the reconnect exactly as cheap as it was.
enum : std::uint8_t { op_write = 1, op_fill = 4, op_jump = 8, op_identify = 0x20 };
// Deployment parameters come from the build (pureboot_add_loader()). The
// signature is not one of them: the chip database is the only universal
// source — a tiny13A cannot read its own signature row from code. An autobaud
@@ -43,8 +75,8 @@ constexpr avr::baud_t wire_baud{PUREBOOT_BAUD};
// The loader owns the top 512 bytes; a staging copy goes in the slot below.
// Chips without a hardware boot section — the tinies and the m48s, whose SPM
// runs from anywhere (Atmel-8271 §26) — keep the application's relocated
// reset vector in the word under the slot.
constexpr std::uint16_t slot_bytes = 512;
// reset vector in the word under the slot. The size itself is the linker's and
// the host's business: nothing in here needs to know where the slot ends.
constexpr std::uint16_t page = spm::page_bytes;
constexpr bool boot_section = avr::hw::curated::has_boot_section();
@@ -77,7 +109,7 @@ static_assert(PUREBOOT_OSCCAL >= 0 && PUREBOOT_OSCCAL <= 0xff, "PUREBOOT_OSCCAL
// The loader's one identity number. The protocol carries none of its own —
// a version implies it, and the host tool holds that map (README.md).
constexpr std::uint8_t version = 8;
constexpr std::uint8_t version = 9;
// The image's identity stamp, for the host tool rather than for the wire: an
// update image is a bare 512-byte slot, and without this nothing in it says
@@ -105,12 +137,18 @@ constexpr std::uint8_t stamp_identity = 2;
// The address spaces a transfer can name, in a selector byte's low nibble.
// Flash is 0 so it is the cheapest to select.
//
// spm_ops is the one that is not memory: a write there hands its byte to
// spm_ops is the one that is not memory: naming it hands the count field to
// SPMCSR and fires the instruction at the transfer's address, which is how
// page erase, page write and RWW re-enable reach the wire without the loader
// carrying a command for each. The hardware's four-cycle store-to-SPM window
// is why this is one fused primitive and not a poke of SPMCSR — no host can
// hit that window across a serial link.
//
// It is the one space with no direction: the opcode's write bit is not
// consulted, because a sealed command naming this space says what it means and
// there is nothing for the other direction to denote. Testing the bit anyway
// would cost six bytes to catch a host contradicting itself, which is the same
// trade the running-slot guard lost.
enum : std::uint8_t { sp_flash = 0, sp_eeprom = 1, sp_data = 2, sp_fuse = 3, sp_spm = 4 };
// A selector's high nibble is the flash bank — the address bits above the
@@ -128,22 +166,6 @@ enum : std::uint8_t { sp_flash = 0, sp_eeprom = 1, sp_data = 2, sp_fuse = 3, sp_
return static_cast<std::uint8_t>(selector >> 4);
}
// The slot a flash address falls in, as one byte. A slot is half as many words
// as bytes, so the word address's high byte is exactly this index — which is
// what lets the write guard compare a single byte, and what the running copy's
// own return address yields for free.
constexpr std::uint8_t slot_shift = std::countr_zero(slot_bytes);
constexpr std::uint8_t bank_shift = 16 - slot_shift;
[[gnu::always_inline]] inline std::uint8_t slot_of([[maybe_unused]] std::uint8_t bank, std::uint16_t at)
{
const auto within = static_cast<std::uint8_t>(at >> slot_shift);
if constexpr (banked_flash)
return static_cast<std::uint8_t>((bank << bank_shift) | within);
else
return within;
}
// The serial link, per the build's PUREBOOT_USART / PUREBOOT_SOFT_SERIAL /
// PUREBOOT_AUTOBAUD, defaulting to the chip's USART0 where it has one. The
// software receiver is the polled one: the vector table belongs to the
@@ -474,37 +496,42 @@ void await_host()
}
// One byte into a writable space. Flash is not one of them — it arrives a
// page at a time through 'W' and is committed through sp_spm — and the fuses
// are not writable at all: SPM reaches flash and boot lock bits only.
[[gnu::always_inline]] inline void store(std::uint8_t space, std::uint8_t bank, std::uint16_t at, std::uint8_t value,
std::uint8_t slot_high)
// page at a time through 'W' and is committed by the sealed SPM command — and
// the fuses are not writable at all: SPM reaches flash and boot lock bits only.
[[gnu::always_inline]] inline void store(std::uint8_t space, std::uint16_t at, std::uint8_t value)
{
if (space == sp_data) {
*reinterpret_cast<volatile std::uint8_t *>(at) = value;
return;
}
if (space == sp_spm) {
// The running-slot write guard. An SPM command aimed at the slot this
// code executes from is dropped, so a broken host cannot brick the
// running loader — while a copy one slot lower may still rewrite the
// resident one, which is what a self-update is. Guarding the commit
// rather than the page fill covers erase and write both, and leaves a
// refused page's words in the buffer: harmless, since the next page
// write auto-erases it (§26.2.1).
if (slot_of(bank, at) != slot_high)
spm::command<off>(value, flash_address(bank, at));
// Only a boot-sectioned mega runs on while its RWW section programs;
// everywhere else the CPU halts through erase and write, so the wait
// is already over by the time it returns.
if constexpr (boot_section)
spm::wait();
return;
}
// Host-paced: the ack goes out once the write has begun, so the next byte
// arrives while it completes and nothing is missed without a buffer.
ee::write<off>(at, value);
}
// The irreversible half of the protocol, and the whole of it: page erase, page
// write and the lock bits are one SPM command each, and nothing else the loader
// does outlasts being done again. Reached only from a sealed command (run()),
// so both the byte handed to SPMCSR and the address it fires at are the ones
// the host computed its seal over.
//
// Nothing here refuses an address. A loader that will not write its own slot
// cannot plant anything in it either, and a resident copy able to rewrite its
// own trailing page is what lets a 512-byte boot section — where no staging
// copy can run SPM at all — carry an SPM primitive for an application-side
// installer to drive. The protection that made the guard look necessary is the
// seal: a wire fault can no longer name an address, only a host can, and a host
// that names this one means it.
[[gnu::always_inline]] inline void commit(std::uint8_t bank, std::uint16_t at, std::uint8_t value)
{
spm::command<off>(value, flash_address(bank, at));
// Only a boot-sectioned mega runs on while its RWW section programs;
// everywhere else the CPU halts through erase and write, so the wait
// is already over by the time it returns.
if constexpr (boot_section)
spm::wait();
}
// One page into the SPM buffer, and only that: the erase and the write that
// commit it are host-issued sp_spm stores, which reach the same fused
// store-and-SPM pair through the transfer path's own address and data.
@@ -541,13 +568,6 @@ void fill_page(std::uint8_t bank, std::uint16_t at)
run_app();
link::init();
// The slot this copy runs in, which the write guard follows: the return
// address is a word address and a slot is half as many words as bytes, so
// its high byte is the slot index outright. No absolute address is ever
// formed, so the image stays position-independent.
const auto slot_high = avr::startup::caller_page();
await_host();
for (;;) {
@@ -556,54 +576,99 @@ void fill_page(std::uint8_t bank, std::uint16_t at)
ee::wait();
tx_ack();
const std::uint8_t command = link::rx();
switch (command) {
case 'b': // identity: the version, then the three signature bytes
// Straight out of the stamp, so the wire and the image can never
// disagree about what this loader is. The indices are constant and
// the array is constexpr, so these are immediates, not flash reads:
// nothing here needs the stamp's runtime address.
if (command & op_identify) {
// Identity: the version, then the three signature bytes. Straight
// out of the stamp, so the wire and the image can never disagree
// about what this loader is. The indices are constant and the array
// is constexpr, so these are immediates, not flash reads: nothing
// here needs the stamp's runtime address. Unsealed, because it
// takes no argument and changes nothing — and because a command
// that cannot be got wrong is what a lost host resynchronises on.
for (std::uint8_t at = stamp_identity; at != sizeof identity_stamp; ++at)
link::tx(identity_stamp[at]);
break;
case 'J': // jump: sel8 (reserved), addr16 as a wire word address
case 'W': // fill one flash page buffer: sel8, addr16, then page bytes
case 'G': // read: sel8, addr16, n8 (0 = 256)
case 'g': { // write: sel8, addr16, n8, then n bytes, each acked
} else {
// One decode, one cursor and one loop for every space, both
// directions and the jump: a command per memory would carry a copy
// of all three each. 'J' — the hand-over and staging transfer
// carries a selector it ignores so its address rides the same two
// reads as everything else; 'W' joins the same decode rather than
// keeping an address form of its own, so flash addressing is
// uniform across every command that names it.
// of all three each. The jump — the hand-over and staging transfer
// carries a selector it ignores so its address rides the same two
// reads as everything else; the page fill joins the same decode
// rather than keeping an address form of its own, so flash
// addressing is uniform across every command that names it. Both
// carry the count they do not use for the same reason: one header
// shape is one decode, and one seal covers a fixed set of bytes.
const std::uint8_t selector = link::rx();
const std::uint8_t space = space_of(selector);
const std::uint8_t bank = bank_of(selector);
std::uint16_t at = rx16();
if (command == 'J') {
tx_ack();
link::drain();
jump(reinterpret_cast<void (*)()>(at));
}
if (command == 'W') {
fill_page(bank, at);
break;
}
std::uint8_t count = link::rx();
do {
// Read and write are one letter apart in case, so the direction
// is a single bit and the loop picks it with a one-word skip.
if (command & 0x20) {
store(space, bank, at, link::rx(), slot_high);
tx_ack();
} else
link::tx(load(space, bank, at));
++at;
} while (--count);
break;
}
default: // unknown bytes are ignored; the loop re-acks
break;
const std::uint8_t sealed = link::rx();
// The seal: every field that decides what this command does folded
// into one byte the host chose, tested before any of it happens.
//
// Checked here rather than acknowledged afterwards, which is the
// whole point. An ack reports a command that has already run, and
// for the one command that cannot be taken back a report is not a
// defence. Once the running-slot guard is gone the address is as
// fatal as the command byte — a wrong one reaches the loader's own
// page — so the seal covers the act and the place together, and a
// stream that lost or mangled either cannot produce it.
//
// Folded here, after the last read, and never accumulated across
// the reads: every field is still live at this point because the
// command needs it anyway, so the fold costs one xor each and no
// register. An accumulator would have to survive four calls, and
// paying for that in call-saved registers costs more than the whole
// check costs in arithmetic — measured at fourteen bytes, on a
// budget of ten.
std::uint8_t fold = command;
fold ^= selector;
fold ^= static_cast<std::uint8_t>(at);
fold ^= static_cast<std::uint8_t>(at >> 8);
fold ^= count;
fold ^= sealed;
// The verdict, and it is not a courtesy. Every command whose
// payload the host sends without waiting — a page fill, a write
// burst — would otherwise be handed to a loader that has already
// gone back to reading commands, so a *detected* error would
// become the desync the seal exists to prevent: a 128-byte page
// read as command headers is twenty-one more chances at the one in
// two hundred and fifty-six. Answering the seal before the payload
// is what keeps a refusal local to the command that earned it.
//
// An unknown opcode lands here too — every bit pattern is now some
// command, so it is the seal, not a table of valid letters, that
// rejects noise, and the host hears about it either way.
if (fold != seal) {
link::tx(nak);
} else {
tx_ack();
if (command & op_jump) {
link::drain();
jump(reinterpret_cast<void (*)()>(at));
} else if (command & op_fill) {
fill_page(bank, at);
} else if (space == sp_spm) {
// An SPM command is the whole of what this loader can do
// that doing again will not undo, and it is one byte — so
// it rides the count field, inside the seal, rather than
// arriving as data after the seal has been checked. Which
// is also what makes a deliberate lock-bit write
// expressible, where refusing it outright did not.
commit(bank, at, count);
} else {
do {
// Direction is one bit of the opcode, so the loop
// picks it with a one-word skip.
if (command & op_write) {
store(space, at, link::rx());
tx_ack();
} else
link::tx(load(space, bank, at));
++at;
} while (--count);
}
}
}
}
}

View File

@@ -26,16 +26,20 @@ else:
import termios
PROMPT = b"+"
VERSION = 9 # this tool's own version — free to drift from a loader's
# The refusal, from pureboot 9: the prompt inverted, so no single flipped bit
# turns "nothing happened" into "it did".
NAK = bytes((~PROMPT[0] & 0xFF,))
VERSION = 10 # this tool's own version — free to drift from a loader's
# The loader versions this tool can drive. A pureboot version implies its wire
# protocol, which carries no number of its own, so this window is where that
# map lives: the tool keeps a decoder for every generation in it (14 speak
# the per-memory commands, 5 the unified pair; 6 marks the OSCCAL-carrying
# builds and changes nothing on the wire; 8 the one-wire deployments, whose
# only host-side trace is the --one-wire echo discard), and a version it has
# no decoder for moves the floor.
# only host-side trace is the --one-wire echo discard; 9 seals every command
# and answers each seal before acting), and a version it has no decoder for
# moves the floor.
OLDEST_LOADER = 1
NEWEST_LOADER = 8
NEWEST_LOADER = 9
SLOT = 512 # the loader slot, on every chip
RETRIES = 3 # rewrites of a page that reads back wrong, before the run stops
@@ -53,6 +57,30 @@ RETRIES = 3 # rewrites of a page that reads back wrong, before the run stops
UNIFIED_LOADER = 5
SP_FLASH, SP_EEPROM, SP_RAM, SP_FUSE, SP_SPM = 0, 1, 2, 3, 4
# pureboot 9 replaces the command letters with bits and seals every command.
# The header is one shape for all of them — opcode, selector, address, count,
# seal — and the loader answers the seal *before* it acts: PROMPT accepts, NAK
# refuses and nothing happened. That verdict is what lets a refusal stay local
# to its own command: the payload of a fill or a write burst only goes out
# after the header has been accepted, so a rejected header never leaves the
# host pushing bytes into a loader that has gone back to reading commands.
#
# A transfer is the absence of the other three opcodes, and its direction is
# the low bit. Identify is bit 5 because both knock bytes carry it: 'b' has to
# still ask the version (the host cannot know which generation it is talking to
# until something answers), and 'p' has to stay harmless against a loader
# already in session — pureboot 9 reserves no invalid opcode, so a knock that
# meant nothing before would otherwise eat the five bytes behind it.
SEALED_LOADER = 9
OP_WRITE, OP_FILL, OP_JUMP, OP_IDENTIFY = 1, 4, 8, 0x20
# What a sealed header's fields must fold to. Non-zero, so a run of one
# repeated byte — a stuck line, a page of erased flash read as a header —
# cannot satisfy it.
SEAL = 0x5A
# An SPM command carries its SPMCSR byte in the count field, where the seal
# covers it. There is no data phase: a byte after the header would arrive after
# the seal had already been checked, which is the hole the seal exists to close.
# An autobaud loader keeps its measured bit period readable, encoded as
# delay-loop counts: (bit cycles UNIT_DISCOUNT) / UNIT_LOOP_CYCLES,
# floored — the spin granule and per-bit overhead of libavr's software UART.
@@ -548,8 +576,8 @@ class Info:
The base is where application flash ends, which is a property of the
chip and not of the copy answering: a loader staged one slot lower
reports the same geometry the resident one does, exactly as the loaders
that send a block do. Which slot a copy runs in matters only to its own
write guard, which is the loader's business."""
that send a block do. Which slot a copy runs in is not something the
identity reports, and from pureboot 9 nothing on the device cares."""
if len(raw) != 4:
raise Error(f"bad identity reply: {raw.hex()}")
version, signature = raw[0], tuple(raw[1:4])
@@ -669,6 +697,18 @@ class Loader:
return Info(head + self.port.read_exact(8, 0.5))
return Info.from_identity(head)
def identity(self):
"""Ask a live session who it is.
The identity command takes no argument and changes nothing, which makes
it the one question whose answer is known in advance — so it doubles as
the host's check that the stream is still in step, and as the byte a
lost host resynchronises on."""
self.port.write(b"b")
answer = self._read_identity()
self._expect_prompt()
return answer
def _handshake(self, wait, knock, what):
"""One activation, retried until the loader answers or the window
closes. The identity reply is what proves the loader is listening — a
@@ -758,6 +798,32 @@ class Loader:
if byte != PROMPT:
raise Error(f"expected prompt, got {byte.hex()}")
@property
def sealed(self):
"""pureboot 9 and later: bit opcodes, a sealed header, and a verdict
on that seal before the command runs."""
return self.info is not None and self.info.version >= SEALED_LOADER
def _header(self, op, space, address, count, timeout=2.0):
"""Send a sealed header and take the loader's verdict on it.
Returning normally means the loader has accepted the command and not
yet done it — which is the whole point of the verdict, and why the
payload of a fill or a write burst is sent only after this returns."""
head = bytes((op, selector(space, address), address & 0xFF, (address >> 8) & 0xFF, count & 0xFF))
seal = SEAL
for byte in head:
seal ^= byte
self.port.write(head + bytes((seal,)))
answer = self.port.read_exact(1, timeout)
if answer == NAK:
raise Error(
f"the loader refused the command (opcode {op:#04x}, {address:#06x}): the "
f"seal did not match, so nothing was done — the link mangled the header"
)
if answer != PROMPT:
raise Error(f"expected a verdict on the seal, got {answer.hex()}")
def _command(self, tx, reply_len=0, timeout=2.0):
self.port.write(tx)
reply = self.port.read_exact(reply_len, timeout) if reply_len else b""
@@ -785,9 +851,14 @@ class Loader:
data = b""
while count:
chunk = min(count, 256, 0x10000 - (address & 0xFFFF))
head = bytes((ord("G"), selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, chunk & 0xFF))
data += self._command(head, chunk, 5.0)
if self.sealed:
self._header(0, space, address, chunk, 5.0)
data += self.port.read_exact(chunk, 5.0)
self._expect_prompt(5.0)
else:
head = bytes((ord("G"), selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, chunk & 0xFF))
data += self._command(head, chunk, 5.0)
address += chunk
count -= chunk
return data
@@ -799,9 +870,11 @@ class Loader:
offset = 0
while offset < len(data):
chunk = data[offset : offset + min(256, 0x10000 - (address & 0xFFFF))]
head = bytes((ord("g"), selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, len(chunk) & 0xFF))
self.port.write(head)
if self.sealed:
self._header(OP_WRITE, space, address, len(chunk))
else:
self.port.write(bytes((ord("g"), selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, len(chunk) & 0xFF)))
for byte in chunk:
self.port.write(bytes((byte,)))
self._expect_prompt()
@@ -813,7 +886,16 @@ class Loader:
def spm(self, operation, address):
"""One SPM operation at a flash address — the erase, write and RWW
re-enable that pureboot 4 ran inside 'W' and pureboot 5 leaves here."""
re-enable that pureboot 4 ran inside 'W' and pureboot 5 leaves here.
From pureboot 9 the operation rides the header's count field instead of
arriving as data behind it, which is what puts it inside the seal: the
loader will not hand a byte to SPMCSR that the host did not seal, and
the verdict says whether it did."""
if self.sealed:
self._header(OP_WRITE, SP_SPM, address, operation, 5.0)
self._expect_prompt(5.0)
return
self._write_space(SP_SPM, address, bytes((operation,)))
def read_ram(self, address, count):
@@ -851,12 +933,22 @@ class Loader:
def write_page(self, address, data):
assert len(data) == self.info.page and address % self.info.page == 0
if self.unified:
# 'W' fills the page buffer and stops there; the erase and the write
# are host-issued SPM operations. Only a chip with a boot section
# has RWW to re-enable — on the others bit 4 of SPMCSR means
# something else entirely, so it must not be sent.
head = bytes((ord("W"), selector(SP_FLASH, address), address & 0xFF, (address >> 8) & 0xFF))
self._command(head + data, 0, 2.0)
# The fill loads the page buffer and stops there; the erase and the
# write are host-issued SPM operations. Only a chip with a boot
# section has RWW to re-enable — on the others bit 4 of SPMCSR
# means something else entirely, so it must not be sent.
if self.sealed:
# The page goes out only once the header is accepted. It is the
# protocol's one unacked burst, so a header refused after the
# host had already started sending it would leave the page
# being read as commands — which is exactly what the verdict
# is placed here to prevent.
self._header(OP_FILL, SP_FLASH, address, len(data) & 0xFF)
self.port.write(data)
self._expect_prompt(2.0)
else:
head = bytes((ord("W"), selector(SP_FLASH, address), address & 0xFF, (address >> 8) & 0xFF))
self._command(head + data, 0, 2.0)
self.spm(SPM_ERASE, address)
self.spm(SPM_WRITE, address)
if not self.info.patch_vector:
@@ -891,8 +983,13 @@ class Loader:
def jump(self, word_address):
"""The device acks, then execution continues at the word address.
From v7 'J' rides the unified decode, so it carries a selector byte
the loader ignores; older loaders take the bare address."""
From v7 the jump rides the unified decode, so it carries a selector
byte the loader ignores; older loaders take the bare address. From v9
the ack is the verdict on its seal — a jump to a mangled address is a
jump into arbitrary code, so it is sealed like everything else."""
if self.sealed:
self._header(OP_JUMP, 0, word_address, 0)
return
if self.info.version >= 7:
self.port.write(bytes((ord("J"), 0, word_address & 0xFF, word_address >> 8)))
else:
@@ -1309,7 +1406,7 @@ def op_update_loader(loader, wait, path, state_path, fuse_bytes, staged_link=Non
state.load_or_save(loader)
# A loader already sitting whole in the staging slot IS the staging copy:
# rewriting it would only meet its own running-slot guard. Any pureboot
# rewriting it in place would be a copy overwriting itself as it runs. Any pureboot
# with the device's info block serves, since a staged copy only streams
# pages. "Whole" needs both checks — the block where every image carries
# it and matching byte for byte, and the slot unchanged since this update

124
test/pbglitch.py Normal file
View File

@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""A link that damages bytes, deliberately and reproducibly, against the seal
that exists for it.
The board this was written for loses and mangles bytes on its own serial path,
and the failure that made it matter — a page-fill byte lost, the stream one
byte out, a page-address byte arriving where an SPMCSR value belongs — is not
reachable by asking a healthy link nicely. So the damage is injected here, at
a named byte index rather than a probability: a failing case is a case that
fails again.
Every check is a pair. The same bit flipped in the same field is applied on
one side of the seal and then the other: *after* the host seals the header,
which is a mangled command and must be refused, and *before*, which is a
well-formed command for something else and must be obeyed. Only the pair
proves anything — a test that showed the refusal alone would pass against a
loader that had simply stopped doing SPM, and one that showed the corruption
alone would not say what caught it.
Usage: pbglitch.py <device_bin> <pureboot_elf> <mcu> <hz> <base_hex> <page>
<baud> <tool_py> <workdir>
"""
import os
import sys
def fail(message):
print(f"FAIL: {message}")
sys.exit(1)
def frame(pb, op, space, address, count, damage=None, before_seal=False):
"""A sealed command header, optionally with one byte damaged.
`damage` is (index, mask). Applied before the seal is computed it produces
a valid command for whatever the damaged fields now say; applied after, a
command whose seal no longer matches its own body — which is the shape a
link fault actually has."""
head = bytearray((op, pb.selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, count & 0xFF))
if damage and before_seal:
head[damage[0]] ^= damage[1]
seal = pb.SEAL
for byte in head:
seal ^= byte
out = bytearray(head + bytes((seal,)))
if damage and not before_seal:
out[damage[0]] ^= damage[1]
return bytes(out)
def main():
device_bin, elf, mcu, hz, base_hex, page, baud, tool, workdir = sys.argv[1:]
base, page, baud = int(base_hex, 0), int(page), int(baud)
sys.path.insert(0, os.path.dirname(os.path.abspath(tool)))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pbsim
import pureboot as pb
os.makedirs(workdir, exist_ok=True)
dump = os.path.join(workdir, "dump.bin")
device = pbsim.Device(device_bin, elf, mcu, hz, base_hex, page, baud, dump)
try:
port = pb.Port(device.pty, baud)
loader = pb.Loader(port)
info = loader.connect(25)
if info.version < pb.SEALED_LOADER:
fail(f"this test is for pureboot {pb.SEALED_LOADER} and later, not {info.version}")
# A page of known bytes to watch. Everything below aims at it, so
# "nothing happened" is a readable claim rather than an absence.
marker = bytes((0x40 + (i & 0x3F)) for i in range(page))
loader.write_page(0, marker)
if loader.read_flash(0, page) != marker:
fail("the marker page did not survive an undamaged write")
# Every field of the header, one bit each. A damaged seal must be
# refused, the loader must re-prompt, and the page must be untouched —
# and it is the erase being aimed at it, so a single escape is visible.
for index in range(6):
bad = frame(pb, pb.OP_WRITE, pb.SP_SPM, 0, pb.SPM_ERASE, damage=(index, 0x01))
port.write(bad)
answer = port.read_exact(1, 5.0)
if answer != pb.NAK:
fail(f"a header damaged in byte {index} was not refused (got {answer.hex()})")
if port.read_exact(1, 5.0) != pb.PROMPT:
fail(f"no prompt after refusing a header damaged in byte {index}")
if loader.read_flash(0, page) != marker:
fail(f"damage in byte {index} reached flash — the marker page changed")
# The fill, whose payload is the protocol's one unacked burst: a
# refused fill must be refused *before* the page is sent, or the host
# is left pushing 128 bytes into a loader reading commands. Nothing is
# sent after the verdict here, and the very next command must be
# understood — that is the whole claim.
bad = frame(pb, pb.OP_FILL, pb.SP_FLASH, 0, page, damage=(3, 0x80))
port.write(bad)
if port.read_exact(1, 5.0) != pb.NAK:
fail("a damaged fill header was not refused")
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("no prompt after refusing a damaged fill header")
if loader.identity().raw != info.raw:
fail("the loader was out of step after refusing a fill")
# The pair's other half. The identical flip, applied before the seal:
# a well-formed erase of the page one bit away from the one intended.
# It must be obeyed — otherwise the refusals above prove nothing about
# the seal and only that this loader stopped erasing.
port.write(frame(pb, pb.OP_WRITE, pb.SP_SPM, 0, pb.SPM_ERASE,
damage=(2, 0x01), before_seal=True))
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("a correctly sealed erase was refused")
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("no prompt after a correctly sealed erase")
if loader.read_flash(0, page) != b"\xff" * page:
fail("the sealed erase did not reach flash — the marker page is intact")
port.close()
finally:
device.stop()
print("pbglitch: damaged headers are refused, the identical damage sealed is obeyed")
main()

View File

@@ -3,11 +3,10 @@
canonical slot must still be a working loader, and the ordinary
--update-loader flow must put a build into the top slot from there.
Two positions. Address 0, a raw .bin handed to a programmer: the staging
install and the word-0 redirect run from copies outside page 0's slot, so the
running-slot guard never blocks them. And the staging slot itself, where a
loader already sitting there IS the staging copy — recognized by its embedded
block and left in place, then streaming the new resident like any staged copy.
Two positions. Address 0, a raw .bin handed to a programmer. And the staging
slot itself, where a loader already sitting there IS the staging copy —
recognized by its embedded block and left in place, then streaming the new
resident like any staged copy.
Usage: pbrehome.py <device_bin> <pureboot_elf> <update_bin> <mcu> <hz>
<base_hex> <page> <baud> <app_bin> <tool_py> <workdir>
@@ -22,7 +21,7 @@ def fail(message):
sys.exit(1)
def rehome_from(pbsim, pb, device_bin, elf, place_hex, guard_probe, update_bin, base, page, baud, app_bin, workdir,
def rehome_from(pbsim, pb, device_bin, elf, place_hex, update_bin, base, page, baud, app_bin, workdir,
mcu, hz):
"""Place the loader at `place_hex`, heal through --update-loader, flash
the application, expect the banner."""
@@ -38,14 +37,6 @@ def rehome_from(pbsim, pb, device_bin, elf, place_hex, guard_probe, update_bin,
if info.base != base:
fail(f"the misplaced copy reports base {info.base:#06x} — the info block must stay canonical")
# The accidental slot still guards itself; re-homing rides on the
# canonical slots being writable from it.
probe = int(guard_probe, 0)
before = loader.read_flash(probe, info.page)
loader.write_page(probe, bytes(info.page))
if loader.read_flash(probe, info.page) != before:
fail("the misplaced copy's guard let its own slot change")
# The ordinary update flow puts the build into the top slot.
pb.op_update_loader(loader, 25, update_bin, state, None)
update = open(update_bin, "rb").read()
@@ -76,16 +67,15 @@ def main():
os.makedirs(workdir, exist_ok=True)
# Address 0: the raw-.bin-to-a-programmer accident. The guard probe is
# the copy's own page 0.
rehome_from(pbsim, pb, device_bin, elf, "0x0", "0x0", update_bin, base, page, baud, app_bin, workdir, mcu, hz)
# Address 0: the raw-.bin-to-a-programmer accident.
rehome_from(pbsim, pb, device_bin, elf, "0x0", update_bin, base, page, baud, app_bin, workdir, mcu, hz)
print("re-home from address 0: converged")
# The staging slot: erased flash with the loader sitting exactly where
# a staging copy would — the tool must leave it in place and let it
# stream the (different) update build into the resident slot.
stage = base - pb.SLOT
rehome_from(pbsim, pb, device_bin, elf, hex(stage), hex(stage), update_bin, base, page, baud, app_bin, workdir,
rehome_from(pbsim, pb, device_bin, elf, hex(stage), update_bin, base, page, baud, app_bin, workdir,
mcu, hz)
print("re-home from the staging slot: converged")

View File

@@ -1,9 +1,8 @@
#!/usr/bin/env python3
"""Position-independence acceptance test: the identical binary, flashed one
slot below the resident, must serve the complete command set from there. The
info block must come back byte-identical, the write guard must refuse the
staged copy's own slot and permit the resident's, and the staged copy must be
able to rewrite the resident verbatim.
info block must come back byte-identical, and the staged copy must be able to
rewrite the resident verbatim — which is the whole of what relocation is for.
Usage: pbreloc.py <device_bin> <pureboot_elf> <mcu> <hz> <base_hex> <page>
<baud> <tool_py> <workdir>
@@ -64,14 +63,14 @@ def main():
if loader.read_eeprom(0, len(pattern)) != pattern:
fail("EEPROM round-trip through the staged copy")
# The guard, both ways: its own slot refused (drained, unchanged), the
# resident slot writable. The refusal leaves its drained words in the
# SPM buffer, so the write that follows may take them — and clears
# them by writing, so the retry must not.
before = loader.read_flash(stage, page)
loader.write_page(stage, bytes(page))
if loader.read_flash(stage, page) != before:
fail("the staged copy's guard let its own slot change")
# The resident slot, written from the copy standing beside it — the
# whole point of relocating. pureboot 9 dropped the running-slot guard
# that used to sit behind this, so the probe that used to accompany it
# (aim a write at the copy's *own* slot and watch it be refused) is
# gone with it: there is nothing to refuse now, and a copy that erases
# the page it is executing from does not come back to report it.
# pbselfwrite.py gates that direction on a device it is allowed to
# destroy.
marker = bytes((i * 3) & 0xFF for i in range(page))
loader.write_page(base, marker)
if loader.read_flash(base, page) != marker:

102
test/pbselfwrite.py Normal file
View File

@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""The seal, gated on the one command that proves it: erase the page the
loader is executing from.
pureboot 9 dropped the running-slot write guard, so this command is now
permitted — that is what lets a resident copy plant something in its own slot,
which on a chip whose boot section *is* the loader slot is the only route a
self-update has. Permitted means the loader must actually do it, and the only
honest proof is the flash afterwards.
What stands in the guard's place is the seal, and the two halves are tested
against each other here: the identical destructive command, refused when its
seal is wrong and honoured when it is right. A test that only showed the
refusal would pass just as well against a loader that ignores SPM entirely.
Usage: pbselfwrite.py <device_bin> <pureboot_elf> <mcu> <hz> <base_hex> <page>
<baud> <tool_py> <workdir>
"""
import os
import sys
def fail(message):
print(f"FAIL: {message}")
sys.exit(1)
def sealed_frame(pb, op, space, address, count):
"""A command header and its seal, built here rather than borrowed from the
tool: this test is about what the loader accepts, and a probe that shares
the host's frame builder cannot tell a wrong frame from a wrong loader."""
head = bytes((op, pb.selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, count & 0xFF))
seal = pb.SEAL
for byte in head:
seal ^= byte
return head + bytes((seal,))
def main():
device_bin, elf, mcu, hz, base_hex, page, baud, tool, workdir = sys.argv[1:]
base, page, baud = int(base_hex, 0), int(page), int(baud)
sys.path.insert(0, os.path.dirname(os.path.abspath(tool)))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pbsim
import pureboot as pb
os.makedirs(workdir, exist_ok=True)
dump = os.path.join(workdir, "dump.bin")
device = pbsim.Device(device_bin, elf, mcu, hz, base_hex, page, baud, dump)
try:
port = pb.Port(device.pty, baud)
loader = pb.Loader(port)
info = loader.connect(25)
if info.version < pb.SEALED_LOADER:
fail(f"this test is for pureboot {pb.SEALED_LOADER} and later, not {info.version}")
# Erase the first page of the running slot: the entry stub and the
# command loop are both in it, so a loader that performs this does not
# answer again. Nothing else in the protocol is as sharp a probe.
frame = sealed_frame(pb, pb.OP_WRITE, pb.SP_SPM, base, pb.SPM_ERASE)
# Red: the same command with one bit wrong in its seal. Refused before
# anything happens, and the loader is still there to say so.
broken = bytearray(frame)
broken[-1] ^= 0x01
port.write(bytes(broken))
if port.read_exact(1, 5.0) != pb.NAK:
fail("an unsealed erase of the running page was not refused")
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("the loader did not re-prompt after refusing the erase")
alive = loader.read_flash(base, 8)
if alive == b"\xff" * 8:
fail("the refused erase happened anyway — the running page reads erased")
# Green: the identical command, correctly sealed. Nothing is required
# of the link from here on. The verdict is *issued* before the SPM, but
# the erase takes the code that would have finished saying it, and how
# much of it survives is the chip's business — an erase removes one page
# and nothing else, so a loader whose command loop lives past the page
# erased will prompt as usual where one with 128-byte pages goes with
# the stub. None of that is the claim. The claim is that the erase
# reached flash, and the dump is both the only witness for it and a
# better one: it tells "accepted and performed" from "merely answered".
port.write(frame)
try:
port.read_exact(2, 2.0)
except pb.Error:
pass
port.close()
finally:
device.stop()
# Ground truth: the simulator's flash, not the loader's opinion of it.
flash = open(dump, "rb").read()
if flash[base : base + page] != b"\xff" * page:
fail("the sealed erase did not reach flash — the running page is intact")
print("pbselfwrite: the running slot is refused unsealed and erased sealed")
main()

View File

@@ -131,19 +131,42 @@ def main():
fail(f"loader reports pureboot {live.version}, the tool speaks "
f"{pb.OLDEST_LOADER}..{pb.NEWEST_LOADER}")
# A W addressed inside a page rather than at its base must still
# A fill addressed inside a page rather than at its base must still
# consume exactly one page and prompt. The loader's own slot is the
# target the guard refuses to commit it — and the payload is
# erased-state bytes, so the probe can disturb neither the image nor
# the page buffer it leaves behind. Hand-built rather than through
# write_page(), which would follow the fill with its erase and
# write; the point here is that the fill alone consumes exactly one
# page whatever the address's low bits say.
# target and the payload is erased-state bytes, so the probe can
# disturb neither the image nor the page buffer it leaves behind: a
# fill only loads the buffer, and nothing commits it. Hand-built
# rather than through write_page(), which would follow the fill
# with its erase and write; the point here is that the fill alone
# consumes exactly one page whatever the address's low bits say.
# Hand-sealed too — a protocol probe that borrowed the tool's own
# frame builder could not tell a wrong frame from a wrong loader.
wire = base + 1
port.write(bytes((ord("W"), pb.selector(pb.SP_FLASH, wire), wire & 0xFF, (wire >> 8) & 0xFF))
+ b"\xff" * page)
head = bytes((pb.OP_FILL, pb.selector(pb.SP_FLASH, wire), wire & 0xFF,
(wire >> 8) & 0xFF, page & 0xFF))
seal = pb.SEAL
for byte in head:
seal ^= byte
port.write(head + bytes((seal,)))
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("unaligned W did not return to the prompt")
fail("the loader refused a correctly sealed fill")
port.write(b"\xff" * page)
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("unaligned fill did not return to the prompt")
# And the seal itself, red: one wrong bit in the address of that
# same frame must be refused outright. The verdict has to arrive
# *before* the page would have been sent — that ordering is what
# keeps a refusal from turning into a desync — so the probe sends
# no payload at all and expects the loader straight back at the
# command level.
broken = bytearray(head + bytes((seal,)))
broken[2] ^= 0x01
port.write(bytes(broken))
if port.read_exact(1, 5.0) != pb.NAK:
fail("a header with a broken seal was not refused")
if port.read_exact(1, 5.0) != pb.PROMPT:
fail("the loader did not re-prompt after refusing a broken seal")
loader.run_application()
banner = port.read_exact(3, 5.0)

View File

@@ -161,7 +161,7 @@ class Suite:
self.check("application flash reads back", rc == 0 and len(got) == info.base,
f"{len(got)} B of {info.base}")
def erase_and_guard(self, info, loader_image: pathlib.Path | None) -> None:
def erase_and_slot(self, info, loader_image: pathlib.Path | None) -> None:
rc, out = self.rig.pureboot("--erase-flash")
self.check("application region erases", rc == 0, self._brief(out))
@@ -188,6 +188,80 @@ class Suite:
else:
print(" skip loader slot comparison (pass --loader <image.bin>)")
def seal(self, info, rounds: int = 1) -> None:
"""The seal, adversarially, over the real link.
pureboot 9 has no running-slot guard: what stops a mangled command from
erasing the loader is the seal and nothing else. So this aims the worst
command the protocol has — an SPM erase at the loader's own first page —
and damages one header byte at a time. Every one must come back NAK with
the slot untouched and the session still in step.
On a board whose link drops or mangles bytes of its own accord this is
also the stress test: `--seal-rounds` repeats it, and a link fault
during a round is indistinguishable to the loader from the damage being
injected, which is the point.
"""
module = pbrig.load_pureboot(self.rig.d.pureboot)
self.rig.reset()
port = self.rig.open_port()
try:
loader = module.Loader(port)
if self.rig.d.autobaud:
loader.connect_autobaud(self.rig.d.wait)
else:
loader.connect(self.rig.d.wait)
if loader.info.version < module.SEALED_LOADER:
print(f" skip seal checks (loader is pureboot {loader.info.version})")
return
head_of = lambda dmg: self._sealed(module, module.OP_WRITE, module.SP_SPM,
info.base, module.SPM_ERASE, dmg)
refused = 0
attempts = 0
for _ in range(rounds):
for index in range(6):
attempts += 1
port.write(head_of((index, 0x01)))
verdict = port.read_exact(1, 5.0)
if verdict != module.NAK:
self.check(f"damaged byte {index} refused", False,
f"verdict {verdict.hex()}")
return
if port.read_exact(1, 5.0) != module.PROMPT:
self.check(f"re-prompt after byte {index}", False, "no prompt")
return
refused += 1
self.check("damaged headers refused", refused == attempts,
f"{refused}/{attempts}, every header byte")
self.check("session still in step", loader.identity().raw == info.raw)
# And the slot itself, read back over the link: the loader is the
# thing that would have been erased, so its own account of its
# first bytes is a real witness — an erased page reads all 0xff.
head = loader.read_flash(info.base, 16)
self.check("loader slot intact", set(head) != {0xFF}, head[:8].hex())
except Exception as error: # noqa: BLE001 — a dead link is a result
self.check("seal checks", False, str(error)[:70])
finally:
try:
port.close()
except Exception: # noqa: BLE001
pass
@staticmethod
def _sealed(module, op, space, address, count, damage=None):
"""A sealed header, damaged after sealing — the shape a link fault has."""
head = bytearray((op, module.selector(space, address), address & 0xFF,
(address >> 8) & 0xFF, count & 0xFF))
seal = module.SEAL
for byte in head:
seal ^= byte
out = bytearray(head + bytes((seal,)))
if damage:
out[damage[0]] ^= damage[1]
return bytes(out)
def refusals(self, info) -> None:
# One word too many: a patched-vector part spends the slot's last word
# on the trampoline, so its application stops two bytes short.
@@ -200,7 +274,7 @@ class Suite:
# ------------------------------------------------------------------- run
def run(self, app: pathlib.Path | None, loader_image: pathlib.Path | None,
marker: str, marker_wait: float = 2.5) -> int:
marker: str, marker_wait: float = 2.5, seal_rounds: int = 1) -> int:
print("identity")
info = self.identity()
if info is None:
@@ -220,8 +294,11 @@ class Suite:
else:
print("\nskip application checks (pass --app <image.hex>)")
print("\nerase and the write guard")
self.erase_and_guard(info, loader_image)
print("\nerase and the slot boundary")
self.erase_and_slot(info, loader_image)
print("\nthe seal")
self.seal(info, seal_rounds)
print("\nrefusals")
self.refusals(info)
@@ -240,6 +317,8 @@ def main(argv: list[str] | None = None) -> int:
help="application image to flash (test/pbapp.cpp built for this deployment)")
parser.add_argument("--loader", type=pathlib.Path,
help="the resident loader's .bin, to prove the slot survives an erase")
parser.add_argument("--seal-rounds", type=int, default=1,
help="repeat the adversarial seal sweep N times (a lossy board's stress test)")
parser.add_argument("--marker", default="",
help="text the application emits when it runs, e.g. APP")
parser.add_argument("--marker-wait", type=float, default=2.5,
@@ -254,7 +333,7 @@ def main(argv: list[str] | None = None) -> int:
print("this overwrites the application flash and EEPROM\n")
with tempfile.TemporaryDirectory(prefix="pbhw-") as temporary:
return Suite(rig, pathlib.Path(temporary)).run(args.app, args.loader, args.marker,
args.marker_wait)
args.marker_wait, args.seal_rounds)
if __name__ == "__main__":