10 Commits

Author SHA1 Message Date
445e187722 tsb: document the three tiers at full parity in the build file
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UHeP42XU3wf6RfhyuxBTE5
2026-07-19 16:50:18 +02:00
250aba5cfb tsb: protocol test covers the password gate and emergency erase
Each scenario group now runs on its own freshly-reset device: the round-trip
on a blank config page, plus a password-config device that must be sent the
password after the knock to activate, and an emergency-erase device where a
0-byte + two confirms wipes flash, EEPROM and the config page (verified by
reading all three back as 0xff). All three tiers pass every group.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UHeP42XU3wf6RfhyuxBTE5
2026-07-19 16:49:20 +02:00
5c900720e3 tsb: pure and tricks tiers reach full oracle feature parity
Both tiers gain the features the asm tier already carries — one-wire
half-duplex (via libavr's new .half_duplex), the config-page activation
timeout, and emergency erase (password \0 + double-confirm wipes flash,
EEPROM and the config page) — on top of the watchdog bail, password gate and
config/flash/EEPROM read-write they already had. pure stays idiomatic
(flash_table info block, one function per command) at 950 B; tricks keeps its
compiler trickery (call-saved global-register page walk, unified runtime-flag
paths pinned noinline/noclone, streaming stores, arithmetic command decode)
at 808 B. Both byte-identical across generated and reflect modes; the size
gradient across the three tiers is now 502 / 808 / 950 B.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UHeP42XU3wf6RfhyuxBTE5
2026-07-19 16:47:21 +02:00
7d6ef959b2 tsb: asm tier reaches full oracle feature parity at 502 B
Rewrite the inline-asm tier so it matches the hand-written fixed-baud oracle's
feature set inside the 512 B boot section: watchdog-reset bail, one-wire
half-duplex (RXEN/TXEN toggled per direction, TX turnaround guard),
config-page activation timeout, the password gate (wrong byte hangs draining
the UART), emergency erase (password \0 + double-confirm wipes flash, EEPROM
and the config page), and config/flash/EEPROM read-write. Every geometry,
baud and info-block constant comes from libavr consteval; only the dense
control flow is hand-written. 502 B, byte-identical across generated and
reflect modes.

Test harness: seed the config page from TSB_CONFIG so the password and
emergency-erase paths are exercisable, and clear simavr's AVR_UART_FLAG_POLL_
SLEEP — a host-CPU-saving usleep(1)-per-idle-poll hack that models no hardware
and paces a one-wire loader (which releases TX between bytes) in real time,
distorting protocol timing.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UHeP42XU3wf6RfhyuxBTE5
2026-07-19 16:23:16 +02:00
11ffbce2e2 tsb: vendor the fixed-baud assembly oracle as the size/feature bar
The Seed Robotics native-UART fixed-baud TinySafeBoot (GPLv3), reference
only — not built. Assembles to 500 B with the full feature set, proving
≤512 B and full feature parity are simultaneously reachable. Also drops the
stale empty stk500v2/ leftover.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UHeP42XU3wf6RfhyuxBTE5
2026-07-19 15:29:58 +02:00
f32a27ff15 tsb: use the named register surface
Direct register access now reads through the named surface
(hw::mcusr::wdrf.test(), hw::ucsr0b::write(...)) instead of the string form,
matching how libavr itself is written. Zero-overhead: pure 740 B, tricks 658 B,
asm 508 B unchanged, all byte-identical across modes, protocol green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 14:55:01 +02:00
57d94cf631 tsb: refactor the pure tier onto libavr sugar
The showcase tier now leans on the helpers it fed back instead of reaching under
them: the info block is an avr::flash_table (no raw [[gnu::progmem]]), a page is
filled with spm::fill(addr, span) (no hand-packed lo|hi<<8 loop), and the
WDT-reset bail reads field<"MCUSR","WDRF">::test() (no read() & {}(1).value).

Zero-overhead throughout: .text stays 740 B, byte-identical across generated and
reflect modes, protocol test green. The info block streams through the existing
address-based send_flash rather than a range-for over the flash_table — the
range-for is a distinct loop that cannot share the loader's one flash streamer,
so it would add 14 B for no functional gain.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 13:33:53 +02:00
8203a24f33 tsb: slim the port branch to the libavr reimplementation
main carried the whole pre-libavr tree beside the port: the other-bootloader
directories (blink, stk500v2), the Atmel Studio solution/project, and — dead in
the tsb dir itself — four submodule links to the superseded io/flash/uart/type
libraries the libavr sources never include. None are build inputs; CMake drives
the three variants through FetchContent. master keeps the full legacy tree
untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 13:12:56 +02:00
2906da3272 tsb: drop the local -O3 strip, now handled by the libavr toolchain
The -O3 leak is fixed upstream (cmake/release-os.cmake via CMAKE_PROJECT_INCLUDE),
so the port no longer needs its own string(REPLACE); a Release build is -Os
through the toolchain file. Verified: all three variants build at their sizes
(508/658/740) and pass the size + protocol ctest.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 10:52:13 +02:00
64c1e484b5 tsb: reimplement TinySafeBoot on libavr in three size tiers
The native-UART fixed-baud TinySafeBoot protocol, ported onto libavr as a
crt-free boot-section loader, in three variants that trade clarity for size:

  tsb_pure   740 B  idiomatic C++: SRAM page buffer, separate flash/EEPROM
                    leaves, shared framing; the polled `unused` guard posture.
  tsb_tricks 658 B  unified runtime-flag paths (noinline/noclone), call-saved
                    global-register page walk — attributes only, no asm.
  tsb_asm    508 B  streaming store + hand-rolled UART/SPM/EEPROM/erase loops;
                    fits the 512 B boot section (BOOTSZ=11). Trims the optional
                    password gate and WDT-reset bail — unreachable in C++ with
                    both (hand-asm is ~15 % denser). Tiers 1-2 keep them and
                    live in the 1 KB section they fit.

All three are .text byte-identical across libavr's generated and reflect modes.
The CMake build strips the leaked -O3 (a Release build is silently -O3, not the
-Os this loader is measured against) and gates each variant's size against its
section. A simavr harness (test/device.c + test/tsbtest.py) drives the real wire
protocol over a pty and flashes the device; the size and protocol tests run in
ctest. Verified byte-for-byte against the reference tsbloader_adv (C#/mono):
activate, read info, flash write + verify.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 05:00:51 +02:00
23 changed files with 741 additions and 1890 deletions

View File

@@ -7,9 +7,8 @@ TabWidth: 4
UseTab: ForIndentation UseTab: ForIndentation
AlignEscapedNewlines: DontAlign AlignEscapedNewlines: DontAlign
AllowShortFunctionsOnASingleLine: Empty AllowShortFunctionsOnASingleLine: Empty
BreakTemplateDeclarations: Yes AlwaysBreakTemplateDeclarations: true
BreakBeforeBraces: Custom BreakBeforeBraces: Custom
BraceWrapping: BraceWrapping:
AfterFunction: true AfterFunction: true
InsertBraces: true
... ...

38
.clangd
View File

@@ -1,38 +0,0 @@
# Editor accommodations for the second frontend. No compilation database is
# named here: this repo rides as a submodule in its consumers, and this file
# travels with it — a consumer's own database then covers these sources, with
# that project's loader flags. The checkout that is opened as a folder names
# its build tree in .vscode/settings.json instead.
CompileFlags:
Add:
# clang has no 24-bit integer and GCC's are keywords, not macros, so the
# editor needs a stand-in for avr::uint24_t. The next width up is the only
# one available — clang rejects _BitInt(24) on this target.
- -D__uint24=unsigned long
- -D__int24=long
# clangd forwards the driver's system includes but not its own header
# directory, so <stdint.h> resolves to avr-libc's, which still gates the
# limit and constant macros on the C++98 opt-in.
- -D__STDC_LIMIT_MACROS
- -D__STDC_CONSTANT_MACROS
# isr::emit spells a vector number into [[gnu::signal(N)]], which clang
# rejects rather than ignores — enough of them in one TU to reach the
# default limit of 19 inside the headers and truncate the parse.
- -ferror-limit=0
Remove:
# Codegen shaping the loader TUs carry and clang has no spelling for.
- -fira-algorithm=*
- -fno-split-wide-types
- -fno-tree-ter
- -fno-ivopts
- -fno-move-loop-invariants
# The build promotes warnings for the compiler that has to be right about
# them; in the editor the flag paints a second frontend's opinions in the
# colour reserved for things that do not compile.
- -Werror
Diagnostics:
Suppress:
# clang's AVR `signal` attribute takes no arguments and it knows none of
# progmem, naked or OS_main. A misspelling is what the build is for.
- attribute_wrong_number_arguments
- unknown-attributes

13
.gitattributes vendored
View File

@@ -1,11 +1,8 @@
# Line endings are the repository's, not the editing machine's: this checkout *.h eol=lf
# is reached from two hosts, and a file rewritten by a Windows tool comes back *.hpp eol=lf
# with every line changed unless something says otherwise. Naming the source *.c eol=lf
# extensions left Markdown, Python, shell and CMake to whatever the writing *.cpp eol=lf
# tool defaulted to, which is CRLF on one of the two. .git* eol=lf
* text=auto eol=lf
# Atmel Studio writes these and expects them back.
*.vcxproj* eol=crlf *.vcxproj* eol=crlf
*.cppproj eol=crlf *.cppproj eol=crlf
*.sln eol=crlf *.sln eol=crlf

5
.gitignore vendored
View File

@@ -12,10 +12,5 @@ Debug
# CMake / clangd # CMake / clangd
/build/ /build/
/local/
compile_commands.json compile_commands.json
.cache/ .cache/
# Python
__pycache__/
*.pyc

3
.gitmodules vendored
View File

@@ -1,3 +0,0 @@
[submodule "libavr"]
path = libavr
url = ../libavr.git

View File

@@ -1,6 +0,0 @@
{
"recommendations": [
"llvm-vs-code-extensions.vscode-clangd",
"ms-vscode.cmake-tools"
]
}

36
.vscode/settings.json vendored
View File

@@ -1,36 +0,0 @@
{
// clangd is the language server; the cpptools engine would parse every file
// a second time and disagree, since nothing tells it about a cross
// compiler.
"C_Cpp.intelliSenseEngine": "disabled",
// --query-driver lets clangd ask the cross compiler for its own system
// includes and target. The database is named here rather than in .clangd
// because that file travels with the driver into a consumer's submodule,
// where a build tree of this repo's own need not exist.
"clangd.arguments": [
"--compile-commands-dir=${workspaceFolder}/build/atmega328p-generated",
"--query-driver=**avr-g++*",
"--header-insertion=never"
],
// The presets are the build interface, and the toolchain file inside the
// libavr submodule is the one place the compiler is chosen. **No prefix is
// named here**: a committed file may not name a path that is true of one
// machine (libavr guidance rule 50), so the gitignored local/machine.cmake
// at this repository's root is where a checkout says where its toolchain
// is - one file, and it answers for both hosts.
"cmake.useCMakePresets": "always",
"cmake.configureOnOpen": true,
"cmake.options.statusBarVisibility": "compact",
"files.watcherExclude": {
"**/build/**": true,
"**/libavr/**": true
},
"files.associations": {
".clangd": "yaml",
".clang-format": "yaml"
}
}

View File

@@ -2,119 +2,56 @@ cmake_minimum_required(VERSION 3.28)
project(tsb_libavr LANGUAGES CXX) project(tsb_libavr LANGUAGES CXX)
# libavr rides as the pinned submodule; LIBAVR_ROOT (cache or environment) # libavr from a local checkout (LIBAVR_ROOT) or the forge; the toolchain file
# overrides it for tandem development against a working tree. The toolchain # comes from the same checkout via CMakePresets.json.
# file comes from the submodule via CMakePresets.json either way. include(FetchContent)
if(NOT LIBAVR_ROOT AND DEFINED ENV{LIBAVR_ROOT}) if(NOT LIBAVR_ROOT AND DEFINED ENV{LIBAVR_ROOT})
set(LIBAVR_ROOT $ENV{LIBAVR_ROOT}) set(LIBAVR_ROOT $ENV{LIBAVR_ROOT})
endif() endif()
if(NOT LIBAVR_ROOT) if(LIBAVR_ROOT)
set(LIBAVR_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/libavr) FetchContent_Declare(libavr SOURCE_DIR ${LIBAVR_ROOT})
else()
FetchContent_Declare(libavr GIT_REPOSITORY git@git.blackmark.me:avr/libavr.git GIT_TAG main)
endif() endif()
if(NOT EXISTS ${LIBAVR_ROOT}/CMakeLists.txt) FetchContent_MakeAvailable(libavr)
message(FATAL_ERROR "libavr not found at ${LIBAVR_ROOT} - run: git submodule update --init libavr")
endif()
add_subdirectory(${LIBAVR_ROOT} libavr-build)
include(${LIBAVR_ROOT}/cmake/checks.cmake)
if(PROJECT_IS_TOP_LEVEL) if(PROJECT_IS_TOP_LEVEL)
add_compile_options(-Werror) # warnings are errors for the port's own code add_compile_options(-Werror) # warnings are errors for the port's own code
enable_testing() enable_testing()
# Rules 11 and 33 over this repo's own sources. The oracle's assembly needs # The behavioral test drives the real TinySafeBoot wire protocol over a
# no exclusion: it is neither formatted nor ASCII-checked, being in neither # simavr pty (as the host tools do) and actually flashes the device. The
# glob, which is the right answer for a vendored reference whose text is # runner is a host program built at configure time against libsimavr; if it
# the artifact. # or Python is missing, only the size tests run.
libavr_format_test() find_program(_host_cc NAMES cc gcc)
find_package(Python3 COMPONENTS Interpreter)
# The behavioral tests drive the real wire protocols over a simavr pty if(_host_cc AND Python3_FOUND)
# (as the host tools do) and actually flash the device. The runner is a
# host program built at configure time against libsimavr (C++23 - what the
# distribution's compiler speaks in full).
#
# **A host that cannot build it registers those tests anyway and skips
# them.** They used to be left out, which makes the suite a different size
# on a different machine - and a suite whose size is a property of the
# machine is one nothing can be compared against.
set(TSB_DEVICE ${CMAKE_BINARY_DIR}/tsb_device) set(TSB_DEVICE ${CMAKE_BINARY_DIR}/tsb_device)
find_program(_host_cxx NAMES c++ g++)
set(_tsb_absent "${LIBAVR_NO_PYTHON}")
if(NOT _host_cxx)
set(_tsb_absent "no host C++ compiler on PATH, and the simavr device is a host program")
elseif(NOT _tsb_absent)
execute_process( execute_process(
COMMAND ${_host_cxx} -std=c++23 -Wall -Wextra -O2 COMMAND ${_host_cc} -O2 -I/usr/include/simavr -I/usr/include/simavr/parts
-I/usr/include/simavr -I/usr/include/simavr/parts -o ${TSB_DEVICE} ${CMAKE_CURRENT_SOURCE_DIR}/test/device.c
-o ${TSB_DEVICE} ${CMAKE_CURRENT_SOURCE_DIR}/test/device.cpp
-lsimavr -lsimavrparts -lelf -lsimavr -lsimavrparts -lelf
RESULT_VARIABLE _dev_res ERROR_VARIABLE _dev_err) RESULT_VARIABLE _dev_res ERROR_VARIABLE _dev_err)
if(NOT _dev_res EQUAL 0) if(NOT _dev_res EQUAL 0)
# One bounded line of it: this becomes a single argument on a message(STATUS "tsb_device not built (${_dev_err}) — protocol tests skipped")
# command line, and the reading has to say what stopped the build unset(TSB_DEVICE)
# rather than that something did.
string(REGEX REPLACE "[\r\n\t]+" " " _dev_err "${_dev_err}")
string(REPLACE ";" "," _dev_err "${_dev_err}")
string(LENGTH "${_dev_err}" _dev_len)
if(_dev_len GREATER 240)
string(SUBSTRING "${_dev_err}" 0 240 _dev_err)
endif() endif()
set(_tsb_absent "test/device.cpp does not build here: ${_dev_err}")
endif()
endif()
libavr_launcher(_tsb_python "${_tsb_absent}" ${Python3_EXECUTABLE})
if(_tsb_absent)
message(STATUS "the protocol tests skip here - ${_tsb_absent}")
endif() endif()
endif() endif()
# The ELF is only a container (symbols, section headers) and is never flashed - # The TinySafeBoot protocol reimplemented on libavr in three variants that trade
# and the host tool's load_image() dispatches on extension, so handing it one
# would silently program the header bytes. Every loader image therefore gets
# both flashable forms beside it at link time: .hex for avrdude, and .bin for
# the host tool's raw path (which is what the reloc and update tests convert to
# on the fly). .eeprom is dropped - EEPROM content is its own update.
function(add_image_outputs name)
add_custom_command(TARGET ${name} POST_BUILD
COMMAND ${CMAKE_OBJCOPY} -O ihex -R .eeprom
$<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.hex
COMMAND ${CMAKE_OBJCOPY} -O binary -R .eeprom
$<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.bin)
endfunction()
# The TinySafeBoot protocol reimplemented on libavr in variants that trade
# clarity for size. Each links into the ATmega328P boot section (BOOTSZ selects # clarity for size. Each links into the ATmega328P boot section (BOOTSZ selects
# its size; BOOTRST vectors a reset to its base) with -nostartfiles - a polled # its size; BOOTRST vectors a reset to its base) with -nostartfiles a polled
# loader has no use for the crt or the vector table. The entry sits in # loader has no use for the crt or the vector table. The naked entry sits in
# .vectors, laid first, and runs - avr::startup::entry on the policy tier, # .vectors, laid first, and runs. The boot base is FLASHEND+1 minus the section
# the experiment tiers' own naked stubs elsewhere, each documented in its # size; the linker section-start and the source's boot_bytes agree.
# source. The boot base is FLASHEND+1 minus the section size; the linker # All three implement the full oracle feature set (see oracle/README.md):
# section-start and the source's boot_bytes agree. tsb_app is
# the application's reset vector, pinned to 0 here so the loaders jump to a
# named function; --pmem-wrap-around lets relaxation turn that absolute jump
# into the wrapped rjmp AVR's modulo-flash PC actually executes.
# All four implement the full oracle feature set (see oracle/README.md):
# watchdog bail, one-wire half-duplex, config-page activation timeout, password # watchdog bail, one-wire half-duplex, config-page activation timeout, password
# gate, emergency erase, config/flash/EEPROM read-write. They differ only in how, # gate, emergency erase, config/flash/EEPROM read-write. They differ only in how.
# and the size gradient is the cost of that "how". # tsb_asm — minimal inline asm, the headline: 502 B in the 512 B section,
# tsb_asm - the tricks tier's C++ with exactly two routines in asm: the # matching the hand-written oracle's size and features.
# bounded rx and the page-store loop, the two whose remaining # tsb_tricks — compiler trickery, no asm: 808 B in the 1 KB section (BOOTSZ=10).
# cost is the C ABI itself. Everything else, bring-up to # tsb_pure — pure idiomatic libavr: 950 B in the 1 KB section.
# dispatch, is C++ on libavr.
# tsb_tricks - no asm at all: the whole-loader register allocation lives in
# global register variables (Y walks the page pointer), every
# helper is a tiny noinline primitive placed by the
# global-register store rules, pages stream straight to
# SPM/EEPROM.
# tsb_pure - pure idiomatic libavr, one function per command, TU-local
# (internal linkage), streaming (no SRAM page buffer).
# tsb_policy - the policy floor: no inline assembly and no global register
# variables, which is philosophy #5's own bound, and the
# measured evidence that the 512 B fit is a property of the
# mechanisms it bans.
#
# What each measures is oracle/README.md's table, which is the one place the
# four numbers and the hand-written loader's own are compared.
# #
# add_tsb_variant(<name> <boot-section-bytes>) # add_tsb_variant(<name> <boot-section-bytes>)
function(add_tsb_variant name bytes) function(add_tsb_variant name bytes)
@@ -122,36 +59,20 @@ function(add_tsb_variant name bytes)
math(EXPR base_hex "${base_dec}" OUTPUT_FORMAT HEXADECIMAL) math(EXPR base_hex "${base_dec}" OUTPUT_FORMAT HEXADECIMAL)
add_executable(${name} tsb/${name}.cpp) add_executable(${name} tsb/${name}.cpp)
target_link_libraries(${name} PRIVATE libavr) target_link_libraries(${name} PRIVATE libavr)
target_link_options(${name} PRIVATE -nostartfiles -Wl,--section-start=.text=${base_hex} target_link_options(${name} PRIVATE -nostartfiles -Wl,--section-start=.text=${base_hex})
-Wl,--defsym=tsb_app=0 -Wl,--pmem-wrap-around=32k)
add_custom_command(TARGET ${name} POST_BUILD COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${name}>) add_custom_command(TARGET ${name} POST_BUILD COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${name}>)
add_image_outputs(${name})
if(PROJECT_IS_TOP_LEVEL) if(PROJECT_IS_TOP_LEVEL)
add_test(NAME ${name}.size add_test(NAME ${name}.size
COMMAND ${CMAKE_COMMAND} -DSIZE_TOOL=${CMAKE_SIZE} -DELF=$<TARGET_FILE:${name}> COMMAND ${CMAKE_COMMAND} -DSIZE_TOOL=${CMAKE_SIZE} -DELF=$<TARGET_FILE:${name}>
-DLIMIT=${bytes} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/check_size.cmake) -DLIMIT=${bytes} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/check_size.cmake)
if(DEFINED TSB_DEVICE)
add_test(NAME ${name}.protocol add_test(NAME ${name}.protocol
COMMAND ${_tsb_python} ${CMAKE_CURRENT_SOURCE_DIR}/test/tsbtest.py COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/tsbtest.py
${TSB_DEVICE} $<TARGET_FILE:${name}> ${base_hex}) ${TSB_DEVICE} $<TARGET_FILE:${name}> ${base_hex})
endif() endif()
endif()
endfunction() endfunction()
# The tiers reimplement the ATmega328P-only reference protocol, so the guard is add_tsb_variant(tsb_asm 512)
# the whole of what this repo builds. add_tsb_variant(tsb_pure 1024)
if(LIBAVR_MCU STREQUAL "atmega328p") add_tsb_variant(tsb_tricks 1024)
add_tsb_variant(tsb_asm 512)
add_tsb_variant(tsb_policy 1024)
add_tsb_variant(tsb_pure 1024)
add_tsb_variant(tsb_tricks 1024)
# The policy tier's floor needs these two: a loader's loop bodies all
# contain calls, which is what makes hoisting an invariant out of one cost
# more than it saves. The other tiers keep the flag set their recorded
# floors were measured with - none.
target_compile_options(tsb_policy PRIVATE -fno-move-loop-invariants -fno-tree-ter)
endif()
# Every test registered above carries the marker a stubbed launcher prints, so
# a check this host cannot run reads as Skipped rather than Failed.
if(PROJECT_IS_TOP_LEVEL)
libavr_skip_unverified()
endif()

View File

@@ -6,7 +6,7 @@
"hidden": true, "hidden": true,
"generator": "Ninja", "generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}", "binaryDir": "${sourceDir}/build/${presetName}",
"toolchainFile": "${sourceDir}/libavr/cmake/avr-toolchain.cmake", "toolchainFile": "$env{LIBAVR_ROOT}/cmake/avr-toolchain.cmake",
"cacheVariables": { "cacheVariables": {
"CMAKE_BUILD_TYPE": "Release", "CMAKE_BUILD_TYPE": "Release",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
@@ -16,69 +16,29 @@
{ {
"name": "atmega328p-generated", "name": "atmega328p-generated",
"inherits": "base", "inherits": "base",
"cacheVariables": { "cacheVariables": { "LIBAVR_MCU": "atmega328p", "LIBAVR_REFLECT": "OFF" }
"LIBAVR_MCU": "atmega328p",
"LIBAVR_REFLECT": "OFF"
}
}, },
{ {
"name": "atmega328p-reflect", "name": "atmega328p-reflect",
"inherits": "base", "inherits": "base",
"cacheVariables": { "cacheVariables": { "LIBAVR_MCU": "atmega328p", "LIBAVR_REFLECT": "ON" }
"LIBAVR_MCU": "atmega328p",
"LIBAVR_REFLECT": "ON"
}
} }
], ],
"buildPresets": [ "buildPresets": [
{ { "name": "atmega328p-generated", "configurePreset": "atmega328p-generated" },
"name": "atmega328p-generated", { "name": "atmega328p-reflect", "configurePreset": "atmega328p-reflect" }
"configurePreset": "atmega328p-generated"
},
{
"name": "atmega328p-reflect",
"configurePreset": "atmega328p-reflect"
}
],
"testPresets": [
{
"name": "atmega328p-generated",
"configurePreset": "atmega328p-generated",
"output": {
"outputOnFailure": true
}
}
], ],
"workflowPresets": [ "workflowPresets": [
{ {
"name": "atmega328p-generated", "name": "atmega328p-generated",
"steps": [ "steps": [
{ { "type": "configure", "name": "atmega328p-generated" },
"type": "configure", { "type": "build", "name": "atmega328p-generated" },
"name": "atmega328p-generated" { "type": "test", "name": "atmega328p-generated" }
},
{
"type": "build",
"name": "atmega328p-generated"
},
{
"type": "test",
"name": "atmega328p-generated"
}
]
},
{
"name": "atmega328p-reflect",
"steps": [
{
"type": "configure",
"name": "atmega328p-reflect"
},
{
"type": "build",
"name": "atmega328p-reflect"
}
] ]
} }
],
"testPresets": [
{ "name": "atmega328p-generated", "configurePreset": "atmega328p-generated", "output": { "outputOnFailure": true } }
] ]
} }

View File

@@ -1,67 +0,0 @@
# Atmel Studio
`master` carries `bootloader.atsln`, so this branch does too: `ide/bootloader.atsln`
builds the loader from the same source Ninja does, to a **byte-identical
`.text`** — the `tsb_asm` tier in its 512-byte section (`check-flags.py` below
is what holds the flag sets equal, so the size is Ninja's own). CMake remains
the build system; the solution is here so the port opens in Studio as its
predecessor did.
## One project, of four tiers
A `.cppproj` is one binary at one set of flags. `tsb_asm` is the tier that
occupies the same 512-byte section `master`'s `tsb` project targeted, which is
the one worth opening in Studio.
The other three tiers (`tsb_pure`, `tsb_tricks`, `tsb_policy`) are not here.
They differ from `tsb_asm` in their source file, their section size, and — for
`tsb_policy` — two loop flags; nothing about that is a Studio concern, and what
they exist to demonstrate is a size gradient only the CMake size tests measure.
Adding one is a copy of `tsb_asm/tsb_asm.cppproj` in its own directory, with its
name, its GUID, its source path and its `--section-start` changed (`0x7c00` for
the 1 KiB tiers), plus four lines in the solution.
`avrdevice` is a project property, so each project gets its own directory:
Studio builds into `<project dir>/<Configuration>` whatever `OutputDirectory`
says, and two projects sharing a directory would share one object file.
## Debug keeps `-Os`
Both configurations compile at `-Os`; Debug adds only `-gdwarf-4`. The `.text`
is therefore identical in both, which is the point — a loader's section is a
**correctness** bound and not a budget. A debug configuration that silently
overruns the section is worse than none, and DWARF costs no flash, so the
optimisation level stays where correctness needs it.
## What Studio needs from the machine
libavr from the **submodule**, found at
`$(MSBuildProjectDirectory)\..\..\libavr\include` — correct by construction, and
anchored to the project because a plain relative path resolves against the
generated makefile's directory (the configuration's output directory), not the
project's. There is no `LIBAVR_ROOT` escape hatch: a variable exported in a
shell is invisible to Studio launched from the Start menu, and the failure reads
as a missing `libavr/libavr.hpp` — which is what the submodule answers.
A GCC 16.1 toolchain registered as flavour `avr-g++-16.1.0`, nothing older
reaching `-std=c++26`.
## Generating and gating
One generated file is required before the project will load at all, and one
command checks the flags have not drifted (both from libavr's
`tools/atmelstudio/`):
```sh
python libavr/tools/atmelstudio/componentinfo.py \
ide/tsb_asm/tsb_asm.componentinfo.xml --device ATmega328P
python libavr/tools/atmelstudio/check-flags.py \
--solution ide/bootloader.atsln --project tsb_asm --target tsb_asm \
--compile-commands build/atmega328p-generated/compile_commands.json \
--log build/as-tsb_asm.log
```
Release is what the gate compares — the presets define no debug build, and
Debug differs from Release only in `-gdwarf-4`.
Legacy (the yazoalfa-era submodules) stays on `master`.

View File

@@ -1,22 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Atmel Studio Solution File, Format Version 11.00
VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{E66E83B9-2572-4076-B26E-6BE79FF3018A}") = "tsb_asm", "tsb_asm\tsb_asm.cppproj", "{6618D3BE-7EB3-49A2-9113-F128E396FF06}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AVR = Debug|AVR
Release|AVR = Release|AVR
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6618D3BE-7EB3-49A2-9113-F128E396FF06}.Debug|AVR.ActiveCfg = Debug|AVR
{6618D3BE-7EB3-49A2-9113-F128E396FF06}.Debug|AVR.Build.0 = Debug|AVR
{6618D3BE-7EB3-49A2-9113-F128E396FF06}.Release|AVR.ActiveCfg = Release|AVR
{6618D3BE-7EB3-49A2-9113-F128E396FF06}.Release|AVR.Build.0 = Release|AVR
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,112 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="14.0">
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
<ProjectVersion>7.0</ProjectVersion>
<ToolchainName>com.Atmel.AVRGCC8.CPP</ToolchainName>
<ProjectGuid>6618d3be-7eb3-49a2-9113-f128e396ff06</ProjectGuid>
<avrdevice>ATmega328P</avrdevice>
<avrdeviceseries>none</avrdeviceseries>
<OutputType>Executable</OutputType>
<Language>CPP</Language>
<OutputFileName>$(MSBuildProjectName)</OutputFileName>
<OutputFileExtension>.elf</OutputFileExtension>
<OutputDirectory>$(MSBuildProjectDirectory)\$(Configuration)</OutputDirectory>
<AssemblyName>tsb_asm</AssemblyName>
<Name>tsb_asm</Name>
<RootNamespace>tsb_asm</RootNamespace>
<ToolchainFlavour>avr-g++-16.1.0</ToolchainFlavour>
<KeepTimersRunning>true</KeepTimersRunning>
<OverrideVtor>false</OverrideVtor>
<CacheFlash>true</CacheFlash>
<ProgFlashFromRam>true</ProgFlashFromRam>
<RamSnippetAddress>0x20000000</RamSnippetAddress>
<UncachedRange />
<preserveEEPROM>true</preserveEEPROM>
<OverrideVtorValue>exception_table</OverrideVtorValue>
<BootSegment>2</BootSegment>
<ResetRule>0</ResetRule>
<eraseonlaunchrule>0</eraseonlaunchrule>
<EraseKey />
<AsfFrameworkConfig>
<framework-data xmlns="">
<options />
<configurations />
<files />
<documentation help="" />
<offline-documentation help="" />
<dependencies>
<content-extension eid="atmel.asf" uuidref="Atmel.ASF" version="3.52.0" />
</dependencies>
</framework-data>
</AsfFrameworkConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<ToolchainSettings>
<AvrGccCpp>
<avrgcc.common.Device>-mmcu=atmega328p</avrgcc.common.Device>
<avrgcc.common.outputfiles.hex>True</avrgcc.common.outputfiles.hex>
<avrgcc.common.outputfiles.lss>True</avrgcc.common.outputfiles.lss>
<avrgcc.common.outputfiles.eep>True</avrgcc.common.outputfiles.eep>
<avrgcc.common.outputfiles.srec>True</avrgcc.common.outputfiles.srec>
<avrgcc.common.outputfiles.usersignatures>False</avrgcc.common.outputfiles.usersignatures>
<avrgcccpp.compiler.symbols.DefSymbols>
<ListValues>
<Value>NDEBUG</Value>
</ListValues>
</avrgcccpp.compiler.symbols.DefSymbols>
<avrgcccpp.compiler.directories.IncludePaths>
<ListValues>
<Value>$(MSBuildProjectDirectory)\..\..\libavr\include</Value>
</ListValues>
</avrgcccpp.compiler.directories.IncludePaths>
<avrgcccpp.compiler.optimization.level>Optimize for size (-Os)</avrgcccpp.compiler.optimization.level>
<avrgcccpp.compiler.optimization.PrepareFunctionsForGarbageCollection>True</avrgcccpp.compiler.optimization.PrepareFunctionsForGarbageCollection>
<avrgcccpp.compiler.optimization.PrepareDataForGarbageCollection>True</avrgcccpp.compiler.optimization.PrepareDataForGarbageCollection>
<avrgcccpp.compiler.warnings.AllWarnings>True</avrgcccpp.compiler.warnings.AllWarnings>
<avrgcccpp.compiler.miscellaneous.OtherFlags>-std=c++26 -Wextra -Werror -mrelax -fno-exceptions -fno-rtti -fno-threadsafe-statics</avrgcccpp.compiler.miscellaneous.OtherFlags>
<avrgcccpp.linker.optimization.GarbageCollectUnusedSections>True</avrgcccpp.linker.optimization.GarbageCollectUnusedSections>
<avrgcccpp.linker.miscellaneous.LinkerFlags>-mrelax -nostartfiles -Wl,--section-start=.text=0x7e00 -Wl,--defsym=tsb_app=0 -Wl,--pmem-wrap-around=32k</avrgcccpp.linker.miscellaneous.LinkerFlags>
</AvrGccCpp>
</ToolchainSettings>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<ToolchainSettings>
<AvrGccCpp>
<avrgcc.common.Device>-mmcu=atmega328p</avrgcc.common.Device>
<avrgcc.common.outputfiles.hex>True</avrgcc.common.outputfiles.hex>
<avrgcc.common.outputfiles.lss>True</avrgcc.common.outputfiles.lss>
<avrgcc.common.outputfiles.eep>True</avrgcc.common.outputfiles.eep>
<avrgcc.common.outputfiles.srec>True</avrgcc.common.outputfiles.srec>
<avrgcc.common.outputfiles.usersignatures>False</avrgcc.common.outputfiles.usersignatures>
<avrgcccpp.compiler.symbols.DefSymbols>
<ListValues>
<Value>DEBUG</Value>
</ListValues>
</avrgcccpp.compiler.symbols.DefSymbols>
<avrgcccpp.compiler.directories.IncludePaths>
<ListValues>
<Value>$(MSBuildProjectDirectory)\..\..\libavr\include</Value>
</ListValues>
</avrgcccpp.compiler.directories.IncludePaths>
<avrgcccpp.compiler.optimization.level>Optimize for size (-Os)</avrgcccpp.compiler.optimization.level>
<avrgcccpp.compiler.optimization.PrepareFunctionsForGarbageCollection>True</avrgcccpp.compiler.optimization.PrepareFunctionsForGarbageCollection>
<avrgcccpp.compiler.optimization.PrepareDataForGarbageCollection>True</avrgcccpp.compiler.optimization.PrepareDataForGarbageCollection>
<avrgcccpp.compiler.warnings.AllWarnings>True</avrgcccpp.compiler.warnings.AllWarnings>
<avrgcccpp.compiler.miscellaneous.OtherFlags>-std=c++26 -Wextra -Werror -mrelax -fno-exceptions -fno-rtti -fno-threadsafe-statics -gdwarf-4</avrgcccpp.compiler.miscellaneous.OtherFlags>
<avrgcccpp.linker.optimization.GarbageCollectUnusedSections>True</avrgcccpp.linker.optimization.GarbageCollectUnusedSections>
<avrgcccpp.linker.miscellaneous.LinkerFlags>-mrelax -nostartfiles -Wl,--section-start=.text=0x7e00 -Wl,--defsym=tsb_app=0 -Wl,--pmem-wrap-around=32k</avrgcccpp.linker.miscellaneous.LinkerFlags>
</AvrGccCpp>
</ToolchainSettings>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\tsb\tsb_asm.cpp">
<SubType>compile</SubType>
<Link>tsb\tsb_asm.cpp</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<Folder Include="tsb" />
</ItemGroup>
<Import Project="$(AVRSTUDIO_EXE_PATH)\Vs\Compiler.targets" />
</Project>

1
libavr

Submodule libavr deleted from 93d8b0e491

View File

@@ -38,23 +38,9 @@ avra -I /usr/share/avra tsb-fixedbaud.asm # after uncommenting .include "m328P
``` ```
**500 bytes with every feature** — the proof that ≤512 B and full feature parity **500 bytes with every feature** — the proof that ≤512 B and full feature parity
are simultaneously reachable. The port's four tiers reach it from the other are simultaneously reachable. The port's `tsb_asm` tier matches this bar; `tsb_pure`
side, and the gradient between them is the cost of the mechanisms each is and `tsb_tricks` implement the same protocol at larger sizes in the 1 KB section,
allowed: trading bytes for readability.
| tier | bytes | section | what it is allowed |
|---|---|---|---|
| oracle | 500 | 512 B | hand-written assembly, the reference |
| `tsb_asm` | 512 | 512 B | C++ on libavr, two routines in asm |
| `tsb_tricks` | 528 | 1 KB | no asm; global register variables |
| `tsb_policy` | 630 | 1 KB | pureboot's rules: no asm, no register variables |
| `tsb_pure` | 776 | 1 KB | idiomatic libavr throughout |
The two routines `tsb_asm` keeps are the ones whose remaining cost is the
calling convention itself: the bounded rx and the page-store loop. It fills
its section exactly, with the same one-bit-time turn-around guard the oracle
spends six bytes on - every tier implements the whole feature set, which is
what makes the column a gradient rather than four different loaders.
The oracle targets 20 MHz / 33333 baud; the port targets 16 MHz / 115200 baud The oracle targets 20 MHz / 33333 baud; the port targets 16 MHz / 115200 baud
(what the simavr protocol test drives). Baud and geometry differ, code size and (what the simavr protocol test drives). Baud and geometry differ, code size and

View File

@@ -4,9 +4,6 @@ if(NOT _res EQUAL 0)
endif() endif()
# avr-size line 2 is "<text> <data> <bss> <dec> <hex> <file>". # avr-size line 2 is "<text> <data> <bss> <dec> <hex> <file>".
string(REGEX MATCH "\n[ \t]*([0-9]+)" _m "${_out}") string(REGEX MATCH "\n[ \t]*([0-9]+)" _m "${_out}")
if(NOT _m)
message(FATAL_ERROR "could not read a .text size out of ${SIZE_TOOL}'s output for ${ELF}:\n${_out}")
endif()
set(_text ${CMAKE_MATCH_1}) set(_text ${CMAKE_MATCH_1})
if(_text GREATER LIMIT) if(_text GREATER LIMIT)
message(FATAL_ERROR ".text is ${_text} bytes, over the ${LIMIT}-byte boot section") message(FATAL_ERROR ".text is ${_text} bytes, over the ${LIMIT}-byte boot section")

View File

@@ -7,122 +7,103 @@
// SPM genuinely writes avr->flash on the mega cores, so on exit (or SIGTERM) // SPM genuinely writes avr->flash on the mega cores, so on exit (or SIGTERM)
// we dump the flash image to a file for a ground-truth cross-check against // we dump the flash image to a file for a ground-truth cross-check against
// what the client read back through the bootloader. // what the client read back through the bootloader.
#include <array> #include <signal.h>
#include <csignal> #include <stdint.h>
#include <cstdint> #include <stdio.h>
#include <cstdio> #include <stdlib.h>
#include <cstdlib> #include <string.h>
#include <cstring>
#include <print>
#include <unistd.h> #include <unistd.h>
// The parts headers (uart_pty.h) carry no C++ linkage guards of their own,
// unlike simavr's core headers - the block covers both harmlessly.
extern "C" {
#include "avr_uart.h" #include "avr_uart.h"
#include "sim_avr.h" #include "sim_avr.h"
#include "sim_elf.h" #include "sim_elf.h"
#include "uart_pty.h" #include "uart_pty.h"
}
namespace { static avr_t *avr;
static uart_pty_t uart_pty;
static const char *dump_path;
avr_t *avr; static void finish(int sig)
uart_pty_t uart_pty;
const char *dump_path;
[[noreturn]] void finish(int)
{ {
(void)sig;
if (dump_path) { if (dump_path) {
std::FILE *f = std::fopen(dump_path, "wb"); FILE *f = fopen(dump_path, "wb");
if (f) { if (f) {
std::fwrite(avr->flash, 1, avr->flashend + 1, f); fwrite(avr->flash, 1, avr->flashend + 1, f);
std::fclose(f); fclose(f);
} }
} }
uart_pty_stop(&uart_pty); uart_pty_stop(&uart_pty);
_exit(0); _exit(0);
} }
} // namespace
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
if (argc < 3) { if (argc < 3) {
std::println(stderr, "usage: {} <tsb.elf> <boot_base_hex> [flash_dump.bin]", argv[0]); fprintf(stderr, "usage: %s <tsb.elf> <boot_base_hex> [flash_dump.bin]\n", argv[0]);
return 2; return 2;
} }
auto boot_base = static_cast<std::uint32_t>(std::strtoul(argv[2], nullptr, 0)); uint32_t boot_base = (uint32_t)strtoul(argv[2], NULL, 0);
dump_path = argc >= 4 ? argv[3] : nullptr; dump_path = argc >= 4 ? argv[3] : NULL;
avr = avr_make_mcu_by_name("atmega328p"); avr = avr_make_mcu_by_name("atmega328p");
if (!avr) { if (!avr) {
std::println(stderr, "device: no ATmega328P core"); fprintf(stderr, "device: no ATmega328P core\n");
return 1; return 1;
} }
avr_init(avr); avr_init(avr);
avr->frequency = 16000000; avr->frequency = 16000000;
// Real flash powers up erased (0xff); the app region must look erased // Real flash powers up erased (0xff); the app region must look erased
// before the bootloader programs it. // before the bootloader programs it.
std::memset(avr->flash, 0xff, avr->flashend + 1); memset(avr->flash, 0xff, avr->flashend + 1);
// simavr's ELF loader flattens the flash base to 0 (it expects an app at // simavr's ELF loader flattens the flash base to 0 (it expects an app at
// 0x0), but it hands back the boot code in fw.flash; place it at the boot // 0x0), but it hands back the boot code in fw.flash; place it at the boot
// section base ourselves and enter there (BOOTRST is not modelled). // section base ourselves and enter there (BOOTRST is not modelled).
elf_firmware_t fw{}; elf_firmware_t fw = {0};
if (elf_read_firmware(argv[1], &fw) != 0) { if (elf_read_firmware(argv[1], &fw) != 0) {
std::println(stderr, "device: cannot read {}", argv[1]); fprintf(stderr, "device: cannot read %s\n", argv[1]);
return 1; return 1;
} }
// An image that runs past flash end cannot execute on hardware, and a memcpy(avr->flash + boot_base, fw.flash, fw.flashsize);
// naive copy of it would smash the heap beyond avr->flash - after which
// the simulation misbehaves in ways that point everywhere but here.
// Refuse it loudly instead.
if (boot_base + fw.flashsize > avr->flashend + 1) {
std::println(stderr, "device: {} B at {:#x} runs past flash end {:#x} - image does not fit its slot",
fw.flashsize, boot_base, avr->flashend);
return 1;
}
std::memcpy(avr->flash + boot_base, fw.flash, fw.flashsize);
avr->pc = boot_base; avr->pc = boot_base;
avr->codeend = avr->flashend; avr->codeend = avr->flashend;
// Optional: seed the config page (one page below the boot section) with a // Optional: seed the config page (one page below the boot section) with a
// hex byte string, so the password gate and emergency erase can be tested. // hex byte string, so the password gate and emergency erase can be tested.
// Layout: [appjump lo][appjump hi][timeout][password...][0xff]. // Layout: [appjump lo][appjump hi][timeout][password...][0xff].
const char *cfg = std::getenv("TSB_CONFIG"); const char *cfg = getenv("TSB_CONFIG");
if (cfg) { if (cfg) {
std::uint32_t app_end = boot_base - 128; // config page sits directly below the boot code uint32_t app_end = boot_base - 128; // config page sits directly below the boot code
for (int i = 0; cfg[i] && cfg[i + 1]; i += 2) { for (int i = 0; cfg[i] && cfg[i + 1]; i += 2) {
const std::array pair{cfg[i], cfg[i + 1], '\0'}; char b[3] = {cfg[i], cfg[i + 1], 0};
avr->flash[app_end + i / 2] = static_cast<std::uint8_t>(std::strtoul(pair.data(), nullptr, 16)); avr->flash[app_end + i / 2] = (uint8_t)strtoul(b, NULL, 16);
} }
} }
// POLL_SLEEP makes simavr usleep(1) on every status-register read while the // POLL_SLEEP makes simavr usleep(1) on every status-register read while the
// UART is idle - a host-CPU-saving hack that models no hardware and paces a // UART is idle a host-CPU-saving hack that models no hardware and paces a
// tight-polling loader (one that releases TX between bytes, as one-wire does) // tight-polling loader (one that releases TX between bytes, as one-wire does)
// in real time, distorting protocol timing. Clear it so the loader runs at // in real time, distorting protocol timing. Clear it so the loader runs at
// true cycle speed. // true cycle speed.
std::uint32_t uflags = 0; uint32_t uflags = 0;
avr_ioctl(avr, AVR_IOCTL_UART_GET_FLAGS('0'), &uflags); avr_ioctl(avr, AVR_IOCTL_UART_GET_FLAGS('0'), &uflags);
uflags &= ~AVR_UART_FLAG_POLL_SLEEP; uflags &= ~AVR_UART_FLAG_POLL_SLEEP;
avr_ioctl(avr, AVR_IOCTL_UART_SET_FLAGS('0'), &uflags); avr_ioctl(avr, AVR_IOCTL_UART_SET_FLAGS('0'), &uflags);
uart_pty_init(avr, &uart_pty); uart_pty_init(avr, &uart_pty);
uart_pty_connect(&uart_pty, '0'); uart_pty_connect(&uart_pty, '0');
std::println("TSB_PTY {}", uart_pty.pty.slavename); printf("TSB_PTY %s\n", uart_pty.pty.slavename);
std::fflush(stdout); fflush(stdout);
std::signal(SIGTERM, finish); signal(SIGTERM, finish);
std::signal(SIGINT, finish); signal(SIGINT, finish);
for (;;) { for (;;) {
int state = avr_run(avr); int state = avr_run(avr);
if (state == cpu_Done || state == cpu_Crashed) { if (state == cpu_Done || state == cpu_Crashed)
break; break;
} }
}
finish(0); finish(0);
return 0;
} }

View File

@@ -144,7 +144,7 @@ class Host:
self._expect(CONFIRM, "C end") self._expect(CONFIRM, "C end")
return echo return echo
# Activation when the config page carries a password: 3x'@' then the # Activation when the config page carries a password: 3×'@' then the
# password bytes, then the info block + mainloop '!'. # password bytes, then the info block + mainloop '!'.
def activate_password(self, password): def activate_password(self, password):
self.s.reset_input_buffer() self.s.reset_input_buffer()
@@ -167,20 +167,6 @@ class Host:
self._expect(CONFIRM, "emergency mainloop ready") self._expect(CONFIRM, "emergency mainloop ready")
# A wrong password byte hangs the loader, still draining the line. Two
# things must not happen: it must not activate, and it must not fall
# through to the emergency erase - a byte the gate has already refused
# reaching the erase would let a guess wipe the part.
def refuse_password(self, byte):
self.s.reset_input_buffer()
self.s.write(bytes([KNOCK, KNOCK, KNOCK, byte]))
return self.s.read(1)
def say(self, byte):
self.s.write(bytes([byte]))
return self.s.read(1)
def check(cond, msg): def check(cond, msg):
if not cond: if not cond:
raise AssertionError(msg) raise AssertionError(msg)
@@ -195,7 +181,7 @@ PW_BYTES = bytes([0x50, 0x57])
def scenario_roundtrip(host): def scenario_roundtrip(host):
"""Activation + info block + flash/EEPROM/config read-write round-trips, on """Activation + info block + flash/EEPROM/config read-write round-trips, on
a device with a blank (erased) config page - the usual no-password case.""" a device with a blank (erased) config page the usual no-password case."""
info = host.activate() info = host.activate()
check(info[0:3] == b"TSB", f"magic 'TSB' (got {info[0:3]!r})") check(info[0:3] == b"TSB", f"magic 'TSB' (got {info[0:3]!r})")
check(info[6:9] == bytes([0x1E, 0x95, 0x0F]), f"signature 1E 95 0F (got {info[6:9].hex()})") check(info[6:9] == bytes([0x1E, 0x95, 0x0F]), f"signature 1E 95 0F (got {info[6:9].hex()})")
@@ -233,15 +219,6 @@ def scenario_emergency(host):
check(host.read_eeprom(1) == b"\xff" * PAGE, "EEPROM wiped") check(host.read_eeprom(1) == b"\xff" * PAGE, "EEPROM wiped")
def scenario_wrong_password(host):
"""A wrong password byte neither activates the loader nor opens the
emergency erase behind it - the oracle carries a dedicated fix for the
second, and nothing here exercised either half."""
check(host.refuse_password(PW_BYTES[0] ^ 1) == b"", "a wrong password byte draws no reply")
check(host.say(0x00) == b"", "a 0 byte after it does not request the erase")
check(host.say(CONFIRM) == b"", "and neither does a confirm")
def main(): def main():
binary, elf, boot_base = sys.argv[1], sys.argv[2], sys.argv[3] binary, elf, boot_base = sys.argv[1], sys.argv[2], sys.argv[3]
failures = [] failures = []
@@ -252,7 +229,6 @@ def main():
("round-trip", None, scenario_roundtrip), ("round-trip", None, scenario_roundtrip),
("password activation", PW_CONFIG, scenario_password), ("password activation", PW_CONFIG, scenario_password),
("emergency erase", PW_CONFIG, scenario_emergency), ("emergency erase", PW_CONFIG, scenario_emergency),
("wrong password", PW_CONFIG, scenario_wrong_password),
] ]
for name, config, fn in groups: for name, config, fn in groups:
print(f"--- {name} ---") print(f"--- {name} ---")

View File

@@ -1,60 +0,0 @@
#!/bin/bash
# The port's gate: the generated workflow - build, size tests, and the
# simulator-driven protocol suite. --full adds the reflect build, which
# compiles the same TUs through libavr's other producer. libavr resolves from
# the `libavr/` submodule; LIBAVR_ROOT overrides it for a working tree.
set -e
cd "$(dirname "$0")/.."
full=0
[[ "$1" == "--full" ]] && { full=1; shift; }
# The chip lists come from the presets rather than being spelled a second time
# here: a chip added to make_presets.py and missed in a copy of its list would
# be a gate that silently never builds it, which is the one failure mode a gate
# cannot report. tools/make_presets.py is the single source, CMakePresets.json
# is its output, and this reads that.
readarray -t WORKFLOWS < <(python3 -c '
import json, sys
presets = json.load(open("CMakePresets.json"))["workflowPresets"]
print("\n".join(p["name"] for p in presets))')
if ((${#WORKFLOWS[@]} == 0)); then
echo "no workflow presets in CMakePresets.json - run tools/make_presets.py" >&2
exit 1
fi
CHIPS=()
REFLECT_SPOT=()
for workflow in "${WORKFLOWS[@]}"; do
case $workflow in
*-generated) CHIPS+=("${workflow%-generated}") ;;
*-reflect) REFLECT_SPOT+=("${workflow%-reflect}") ;;
esac
done
# Every preset runs even after one goes red, and the gate fails at the end
# naming all of them: stopping at the first failure turns a red - a stale size
# canary above all - into an alibi for every chip behind it, and a loader can
# ship on a chip this gate has not compiled since.
red=()
run_preset() {
echo "==== $1 ===="
cmake --workflow --preset "$1" "${@:2}" || red+=("$1")
}
for chip in "${CHIPS[@]}"; do
run_preset "$chip-generated" "$@"
done
if ((full)); then
for chip in "${REFLECT_SPOT[@]}"; do
run_preset "$chip-reflect" "$@"
done
fi
if ((${#red[@]})); then
printf '==== red presets ====\n' >&2
printf ' %s\n' "${red[@]}" >&2
exit 1
fi
echo "check: every chip green"

View File

@@ -1,90 +0,0 @@
#!/usr/bin/env python3
"""Regenerate CMakePresets.json - one uniform pipeline per chip.
The tiers reimplement the ATmega328P-only reference protocol, so that is the
whole chip list. It stays a generated file rather than a hand-written one
because the shape - configure, build, test, workflow, and a reflect pair
without tests - is the shape a second chip would need too.
Run from the repo root: tools/make_presets.py - or with --check, which
verifies the committed file matches this generator and edits nothing (the
ctest entry `presets.generated` runs that, so drift reds the gate).
"""
import json
import os
import sys
CHIPS = [
"atmega328p",
]
# The reflect pair: the same chip, built in libavr's other mode.
REFLECT_SPOT = [
"atmega328p",
]
def main():
configure = [{
"name": "base",
"hidden": True,
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"toolchainFile": "${sourceDir}/libavr/cmake/avr-toolchain.cmake",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
"CMAKE_COLOR_DIAGNOSTICS": "ON",
},
}]
build, test, workflows = [], [], []
def add(chip, mode):
name = f"{chip}-{mode}"
configure.append({
"name": name,
"inherits": "base",
"cacheVariables": {
"LIBAVR_MCU": chip,
"LIBAVR_REFLECT": "ON" if mode == "reflect" else "OFF",
},
})
build.append({"name": name, "configurePreset": name})
steps = [{"type": "configure", "name": name}, {"type": "build", "name": name}]
if mode == "generated":
test.append({"name": name, "configurePreset": name, "output": {"outputOnFailure": True}})
steps.append({"type": "test", "name": name})
workflows.append({"name": name, "steps": steps})
for chip in CHIPS:
add(chip, "generated")
for chip in REFLECT_SPOT:
add(chip, "reflect")
# CMake rejects unknown fields in the presets root, $comment included, so
# the file cannot carry a generated-file marker; the --check ctest is the
# whole of rule 10's guard here.
presets = {
"version": 8,
"configurePresets": configure,
"buildPresets": build,
"testPresets": test,
"workflowPresets": workflows,
}
rendered = json.dumps(presets, indent=1) + "\n"
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "CMakePresets.json")
if "--check" in sys.argv[1:]:
current = open(path).read() if os.path.exists(path) else ""
if current != rendered:
print("CMakePresets.json does not match its generator - run tools/make_presets.py")
return 1
return 0
with open(path, "w") as f:
f.write(rendered)
print(f"{len(CHIPS)} chips, {len(REFLECT_SPOT)} reflect: {os.path.normpath(path)}")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -1,401 +1,360 @@
// TinySafeBoot on libavr - tier 3: full feature parity in the 512-byte boot // TinySafeBoot on libavr tier 3: full feature parity in ≤512 B.
// section, in C++ except where the C ABI itself is the cost.
// //
// The complete TinySafeBoot feature set - watchdog-reset bail, one-wire // The complete TinySafeBoot feature set watchdog-reset bail, one-wire
// half-duplex UART, a config-page activation timeout, the password gate, // half-duplex UART, a config-page activation timeout, the password gate,
// emergency erase, and config/flash/EEPROM read-write - inside the 512-byte // emergency erase, and config/flash/EEPROM read-write — reimplemented for the
// BOOTSZ=11 section the hand-written oracle occupies (oracle/README.md holds // 512-byte ATmega328P boot section. Matching the hand-written assembly oracle's
// what each tier measures, in one table rather than four). The // size and features at once is only reachable at assembly density, so the loader
// body is the tricks tier's C++ (same register protocol, same structure - see // body is one cohesive inline-asm routine. libavr still does the datasheet work:
// tsb_tricks.cpp, including the global-register miscompile rules) with exactly // every geometry, baud and info-block constant below is computed by the library,
// two routines kept in assembly, the two whose remaining cost *is* the calling // never hand-entered, and the loader references them as assembler immediates.
// convention:
// //
// rx the bounded receive: C++ must re-floor the timeout window on every // The wire protocol is strict request/response, which makes the one-wire
// call (the global-register-store miscompile) and split it across // turn-around safe: the device owns the line whenever it drives a byte and
// call-saved registers; the asm keeps the oracle's X-register nested // releases it (RX-only) whenever it waits for one.
// countdown.
// store the page-store loop: C++ cannot hold the receive byte pair and the
// walked Z pointer across the rx calls without call-saved staging
// (push/pop + a Y->Z copy per word); the asm calls rx knowing exactly
// which registers it touches and walks Z live across the whole page.
//
// Everything else - bring-up, activation, password gate, emergency erase,
// dispatch, every SPM/EEPROM/flash primitive, every geometry/baud/info
// constant - is C++ on libavr, and the two asm routines splice into the same
// global-register protocol the C++ uses (g_addr in Y, g_cnt in r16, g_window
// in r7, g_receiving in r6), so calls cross the boundary with no marshalling.
//
// The wire protocol is strict request/response, which is what makes the shared
// line safe: the device drives it only between a received command and its
// reply, and releases it (RXEN0 only) whenever it waits.
#include <libavr/libavr.hpp> #include <libavr/libavr.hpp>
#include <avr/io.h> // SP / RAMEND for the crt-free boot entry, SFR addresses for the asm routines #include <avr/boot.h> // __SPM_ENABLE and the SPM page-op bit names
#include <avr/io.h> // SFR addresses / bit numbers for the boot entry
using namespace avr::literals; using namespace avr::literals;
namespace spm = avr::spm; namespace spm = avr::spm;
namespace ee = avr::eeprom;
namespace hw = avr::hw;
namespace tsb { namespace tsb {
namespace {
// The loader is purely polled - it never enables interrupts - so every SPM and // Boot geometry — the chip database's to know, not ours.
// EEPROM lock folds to nothing under this posture. constexpr std::uint16_t page = spm::page_bytes; // 128
constexpr auto off = avr::irq::guard_policy::unused; constexpr std::uint16_t boot_bytes = 512; // BOOTSZ=11
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page; // config page base
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Strict request/response: every SPM operation is waited out before the next // Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud.
// byte moves, so no flash operation is ever in flight at an EEPROM access - constexpr auto baud = avr::uart::detail::solve_baud(16_MHz, 115200_Bd);
// the write procedure's step 2 has nothing to guard, the omission the static_assert(baud.u2x && baud.ubrr < 256, "asm bring-up writes UBRR0L only, with U2X0");
// datasheet grants (DS40002061B section 8.6.3).
constexpr auto no_spm = ee::spm_interlock::omitted; // Activation window: the config page's timeout byte, floored so a corrupt page
// can never lock the loader out (at least the clock rate in MHz → ~0.5 s here).
constexpr std::uint8_t act_min = 16;
// Post-activation communication timeout (~several seconds); the loader bails to
// the application if the host falls silent mid-session.
constexpr std::uint8_t comm_timeout = 200;
constexpr std::uint8_t confirm = '!'; constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?'; constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@'; constexpr std::uint8_t knock = '@';
// Boot geometry for the 512 B boot section (BOOTSZ=11); the page size and the constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19;
// flash/EEPROM extents are the chip database's to know. app_end is the config
// page (TSB's LASTPAGE), one page below the boot section.
constexpr std::uint16_t page = spm::page_bytes;
constexpr std::uint16_t boot_bytes = 512;
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Lockout-proof floor for the activation window: the oracle's F_CPU/1MHz, so // The 16-byte device-info block, LPM-read on activation. A plain progmem array:
// it follows the clock rather than restating it (rule 41). // the loader streams it straight out with LPM, so a flash_table wrapper would
constexpr auto act_min = static_cast<std::uint8_t>((16_MHz).hz / 1'000'000); // add nothing here.
// Post-activation window: the host gets seconds, not milliseconds, mid-session.
constexpr std::uint8_t comm_window = 200;
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20;
// Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud.
constexpr auto baud = avr::uart::solve_baud(16_MHz, 115200_Bd, 8, avr::uart::parity::none);
// One bit time on the wire: the turn-around a shared-line peer needs to stop
// driving before this one starts. Derived from the solved rate, so it follows
// the link rather than a count measured against one.
constexpr auto guard_cycles = static_cast<std::uint32_t>((16_MHz).hz / baud.actual);
// The 16-byte device-info block, streamed out on activation.
// clang-format off // clang-format off
[[gnu::progmem]] constexpr auto info = std::to_array<std::uint8_t>({ [[gnu::progmem]] constexpr std::uint8_t info[16] = {
'T', 'S', 'B', 'T', 'S', 'B',
build_date & 0xFF, build_date >> 8, build_date & 0xFF, build_date >> 8,
0xF3, // status: native-UART fixed-baud lineage 0xF3, // status: native-UART fixed-baud lineage
avr::hw::db.signature[0], avr::hw::db.signature[1], avr::hw::db.signature[2], 0x1E, 0x95, 0x0F, // ATmega328P signature
page / 2, // page size in words page / 2, // page size in words
(app_end / 2) & 0xFF, (app_end / 2) >> 8, (app_end / 2) & 0xFF, (app_end / 2) >> 8,
eeprom_end & 0xFF, eeprom_end >> 8, eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA, 0xAA, 0xAA,
}); };
// clang-format on // clang-format on
register std::uint16_t g_addr asm("r28"); } // namespace tsb
register std::uint8_t g_cnt asm("r16");
register std::uint8_t g_window asm("r7");
register std::uint8_t g_receiving asm("r6");
const std::uint8_t *flash_ptr(std::uint16_t addr) // Reset lands here: BOOTRST vectors to the boot base, .vectors is laid first, and
// no crt runs. The whole loader is this one naked routine.
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
{ {
return reinterpret_cast<const std::uint8_t *>(addr); asm volatile(
} // --- bring-up ------------------------------------------------------
" ldi r16, lo8(%[ramend]) \n\t"
// Bounded byte receive (asm 1 of 2): release the one-wire line on a direction " out %[spl], r16 \n\t"
// change, poll RXC0 under the oracle's nested X-register countdown seeded from " ldi r16, hi8(%[ramend]) \n\t"
// g_window (floored against lockout), byte or 0-on-silence in r24. Z survives " out %[sph], r16 \n\t"
// - the property the store's word loop rides on. " in r16, %[mcusr] \n\t" // watchdog reset → hand straight back
[[gnu::noinline, gnu::noclone]] std::uint8_t rx() " sbrc r16, 3 \n\t" // MCUSR bit 3 = WDRF
{ " rjmp 9f \n\t" // 9: = appjump
std::uint8_t byte; " ldi r16, %[ubrr] \n\t" // fixed baud, UBRR0L only
asm volatile(" tst %[dir] \n\t" // already receiving? keep the line released " sts %[ubrr0l], r16 \n\t"
" brne 1f \n\t" " ldi r16, 0x02 \n\t" // 1<<U2X0
" ldi %[b], 0x10 \n\t" // RXEN0 alone: release the line and listen " sts %[ucsr0a], r16 \n\t"
" sts %[ucsr0b], %[b] \n\t" " clr r22 \n\t" // direction flag bit0: 0 = receiving, 1 = driving the line
" ser %[b] \n\t" // --- activation: 3×'@' inside a config-page-timed window -----------
" mov %[dir], %[b] \n\t" " ldi r30, lo8(%[appto]) \n\t" // Z = config page + 2
"1: mov r27, %[to] \n\t" // outer countdown high byte = window " ldi r31, hi8(%[appto]) \n\t"
" ori r27, %[actmin] \n\t" // lockout-proof floor " lpm r23, Z+ \n\t" // timeout byte; Z password
" clr r26 \n\t" " ori r23, %[actmin] \n\t" // lockout-proof floor
"2: ser %[b] \n\t" " clr r17 \n\t" // knock counter
"3: lds %[b], %[ucsr0a] \n\t" "1: rcall tsb_rx \n\t"
" sbrc %[b], 7 \n\t" // RXC0 " brcs 9f \n\t" // window elapsed → application
" rjmp 4f \n\t" " cpi r16, %[knock] \n\t"
" dec %[b] \n\t" " brne 9f \n\t" // any non-'@' → application
" brne 3b \n\t" " inc r17 \n\t"
" sbiw r26, 1 \n\t" " cpi r17, 3 \n\t"
" brcc 2b \n\t" " brne 1b \n\t"
" clr %[b] \n\t" // silence -> 0, which no compare accepts // --- password / emergency erase (Z at config-page password) --------
" rjmp 5f \n\t" " ldi r23, %[commto] \n\t" // widen the timeout for the session
"4: lds %[b], %[udr0] \n\t" "2: ser r19 \n\t" // r19=0xff → comparison enabled
"5: \n\t" "3: lpm r18, Z+ \n\t"
: [b] "=&d"(byte), [dir] "+r"(g_receiving) " and r18, r19 \n\t" // a prior mismatch (r19=0) blanks the rest
: [to] "r"(g_window), [actmin] "M"(act_min), [ucsr0a] "n"(_SFR_MEM_ADDR(UCSR0A)), " cpi r18, 0xff \n\t"
[ucsr0b] "n"(_SFR_MEM_ADDR(UCSR0B)), [udr0] "n"(_SFR_MEM_ADDR(UDR0)) " breq tsb_info \n\t" // 0xff terminator → password satisfied
: "r26", "r27", "cc"); " rcall tsb_rx \n\t"
return byte; " cpi r16, 0 \n\t"
} " breq 5f \n\t" // a 0 byte requests emergency erase
" cp r16, r18 \n\t"
// One-wire transmit: take the line (TXEN0 alone) on a direction change with a " breq 2b \n\t" // char matched → next, comparison re-armed
// turn-around guard, put the byte out, hold the line until the whole frame is " clr r19 \n\t" // mismatch → drain forever, never erase
// out (TXC0, not UDRE0), W1C TXC0 by storing the sampled status back (keeps " rjmp 3b \n\t"
// U2X0). Plain C++ - it compiles *smaller* than the oracle's routine. "5: cpi r19, 0 \n\t" // only offer erase if not already wrong
[[gnu::noinline, gnu::noclone]] void tx(std::uint8_t byte) " breq 3b \n\t"
{ " rcall tsb_rcnf \n\t" // two confirmations guard the wipe
if (g_receiving) { " brts 9f \n\t"
g_receiving = 0; " rcall tsb_rcnf \n\t"
hw::ucsr0b::write(hw::ucsr0b::txen0(1)); " brts 9f \n\t"
avr::delay::cycles<guard_cycles>(); " rcall tsb_emerg \n\t"
} " rjmp tsb_main \n\t"
hw::udr0::write(byte); // --- device info, then the command loop ----------------------------
std::uint8_t status; "tsb_info: \n\t"
do { " ldi r30, lo8(%[info]) \n\t"
status = hw::ucsr0a::read(); " ldi r31, hi8(%[info]) \n\t"
} while (!(status & hw::ucsr0a::txc0(1).value)); " ldi r20, 16 \n\t"
hw::ucsr0a::write(status); " rcall tsb_sendf \n\t"
} "tsb_main: \n\t"
" clr r30 \n\t" // Z = 0 for the memory commands
// '?', then hand back the host's reply for the callers' one-byte compare. " clr r31 \n\t"
[[gnu::noinline, gnu::noclone]] std::uint8_t rcnf() " ldi r16, %[cfm] \n\t" // mainloop ready
{ " rcall tsb_tx \n\t"
tx(request); " rcall tsb_rx \n\t"
return rx(); " rcall tsb_disp \n\t"
} " rjmp tsb_main \n\t"
"tsb_disp: \n\t"
// One flash byte <- [g_addr++] (the advance right before ret - the " cpi r16, 'f' \n\t"
// global-register rule, see tsb_tricks.cpp). " breq tsb_rflash \n\t"
[[gnu::noinline, gnu::noclone]] std::uint8_t sflash() " cpi r16, 'F' \n\t"
{ " breq tsb_wflash \n\t"
std::uint8_t byte = avr::flash_load(flash_ptr(g_addr)); " cpi r16, 'e' \n\t"
++g_addr; " breq tsb_reep \n\t"
return byte; " cpi r16, 'E' \n\t"
} " breq tsb_weep \n\t"
" cpi r16, 'c' \n\t"
// One EEPROM byte <- [g_addr++]. " breq tsb_rconf \n\t"
[[gnu::noinline, gnu::noclone]] std::uint8_t eerd() " cpi r16, 'C' \n\t"
{ " breq tsb_wconf \n\t"
std::uint8_t byte = ee::read<no_spm>(g_addr); "9: rcall tsb_spmw \n\t" // appjump: finish any SPM, hand over at 0
++g_addr; " jmp 0 \n\t"
return byte; // --- 'f' read application flash (host-paced) -----------------------
} "tsb_rflash: \n\t"
"1: rcall tsb_rwait \n\t"
// One EEPROM byte -> [g_addr++]. " brts 9f \n\t"
[[gnu::noinline, gnu::noclone]] void eewr(std::uint8_t byte) " ldi r20, %[page] \n\t"
{ " rcall tsb_sendf \n\t"
ee::write<off, no_spm>(g_addr, byte); " cpi r30, lo8(%[appcfg]) \n\t"
++g_addr; " ldi r24, hi8(%[appcfg]) \n\t"
} " cpc r31, r24 \n\t"
" brlo 1b \n\t"
// Stream g_cnt flash bytes from g_addr to the host. "9: ret \n\t"
[[gnu::noinline, gnu::noclone]] void sendf() // --- 'e' read EEPROM (host-paced) ----------------------------------
{ "tsb_reep: \n\t"
do { "1: rcall tsb_rwait \n\t"
tx(sflash()); " brts 9f \n\t"
} while (--g_cnt); " ldi r20, %[page] \n\t"
} "2: out %[earl], r30 \n\t"
" out %[earh], r31 \n\t"
// Wait out a running SPM op, then re-open the RWW section - after every page " sbi %[eecr], 0 \n\t" // EERE
// op and before handing over, as the oracle does. " in r16, %[eedr] \n\t"
[[gnu::noinline, gnu::noclone]] void settle() " rcall tsb_tx \n\t"
{ " adiw r30, 1 \n\t"
spm::wait(); " dec r20 \n\t"
spm::rww_enable<off>(); " brne 2b \n\t"
} " rjmp 1b \n\t"
"9: ret \n\t"
extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --defsym=tsb_app=0 // --- 'F' write application flash -----------------------------------
"tsb_wflash: \n\t"
[[noreturn]] void appjump() " rcall tsb_erapp \n\t" // erase the whole application first (leaves Z=0)
{ "1: rcall tsb_rcnf \n\t"
settle(); " brts 9f \n\t"
tsb_app(); " rcall tsb_store \n\t"
} " cpi r30, lo8(%[appcfg]) \n\t"
" ldi r24, hi8(%[appcfg]) \n\t"
// Step g_addr one page down and erase that page (the decrement lives here - " cpc r31, r24 \n\t"
// the global-register rule). " brlo 1b \n\t"
[[gnu::noinline, gnu::noclone]] void erase_below() "9: ret \n\t"
{ // --- 'E' write EEPROM ----------------------------------------------
g_addr -= page; "tsb_weep: \n\t" // Z already 0 from the mainloop
spm::command<off>(spm::op::erase, g_addr); "1: rcall tsb_rcnf \n\t"
settle(); " brts 9f \n\t"
} " ldi r20, %[page] \n\t"
"2: rcall tsb_rx \n\t"
// Erase the whole application, top-down like the oracle: the loop bound is a " rcall tsb_eewr \n\t"
// compare with zero, and g_addr = 0 is handed back for free. " dec r20 \n\t"
[[gnu::noinline, gnu::noclone]] void erase_application() " brne 2b \n\t"
{ " rjmp 1b \n\t"
g_addr = app_end; "9: ret \n\t"
do { // --- 'c' read config page, 'C' write config page -------------------
erase_below(); "tsb_rconf: \n\t"
} while (g_addr != 0); " ldi r30, lo8(%[appcfg]) \n\t"
} " ldi r31, hi8(%[appcfg]) \n\t"
" ldi r20, %[page] \n\t"
// Stream one host page into the erased flash page at g_addr (asm 2 of 2): the " rjmp tsb_sendf \n\t"
// word pair stages in r0:r1 straight from rx (whose register set is known - "tsb_wconf: \n\t"
// the cross-call liveness C++ cannot express), Z walks the page and PGWRT " rcall tsb_rcnf \n\t"
// programs it. g_addr is left at the next page base. " brts 9f \n\t"
[[gnu::noinline, gnu::noclone]] void store_flash() " ldi r30, lo8(%[appcfg]) \n\t"
{ " ldi r31, hi8(%[appcfg]) \n\t"
asm volatile(" movw r30, r28 \n\t" // Z = page base; rx leaves Z live " rcall tsb_erpage \n\t" // erase the config page (Z unchanged)
" rcall tsb_store \n\t" // program it from the host
" rjmp tsb_rconf \n\t" // rewind Z and echo it back
"9: ret \n\t"
// --- stream one page host→flash at Z, program it (Z → next page) ----
"tsb_store: \n\t"
" ldi r20, %[words] \n\t" " ldi r20, %[words] \n\t"
"1: rcall %x[rx] \n\t" "1: rcall tsb_rx \n\t"
" mov r0, r24 \n\t" // word low byte " mov r0, r16 \n\t"
" rcall %x[rx] \n\t" " rcall tsb_rx \n\t"
" mov r1, r24 \n\t" // word high byte " mov r1, r16 \n\t"
" ldi r24, 0x01 \n\t" // SPMEN: buffer the word at Z " ldi r24, %[spm_fill] \n\t"
" out %[spmcsr], r24 \n\t" " out %[spmcsr], r24 \n\t"
" spm \n\t" " spm \n\t"
" clr r1 \n\t" " clr r1 \n\t"
" adiw r30, 2 \n\t" " adiw r30, 2 \n\t"
" dec r20 \n\t" " dec r20 \n\t"
" brne 1b \n\t" " brne 1b \n\t"
" movw %[base], r30 \n\t" // g_addr = the next page base " subi r30, lo8(%[page]) \n\t" // back to the page base for PGWRT
" subi r30, %[pagelo] \n\t" // Z back to this page's base " sbci r31, hi8(%[page]) \n\t"
" sbci r31, %[pagehi] \n\t" " ldi r24, %[spm_wrt] \n\t"
" ldi r24, 0x05 \n\t" // PGWRT | SPMEN: program the page
" out %[spmcsr], r24 \n\t" " out %[spmcsr], r24 \n\t"
" spm \n\t" " spm \n\t"
: [base] "+r"(g_addr) " rcall tsb_spmw \n\t"
: [rx] "i"(&rx), [spmcsr] "I"(_SFR_IO_ADDR(SPMCSR)), [words] "M"(page / 2), [pagelo] "M"(page & 0xff), " subi r30, lo8(-%[page]) \n\t" // Z → next page base
[pagehi] "M"(page >> 8) " sbci r31, hi8(-%[page]) \n\t"
: "r0", "r1", "r20", "r24", "r26", "r27", "r30", "r31", "cc", "memory"); " ret \n\t"
settle(); // --- erase [0, config page) ----------------------------------------
"tsb_erapp: \n\t"
" clr r30 \n\t"
" clr r31 \n\t"
"1: rcall tsb_erpage \n\t"
" subi r30, lo8(-%[page]) \n\t"
" sbci r31, hi8(-%[page]) \n\t"
" cpi r30, lo8(%[appcfg]) \n\t"
" ldi r24, hi8(%[appcfg]) \n\t"
" cpc r31, r24 \n\t"
" brlo 1b \n\t"
" clr r30 \n\t" // hand callers Z=0
" clr r31 \n\t"
" ret \n\t"
// --- erase one flash page at Z (busy-wait + RWW re-enable) ----------
"tsb_erpage: \n\t"
" ldi r24, %[spm_ers] \n\t"
" out %[spmcsr], r24 \n\t"
" spm \n\t"
" rjmp tsb_spmw \n\t" // tail: wait + RWW re-enable, then ret
// --- emergency erase: application flash, EEPROM, config page -------
"tsb_emerg: \n\t"
" rcall tsb_erapp \n\t" // erases the application, leaves Z=0
" ser r16 \n\t"
"1: rcall tsb_eewr \n\t"
" cpi r30, lo8(%[eeend1]) \n\t"
" ldi r24, hi8(%[eeend1]) \n\t"
" cpc r31, r24 \n\t"
" brne 1b \n\t"
" ldi r30, lo8(%[appcfg]) \n\t"
" ldi r31, hi8(%[appcfg]) \n\t"
" rjmp tsb_erpage \n\t" // erase the config page (tail)
// --- one EEPROM byte r16 → [Z], Z++ --------------------------------
"tsb_eewr: \n\t"
"1: sbic %[eecr], 1 \n\t" // EEPE busy
" rjmp 1b \n\t"
" out %[earl], r30 \n\t"
" out %[earh], r31 \n\t"
" out %[eedr], r16 \n\t"
" sbi %[eecr], 2 \n\t" // EEMPE, then EEPE within 4 cycles
" sbi %[eecr], 1 \n\t" // EEPE
" adiw r30, 1 \n\t"
" ret \n\t"
// --- stream r20 flash bytes from Z to the host ---------------------
"tsb_sendf: \n\t"
"1: lpm r16, Z+ \n\t"
" rcall tsb_tx \n\t"
" dec r20 \n\t"
" brne 1b \n\t"
" ret \n\t"
// --- SPM busy-wait, then re-enable RWW read access -----------------
"tsb_spmw: \n\t"
"1: in r24, %[spmcsr] \n\t"
" sbrc r24, 0 \n\t"
" rjmp 1b \n\t"
" ldi r24, %[spm_rww] \n\t"
" out %[spmcsr], r24 \n\t"
" spm \n\t"
" ret \n\t"
// --- '?' then await '!' (T=1 ⇒ not confirmed) ----------------------
"tsb_rcnf: \n\t"
" ldi r16, %[req] \n\t"
" rcall tsb_tx \n\t"
"tsb_rwait: \n\t"
" rcall tsb_rx \n\t"
" clt \n\t"
" cpi r16, %[cfm] \n\t"
" breq 9f \n\t"
" set \n\t"
"9: ret \n\t"
// --- one-wire transmit r16 (drive the line + guard, wait TXC) ------
// One-wire: RX and TX share the line, so only one direction is enabled
// at a time. Waiting for TXC (whole frame out) before a caller can
// release the line is what makes the shared wiring safe.
"tsb_tx: \n\t"
" sbrc r22, 0 \n\t" // currently receiving? turn the line around
" rjmp 2f \n\t"
"1: sts %[udr0], r16 \n\t"
"3: lds r25, %[ucsr0a] \n\t" // wait for the whole frame out (TXC0)
" sbrs r25, 6 \n\t" // UCSR0A bit 6 = TXC0
" rjmp 3b \n\t"
" sts %[ucsr0a], r25 \n\t" // write 1 to clear TXC
" ret \n\t"
"2: ldi r25, 0x08 \n\t" // TXEN0 only: drive the line (receiver off)
" sts %[ucsr0b], r25 \n\t"
" clr r22 \n\t"
" ser r21 \n\t" // turn-around guard for a shorted receiver
"4: dec r21 \n\t"
" brne 4b \n\t"
" rjmp 1b \n\t"
// --- one-wire receive → r16, C set on timeout ----------------------
"tsb_rx: \n\t"
" sbrc r22, 0 \n\t" // already receiving? keep the line released
" rjmp 1f \n\t"
" ldi r25, 0x10 \n\t" // RXEN0 only: release the line and listen
" sts %[ucsr0b], r25 \n\t"
" ser r22 \n\t"
"1: mov r27, r23 \n\t" // outer countdown high = timeout byte
" clr r26 \n\t"
"2: ser r21 \n\t"
"3: lds r16, %[ucsr0a] \n\t"
" sbrc r16, 7 \n\t" // UCSR0A bit 7 = RXC0
" rjmp 4f \n\t"
" dec r21 \n\t"
" brne 3b \n\t"
" sbiw r26, 1 \n\t"
" brcc 2b \n\t"
" sec \n\t" // timed out
" ret \n\t"
"4: lds r16, %[udr0] \n\t"
" clc \n\t"
" ret \n\t"
:
: [ramend] "i"(RAMEND), [spl] "I"(_SFR_IO_ADDR(SPL)), [sph] "I"(_SFR_IO_ADDR(SPH)),
[mcusr] "I"(_SFR_IO_ADDR(MCUSR)), [ubrr] "n"(tsb::baud.ubrr), [ubrr0l] "n"(_SFR_MEM_ADDR(UBRR0L)),
[ucsr0a] "n"(_SFR_MEM_ADDR(UCSR0A)), [ucsr0b] "n"(_SFR_MEM_ADDR(UCSR0B)), [udr0] "n"(_SFR_MEM_ADDR(UDR0)),
[spmcsr] "I"(_SFR_IO_ADDR(SPMCSR)), [spm_fill] "n"(_BV(__SPM_ENABLE)),
[spm_ers] "n"(_BV(PGERS) | _BV(__SPM_ENABLE)), [spm_wrt] "n"(_BV(PGWRT) | _BV(__SPM_ENABLE)),
[spm_rww] "n"(_BV(RWWSRE) | _BV(__SPM_ENABLE)), [eecr] "I"(_SFR_IO_ADDR(EECR)),
[eedr] "I"(_SFR_IO_ADDR(EEDR)), [earl] "I"(_SFR_IO_ADDR(EEARL)), [earh] "I"(_SFR_IO_ADDR(EEARH)),
[appcfg] "i"(tsb::app_end), [appto] "i"(tsb::app_end + 2), [eeend1] "i"(tsb::eeprom_end + 1),
[info] "i"(&tsb::info[0]), [page] "n"(tsb::page), [words] "n"(tsb::page / 2), [actmin] "n"(tsb::act_min),
[commto] "n"(tsb::comm_timeout), [cfm] "n"(tsb::confirm), [req] "n"(tsb::request), [knock] "n"(tsb::knock)
: "r0", "r1", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r30", "r31",
"cc", "memory");
} }
[[noreturn, gnu::noinline]] void run()
{
// A watchdog reset hands straight back to the application, as the
// reference loader does, rather than re-entering the bootloader.
if (hw::mcusr::wdrf.test()) {
appjump();
}
// Lean bring-up from reset state: UCSR0C already reads 8N1, UBRR0H reads
// 0, and rx()/tx() raise RXEN0/TXEN0 on first use - only the divisor low
// byte and U2X0 need a store. The library still does the datasheet work.
static_assert(baud.u2x && baud.ubrr < 256, "lean bring-up writes UBRR0L only, with U2X0");
hw::ubrr0::write(static_cast<std::uint8_t>(baud.ubrr));
hw::ucsr0a::write(hw::ucsr0a::u2x0(1));
// General-purpose registers are undefined at power-on (no crt zeroes them);
// the direction latch must start "not receiving" so the first rx() enables
// the receiver. The reference loader clears its shadow register for the
// same reason.
g_receiving = 0;
// Activation: 3x'@', each inside the config page's timeout window (rx
// floors it so a corrupt page cannot lock the loader out); anything else -
// including silence - hands over.
g_window = avr::flash_load(flash_ptr(app_end + 2));
for (std::uint8_t k = 3; k; --k) {
if (rx() != knock) {
appjump();
}
}
g_window = comm_window;
// Password gate (config page from app_end+3, 0xff-terminated; a blank
// page is no password). A wrong byte blanks the comparison and drains the
// line forever, so a wrong password can never fall through; a 0 requests
// emergency erase behind two confirms. On pass the info block goes out;
// the emergency path skips it and drops into the command loop.
g_addr = app_end + 3;
std::uint8_t mask = 0xff;
for (;;) {
std::uint8_t expected = avr::flash_load(flash_ptr(g_addr)) & mask;
++g_addr;
if (expected == 0xff) {
g_addr = reinterpret_cast<std::uint16_t>(info.data());
g_cnt = sizeof(info);
sendf();
break;
}
std::uint8_t got = rx();
if (got == 0) {
if (mask == 0) {
continue;
}
if (rcnf() != confirm || rcnf() != confirm) {
appjump();
}
erase_application(); // leaves g_addr = 0 for the EEPROM walk
do {
eewr(0xff);
} while (g_addr <= eeprom_end);
g_addr = app_end + page;
erase_below();
break;
}
if (got != expected) {
mask = 0;
}
}
for (;;) {
tx(confirm); // Mainloop ready
g_addr = 0;
switch (rx()) {
case 'f': // read application flash, one page per host '!'
for (;;) {
if (rx() != confirm) {
break;
}
g_cnt = page;
sendf();
if (g_addr >= app_end) {
break;
}
}
break;
case 'F': // erase the application, then take pages behind '?'
erase_application(); // leaves g_addr = 0, the write start
while (rcnf() == confirm) {
store_flash();
}
break;
case 'e': // read EEPROM, one page per host '!', until the host stops
for (;;) {
if (rx() != confirm) {
break;
}
g_cnt = page;
do {
tx(eerd());
} while (--g_cnt);
}
break;
case 'E': // take EEPROM pages behind '?'
while (rcnf() == confirm) {
g_cnt = page;
do {
eewr(rx());
} while (--g_cnt);
}
break;
case 'c': // read the config page
read_config:
g_addr = app_end;
g_cnt = page;
sendf();
break;
case 'C': // replace the config page, then echo it back to verify
if (rcnf() != confirm) {
break;
}
g_addr = app_end + page;
erase_below(); // leaves g_addr = app_end, the store target
store_flash();
goto read_config;
default: // 'q' or any other byte runs the application
appjump();
}
}
}
} // namespace
} // namespace tsb
// Reset lands at the boot section base (BOOTRST): the entry stub in .vectors
// is laid first and does the one line of crt a crt-less image needs.
template struct avr::startup::entry<tsb::run, avr::startup::stack::hardware>;

View File

@@ -1,329 +0,0 @@
// TinySafeBoot on libavr - the policy floor: pureboot's rules, measured.
//
// The full TinySafeBoot feature set - watchdog bail, one-wire half-duplex,
// config-page activation timeout, password gate, emergency erase, and
// config/flash/EEPROM read-write - under philosophy #5 exactly as pureboot
// obeys it: no assembly, no register variables; code, attributes, and flags
// only. Every lesson pureboot's development produced is applied - the
// library's half-duplex serial and startup entry, lean bring-up from reset
// state, one merged send loop over both memories, oracle-shaped loop bounds,
// locals threaded through noinline primitives, pureboot's codegen flags -
// and the result sits below the idiomatic tier and above the 512 B boot
// section the tricks/asm tiers reach with the banned mechanisms
// (oracle/README.md holds all four). This tier exists to keep that gap an
// artifact
// rather than a claim: the gap to 512 is the rent of policy-clean C++ -
// helpers that hold a cursor across rx()/tx() pay push/pop and argument
// threading where a global-register protocol pays nothing, and both
// control-flow merges tried (a parametrized paged session, a merged store
// loop) measured larger than the split cases they replaced. TSB's wire fixes
// the per-command loop shapes on the device, so pureboot 5's one-transfer-
// loop collapse has no purchase here.
//
// The wire protocol is strict request/response, which is what makes the
// shared line safe: the device drives it only between a received command and
// its reply, and releases it (the library's half-duplex choreography)
// whenever it waits.
#include <libavr/libavr.hpp>
using namespace avr::literals;
namespace spm = avr::spm;
namespace ee = avr::eeprom;
using dev = avr::device<{.clock = 16_MHz}>;
// One-wire: RX and TX share the line, exactly as the native-UART TSB expects.
// 115200 at 16 MHz lands +2.1 % off, past the receiver-tolerance table the
// solver holds rates to - the oracle's own deployment has run there for a
// decade, so the override states that it is meant.
using serial_t = dev::uart0<{
.baud = 115200_Bd,
.allow_baud_error = true,
.half_duplex = true,
}>;
inline constexpr serial_t serial{};
namespace tsb {
namespace {
// The loader is purely polled - it never enables interrupts - so every SPM and
// EEPROM lock folds to nothing under this posture.
constexpr auto off = avr::irq::guard_policy::unused;
// Strict request/response: every SPM operation is waited out before the next
// byte moves, so no flash operation is ever in flight at an EEPROM access -
// the write procedure's step 2 has nothing to guard, the omission the
// datasheet grants (DS40002061B section 8.6.3).
constexpr auto no_spm = ee::spm_interlock::omitted;
// The handshake bytes, identical across every TSB host.
constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@';
// Boot geometry for the 1 KB boot section (BOOTSZ=10); the page size and the
// flash/EEPROM extents are the chip database's to know. app_end is the config
// page (TSB's LASTPAGE), one page below the boot section.
constexpr std::uint16_t page = spm::page_bytes;
constexpr std::uint16_t boot_bytes = 1024;
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Lockout-proof floor for the activation window: the oracle's F_CPU/1MHz, so
// it follows the clock rather than restating it (rule 41).
constexpr auto act_min = static_cast<std::uint8_t>(dev::clock.hz / 1'000'000);
// Post-activation window: the host gets seconds, not milliseconds, mid-session.
constexpr std::uint8_t comm_window = 200;
// Firmware version stamp: YY*512 + MM*32 + DD, the encoding the host decodes.
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 27;
// The 16-byte device-info block, streamed out on activation.
// clang-format off
[[gnu::progmem]] constexpr auto info = std::to_array<std::uint8_t>({
'T', 'S', 'B',
build_date & 0xFF, build_date >> 8,
0xF3, // status: native-UART fixed-baud lineage
avr::hw::db.signature[0], avr::hw::db.signature[1], avr::hw::db.signature[2],
page / 2, // page size in words
(app_end / 2) & 0xFF, (app_end / 2) >> 8, // app-flash boundary, words
eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA, // ATmega processor-type marker (bytes 14 == 15)
});
// clang-format on
// The receive window, pre-floored where it is set. In .noinit: there is no
// crt to clear a .bss image, and run() stores it before the first receive.
[[gnu::section(".noinit")]] std::uint8_t window;
const std::uint8_t *flash_ptr(std::uint16_t addr)
{
return reinterpret_cast<const std::uint8_t *>(addr);
}
// Bounded byte receive: poll under nested countdowns, 0 on silence. The 0
// then falls through every compare - not a knock, not a confirm, not a
// command - so a silent host unwinds the loader to the application from
// anywhere, and a mid-session cable pull cannot wedge it. The line release on
// a direction change is the serial backend's.
[[gnu::noinline]] std::uint8_t rx()
{
std::uint16_t outer = static_cast<std::uint16_t>(window) << 8;
do {
std::uint8_t fine = 0;
do {
if (auto byte = serial.read()) {
return *byte;
}
} while (--fine);
} while (--outer);
return 0;
}
// One-wire transmit: the backend takes the line with a turn-around guard and
// holds it until the whole frame is out.
[[gnu::noinline]] void tx(std::uint8_t byte)
{
serial.write(byte);
}
// '?', then hand back the host's reply for the callers' one-byte compare.
[[gnu::noinline]] std::uint8_t rcnf()
{
tx(request);
return rx();
}
// The one send loop: the info block, the config page, application flash and
// EEPROM pages all stream through here.
[[gnu::noinline]] void send_block(bool eep, std::uint16_t at, std::uint8_t count)
{
do {
tx(eep ? ee::read<no_spm>(at) : avr::flash_load(flash_ptr(at)));
++at;
} while (--count);
}
// One EEPROM byte in - shared by the emergency wipe and the 'E' stream.
[[gnu::noinline]] void eeput(std::uint16_t at, std::uint8_t value)
{
ee::write<off, no_spm>(at, value);
}
// Wait out a running SPM op, then re-open the RWW section - after every page
// op and before handing over, as the oracle does.
[[gnu::noinline]] void settle()
{
spm::wait();
spm::rww_enable<off>();
}
// One host page straight into the erased flash page at `at` - through the SPM
// word buffer (low byte then high), no SRAM staging - then committed. `at`
// names a page base, so the cursor's low byte reaching the boundary ends the
// walk.
[[gnu::noinline]] void store_flash_page(std::uint16_t at)
{
const auto open = spm::page::begin<spm::from::boot_section, off>(at);
do {
std::uint8_t low = rx();
std::uint8_t high = rx();
spm::fill<off>(open, at, std::bit_cast<std::uint16_t>(std::array{low, high}));
at += 2;
} while (static_cast<std::uint8_t>(at) & (page - 1));
spm::command<off>(spm::op::write, at - page);
settle();
}
extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --defsym=tsb_app=0
[[noreturn]] void appjump()
{
settle();
tsb_app();
}
// Step one page down and erase it - the erase shared by the whole-app walk,
// the config rewrite and the emergency wipe; hands the stepped address back.
[[gnu::noinline]] std::uint16_t erase_below(std::uint16_t at)
{
at -= page;
spm::command<off>(spm::op::erase, at);
settle();
return at;
}
// Erase the whole application, top-down like the oracle: the loop bound is a
// compare with zero, and the returned 0 is the address every caller wants
// next.
[[gnu::noinline]] std::uint16_t erase_application()
{
std::uint16_t at = app_end;
do {
at = erase_below(at);
} while (at != 0);
return at;
}
[[noreturn]] void run()
{
// A watchdog reset hands straight back to the application, as the
// reference loader does, rather than re-entering the bootloader.
if (avr::hw::mcusr::wdrf.test()) {
appjump();
}
// Lean bring-up from reset state: UCSR0C already reads 8N1, UBRR0H reads
// 0, and the half-duplex write()/read() raise TXEN0/RXEN0 on first use -
// only the divisor low byte and U2X0 need a store. The solver still does
// the datasheet work; the asserts pin the reset-state assumptions.
{
constexpr auto sol = avr::uart::solve_baud(dev::clock, 115200_Bd, 8, avr::uart::parity::none);
static_assert(sol.u2x && sol.ubrr < 256, "lean bring-up writes UBRR0L only, with U2X0");
avr::hw::ubrr0::write(static_cast<std::uint8_t>(sol.ubrr));
avr::hw::ucsr0a::write(avr::hw::ucsr0a::u2x0(1));
}
// Activation: 3x'@', each inside the config page's timeout window
// (floored so a corrupt page cannot lock the loader out); anything else -
// including silence - hands over.
window = avr::flash_load(flash_ptr(app_end + 2)) | act_min;
for (std::uint8_t k = 3; k; --k) {
if (rx() != knock) {
appjump();
}
}
window = comm_window;
// Password gate (config page from app_end+3, 0xff-terminated; a blank
// page is no password). A wrong byte blanks the comparison and drains the
// line forever, so a wrong password can never fall through; a 0 requests
// emergency erase behind two confirms. On pass the info block goes out;
// the emergency path skips it and drops into the command loop.
std::uint16_t at = app_end + 3;
std::uint8_t mask = 0xff;
for (;;) {
std::uint8_t expected = avr::flash_load(flash_ptr(at)) & mask;
++at;
if (expected == 0xff) {
send_block(false, reinterpret_cast<std::uint16_t>(info.data()), info.size());
break;
}
std::uint8_t got = rx();
if (got == 0) {
if (mask == 0) {
continue;
}
if (rcnf() != confirm || rcnf() != confirm) {
appjump();
}
std::uint16_t a = erase_application();
do {
eeput(a, 0xff);
} while (++a <= eeprom_end);
erase_below(app_end + page);
break;
}
if (got != expected) {
mask = 0;
}
}
for (;;) {
tx(confirm); // Mainloop ready
const std::uint8_t command = rx();
switch (command) {
case 'f': // read application flash, one page per host '!'
for (std::uint16_t a = 0; a < app_end; a += page) {
if (rx() != confirm) {
break;
}
send_block(false, a, page);
}
break;
case 'e': // read EEPROM, one page per host '!', until the host stops
for (std::uint16_t a = 0;; a += page) {
if (rx() != confirm) {
break;
}
send_block(true, a, page);
}
break;
case 'F': { // erase the application, then take pages behind '?'
std::uint16_t a = erase_application();
for (; rcnf() == confirm; a += page) {
store_flash_page(a);
}
break;
}
case 'E': // take EEPROM pages behind '?', each write host-paced
for (std::uint16_t a = 0; rcnf() == confirm;) {
std::uint8_t count = page;
do {
eeput(a, rx());
++a;
} while (--count);
}
break;
case 'c': // read the config page
read_config:
send_block(false, app_end, page);
break;
case 'C': // replace the config page, then echo it back to verify
if (rcnf() != confirm) {
break;
}
store_flash_page(erase_below(app_end + page));
goto read_config;
default: // 'q' or any other byte runs the application
appjump();
}
}
}
} // namespace
} // namespace tsb
// Reset lands at the boot section base (BOOTRST): the entry stub in .vectors
// is laid first and does the one line of crt a crt-less image needs.
template struct avr::startup::entry<tsb::run, avr::startup::stack::hardware>;

View File

@@ -1,10 +1,10 @@
// TinySafeBoot on libavr - tier 1: pure, idiomatic C++. // TinySafeBoot on libavr tier 1: pure, idiomatic C++.
// //
// A serial flash bootloader for the ATmega328P boot section, reimplementing the // A serial flash bootloader for the ATmega328P boot section, reimplementing the
// TinySafeBoot native-UART fixed-baud protocol on libavr with the full feature // TinySafeBoot native-UART fixed-baud protocol on libavr with the full feature
// set of the hand-written oracle: a watchdog-reset bail, one-wire half-duplex, // set of the hand-written oracle: a watchdog-reset bail, one-wire half-duplex,
// a config-page activation timeout, the password gate, emergency erase, and // a config-page activation timeout, the password gate, emergency erase, and
// config/flash/EEPROM read-write. This variant is written for clarity - // config/flash/EEPROM read-write. This variant is written for clarity
// well-factored functions, no compiler-specific size hacks, no inline assembly. // well-factored functions, no compiler-specific size hacks, no inline assembly.
// The one-wire wiring, the flash-resident info block and every SPM/EEPROM lock // The one-wire wiring, the flash-resident info block and every SPM/EEPROM lock
// are libavr's to handle; the only attribute is the naked reset entry that // are libavr's to handle; the only attribute is the naked reset entry that
@@ -20,29 +20,15 @@ namespace ee = avr::eeprom;
using dev = avr::device<{.clock = 16_MHz}>; using dev = avr::device<{.clock = 16_MHz}>;
// One-wire: RX and TX share the line, exactly as the native-UART TSB expects. // One-wire: RX and TX share the line, exactly as the native-UART TSB expects.
// 115200 at 16 MHz lands +2.1 % off, past the receiver-tolerance table the using serial_t = dev::uart0<{.baud = 115200_Bd, .max_baud_error = 3_pct, .half_duplex = true}>;
// solver holds rates to - the oracle's own deployment has run there for a
// decade, so the override states that it is meant.
using serial_t = dev::uart0<{
.baud = 115200_Bd,
.allow_baud_error = true,
.half_duplex = true,
}>;
inline constexpr serial_t serial{}; inline constexpr serial_t serial{};
namespace tsb { namespace tsb {
namespace {
// The loader is purely polled - it never enables interrupts - so every SPM and // The loader is purely polled it never enables interrupts so every SPM and
// EEPROM lock folds to nothing under this posture. // EEPROM lock folds to nothing under this posture.
constexpr auto off = avr::irq::guard_policy::unused; constexpr auto off = avr::irq::guard_policy::unused;
// Strict request/response: every SPM operation is waited out before the next
// byte moves, so no flash operation is ever in flight at an EEPROM access -
// the write procedure's step 2 has nothing to guard, the omission the
// datasheet grants (DS40002061B section 8.6.3).
constexpr auto no_spm = ee::spm_interlock::omitted;
// The handshake bytes, identical across every TSB host. // The handshake bytes, identical across every TSB host.
constexpr std::uint8_t confirm = '!'; constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?'; constexpr std::uint8_t request = '?';
@@ -58,53 +44,35 @@ constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1; constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Firmware version stamp: YY*512 + MM*32 + DD, the encoding the host decodes. // Firmware version stamp: YY*512 + MM*32 + DD, the encoding the host decodes.
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20; constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19;
// The 16-byte device-info block the host reads on activation. A flash_table // The 16-byte device-info block the host reads on activation. A flash_table
// keeps it in progmem with no .data image (there is no crt to copy one). // keeps it in progmem with no .data image (there is no crt to copy one).
// clang-format off // clang-format off
inline constexpr auto info_data = std::to_array<std::uint8_t>({ inline constexpr std::array<std::uint8_t, 16> info_data = {
'T', 'S', 'B', 'T', 'S', 'B',
build_date & 0xFF, build_date >> 8, build_date & 0xFF, build_date >> 8,
0xF3, // status byte (native-UART fixed-baud lineage) 0xF3, // status byte (native-UART fixed-baud lineage)
avr::hw::db.signature[0], avr::hw::db.signature[1], avr::hw::db.signature[2], 0x1E, 0x95, 0x0F, // ATmega328P signature
page / 2, // page size in words page / 2, // page size in words
(app_end / 2) & 0xFF, (app_end / 2) >> 8, // app-flash boundary, words (app_end / 2) & 0xFF, (app_end / 2) >> 8, // app-flash boundary, words
eeprom_end & 0xFF, eeprom_end >> 8, eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA, // ATmega processor-type marker (bytes 14 == 15) 0xAA, 0xAA, // ATmega processor-type marker (bytes 14 == 15)
}); };
// clang-format on // clang-format on
using info = avr::flash_table<info_data>; using info = avr::flash_table<info_data>;
// The lockout-proof floor for the receive window: the oracle's F_CPU/1MHz, so // One page staged in SRAM. Scratch that is always filled before it is read, so
// it follows the clock rather than restating it. // it lives in .noinit — no startup clear (there is no crt) and no .text bytes.
constexpr auto act_min = static_cast<std::uint8_t>(dev::clock.hz / 1'000'000); [[gnu::section(".noinit")]] std::uint8_t buffer[page];
// The receive window, pre-floored where it is set. In .noinit: there is no crt // Blocking byte read/write over the one-wire line: read() releases the line to
// to clear a .bss image, and run() stores it before the first receive. // the receiver, write() takes it and holds it until the frame is out.
[[gnu::section(".noinit")]] std::uint8_t window;
// Bounded byte read over the one-wire line - read() releases the line to the
// receiver - answering 0 on silence. That 0 falls through every compare below:
// not a knock, not a confirm, not a command, so a silent host unwinds the
// loader to the application from anywhere and a mid-session cable pull cannot
// wedge it. The oracle lists that timeout among its own fixes, and a blocking
// read is how a tier loses it.
std::uint8_t rx() std::uint8_t rx()
{ {
std::uint16_t outer = static_cast<std::uint16_t>(window) << 8; return serial.read_blocking();
do {
std::uint8_t fine = 0;
do {
if (auto byte = serial.read()) {
return *byte;
}
} while (--fine);
} while (--outer);
return 0;
} }
// write() takes the line and holds it until the frame is out.
void tx(std::uint8_t byte) void tx(std::uint8_t byte)
{ {
serial.write(byte); serial.write(byte);
@@ -116,18 +84,23 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
} }
// Stream `count` bytes to the host, from flash (LPM) or from EEPROM. // Stream `count` bytes to the host, from flash (LPM) or from EEPROM.
void send_flash(std::uint16_t addr, std::uint8_t count) void send_flash(std::uint16_t addr, std::uint16_t count)
{ {
while (count--) { while (count--)
tx(avr::flash_load(flash_ptr(addr++))); tx(avr::flash_load(flash_ptr(addr++)));
}
} }
void send_eeprom(std::uint16_t addr, std::uint8_t count) void send_eeprom(std::uint16_t addr, std::uint16_t count)
{ {
while (count--) { while (count--)
tx(ee::read<no_spm>(addr++)); tx(ee::read(addr++));
} }
// Take one page from the host into the SRAM buffer.
void get_page()
{
for (std::uint16_t i = 0; i < page; ++i)
buffer[i] = rx();
} }
// Prompt the host with '?' and report whether it answered '!'. // Prompt the host with '?' and report whether it answered '!'.
@@ -137,57 +110,39 @@ bool request_confirm()
return rx() == confirm; return rx() == confirm;
} }
// Stream one page from the host straight into the already-erased flash page at // Program the SRAM buffer into one already-erased flash page (low byte then
// `addr`, filling the SPM word buffer low byte then high - no SRAM staging, so // high, as the SPM word buffer wants).
// receiving and programming are the same loop. void write_flash_page(std::uint16_t addr)
void store_flash_page(std::uint16_t addr)
{ {
const auto open = spm::page::begin<spm::from::boot_section, off>(addr); spm::fill<off>(addr, std::span<const std::uint8_t>{buffer, page});
for (std::uint16_t i = 0; i < page; i += 2) { spm::write_page<off>(addr);
std::uint8_t lo = rx(); spm::wait();
std::uint8_t hi = rx();
spm::fill<off>(open, addr + i, static_cast<std::uint16_t>(lo | (hi << 8)));
}
spm::write_page<spm::from::boot_section, off>(addr); // blocking: waits the write out
} }
// Stream one page from the host straight into EEPROM, byte by byte. // Write the SRAM buffer into EEPROM byte by byte.
void store_eeprom_page(std::uint16_t addr) void write_eeprom_page(std::uint16_t addr)
{ {
for (std::uint16_t i = 0; i < page; ++i) { for (std::uint16_t i = 0; i < page; ++i)
ee::write<off, no_spm>(addr + i, rx()); ee::write<off>(addr + i, buffer[i]);
}
} }
// Erase one flash page, waited out by the blocking spelling - the erase step // Erase the whole application, one page at a time (unwritten pages stay erased).
// shared by the whole-app erase, the config-page rewrite and the emergency
// wipe.
void erase_page(std::uint16_t addr)
{
spm::erase_page<spm::from::boot_section, off>(addr);
}
// Erase the whole application, one page at a time, top-down as the reference
// loader does (unwritten pages stay erased and the host cannot observe the
// order; the loop bound becomes a compare with zero).
void erase_application() void erase_application()
{ {
for (std::uint16_t a = app_end; a != 0;) { for (std::uint16_t a = 0; a < app_end; a += page) {
a -= page; spm::erase_page<off>(a);
erase_page(a); spm::wait();
} }
spm::rww_enable<off>(); spm::rww_enable<off>();
} }
// The application's reset vector; the linker pins it to 0x0000 (--defsym). // Run the application: reset vector at 0x0000. Any non-command byte, a wrong
extern "C" [[noreturn]] void tsb_app(); // password, or an idle programmer port lands here.
// Run the application. Any non-command byte, a wrong password, or an idle
// programmer port lands here.
[[noreturn]] void appjump() [[noreturn]] void appjump()
{ {
spm::wait(); // make sure any pending SPM finished before handing over spm::wait(); // make sure any pending SPM finished before handing over
tsb_app(); reinterpret_cast<void (*)()>(0)();
__builtin_unreachable();
} }
// 'f': stream the application flash back, one page per host '!'. Self-terminates // 'f': stream the application flash back, one page per host '!'. Self-terminates
@@ -195,9 +150,8 @@ extern "C" [[noreturn]] void tsb_app();
void read_flash() void read_flash()
{ {
for (std::uint16_t a = 0; a < app_end; a += page) { for (std::uint16_t a = 0; a < app_end; a += page) {
if (rx() != confirm) { if (rx() != confirm)
return; return;
}
send_flash(a, page); send_flash(a, page);
} }
} }
@@ -206,9 +160,8 @@ void read_flash()
void read_eeprom() void read_eeprom()
{ {
for (std::uint16_t a = 0;; a += page) { for (std::uint16_t a = 0;; a += page) {
if (rx() != confirm) { if (rx() != confirm)
return; return;
}
send_eeprom(a, page); send_eeprom(a, page);
} }
} }
@@ -219,7 +172,8 @@ void write_flash()
{ {
erase_application(); erase_application();
for (std::uint16_t a = 0; request_confirm(); a += page) { for (std::uint16_t a = 0; request_confirm(); a += page) {
store_flash_page(a); get_page();
write_flash_page(a);
} }
} }
@@ -227,18 +181,20 @@ void write_flash()
void write_eeprom() void write_eeprom()
{ {
for (std::uint16_t a = 0; request_confirm(); a += page) { for (std::uint16_t a = 0; request_confirm(); a += page) {
store_eeprom_page(a); get_page();
write_eeprom_page(a);
} }
} }
// 'C': replace the config page, then echo it back for the host to verify. // 'C': replace the config page, then echo it back for the host to verify.
void write_config() void write_config()
{ {
if (!request_confirm()) { if (!request_confirm())
return; return;
} get_page();
erase_page(app_end); spm::erase_page<off>(app_end);
store_flash_page(app_end); spm::wait();
write_flash_page(app_end);
spm::rww_enable<off>(); spm::rww_enable<off>();
send_flash(app_end, page); send_flash(app_end, page);
} }
@@ -249,10 +205,10 @@ void write_config()
void emergency_erase() void emergency_erase()
{ {
erase_application(); erase_application();
for (std::uint16_t a = 0; a <= eeprom_end; ++a) { for (std::uint16_t a = 0; a <= eeprom_end; ++a)
ee::write<off, no_spm>(a, 0xff); ee::write<off>(a, 0xff);
} spm::erase_page<off>(app_end);
erase_page(app_end); spm::wait();
spm::rww_enable<off>(); spm::rww_enable<off>();
} }
@@ -266,54 +222,45 @@ gate password_gate()
{ {
for (const std::uint8_t *pw = flash_ptr(app_end + 3);; ++pw) { for (const std::uint8_t *pw = flash_ptr(app_end + 3);; ++pw) {
std::uint8_t expected = avr::flash_load(pw); std::uint8_t expected = avr::flash_load(pw);
if (expected == 0xff) { if (expected == 0xff)
return gate::pass; return gate::pass;
}
std::uint8_t got = rx(); std::uint8_t got = rx();
if (got == 0) { if (got == 0)
return gate::emergency; return gate::emergency;
} if (got != expected)
if (got != expected) { for (;;)
for (;;) {
rx(); rx();
} }
}
}
} }
[[noreturn]] void run() [[noreturn]] void run()
{ {
// A watchdog reset hands straight back to the application, as the reference // A watchdog reset hands straight back to the application, as the reference
// loader does, rather than re-entering the bootloader. // loader does, rather than re-entering the bootloader.
if (avr::hw::mcusr::wdrf.test()) { if (avr::hw::mcusr::wdrf.test())
appjump(); appjump();
}
avr::init<serial_t>(); avr::init<serial_t>();
// Activation: the host knocks three '@' inside a window whose length is the // Activation: the host knocks three '@' inside a window whose length is the
// config page's timeout byte, floored so a corrupt page can never lock the // config page's timeout byte (floored so a corrupt page can never lock the
// loader out. An idle port times out and boots the application; the same // loader out). An idle port times out and boots the application.
// window then bounds every receive of the session. std::uint32_t idle = static_cast<std::uint32_t>(avr::flash_load(flash_ptr(app_end + 2)) | 16) << 16;
window = avr::flash_load(flash_ptr(app_end + 2)) | act_min;
__uint24 idle = static_cast<__uint24>(window) << 16;
std::uint8_t knocks = 0; std::uint8_t knocks = 0;
while (knocks < 3) { while (knocks < 3) {
if (auto byte = serial.read()) { if (auto byte = serial.read())
knocks = *byte == knock ? knocks + 1 : 0; knocks = *byte == knock ? knocks + 1 : 0;
} else if (--idle == 0) { else if (--idle == 0)
appjump(); appjump();
} }
}
switch (password_gate()) { switch (password_gate()) {
case gate::pass: case gate::pass:
send_flash(reinterpret_cast<std::uint16_t>(info::storage.data()), info::size()); send_flash(reinterpret_cast<std::uint16_t>(info::storage.data()), info::size());
break; break;
case gate::emergency: case gate::emergency:
if (!request_confirm() || !request_confirm()) { if (!request_confirm() || !request_confirm())
appjump(); appjump();
}
emergency_erase(); emergency_erase();
break; break;
} }
@@ -345,9 +292,13 @@ gate password_gate()
} }
} }
} // namespace
} // namespace tsb } // namespace tsb
// Reset lands at the boot section base (BOOTRST): the entry stub in .vectors // Reset lands here: BOOTRST vectors to the boot section base and .vectors is
// is laid first and does the one line of crt a crt-less image needs. // laid first, so this is the first instruction executed. No crt ran, so set the
template struct avr::startup::entry<tsb::run, avr::startup::stack::hardware>; // stack pointer before anything is called.
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
{
SP = RAMEND;
tsb::run();
}

View File

@@ -1,33 +1,15 @@
// TinySafeBoot on libavr - tier 2: C++ with compiler trickery, no assembly. // TinySafeBoot on libavr tier 2: C++ with compiler trickery.
// //
// The full TinySafeBoot feature set - watchdog bail, one-wire half-duplex, // Same protocol, libavr surface and full feature set as the pure variant
// config-page activation timeout, password gate, emergency erase, and // (tsb_pure.cpp) — watchdog bail, one-wire, config-page timeout, password gate,
// config/flash/EEPROM read-write - in pure C++, a little over the 512-byte boot // emergency erase, config/flash/EEPROM read-write — but the readable
// section the hand-written oracle fits (oracle/README.md holds what each tier // one-handler-per-command shape is traded for size. Flash and EEPROM share a
// measures). The structure mirrors the oracle's: a handful of tiny noinline // single code path selected by a *runtime* flag decoded from the command byte,
// primitives sharing one whole-loader register allocation, expressed as global // so the compiler cannot constant-propagate it into two clones; attributes
// register variables so no helper ever saves, spills, or reloads any of it. // (noinline/noclone) pin that sharing down; the hot page address and byte
// // counter live in call-saved global registers to erase the prologue push/pop
// The register protocol (all call-saved, so calls preserve them by ABI): // that C++ function decomposition otherwise pays; and pages stream straight to
// Y (r28:r29) g_addr the walked flash/EEPROM address - adiw-able // SPM/EEPROM with no SRAM staging. No inline assembly.
// r16 g_cnt byte countdown of the running block - ldi-able
// r7 g_window rx timeout, roughly 30 ms units at 16 MHz
// r6 g_receiving one-wire direction latch, cleared at bring-up
// (power-on registers are undefined)
//
// GCC 16.1 miscompiles stores into global register variables: an update whose
// remaining uses all hide inside callees is deleted whenever a CALL follows it
// before any jump/ret (the backend's liveness walk lumps fixed registers with
// call-clobbered ones - minimal repro in libavr's
// test/upstream/gcc-avr-globalreg-repro.cpp). Every
// g_* update below therefore sits where a *local* read or a jump/ret follows
// it - the helpers advance g_addr immediately before returning, and rx()
// re-floors the window on every call instead of storing the floored value
// once. The layout is load-bearing; do not "simplify" it.
//
// The wire protocol is strict request/response, which is what makes the shared
// line safe: the device drives it only between a received command and its
// reply, and releases it (RXEN0 only) whenever it waits.
#include <libavr/libavr.hpp> #include <libavr/libavr.hpp>
@@ -36,344 +18,255 @@
using namespace avr::literals; using namespace avr::literals;
namespace spm = avr::spm; namespace spm = avr::spm;
namespace ee = avr::eeprom; namespace ee = avr::eeprom;
namespace hw = avr::hw;
using dev = avr::device<{.clock = 16_MHz}>;
using serial_t = dev::uart0<{.baud = 115200_Bd, .max_baud_error = 3_pct, .half_duplex = true}>;
inline constexpr serial_t serial{};
namespace tsb { namespace tsb {
namespace {
// The loader is purely polled - it never enables interrupts - so every SPM and
// EEPROM lock folds to nothing under this posture.
constexpr auto off = avr::irq::guard_policy::unused; constexpr auto off = avr::irq::guard_policy::unused;
// Strict request/response: every SPM operation is waited out before the next
// byte moves, so no flash operation is ever in flight at an EEPROM access -
// the write procedure's step 2 has nothing to guard, the omission the
// datasheet grants (DS40002061B section 8.6.3).
constexpr auto no_spm = ee::spm_interlock::omitted;
constexpr std::uint8_t confirm = '!'; constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?'; constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@'; constexpr std::uint8_t knock = '@';
// Boot geometry for the 1 KB boot section (BOOTSZ=10); the page size and the
// flash/EEPROM extents are the chip database's to know. app_end is the config
// page (TSB's LASTPAGE), one page below the boot section.
constexpr std::uint16_t page = spm::page_bytes; constexpr std::uint16_t page = spm::page_bytes;
constexpr std::uint16_t boot_bytes = 1024; constexpr std::uint16_t boot_bytes = 1024;
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page; constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1; constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Lockout-proof floor for the activation window: the oracle's F_CPU/1MHz, so constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19;
// it follows the clock rather than restating it (rule 41).
constexpr auto act_min = static_cast<std::uint8_t>((16_MHz).hz / 1'000'000);
// Post-activation window: the host gets seconds, not milliseconds, mid-session.
constexpr std::uint8_t comm_window = 200;
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20;
// Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud.
constexpr auto baud = avr::uart::solve_baud(16_MHz, 115200_Bd, 8, avr::uart::parity::none);
// One bit time on the wire: the turn-around a shared-line peer needs to stop
// driving before this one starts. Derived from the solved rate, so it follows
// the link rather than a count measured against one.
constexpr auto guard_cycles = static_cast<std::uint32_t>((16_MHz).hz / baud.actual);
// The 16-byte device-info block, streamed out on activation.
// clang-format off // clang-format off
[[gnu::progmem]] constexpr auto info = std::to_array<std::uint8_t>({ [[gnu::progmem]] constexpr std::uint8_t info[16] = {
'T', 'S', 'B', 'T', 'S', 'B',
build_date & 0xFF, build_date >> 8, build_date & 0xFF, build_date >> 8,
0xF3, // status: native-UART fixed-baud lineage 0xF3,
avr::hw::db.signature[0], avr::hw::db.signature[1], avr::hw::db.signature[2], 0x1E, 0x95, 0x0F,
page / 2, // page size in words page / 2,
(app_end / 2) & 0xFF, (app_end / 2) >> 8, (app_end / 2) & 0xFF, (app_end / 2) >> 8,
eeprom_end & 0xFF, eeprom_end >> 8, eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA, 0xAA, 0xAA,
}); };
// clang-format on // clang-format on
register std::uint16_t g_addr asm("r28"); // The hot page walk lives in call-saved global registers, TSB-style: g_addr is
register std::uint8_t g_cnt asm("r16"); // the running flash/EEPROM byte address, g_cnt the byte countdown. Being global
register std::uint8_t g_window asm("r7"); // they are never spilled around the rx/tx/spm calls the way a local would be —
register std::uint8_t g_receiving asm("r6"); // r4-r7 are call-saved, so the library's UART and SPM helpers preserve them.
register std::uint16_t g_addr asm("r4");
register std::uint8_t g_cnt asm("r6");
std::uint8_t rx()
{
return serial.read_blocking();
}
void tx(std::uint8_t byte)
{
serial.write(byte);
}
const std::uint8_t *flash_ptr(std::uint16_t addr) const std::uint8_t *flash_ptr(std::uint16_t addr)
{ {
return reinterpret_cast<const std::uint8_t *>(addr); return reinterpret_cast<const std::uint8_t *>(addr);
} }
// Bounded byte receive, the oracle's shape: release the one-wire line on a // Stream g_cnt bytes to the host from flash (LPM) or EEPROM, memory chosen at
// direction change, poll RXC0 under nested countdowns, 0 on silence. The 0 // run time so the optimiser cannot split the loop into two clones.
// then falls through every compare - not a knock, not a confirm, not a [[gnu::noinline, gnu::noclone]] void send(bool flash)
// command - so a silent host unwinds the loader to the application from
// anywhere, and a mid-session cable pull cannot wedge it.
[[gnu::noinline, gnu::noclone]] std::uint8_t rx()
{ {
if (!g_receiving) {
g_receiving = 1;
hw::ucsr0b::write(hw::ucsr0b::rxen0(1)); // RXEN0 alone: release and listen
}
// act_min ORs in here, per call, not once into g_window at setup - the
// one placement the global-register-store miscompile cannot delete.
std::uint16_t outer = static_cast<std::uint16_t>(g_window | act_min) << 8;
do { do {
std::uint8_t fine = 0; tx(flash ? avr::flash_load(flash_ptr(g_addr)) : ee::read(g_addr));
do {
auto status = hw::ucsr0a::read();
if (status & hw::ucsr0a::rxc0(1).value) {
return hw::udr0::read();
}
} while (--fine);
} while (--outer);
return 0;
}
// One-wire transmit: take the line (TXEN0 alone - the receiver must be off
// while driving) on a direction change, with a turn-around guard so a shorted
// peer can switch first; then hold the line until the whole frame is out
// (TXC0, not UDRE0 - the stop bit must be on the wire before a caller may
// release the line), and W1C TXC0 by storing the sampled status back, which
// keeps U2X0.
[[gnu::noinline, gnu::noclone]] void tx(std::uint8_t byte)
{
if (g_receiving) {
g_receiving = 0;
hw::ucsr0b::write(hw::ucsr0b::txen0(1));
avr::delay::cycles<guard_cycles>();
}
hw::udr0::write(byte);
std::uint8_t status;
do {
status = hw::ucsr0a::read();
} while (!(status & hw::ucsr0a::txc0(1).value));
hw::ucsr0a::write(status);
}
// '?', then hand back the host's reply for the callers' one-byte compare.
[[gnu::noinline, gnu::noclone]] std::uint8_t rcnf()
{
tx(request);
return rx();
}
// One flash byte <- [g_addr++] (the advance right before ret - see header).
[[gnu::noinline, gnu::noclone]] std::uint8_t sflash()
{
std::uint8_t byte = avr::flash_load(flash_ptr(g_addr));
++g_addr; ++g_addr;
return byte;
}
// One EEPROM byte <- [g_addr++].
[[gnu::noinline, gnu::noclone]] std::uint8_t eerd()
{
std::uint8_t byte = ee::read<no_spm>(g_addr);
++g_addr;
return byte;
}
// One EEPROM byte -> [g_addr++].
[[gnu::noinline, gnu::noclone]] void eewr(std::uint8_t byte)
{
ee::write<off, no_spm>(g_addr, byte);
++g_addr;
}
// Stream g_cnt flash bytes from g_addr to the host.
[[gnu::noinline, gnu::noclone]] void sendf()
{
do {
tx(sflash());
} while (--g_cnt); } while (--g_cnt);
} }
// Wait out a running SPM op, then re-open the RWW section - after every page [[gnu::noinline]] bool request_confirm()
// op and before handing over, as the oracle does.
[[gnu::noinline, gnu::noclone]] void settle()
{ {
tx(request);
return rx() == confirm;
}
// Stream one page straight from the host into the already-erased flash page at
// g_addr (SPM word buffer, low byte then high) or into EEPROM — no SRAM staging,
// so receive and store are one loop. The memory is a run-time flag.
[[gnu::noinline, gnu::noclone]] void store_page(bool flash)
{
g_cnt = 0;
if (flash) {
do {
std::uint8_t lo = rx();
std::uint8_t hi = rx();
spm::fill<off>(g_addr + g_cnt, static_cast<std::uint16_t>(lo | (hi << 8)));
g_cnt += 2;
} while (g_cnt != page);
spm::write_page<off>(g_addr);
spm::wait();
} else {
do {
ee::write<off>(g_addr + g_cnt, rx());
} while (++g_cnt != page);
}
}
[[noreturn]] void appjump()
{
spm::wait();
reinterpret_cast<void (*)()>(0)();
__builtin_unreachable();
}
// Erase the whole application, one page at a time.
[[gnu::noinline]] void erase_application()
{
g_addr = 0;
do {
spm::erase_page<off>(g_addr);
spm::wait();
g_addr += page;
} while (g_addr < app_end);
spm::rww_enable<off>();
}
// 'f'/'e': stream memory back one page per host '!'. send advances g_addr, so
// flash self-terminates at the application boundary; EEPROM runs until the host
// stops.
[[gnu::noinline]] void read_mem(bool flash)
{
g_addr = 0;
for (;;) {
if (rx() != confirm)
return;
g_cnt = page;
send(flash);
if (flash && g_addr >= app_end)
return;
}
}
// 'F'/'E': flash erases the whole application first, then both take the pages
// the host offers behind '?'.
[[gnu::noinline]] void write_mem(bool flash)
{
if (flash)
erase_application();
g_addr = 0;
while (request_confirm()) {
store_page(flash);
g_addr += page;
}
}
// 'C': replace the config page, then echo it back for the host to verify.
void write_config()
{
if (!request_confirm())
return;
g_addr = app_end;
spm::erase_page<off>(g_addr);
spm::wait();
store_page(true);
spm::rww_enable<off>();
g_addr = app_end;
g_cnt = page;
send(true);
}
// Emergency erase: wipe the application flash, the EEPROM and the config page.
[[gnu::noinline]] void emergency_erase()
{
erase_application();
g_addr = 0;
do {
ee::write<off>(g_addr, 0xff);
} while (++g_addr <= eeprom_end);
spm::erase_page<off>(app_end);
spm::wait(); spm::wait();
spm::rww_enable<off>(); spm::rww_enable<off>();
} }
extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --defsym=tsb_app=0 // The password gate. A byte of 0 requests emergency erase; a wrong byte hangs
// the loader (still draining the line), so it can never fall through to erase.
enum class gate : std::uint8_t { pass, emergency };
[[noreturn]] void appjump() [[gnu::noinline]] gate password_gate()
{ {
settle(); for (const std::uint8_t *pw = flash_ptr(app_end + 3);; ++pw) {
tsb_app(); std::uint8_t expected = avr::flash_load(pw);
} if (expected == 0xff)
return gate::pass;
// Step g_addr one page down and erase that page. The decrement lives in here,
// before the erase's own use of it, not in the caller's loop where a following
// call would get it deleted (see header).
[[gnu::noinline, gnu::noclone]] void erase_below()
{
g_addr -= page;
spm::command<off>(spm::op::erase, g_addr);
settle();
}
// Erase the whole application, top-down like the oracle: the loop bound is a
// compare with zero, and g_addr = 0 - the value every caller wants next - is
// handed back for free.
[[gnu::noinline, gnu::noclone]] void erase_application()
{
g_addr = app_end;
do {
erase_below();
} while (g_addr != 0);
}
// Stream one host page into the erased flash page at g_addr (SPM word buffer,
// low byte then high) - no SRAM staging, receive and program are one loop.
// g_addr is left at the next page base.
[[gnu::noinline, gnu::noclone]] void store_flash()
{
const auto open = spm::page::begin<spm::from::boot_section, off>(g_addr);
g_cnt = page / 2;
do {
std::uint16_t word = rx();
word |= static_cast<std::uint16_t>(rx()) << 8;
spm::fill<off>(open, g_addr, word);
g_addr += 2;
} while (--g_cnt);
spm::command<off>(spm::op::write, g_addr - page);
settle();
}
[[noreturn, gnu::noinline]] void run()
{
// A watchdog reset hands straight back to the application, as the
// reference loader does, rather than re-entering the bootloader.
if (hw::mcusr::wdrf.test()) {
appjump();
}
// Lean bring-up from reset state: UCSR0C already reads 8N1, UBRR0H reads
// 0, and rx()/tx() raise RXEN0/TXEN0 on first use - only the divisor low
// byte and U2X0 need a store. The library still does the datasheet work.
static_assert(baud.u2x && baud.ubrr < 256, "lean bring-up writes UBRR0L only, with U2X0");
hw::ubrr0::write(static_cast<std::uint8_t>(baud.ubrr));
hw::ucsr0a::write(hw::ucsr0a::u2x0(1));
// General-purpose registers are undefined at power-on (no crt zeroes them);
// the direction latch must start "not receiving" so the first rx() enables
// the receiver. The reference loader clears its shadow register for the
// same reason.
g_receiving = 0;
// Activation: 3x'@', each inside the config page's timeout window (rx
// floors it so a corrupt page cannot lock the loader out); anything else -
// including silence - hands over.
g_window = avr::flash_load(flash_ptr(app_end + 2));
for (std::uint8_t k = 3; k; --k) {
if (rx() != knock) {
appjump();
}
}
g_window = comm_window;
// Password gate (config page from app_end+3, 0xff-terminated; a blank
// page is no password). A wrong byte blanks the comparison and drains the
// line forever, so a wrong password can never fall through; a 0 requests
// emergency erase behind two confirms. On pass the info block goes out;
// the emergency path skips it and drops into the command loop.
g_addr = app_end + 3;
std::uint8_t mask = 0xff;
for (;;) {
std::uint8_t expected = avr::flash_load(flash_ptr(g_addr)) & mask;
++g_addr;
if (expected == 0xff) {
g_addr = reinterpret_cast<std::uint16_t>(info.data());
g_cnt = sizeof(info);
sendf();
break;
}
std::uint8_t got = rx(); std::uint8_t got = rx();
if (got == 0) { if (got == 0)
if (mask == 0) { return gate::emergency;
continue; if (got != expected)
for (;;)
rx();
} }
if (rcnf() != confirm || rcnf() != confirm) { }
[[noreturn]] void run()
{
if (avr::hw::mcusr::wdrf.test())
appjump();
avr::init<serial_t>();
std::uint32_t idle = static_cast<std::uint32_t>(avr::flash_load(flash_ptr(app_end + 2)) | 16) << 16;
std::uint8_t knocks = 0;
while (knocks < 3) {
if (auto byte = serial.read())
knocks = *byte == knock ? knocks + 1 : 0;
else if (--idle == 0)
appjump(); appjump();
} }
erase_application(); // leaves g_addr = 0 for the EEPROM walk
do { switch (password_gate()) {
eewr(0xff); case gate::pass:
} while (g_addr <= eeprom_end); g_addr = reinterpret_cast<std::uint16_t>(&info[0]);
g_addr = app_end + page; g_cnt = sizeof(info);
erase_below(); send(true);
break;
case gate::emergency:
if (!request_confirm() || !request_confirm())
appjump();
emergency_erase();
break; break;
}
if (got != expected) {
mask = 0;
}
} }
for (;;) { for (;;) {
tx(confirm); // Mainloop ready tx(confirm); // Mainloop ready
g_addr = 0; // Decode the command arithmetically so flash/write stay run-time values:
switch (rx()) { // bit 5 is the case bit (upper = write), the folded-lower letter picks the
case 'f': // read application flash, one page per host '!' // memory. A single unified path serves f/F/e/E.
for (;;) { std::uint8_t cmd = rx();
if (rx() != confirm) { std::uint8_t lower = cmd | 0x20;
break; bool write = (cmd & 0x20) == 0;
} if (lower == 'f' || lower == 'e') {
g_cnt = page; bool flash = lower == 'f';
sendf(); if (write)
if (g_addr >= app_end) { write_mem(flash);
break; else
} read_mem(flash);
} } else if (lower == 'c') {
break; if (write) {
case 'F': // erase the application, then take pages behind '?' write_config();
erase_application(); // leaves g_addr = 0, the write start } else {
while (rcnf() == confirm) {
store_flash();
}
break;
case 'e': // read EEPROM, one page per host '!', until the host stops
for (;;) {
if (rx() != confirm) {
break;
}
g_cnt = page;
do {
tx(eerd());
} while (--g_cnt);
}
break;
case 'E': // take EEPROM pages behind '?'
while (rcnf() == confirm) {
g_cnt = page;
do {
eewr(rx());
} while (--g_cnt);
}
break;
case 'c': // read the config page
read_config:
g_addr = app_end; g_addr = app_end;
g_cnt = page; g_cnt = page;
sendf(); send(true);
break;
case 'C': // replace the config page, then echo it back to verify
if (rcnf() != confirm) {
break;
} }
g_addr = app_end + page; } else {
erase_below(); // leaves g_addr = app_end, the store target
store_flash();
goto read_config;
default: // 'q' or any other byte runs the application
appjump(); appjump();
} }
} }
} }
} // namespace
} // namespace tsb } // namespace tsb
// Reset lands at the boot section base (BOOTRST): the entry stub in .vectors extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
// is laid first and does the one line of crt a crt-less image needs. {
template struct avr::startup::entry<tsb::run, avr::startup::stack::hardware>; SP = RAMEND;
tsb::run();
}