Compare commits
119 Commits
dacd21bd78
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 20b1485b6f | |||
| b759618024 | |||
| 22f17b5a25 | |||
| 243b258d4d | |||
| 9575145f0d | |||
| d8211ff440 | |||
|
|
c004d1bdb9 | ||
| 7172d1fc64 | |||
| 7c1a6a140b | |||
| bf9b86d2fc | |||
| 238fb2919c | |||
| 1541818254 | |||
| 37f9747e26 | |||
| 6ff407e7bb | |||
| cbb3c58300 | |||
| c4b7769f84 | |||
| 735ffab7dc | |||
| be78f38f3f | |||
| d3d8d07905 | |||
| b4243a89a3 | |||
| e4390d2ba8 | |||
| 0cb83ff36f | |||
| 8aa1721709 | |||
| 2655d058f4 | |||
| e9c3897d4f | |||
| 546b1589a3 | |||
| eb213e1025 | |||
| 3e4bfbaf48 | |||
| 579ca81b27 | |||
| 5d520a1ff9 | |||
| f71d76a815 | |||
| 47419400f6 | |||
| bad8b6b43e | |||
| 5d1b4497d4 | |||
| a743ea64a3 | |||
| aa66cfccff | |||
| 459d463283 | |||
| 8e7cc86fb3 | |||
| c8ac61779e | |||
| 4362886c39 | |||
| 0513d07e87 | |||
| d4ab28aa17 | |||
| b60f182105 | |||
| 5bc35a9733 | |||
| 8f6319c068 | |||
| a3ea099105 | |||
| c535c4756c | |||
| 321ff8a4ee | |||
| 531ae6c8dc | |||
| b3f41caf6e | |||
| 7716e1e291 | |||
| 1b18f10f4e | |||
| 52c4cdab32 | |||
| 69f089e53a | |||
| fe0d9f8790 | |||
| 3ce817ea03 | |||
| af0dd15a77 | |||
| a54075e526 | |||
| aec430c2e1 | |||
| 9a8a5b0082 | |||
| 7702c6b700 | |||
| 77dd45aeca | |||
| 433bec3e58 | |||
| e89000f73e | |||
| b0737f7cc0 | |||
| 07f93caba8 | |||
| 45f10f843a | |||
| 34b47048ca | |||
| 392035923f | |||
| f98ed406b8 | |||
| a4da885e36 | |||
| 335e494a31 | |||
| 799709efcf | |||
| 7ae80087b3 | |||
| b477f53ca5 | |||
| 84d3f679c2 | |||
| b5020a1e20 | |||
| 1dbf0089d6 | |||
| 39dfe40dbf | |||
| 8470ce3da0 | |||
| d634741015 | |||
| ab842c8d99 | |||
| a58b59c60f | |||
| ceacb61ba1 | |||
| dd7490a3df | |||
| bc24b63e65 | |||
| 332b244ac3 | |||
| 61b687120c | |||
| ef58d5d363 | |||
| 03bb1f56cf | |||
| 6a5e313530 | |||
| a28fccf475 | |||
| 92503fbb2d | |||
| 8ba023ed6b | |||
| 443fd39d31 | |||
| 08a0d77109 | |||
| 260ab2e4e3 | |||
| e4aaf5bc62 | |||
| 653602058a | |||
| 57d1c009cc | |||
| 06bb06d994 | |||
| 9a9a7ef0e8 | |||
| 4acf358dda | |||
| 11c10f986d | |||
| f587f0a26e | |||
| 27c768a102 | |||
| d989b5b8cd | |||
| 314e422b19 | |||
| 3e0717ef06 | |||
| 812be910c1 | |||
| 34529c8031 | |||
| 06bd56af50 | |||
| 75bb84fa3e | |||
| 778b8a0100 | |||
| 48d11fe8e3 | |||
| bb4784ae0c | |||
| d07586652d | |||
| 3a2f2a23c2 | |||
| 4fa058653e |
@@ -7,8 +7,9 @@ TabWidth: 4
|
||||
UseTab: ForIndentation
|
||||
AlignEscapedNewlines: DontAlign
|
||||
AllowShortFunctionsOnASingleLine: Empty
|
||||
AlwaysBreakTemplateDeclarations: true
|
||||
BreakTemplateDeclarations: Yes
|
||||
BreakBeforeBraces: Custom
|
||||
BraceWrapping:
|
||||
AfterFunction: true
|
||||
InsertBraces: true
|
||||
...
|
||||
|
||||
38
.clangd
Normal file
38
.clangd
Normal file
@@ -0,0 +1,38 @@
|
||||
# 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
13
.gitattributes
vendored
@@ -1,8 +1,11 @@
|
||||
*.h eol=lf
|
||||
*.hpp eol=lf
|
||||
*.c eol=lf
|
||||
*.cpp eol=lf
|
||||
.git* eol=lf
|
||||
# Line endings are the repository's, not the editing machine's: this checkout
|
||||
# is reached from two hosts, and a file rewritten by a Windows tool comes back
|
||||
# with every line changed unless something says otherwise. Naming the source
|
||||
# extensions left Markdown, Python, shell and CMake to whatever the writing
|
||||
# tool defaulted to, which is CRLF on one of the two.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Atmel Studio writes these and expects them back.
|
||||
*.vcxproj* eol=crlf
|
||||
*.cppproj eol=crlf
|
||||
*.sln eol=crlf
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -12,6 +12,7 @@ Debug
|
||||
|
||||
# CMake / clangd
|
||||
/build/
|
||||
/local/
|
||||
compile_commands.json
|
||||
.cache/
|
||||
|
||||
|
||||
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
[submodule "libavr"]
|
||||
path = libavr
|
||||
url = ../libavr.git
|
||||
6
.vscode/extensions.json
vendored
Normal file
6
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"llvm-vs-code-extensions.vscode-clangd",
|
||||
"ms-vscode.cmake-tools"
|
||||
]
|
||||
}
|
||||
36
.vscode/settings.json
vendored
Normal file
36
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
// 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"
|
||||
}
|
||||
}
|
||||
316
CMakeLists.txt
316
CMakeLists.txt
@@ -2,61 +2,78 @@ cmake_minimum_required(VERSION 3.28)
|
||||
|
||||
project(tsb_libavr LANGUAGES CXX)
|
||||
|
||||
# libavr from a local checkout (LIBAVR_ROOT) or the forge; the toolchain file
|
||||
# comes from the same checkout via CMakePresets.json.
|
||||
include(FetchContent)
|
||||
# libavr rides as the pinned submodule; LIBAVR_ROOT (cache or environment)
|
||||
# overrides it for tandem development against a working tree. The toolchain
|
||||
# file comes from the submodule via CMakePresets.json either way.
|
||||
if(NOT LIBAVR_ROOT AND DEFINED ENV{LIBAVR_ROOT})
|
||||
set(LIBAVR_ROOT $ENV{LIBAVR_ROOT})
|
||||
endif()
|
||||
if(LIBAVR_ROOT)
|
||||
FetchContent_Declare(libavr SOURCE_DIR ${LIBAVR_ROOT})
|
||||
else()
|
||||
FetchContent_Declare(libavr GIT_REPOSITORY git@git.blackmark.me:avr/libavr.git GIT_TAG main)
|
||||
if(NOT LIBAVR_ROOT)
|
||||
set(LIBAVR_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/libavr)
|
||||
endif()
|
||||
FetchContent_MakeAvailable(libavr)
|
||||
if(NOT EXISTS ${LIBAVR_ROOT}/CMakeLists.txt)
|
||||
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)
|
||||
add_compile_options(-Werror) # warnings are errors for the port's own code
|
||||
enable_testing()
|
||||
|
||||
# Rules 11 and 33 over this repo's own sources. The oracle's assembly needs
|
||||
# no exclusion: it is neither formatted nor ASCII-checked, being in neither
|
||||
# glob, which is the right answer for a vendored reference whose text is
|
||||
# the artifact.
|
||||
libavr_format_test()
|
||||
|
||||
# The behavioral tests drive the real wire protocols over a simavr pty
|
||||
# (as the host tools do) and actually flash the device. The runners are
|
||||
# host programs built at configure time against libsimavr; if they or
|
||||
# Python are missing, only the size tests run.
|
||||
find_program(_host_cc NAMES cc gcc)
|
||||
find_package(Python3 COMPONENTS Interpreter)
|
||||
if(_host_cc AND Python3_FOUND)
|
||||
set(PB_DEVICE ${CMAKE_BINARY_DIR}/pureboot_device)
|
||||
execute_process(
|
||||
COMMAND ${_host_cc} -O2 -I/usr/include/simavr -I/usr/include/simavr/parts
|
||||
-o ${PB_DEVICE} ${CMAKE_CURRENT_SOURCE_DIR}/test/pureboot_device.c
|
||||
-lsimavr -lsimavrparts -lelf -lutil
|
||||
RESULT_VARIABLE _pbdev_res ERROR_VARIABLE _pbdev_err)
|
||||
if(NOT _pbdev_res EQUAL 0)
|
||||
message(STATUS "pureboot_device not built (${_pbdev_err}) — protocol tests skipped")
|
||||
unset(PB_DEVICE)
|
||||
endif()
|
||||
if(LIBAVR_MCU STREQUAL "atmega328p")
|
||||
# (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)
|
||||
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(
|
||||
COMMAND ${_host_cc} -O2 -I/usr/include/simavr -I/usr/include/simavr/parts
|
||||
-o ${TSB_DEVICE} ${CMAKE_CURRENT_SOURCE_DIR}/test/device.c
|
||||
COMMAND ${_host_cxx} -std=c++23 -Wall -Wextra -O2
|
||||
-I/usr/include/simavr -I/usr/include/simavr/parts
|
||||
-o ${TSB_DEVICE} ${CMAKE_CURRENT_SOURCE_DIR}/test/device.cpp
|
||||
-lsimavr -lsimavrparts -lelf
|
||||
RESULT_VARIABLE _dev_res ERROR_VARIABLE _dev_err)
|
||||
if(NOT _dev_res EQUAL 0)
|
||||
message(STATUS "tsb_device not built (${_dev_err}) — protocol tests skipped")
|
||||
unset(TSB_DEVICE)
|
||||
# One bounded line of it: this becomes a single argument on a
|
||||
# command line, and the reading has to say what stopped the build
|
||||
# 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()
|
||||
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()
|
||||
|
||||
# The ELF is only a container (symbols, section headers) and is never flashed —
|
||||
# The ELF is only a container (symbols, section headers) and is never flashed -
|
||||
# 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.
|
||||
# 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
|
||||
@@ -65,35 +82,39 @@ function(add_image_outputs name)
|
||||
$<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.bin)
|
||||
endfunction()
|
||||
|
||||
# The TinySafeBoot protocol reimplemented on libavr in three variants that trade
|
||||
# The TinySafeBoot protocol reimplemented on libavr in variants that trade
|
||||
# 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
|
||||
# loader has no use for the crt or the vector table. The naked entry sits in
|
||||
# .vectors, laid first, and runs. The boot base is FLASHEND+1 minus the section
|
||||
# size; the linker section-start and the source's boot_bytes agree. tsb_app is
|
||||
# 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
|
||||
# .vectors, laid first, and runs - avr::startup::entry on the policy tier,
|
||||
# the experiment tiers' own naked stubs elsewhere, each documented in its
|
||||
# source. The boot base is FLASHEND+1 minus the section size; the linker
|
||||
# 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 three implement the full oracle feature set (see oracle/README.md):
|
||||
# All four implement the full oracle feature set (see oracle/README.md):
|
||||
# watchdog bail, one-wire half-duplex, config-page activation timeout, password
|
||||
# gate, emergency erase, config/flash/EEPROM read-write. They differ only in how,
|
||||
# and the size gradient is the cost of that "how" — see dev/lessons.md.
|
||||
# tsb_asm — the tricks tier's C++ with exactly two routines in asm (the
|
||||
# bounded rx and the page-store loop — the two whose remaining
|
||||
# cost is the C ABI itself): 510 B in the 512 B section the
|
||||
# hand-written 500 B oracle occupies. Everything else, from
|
||||
# bring-up to dispatch, is C++ on libavr.
|
||||
# tsb_tricks — no asm at all: the whole-loader register allocation lives in
|
||||
# and the size gradient is the cost of that "how".
|
||||
# tsb_asm - the tricks tier's C++ with exactly two routines in asm: the
|
||||
# bounded rx and the page-store loop, the two whose remaining
|
||||
# cost is the C ABI itself. Everything else, bring-up to
|
||||
# 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, and the bring-up is the two reset-non-default
|
||||
# registers only. 526 B in the 1 KB section (BOOTSZ=10) — 14
|
||||
# over the oracle's section, from 168 over at this tier's first
|
||||
# floor.
|
||||
# tsb_pure — pure idiomatic libavr, one function per command, TU-local
|
||||
# (internal linkage), streaming (no SRAM page buffer): 836 B in
|
||||
# the 1 KB section.
|
||||
# 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>)
|
||||
function(add_tsb_variant name bytes)
|
||||
@@ -109,197 +130,28 @@ function(add_tsb_variant name bytes)
|
||||
add_test(NAME ${name}.size
|
||||
COMMAND ${CMAKE_COMMAND} -DSIZE_TOOL=${CMAKE_SIZE} -DELF=$<TARGET_FILE:${name}>
|
||||
-DLIMIT=${bytes} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/check_size.cmake)
|
||||
if(DEFINED TSB_DEVICE)
|
||||
add_test(NAME ${name}.protocol
|
||||
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/tsbtest.py
|
||||
COMMAND ${_tsb_python} ${CMAKE_CURRENT_SOURCE_DIR}/test/tsbtest.py
|
||||
${TSB_DEVICE} $<TARGET_FILE:${name}> ${base_hex})
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# The tsb tiers reimplement the ATmega328P-only reference protocol; the other
|
||||
# chips build pureboot alone.
|
||||
# The tiers reimplement the ATmega328P-only reference protocol, so the guard is
|
||||
# the whole of what this repo builds.
|
||||
if(LIBAVR_MCU STREQUAL "atmega328p")
|
||||
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()
|
||||
|
||||
# pureboot — the pure-constraint port (see pureboot/README.md): one source,
|
||||
# no inline assembly, no global register variables, every libavr chip, 512
|
||||
# bytes each. The loader owns the top 512 bytes of flash on every chip; the
|
||||
# application entry symbol is address 0 on the mega (reset re-vectors to the
|
||||
# loader through BOOTRST, so word 0 stays the application's own vector) and
|
||||
# the trampoline word just below the loader on the tinies (host-side vector
|
||||
# surgery points it at the application). --pmem-wrap-around models AVR's
|
||||
# modulo-flash PC where the flash is big enough to need it.
|
||||
#
|
||||
# The image is position-independent (check_pi.py asserts the two link-time
|
||||
# facts that make it so), and on the tinies its budget is 510, not 512: the
|
||||
# slot's last word is the trampoline the host composes — the resident slot's
|
||||
# holds the application entry, and a staging copy's holds the jump through
|
||||
# which it reaches the loader it installed. The activation window is a
|
||||
# compile-time constant; a different PUREBOOT_TIMEOUT builds the re-timed
|
||||
# binary a self-update then installs.
|
||||
set(PUREBOOT_TIMEOUT 8 CACHE STRING "pureboot activation window, seconds")
|
||||
# Every mega runs the loader from its hardware boot section and boots the
|
||||
# application at word 0; the tinies get the trampoline surgery. All megas
|
||||
# assume a 16 MHz crystal at 115200 Bd; the tinies their internal RC at
|
||||
# 57600 Bd over the software UART.
|
||||
if(LIBAVR_MCU STREQUAL "attiny13a")
|
||||
set(_pb_flash 1024)
|
||||
set(_pb_wrap "")
|
||||
set(_pb_page 32)
|
||||
set(_pb_hz 9600000)
|
||||
set(_pb_baud 57600)
|
||||
set(_pb_eeprom 64)
|
||||
set(_pb_limit 510)
|
||||
elseif(LIBAVR_MCU STREQUAL "attiny85")
|
||||
set(_pb_flash 8192)
|
||||
set(_pb_wrap -Wl,--pmem-wrap-around=8k)
|
||||
set(_pb_page 64)
|
||||
set(_pb_hz 8000000)
|
||||
set(_pb_baud 57600)
|
||||
set(_pb_eeprom 512)
|
||||
set(_pb_limit 510)
|
||||
elseif(LIBAVR_MCU MATCHES "^atmega8a?$")
|
||||
set(_pb_flash 8192)
|
||||
set(_pb_wrap -Wl,--pmem-wrap-around=8k)
|
||||
set(_pb_page 64)
|
||||
set(_pb_hz 16000000)
|
||||
set(_pb_baud 115200)
|
||||
set(_pb_eeprom 512)
|
||||
set(_pb_limit 512)
|
||||
elseif(LIBAVR_MCU STREQUAL "atmega16")
|
||||
set(_pb_flash 16384)
|
||||
set(_pb_wrap -Wl,--pmem-wrap-around=16k)
|
||||
set(_pb_page 128)
|
||||
set(_pb_hz 16000000)
|
||||
set(_pb_baud 115200)
|
||||
set(_pb_eeprom 512)
|
||||
set(_pb_limit 512)
|
||||
elseif(LIBAVR_MCU MATCHES "^atmega32a?$")
|
||||
set(_pb_flash 32768)
|
||||
set(_pb_wrap -Wl,--pmem-wrap-around=32k)
|
||||
set(_pb_page 128)
|
||||
set(_pb_hz 16000000)
|
||||
set(_pb_baud 115200)
|
||||
set(_pb_eeprom 1024)
|
||||
set(_pb_limit 512)
|
||||
elseif(LIBAVR_MCU STREQUAL "atmega168a")
|
||||
set(_pb_flash 16384)
|
||||
set(_pb_wrap -Wl,--pmem-wrap-around=16k)
|
||||
set(_pb_page 128)
|
||||
set(_pb_hz 16000000)
|
||||
set(_pb_baud 115200)
|
||||
set(_pb_eeprom 512)
|
||||
set(_pb_limit 512)
|
||||
elseif(LIBAVR_MCU STREQUAL "atmega1284p")
|
||||
# 128 KiB: wire flash addresses are word addresses, reads go through
|
||||
# ELPM, and the PC's modulo wrap exceeds what --pmem-wrap-around models.
|
||||
# The slot is 1 KiB — this chip's own smallest boot sector; the far
|
||||
# machinery cannot fit 512 B (see pureboot/README.md).
|
||||
set(_pb_flash 131072)
|
||||
set(_pb_wrap "")
|
||||
set(_pb_page 256)
|
||||
set(_pb_hz 16000000)
|
||||
set(_pb_baud 115200)
|
||||
set(_pb_eeprom 4096)
|
||||
set(_pb_limit 1024)
|
||||
set(_pb_slot 1024)
|
||||
else()
|
||||
set(_pb_flash 32768)
|
||||
set(_pb_wrap -Wl,--pmem-wrap-around=32k)
|
||||
set(_pb_page 128)
|
||||
set(_pb_hz 16000000)
|
||||
set(_pb_baud 115200)
|
||||
set(_pb_eeprom 1024)
|
||||
set(_pb_limit 512)
|
||||
endif()
|
||||
if(NOT DEFINED _pb_slot)
|
||||
set(_pb_slot 512)
|
||||
endif()
|
||||
math(EXPR _pb_base "${_pb_flash} - ${_pb_slot}")
|
||||
math(EXPR _pb_base_hex "${_pb_base}" OUTPUT_FORMAT HEXADECIMAL)
|
||||
if(LIBAVR_MCU MATCHES "^atmega")
|
||||
set(_pb_app 0)
|
||||
else()
|
||||
math(EXPR _pb_app "${_pb_base} - 2")
|
||||
endif()
|
||||
|
||||
# simavr names its cores after the base dies; the A revisions run on them.
|
||||
set(_pb_sim_mcu ${LIBAVR_MCU})
|
||||
if(LIBAVR_MCU STREQUAL "atmega8a")
|
||||
set(_pb_sim_mcu atmega8)
|
||||
elseif(LIBAVR_MCU STREQUAL "atmega32a")
|
||||
set(_pb_sim_mcu atmega32)
|
||||
elseif(LIBAVR_MCU STREQUAL "atmega168a")
|
||||
set(_pb_sim_mcu atmega168)
|
||||
endif()
|
||||
|
||||
add_executable(pureboot pureboot/pureboot.cpp)
|
||||
target_link_libraries(pureboot PRIVATE libavr)
|
||||
target_compile_definitions(pureboot PRIVATE PUREBOOT_TIMEOUT=${PUREBOOT_TIMEOUT})
|
||||
target_link_options(pureboot PRIVATE -nostartfiles -Wl,--section-start=.text=${_pb_base_hex}
|
||||
-Wl,--defsym=pureboot_app=${_pb_app} ${_pb_wrap})
|
||||
add_custom_command(TARGET pureboot POST_BUILD COMMAND ${CMAKE_SIZE} $<TARGET_FILE:pureboot>)
|
||||
add_image_outputs(pureboot)
|
||||
# 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)
|
||||
add_test(NAME pureboot.size
|
||||
COMMAND ${CMAKE_COMMAND} -DSIZE_TOOL=${CMAKE_SIZE} -DELF=$<TARGET_FILE:pureboot>
|
||||
-DLIMIT=${_pb_limit} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/check_size.cmake)
|
||||
if(Python3_FOUND)
|
||||
add_test(NAME pureboot.pi
|
||||
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/check_pi.py
|
||||
${CMAKE_OBJDUMP} ${CMAKE_NM} $<TARGET_FILE:pureboot> ${_pb_base_hex})
|
||||
add_test(NAME pureboot.planner
|
||||
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/test_planner.py
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/pureboot/pureboot.py)
|
||||
endif()
|
||||
|
||||
# The protocol test flashes this fixture through the loader with the real
|
||||
# host tool and expects its banner after the hand-over; a normally linked
|
||||
# application whose reset vector is what the tinies' surgery re-homes.
|
||||
if(DEFINED PB_DEVICE)
|
||||
add_executable(pbapp test/pbapp.cpp)
|
||||
target_link_libraries(pbapp PRIVATE libavr)
|
||||
add_custom_command(TARGET pbapp POST_BUILD
|
||||
COMMAND ${CMAKE_OBJCOPY} -O binary $<TARGET_FILE:pbapp> $<TARGET_FILE:pbapp>.bin)
|
||||
add_test(NAME pureboot.protocol
|
||||
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/pbtest.py
|
||||
${PB_DEVICE} $<TARGET_FILE:pureboot> ${_pb_sim_mcu} ${_pb_hz} ${_pb_base_hex}
|
||||
${_pb_page} ${_pb_baud} ${_pb_eeprom} $<TARGET_FILE:pbapp>.bin
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/pureboot/pureboot.py
|
||||
${CMAKE_BINARY_DIR}/pbtest-work)
|
||||
set_tests_properties(pureboot.protocol PROPERTIES TIMEOUT 180)
|
||||
|
||||
# The position-independence acceptance test: the identical image,
|
||||
# installed one slot lower, must serve the full command set.
|
||||
add_test(NAME pureboot.reloc
|
||||
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/pbreloc.py
|
||||
${PB_DEVICE} $<TARGET_FILE:pureboot> ${_pb_sim_mcu} ${_pb_hz} ${_pb_base_hex}
|
||||
${_pb_page} ${_pb_baud} ${CMAKE_CURRENT_SOURCE_DIR}/pureboot/pureboot.py
|
||||
${CMAKE_BINARY_DIR}/pbreloc-work)
|
||||
set_tests_properties(pureboot.reloc PROPERTIES TIMEOUT 180
|
||||
ENVIRONMENT "PB_OBJCOPY=${CMAKE_OBJCOPY}")
|
||||
|
||||
# The self-update end-to-end: the re-timed build (same source, only
|
||||
# PUREBOOT_TIMEOUT differs — a byte-different image) replaces the
|
||||
# resident through --update-loader, with every power-fail phase
|
||||
# rehearsed from the runner's flash dumps.
|
||||
add_executable(pureboot9 pureboot/pureboot.cpp)
|
||||
target_link_libraries(pureboot9 PRIVATE libavr)
|
||||
target_compile_definitions(pureboot9 PRIVATE PUREBOOT_TIMEOUT=9)
|
||||
target_link_options(pureboot9 PRIVATE -nostartfiles -Wl,--section-start=.text=${_pb_base_hex}
|
||||
-Wl,--defsym=pureboot_app=${_pb_app} ${_pb_wrap})
|
||||
add_image_outputs(pureboot9)
|
||||
add_test(NAME pureboot.update
|
||||
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/pbupdate.py
|
||||
${PB_DEVICE} $<TARGET_FILE:pureboot> $<TARGET_FILE:pureboot9> ${_pb_sim_mcu}
|
||||
${_pb_hz} ${_pb_base_hex} ${_pb_page} ${_pb_baud} $<TARGET_FILE:pbapp>.bin
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/pureboot/pureboot.py
|
||||
${CMAKE_BINARY_DIR}/pbupdate-work)
|
||||
set_tests_properties(pureboot.update PROPERTIES TIMEOUT 600
|
||||
ENVIRONMENT "PB_OBJCOPY=${CMAKE_OBJCOPY}")
|
||||
endif()
|
||||
libavr_skip_unverified()
|
||||
endif()
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"hidden": true,
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build/${presetName}",
|
||||
"toolchainFile": "$env{LIBAVR_ROOT}/cmake/avr-toolchain.cmake",
|
||||
"toolchainFile": "${sourceDir}/libavr/cmake/avr-toolchain.cmake",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
|
||||
@@ -28,150 +28,6 @@
|
||||
"LIBAVR_MCU": "atmega328p",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attiny85-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "attiny85",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attiny85-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "attiny85",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attiny13a-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "attiny13a",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attiny13a-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "attiny13a",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega8-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega8",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega8-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega8",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega8a-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega8a",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega8a-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega8a",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega16-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega16",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega16-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega16",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega32-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega32",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega32-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega32",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega32a-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega32a",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega32a-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega32a",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega168a-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega168a",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega168a-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega168a",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega1284p-generated",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega1284p",
|
||||
"LIBAVR_REFLECT": "OFF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "atmega1284p-reflect",
|
||||
"inherits": "base",
|
||||
"cacheVariables": {
|
||||
"LIBAVR_MCU": "atmega1284p",
|
||||
"LIBAVR_REFLECT": "ON"
|
||||
}
|
||||
}
|
||||
],
|
||||
"buildPresets": [
|
||||
@@ -182,78 +38,15 @@
|
||||
{
|
||||
"name": "atmega328p-reflect",
|
||||
"configurePreset": "atmega328p-reflect"
|
||||
},
|
||||
}
|
||||
],
|
||||
"testPresets": [
|
||||
{
|
||||
"name": "attiny85-generated",
|
||||
"configurePreset": "attiny85-generated"
|
||||
},
|
||||
{
|
||||
"name": "attiny85-reflect",
|
||||
"configurePreset": "attiny85-reflect"
|
||||
},
|
||||
{
|
||||
"name": "attiny13a-generated",
|
||||
"configurePreset": "attiny13a-generated"
|
||||
},
|
||||
{
|
||||
"name": "attiny13a-reflect",
|
||||
"configurePreset": "attiny13a-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega8-generated",
|
||||
"configurePreset": "atmega8-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega8-reflect",
|
||||
"configurePreset": "atmega8-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega8a-generated",
|
||||
"configurePreset": "atmega8a-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega8a-reflect",
|
||||
"configurePreset": "atmega8a-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega16-generated",
|
||||
"configurePreset": "atmega16-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega16-reflect",
|
||||
"configurePreset": "atmega16-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega32-generated",
|
||||
"configurePreset": "atmega32-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega32-reflect",
|
||||
"configurePreset": "atmega32-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega32a-generated",
|
||||
"configurePreset": "atmega32a-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega32a-reflect",
|
||||
"configurePreset": "atmega32a-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega168a-generated",
|
||||
"configurePreset": "atmega168a-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega168a-reflect",
|
||||
"configurePreset": "atmega168a-reflect"
|
||||
},
|
||||
{
|
||||
"name": "atmega1284p-generated",
|
||||
"configurePreset": "atmega1284p-generated"
|
||||
},
|
||||
{
|
||||
"name": "atmega1284p-reflect",
|
||||
"configurePreset": "atmega1284p-reflect"
|
||||
"name": "atmega328p-generated",
|
||||
"configurePreset": "atmega328p-generated",
|
||||
"output": {
|
||||
"outputOnFailure": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"workflowPresets": [
|
||||
@@ -275,243 +68,17 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "attiny85-generated",
|
||||
"name": "atmega328p-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "attiny85-generated"
|
||||
"name": "atmega328p-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "attiny85-generated"
|
||||
},
|
||||
{
|
||||
"type": "test",
|
||||
"name": "attiny85-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "attiny13a-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "attiny13a-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "attiny13a-generated"
|
||||
},
|
||||
{
|
||||
"type": "test",
|
||||
"name": "attiny13a-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega8-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega8-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega8-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega8-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega8-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega8-reflect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega8a-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega8a-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega8a-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega8a-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega8a-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega8a-reflect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega16-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega16-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega16-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega16-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega16-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega16-reflect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega32-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega32-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega32-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega32-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega32-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega32-reflect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega32a-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega32a-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega32a-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega32a-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega32a-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega32a-reflect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega168a-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega168a-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega168a-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega168a-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega168a-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega168a-reflect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega1284p-generated",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega1284p-generated"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega1284p-generated"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "atmega1284p-reflect",
|
||||
"steps": [
|
||||
{
|
||||
"type": "configure",
|
||||
"name": "atmega1284p-reflect"
|
||||
},
|
||||
{
|
||||
"type": "build",
|
||||
"name": "atmega1284p-reflect"
|
||||
"name": "atmega328p-reflect"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"testPresets": [
|
||||
{
|
||||
"name": "atmega328p-generated",
|
||||
"configurePreset": "atmega328p-generated",
|
||||
"output": {
|
||||
"outputOnFailure": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attiny85-generated",
|
||||
"configurePreset": "attiny85-generated",
|
||||
"output": {
|
||||
"outputOnFailure": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "attiny13a-generated",
|
||||
"configurePreset": "attiny13a-generated",
|
||||
"output": {
|
||||
"outputOnFailure": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
67
ide/README.md
Normal file
67
ide/README.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# 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`.
|
||||
22
ide/bootloader.atsln
Normal file
22
ide/bootloader.atsln
Normal file
@@ -0,0 +1,22 @@
|
||||
|
||||
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
|
||||
112
ide/tsb_asm/tsb_asm.cppproj
Normal file
112
ide/tsb_asm/tsb_asm.cppproj
Normal file
@@ -0,0 +1,112 @@
|
||||
<?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
1
libavr
Submodule
Submodule libavr added at 93d8b0e491
@@ -38,11 +38,23 @@ 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
|
||||
are simultaneously reachable. The port's `tsb_asm` tier meets the same bar at
|
||||
510 B in the same 512 B section, written in C++ on libavr except the two
|
||||
routines whose remaining cost is the calling convention itself (the bounded rx
|
||||
and the page-store loop); `tsb_tricks` needs no assembly at all at 526 B, and
|
||||
`tsb_pure` stays fully idiomatic at 836 B, both in the 1 KB section.
|
||||
are simultaneously reachable. The port's four tiers reach it from the other
|
||||
side, and the gradient between them is the cost of the mechanisms each is
|
||||
allowed:
|
||||
|
||||
| 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
|
||||
(what the simavr protocol test drives). Baud and geometry differ, code size and
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
# pureboot
|
||||
|
||||
A serial bootloader on [libavr](https://git.blackmark.me/avr/libavr), pure by
|
||||
constraint: one C++ source, no inline assembly, no global register variables
|
||||
(attributes allowed), built for every chip libavr targets, **fitting each
|
||||
chip's smallest boot sector**: 512 bytes everywhere — 488 B on the
|
||||
ATtiny13A, 502 B on the ATtiny85, 466–504 B across the megas — except the
|
||||
ATmega1284P, whose smallest boot sector is 1 KiB and whose far-flash
|
||||
machinery (ELPM reads, RAMPZ page commands, word-addressed wire) lands at
|
||||
558 B in a 1 KiB slot: the 512-byte figure is a hardware boundary that chip
|
||||
simply does not have, and no implementation of this feature set fits it
|
||||
there. The device speaks primitives; every composite — verify, erase,
|
||||
reset-vector surgery, updating the loader itself — lives in the host tool
|
||||
(`pureboot.py`).
|
||||
|
||||
The image is **position-independent**: control flow is PC-relative, the
|
||||
read/write paths take wire addresses, the write guard protects the slot the
|
||||
code is *running* in (from the runtime return address), the info block is
|
||||
addressed from that same anchor, and the application jump is an indirect
|
||||
call to an absolute entry. The identical binary therefore runs from any
|
||||
slot with every command intact — which makes pureboot **its own staging
|
||||
loader**: the host installs the same binary one slot below the resident,
|
||||
jumps into it, and lets it rewrite the resident. The slot is 512 bytes
|
||||
(1 KiB on the word-addressed large chips, matching their boot-sector
|
||||
minimum); on the tinies the budget is 510, not 512: a slot's last word
|
||||
belongs to the host-managed trampoline (below).
|
||||
|
||||
## Link
|
||||
|
||||
| Chip | Serial | Baud | Clock assumed |
|
||||
|---|---|---|---|
|
||||
| every ATmega (8/8A, 16, 32/32A, 168A, 328P, 1284P) | the hardware USART (USART0), RXD/TXD per pinout | 115200 8N1 | 16 MHz crystal |
|
||||
| ATtiny85 | software UART, RX = PB0, TX = PB1 | 57600 8N1 | 8 MHz internal RC |
|
||||
| ATtiny13A | software UART, RX = PB0, TX = PB1 | 57600 8N1 | 9.6 MHz internal RC |
|
||||
|
||||
The tiny RX pin has its pull-up enabled; TX idles high. All multi-byte
|
||||
quantities on the wire are little-endian.
|
||||
|
||||
## Activation
|
||||
|
||||
Reset enters the loader (BOOTRST on the mega, the patched reset vector on the
|
||||
tinies) — except a watchdog reset, which hands straight to the application
|
||||
(the application owns its watchdog; it must clear WDRF itself, which also
|
||||
releases the WDRF-forced WDE).
|
||||
|
||||
The host then has one activation window per awaited byte to knock: `p` then
|
||||
`b`. Each awaited byte gets a fresh window; any other byte is discarded and
|
||||
awaited again (line noise cannot lock the loader, only delay it). A window
|
||||
expiring with an idle line boots the application.
|
||||
|
||||
The window length is a compile-time constant — 8 s by default, another value
|
||||
via the `PUREBOOT_TIMEOUT` CMake cache variable — so the whole EEPROM belongs
|
||||
to the application; pureboot never uses it for its own state. Re-timing a
|
||||
deployed loader is a self-update with a re-timed build (below).
|
||||
|
||||
## Session
|
||||
|
||||
After the knock the loader stays in its command loop until `J` jumps away or
|
||||
the chip resets. Before reading each command it waits for any pending EEPROM
|
||||
write to finish and sends the prompt `+` (0x2b) — the prompt is therefore
|
||||
also the completion ack of the previous command. A session is: await `+`,
|
||||
send a command, read its reply, repeat.
|
||||
|
||||
On chips whose flash exceeds 64 KiB (the 1284P — info-block flag bit 1) the
|
||||
`R`/`W` flash addresses are **word** addresses; everywhere else they are byte
|
||||
addresses. EEPROM addresses are always bytes, counts always bytes.
|
||||
|
||||
| Cmd | Arguments | Reply |
|
||||
|---|---|---|
|
||||
| `b` | — | the 12-byte info block |
|
||||
| `R` | addr16, n8 | n flash bytes (n = 0 means 256) |
|
||||
| `W` | addr16, then one page of data | — (completion = next prompt) |
|
||||
| `r` | addr16, n8 | n EEPROM bytes (n = 0 means 256) |
|
||||
| `w` | addr16, n8, then n data bytes | `+` per byte, sent once its write has begun |
|
||||
| `F` | — | 4 bytes: low fuse, lock, extended fuse, high fuse |
|
||||
| `J` | word address (16-bit) | `+`, then execution continues there |
|
||||
| other | — | ignored; the loop re-prompts (send a junk byte, await `+`, to resync) |
|
||||
|
||||
`W` streams exactly one SPM page (size from the info block) into the buffer,
|
||||
then erases and programs; the address must be page-aligned. Pages inside the
|
||||
512-byte slot the loader is *running* in are drained but never programmed — a
|
||||
broken host cannot brick the running copy, and a staged copy may rewrite the
|
||||
resident slot. `w` is host-paced: send the next byte only after the previous
|
||||
byte's `+`. `F` returns the bytes in the hardware's Z order; on a chip
|
||||
without an extended fuse byte (the ATtiny13A) that slot carries no meaning.
|
||||
Fuse *writing* does not exist: SPM reaches flash (and, on the mega, lock
|
||||
bits) only — fuse bytes are external-programming territory by hardware.
|
||||
|
||||
`J` is the one control-transfer primitive: the host uses it to run the
|
||||
application (word 0 on the mega, the trampoline word on the tinies — both
|
||||
known from the info block) and to move between loader copies during a
|
||||
self-update. A jump to a loader slot's base re-enters that copy's own
|
||||
startup; it must then be knocked afresh.
|
||||
|
||||
The info block (`b`):
|
||||
|
||||
| Offset | Content |
|
||||
|---|---|
|
||||
| 0–2 | `'P'`, `'B'`, protocol version (1) |
|
||||
| 3–5 | device signature |
|
||||
| 6 | SPM page size in bytes (0 means 256) |
|
||||
| 7–8 | loader base — application flash ends here (a word address when bit 1 is set) |
|
||||
| 9–10 | EEPROM size |
|
||||
| 11 | bit 0: host must patch the reset vector (no hardware boot section); bit 1: flash wire addresses are word addresses |
|
||||
|
||||
Composites are the host's job: verify = read back and compare, erase =
|
||||
write `0xff` (per page for flash, per byte for EEPROM).
|
||||
|
||||
## Deployment
|
||||
|
||||
**Megas**: program the loader at `flash − 512` with an external programmer.
|
||||
Every mega's smallest-but-one BOOTSZ puts the boot-section start exactly at
|
||||
the loader base (512 B — the m8/16/168A reach it at their second-smallest
|
||||
step, the m32/328P at their smallest), so the ATmega328P profiles below
|
||||
apply to all of them with their own addresses; the per-chip BOOTSZ ladders
|
||||
live in the host tool (`BOOT_FUSE`). The **ATmega1284P** is the exception:
|
||||
its smallest boot section is 1 KB, so the standalone profile does not exist
|
||||
— BOOTSZ = 512 words always, and with BOOTRST programmed reset lands at
|
||||
0x1f800, one erased slot below the loader (the loader-first walk behavior
|
||||
below, built in). Its staging slot sits inside that same 1 KB section, so
|
||||
self-update needs no fuse change.
|
||||
|
||||
ATmega328P profiles (addresses for its 32 KiB):
|
||||
|
||||
| BOOTSZ | BOOTRST | Behavior |
|
||||
|---|---|---|
|
||||
| 256 words (512 B) | programmed | *Standalone*: reset always enters the loader; **self-update impossible** (the staging slot lies outside the boot section, where SPM is disabled). |
|
||||
| 512 words (1 KB) | unprogrammed | *Self-update, app-first*: reset always boots the application, which owns all 31.5 KB and must offer its own jump to 0x7e00 to reach the loader (a virgin chip reaches it by reset across erased flash). Updates are power-fail-safe except mid-rewrite of the resident slot itself (no reset path leads to the staging copy then). |
|
||||
| 512 words (1 KB) | programmed | *Self-update, loader-first*: reset lands at 0x7c00 — the staging slot, normally erased, so execution walks up into the loader; during an update it is the staging copy itself, so a mid-rewrite power loss recovers by reset. The loss windows move to the staging install/retire page writes instead (page-write scale). The host keeps `[0x7c00, 0x7e00)` clear of application data (`--force` overrides). |
|
||||
|
||||
Applications are flashed unmodified — word 0 stays the application's own
|
||||
reset vector, and the hand-over jumps to 0.
|
||||
|
||||
**Tinies** (no boot section): program the loader at `flash − 512`; erased
|
||||
flash below it walks up into the loader, so a virgin chip activates. When
|
||||
flashing an application the host performs reset-vector surgery: word 0 is
|
||||
rewritten to `rjmp` to the loader base, and the application's own entry is
|
||||
re-encoded as a trampoline `rjmp` in the word just below the loader
|
||||
(`base − 2`, where the hand-over jumps). Every other vector stays the
|
||||
application's. The patched page 0 and the trampoline page are written
|
||||
*first*, so from the first write on an interrupted flash still resets into
|
||||
the loader; an erase runs top-down for the same reason.
|
||||
|
||||
## Updating the loader
|
||||
|
||||
`pureboot.py --update-loader new_pureboot.bin` replaces the resident loader
|
||||
with any pureboot build — a re-timed window, a newer protocol — using the
|
||||
loader itself as its own staging loader. The image is the loader's own 512
|
||||
bytes as a raw binary, or the Intel HEX the build emits beside it, which
|
||||
links the loader at its base inside an otherwise blank flash image:
|
||||
|
||||
1. The staging slot `[base−512, base)` is saved to a host-side state file
|
||||
(on the 1 KB tiny13A that is the whole application, vectors included).
|
||||
2. The resident installs the identical update image there. On the tinies the
|
||||
host composes the slot's last word — the same address as the resident's
|
||||
trampoline — as a jump to the resident base, so even an abandoned staging
|
||||
copy times out into a loader, never into garbage.
|
||||
3. `J` enters the staging copy, which rewrites the resident slot. On the
|
||||
t85 the host first re-aims word 0 at the staging copy, so a power loss
|
||||
mid-rewrite still resets into a loader; on the t13a the staging slot
|
||||
carries the reset vector itself.
|
||||
4. `J` enters the new resident, which restores the staging slot's saved
|
||||
content (word 0 and the trampoline with it) and the state file is
|
||||
discarded.
|
||||
|
||||
Every phase is idempotent and keyed off the actual flash state: re-running
|
||||
the same command after any interruption resumes and completes. The state
|
||||
file carries the only bytes not recoverable from the device; if it is lost
|
||||
mid-update the update still completes, and the staging region is restored by
|
||||
reflashing the application. The mega needs its fuses for the preflight
|
||||
(BOOTSZ gate, profile notes) — read from the device, or supplied with
|
||||
`--assume-fuses` where reading is impossible (simulators).
|
||||
|
||||
## Host tool
|
||||
|
||||
`pureboot.py` — Python 3, standard library only. The port layer is the one
|
||||
platform-specific part: termios drives any tty on POSIX (a USB adapter as
|
||||
well as a simavr pty), the Win32 serial API through `ctypes` drives a COM
|
||||
port on Windows (`--port COM6`; the `\\.\` form for two-digit ports is
|
||||
supplied by the tool). Opening the port asserts DTR and RTS on both, so a
|
||||
board that wires DTR to reset gets its reset pulse and opens the activation
|
||||
window by itself.
|
||||
|
||||
pureboot.py --port /dev/ttyUSB0 --baud 57600 \
|
||||
--info --fuses --flash app.hex
|
||||
|
||||
Operations run in a fixed order within one session: info, fuses, loader
|
||||
update, flash (erase / program / read / verify), EEPROM (erase / program /
|
||||
read / verify) — then the loader hands over to the application; `--stay`
|
||||
keeps the session alive instead, and a later invocation reconnects into it
|
||||
(the knock converges there too). `--flash` and `--eeprom` verify by
|
||||
read-back unless `--no-verify`; images are raw binary, or Intel HEX by
|
||||
extension. `--force` overrides the refusable safety checks (today: flashing
|
||||
application data into a mega's reset walk region).
|
||||
|
||||
## Tests
|
||||
|
||||
Per chip preset, `ctest` runs:
|
||||
|
||||
- `pureboot.size` — the 510-byte (tinies) / 512-byte (mega) budget;
|
||||
- `pureboot.pi` — the position-independence lint: no absolute `jmp`/`call`
|
||||
in the image, the info block within its first 256 bytes;
|
||||
- `pureboot.planner` — the host tool's pure logic: programming orders and
|
||||
their recovery properties, the surgery, the staging composition, the
|
||||
boot-fuse decode, and the update preflight's error/warning matrix over
|
||||
synthetic fuse bytes;
|
||||
- `pureboot.protocol` — end to end against a simavr device
|
||||
(`test/pureboot_device.c` — the mega's USART as a pty; on the tinies a
|
||||
cycle-timed GPIO⇄pty bridge for the software UART, plus the SPM/NVM module
|
||||
simavr's tiny cores lack) driven by the real host tool through
|
||||
knock-from-reset, program + verify of both memories, session reconnect, an
|
||||
external reset through the patched vector, and the hand-over to a fixture
|
||||
application whose banner proves the launch — cross-checked against the
|
||||
simulator's ground-truth memory dumps and an independent decode of the
|
||||
surgery's rjmp words;
|
||||
- `pureboot.reloc` — the identical image installed one slot below the
|
||||
resident serves the complete command set from there (the
|
||||
position-independence acceptance test);
|
||||
- `pureboot.update` — the full `--update-loader` flow to a re-timed build,
|
||||
then every power-fail phase: the device is killed mid-write, restarted
|
||||
from its flash dump, and a re-run must complete the update with the
|
||||
application intact throughout.
|
||||
|
||||
`size`, `pi`, and `planner` are host logic and run anywhere; the three
|
||||
simulator-driven targets need simavr and a pty, so they are POSIX-only —
|
||||
on Windows the tool is exercised against real hardware.
|
||||
@@ -1,482 +0,0 @@
|
||||
// pureboot — a serial bootloader on libavr, pure by constraint: one C++
|
||||
// source with no inline assembly and no global register variables, built for
|
||||
// every chip libavr targets, 512 bytes on each. The device speaks primitives
|
||||
// — read/program flash, read/write EEPROM, fuse bytes, an info block, a jump
|
||||
// — and everything composite (verify, erase, reset-vector surgery, updating
|
||||
// the loader itself) lives in the host tool. Protocol reference: README.md
|
||||
// next to this file.
|
||||
//
|
||||
// The image is position-independent: control flow is PC-relative, the write
|
||||
// and read paths take wire addresses, the write guard refuses the 512-byte
|
||||
// slot the code is *running* in (taken from the runtime return address), the
|
||||
// info block is read relative to that same anchor, and the application jump
|
||||
// is an indirect call to an absolute entry. The identical binary therefore
|
||||
// runs from any 512-byte slot with every command intact: flashed one slot
|
||||
// below the resident loader it becomes the staging loader that rewrites the
|
||||
// resident — how pureboot updates itself, host-driven, with no other
|
||||
// firmware involved.
|
||||
//
|
||||
// Entry: reset lands in avr::startup::entry below (BOOTRST on the mega; the
|
||||
// patched reset vector — or erased flash walking up into the loader — on the
|
||||
// tinies). A watchdog reset hands straight to the application. Otherwise the
|
||||
// host has one activation window per awaited knock byte ("pb"); an idle line
|
||||
// boots the application. A session then stays in the command loop until 'J'
|
||||
// jumps away or the chip resets.
|
||||
|
||||
#include <libavr/libavr.hpp>
|
||||
|
||||
using namespace avr::literals;
|
||||
namespace spm = avr::spm;
|
||||
namespace ee = avr::eeprom;
|
||||
|
||||
namespace pureboot {
|
||||
namespace {
|
||||
|
||||
// Purely polled — interrupts stay off, every guard folds to nothing.
|
||||
constexpr auto off = avr::irq::guard_policy::unused;
|
||||
|
||||
constexpr std::uint8_t ack = '+';
|
||||
|
||||
// Per-chip personality: the clocks the dogfood boards run (16 MHz crystal on
|
||||
// the mega, calibrated RC on the tinies). The device signature comes straight
|
||||
// from the chip database (avr::hw::db.signature) — compile-time data is the
|
||||
// only universal source, since the tiny13A cannot even read its signature row
|
||||
// from code.
|
||||
consteval avr::hertz_t clock()
|
||||
{
|
||||
if (avr::hw::db.name == "ATtiny13A")
|
||||
return 9.6_MHz;
|
||||
if (avr::hw::db.name == "ATtiny85")
|
||||
return 8_MHz;
|
||||
return 16_MHz;
|
||||
}
|
||||
|
||||
using dev = avr::device<{.clock = clock()}>;
|
||||
|
||||
// The watchdog reset flag's home: MCUSR, or the classic megas' MCUCSR.
|
||||
consteval std::int16_t wdrf_field()
|
||||
{
|
||||
auto reg = std::string_view{avr::hw::db.regs[static_cast<std::size_t>(avr::power::detail::reset_reg())].name};
|
||||
return avr::hw::db.field_index(reg, "WDRF");
|
||||
}
|
||||
|
||||
// Geometry: the resident loader owns the top slot of flash — 512 bytes,
|
||||
// except on the >64 KiB chips whose own smallest boot sector is 1 KiB (the
|
||||
// 1284P): there the slot is 1 KiB, matching the hardware boundary the
|
||||
// 512-byte figure comes from everywhere else. The word below the slot is
|
||||
// the trampoline (the application's relocated reset vector) on chips
|
||||
// without a hardware boot section. The RWWSRE bit marks a separate boot
|
||||
// section — on classic AVR the two capabilities coincide (the m8/m32 packs
|
||||
// spell its register SPMCR).
|
||||
constexpr std::uint16_t slot_bytes = spm::flash_bytes > 65536 ? 1024 : 512;
|
||||
constexpr std::uint32_t base = spm::flash_bytes - slot_bytes;
|
||||
constexpr std::uint16_t page = spm::page_bytes;
|
||||
constexpr bool boot_section = [] {
|
||||
for (auto reg : {"SPMCSR", "SPMCR"})
|
||||
if (avr::hw::db.field_index(reg, "RWWSRE") >= 0)
|
||||
return true;
|
||||
return false;
|
||||
}();
|
||||
|
||||
// Past 64 KiB a byte address no longer fits the wire's 16 bits, so on the
|
||||
// large chips every flash address on the wire — and all slot arithmetic —
|
||||
// is a word address instead ('J' always was one). A slot spans the same
|
||||
// wire-high-byte pair in either unit (512 B = 2 x 256 bytes, 1 KiB =
|
||||
// 2 x 256 words), so the slot index is the high byte with its low bit
|
||||
// dropped everywhere.
|
||||
constexpr bool word_flash = spm::flash_bytes > 65536;
|
||||
constexpr std::uint16_t wire_base = word_flash ? static_cast<std::uint16_t>(base / 2) : static_cast<std::uint16_t>(base);
|
||||
constexpr std::uint16_t wire_page_mask = word_flash ? (page / 2 - 1) : (page - 1);
|
||||
|
||||
// The activation window, in seconds, is a compile-time constant (the build
|
||||
// may override it): the whole EEPROM belongs to the application, and
|
||||
// re-timing the loader is a bootloader self-update with a re-timed binary.
|
||||
#if !defined(PUREBOOT_TIMEOUT)
|
||||
#define PUREBOOT_TIMEOUT 8
|
||||
#endif
|
||||
constexpr std::uint8_t timeout_seconds = PUREBOOT_TIMEOUT;
|
||||
|
||||
// The 12-byte info block the host reads with the 'b' command; flash-resident
|
||||
// (there is no crt to copy a .data image), word-aligned so its wire (word)
|
||||
// address is exact on the large chips. The page byte is the wire count
|
||||
// convention: 0 means 256.
|
||||
[[gnu::progmem]] alignas(2) inline constexpr std::array<std::uint8_t, 12> info_data = {
|
||||
'P',
|
||||
'B',
|
||||
1, // magic, protocol version
|
||||
avr::hw::db.signature[0],
|
||||
avr::hw::db.signature[1],
|
||||
avr::hw::db.signature[2],
|
||||
static_cast<std::uint8_t>(page),
|
||||
wire_base & 0xff,
|
||||
wire_base >> 8, // app flash ends here; resident loader base (a word address on large chips)
|
||||
avr::hw::db.mem.eeprom_size & 0xff,
|
||||
avr::hw::db.mem.eeprom_size >> 8,
|
||||
// bit 0: host must patch the reset vector (no hardware boot section);
|
||||
// bit 1: flash wire addresses are word addresses
|
||||
static_cast<std::uint8_t>((boot_section ? 0 : 1) | (word_flash ? 2 : 0)),
|
||||
};
|
||||
|
||||
// The serial link: the hardware USART where the chip has one, the polled
|
||||
// software UART (no vector — the table belongs to the application) on PB0/PB1
|
||||
// elsewhere. Both are class templates on the clock so only the selected
|
||||
// backend is ever instantiated. pending() is the cheap line test the
|
||||
// activation window polls; rx() then picks the byte up; drain() holds until
|
||||
// the last transmitted frame is fully on the wire (the jump hand-over must
|
||||
// not let the target's re-init clip the ack).
|
||||
template <avr::hertz_t C>
|
||||
consteval std::int16_t rxc_field()
|
||||
{
|
||||
return avr::uart::detail::ufield<'0', "UCSR#A", "RXC#">();
|
||||
}
|
||||
|
||||
template <avr::hertz_t C>
|
||||
consteval std::int16_t txc_field()
|
||||
{
|
||||
return avr::uart::detail::ufield<'0', "UCSR#A", "TXC#">();
|
||||
}
|
||||
|
||||
template <avr::hertz_t C>
|
||||
consteval std::int16_t status_reg()
|
||||
{
|
||||
return avr::uart::detail::ureg<'0', "UCSR#A">();
|
||||
}
|
||||
|
||||
template <avr::hertz_t C>
|
||||
struct hardware_link {
|
||||
using uart = avr::uart::usart0<C, {.baud = 115200_Bd, .max_baud_error = 2.5_pct}>;
|
||||
|
||||
// The compiled idle poll: lds UCSR0A (2), sbrc skipping the exit (2),
|
||||
// sbiw + sbci + sbci + brne (6).
|
||||
static constexpr std::uint8_t poll_cycles = 10;
|
||||
|
||||
static void init()
|
||||
{
|
||||
avr::init<uart>();
|
||||
}
|
||||
|
||||
static bool pending()
|
||||
{
|
||||
return avr::hw::field_impl<rxc_field<C>()>::test();
|
||||
}
|
||||
|
||||
static std::uint8_t rx()
|
||||
{
|
||||
return uart::read_blocking();
|
||||
}
|
||||
|
||||
static void tx(std::uint8_t byte)
|
||||
{
|
||||
uart::write(byte);
|
||||
}
|
||||
|
||||
static void drain()
|
||||
{
|
||||
// write() leaves the byte draining behind it. Clear a stale TXC0
|
||||
// first (W1C by writing the sampled status back — the store a hand
|
||||
// assembler writes, keeping U2X0), then wait for the fresh
|
||||
// completion; with a byte still ahead in the shifter TXC0 cannot
|
||||
// re-set until the last pending byte has fully left.
|
||||
using status = avr::hw::reg_impl<status_reg<C>()>;
|
||||
status::write(status::read());
|
||||
while (!avr::hw::field_impl<txc_field<C>()>::test()) {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <avr::hertz_t C>
|
||||
struct software_link {
|
||||
using rx_t = avr::uart::software_rx_polled<C, avr::pb0, 57600_Bd>;
|
||||
using tx_t = avr::uart::software_tx<C, avr::pb1, 57600_Bd>;
|
||||
|
||||
// The compiled idle poll: sbis skipping the exit (2), sbiw + sbci +
|
||||
// sbci + brne (6).
|
||||
static constexpr std::uint8_t poll_cycles = 8;
|
||||
|
||||
static void init()
|
||||
{
|
||||
avr::init<rx_t, tx_t>();
|
||||
}
|
||||
|
||||
static bool pending()
|
||||
{
|
||||
return !avr::io::input<avr::pb0>::read(); // a start bit has begun
|
||||
}
|
||||
|
||||
static std::uint8_t rx()
|
||||
{
|
||||
return rx_t::template read_blocking<off>();
|
||||
}
|
||||
|
||||
static void tx(std::uint8_t byte)
|
||||
{
|
||||
tx_t::template write<off>(byte);
|
||||
}
|
||||
|
||||
static void drain()
|
||||
{
|
||||
// The software transmitter returns only after the stop bit.
|
||||
}
|
||||
};
|
||||
|
||||
using link = std::conditional_t<avr::hw::db.has_instance("USART0") || avr::hw::db.has_instance("USART"),
|
||||
hardware_link<dev::clock>, software_link<dev::clock>>;
|
||||
|
||||
// The application's entry, an absolute address the linker pins (--defsym in
|
||||
// CMakeLists.txt): 0x0000 on the mega (word 0 stays the application's own
|
||||
// vector — BOOTRST re-vectors a reset into the loader in hardware) and the
|
||||
// trampoline word at base - 2 on the tinies. Reaching it must not depend on
|
||||
// where this copy runs, so the jump goes through a pointer: [[gnu::noipa]]
|
||||
// keeps the constant from folding back into a PC-relative call.
|
||||
extern "C" [[noreturn]] void pureboot_app();
|
||||
|
||||
[[gnu::noipa, noreturn]] void jump(void (*target)())
|
||||
{
|
||||
target();
|
||||
__builtin_unreachable();
|
||||
}
|
||||
|
||||
[[gnu::noinline, noreturn]] void run_app()
|
||||
{
|
||||
jump(pureboot_app);
|
||||
}
|
||||
|
||||
// One activation window is a single 32-bit poll countdown. The divisor is
|
||||
// the backend's counted poll-loop cycles (its own comment reads them off the
|
||||
// compiled loop); whole-second precision is all the window promises, so the
|
||||
// nearest cycle count is plenty.
|
||||
consteval std::uint32_t window_polls()
|
||||
{
|
||||
return timeout_seconds * static_cast<std::uint32_t>(dev::clock.hz / link::poll_cycles);
|
||||
}
|
||||
|
||||
bool pending_before_deadline()
|
||||
{
|
||||
std::uint32_t polls = window_polls();
|
||||
do {
|
||||
if (link::pending())
|
||||
return true;
|
||||
} while (--polls);
|
||||
return false;
|
||||
}
|
||||
|
||||
// A knock byte under the activation deadline: an idle line means no host is
|
||||
// there, and the application runs.
|
||||
std::uint8_t rx_deadline()
|
||||
{
|
||||
if (!pending_before_deadline())
|
||||
run_app();
|
||||
return link::rx();
|
||||
}
|
||||
|
||||
std::uint16_t rx16()
|
||||
{
|
||||
std::uint16_t low = link::rx();
|
||||
return static_cast<std::uint16_t>(low | (link::rx() << 8));
|
||||
}
|
||||
|
||||
// The streamers take the count in the wire's 8-bit form: 0 means 256.
|
||||
// send_flash stays out of line: its two callers ('b' and 'R') otherwise each
|
||||
// inline a private copy of the loop. On the large chips the address is a
|
||||
// word address and the read goes through ELPM (flash_load_far).
|
||||
[[gnu::noinline]] void send_flash(std::uint16_t address, std::uint8_t count)
|
||||
{
|
||||
if constexpr (word_flash) {
|
||||
// The 24-bit cursor as the machine holds it: the RAMPZ byte and a
|
||||
// 16-bit Z, carried explicitly (the reassembled 32-bit address
|
||||
// folds away inside the inlined far load). A single read never
|
||||
// crosses a 64 KiB boundary — the protocol forbids it and the host
|
||||
// splits its chunks there — so RAMPZ holds for the whole run.
|
||||
std::uint8_t rampz = static_cast<std::uint8_t>(address >> 15);
|
||||
std::uint16_t z = static_cast<std::uint16_t>(address << 1);
|
||||
do {
|
||||
link::tx(avr::flash_load_far<std::uint8_t>((static_cast<std::uint32_t>(rampz) << 16) | z));
|
||||
if (++z == 0)
|
||||
++rampz; // robustness for a host that reads across 64 KiB
|
||||
} while (--count);
|
||||
} else {
|
||||
do
|
||||
link::tx(avr::flash_load(reinterpret_cast<const std::uint8_t *>(address++)));
|
||||
while (--count);
|
||||
}
|
||||
}
|
||||
|
||||
void send_eeprom(std::uint16_t address, std::uint8_t count)
|
||||
{
|
||||
do
|
||||
link::tx(ee::read(address++));
|
||||
while (--count);
|
||||
}
|
||||
|
||||
// EEPROM write, host-paced: each ack goes out once the byte's write has
|
||||
// begun, so the next byte arrives while it completes and the following
|
||||
// write's own ready-wait sees an idle line. Nothing is ever missed, on
|
||||
// either serial backend, without a buffer.
|
||||
void store_eeprom(std::uint16_t address, std::uint8_t count)
|
||||
{
|
||||
do {
|
||||
ee::write<off>(address++, link::rx());
|
||||
link::tx(ack);
|
||||
} while (--count);
|
||||
}
|
||||
|
||||
// One flash page: stream the bytes into the SPM buffer as little-endian
|
||||
// words, then erase and program — except the 512-byte slot this code runs
|
||||
// in, which is drained but never programmed, so a copy can never erase
|
||||
// itself. `slot_high` is the high byte of that running slot's base (run()
|
||||
// derives it); a broken host thus cannot brick the running loader, and a
|
||||
// copy flashed one slot lower may rewrite the slot above it — how pureboot
|
||||
// updates itself. On the mega the RWW section is re-enabled so reads work
|
||||
// immediately.
|
||||
void program_flash(std::uint16_t wire_address, std::uint8_t slot_high)
|
||||
{
|
||||
// A buffer word cannot be loaded twice without an erase (§26.2.1), so a
|
||||
// refused page's drained data must not linger for the next write:
|
||||
// discard the buffer up front — CTPB on the tinies; on the mega writing
|
||||
// RWWSRE aborts a pending load (§26.2.2).
|
||||
if constexpr (boot_section)
|
||||
spm::rww_enable<off>();
|
||||
else
|
||||
spm::clear_buffer<off>();
|
||||
// One induction either way. On the byte-addressed chips the wire address
|
||||
// itself walks the page (aligned, so the offset bits wrap to zero); on
|
||||
// the word-addressed large chips the wire word address becomes a 32-bit
|
||||
// byte cursor once, and their 256-byte page makes its low byte the whole
|
||||
// in-page offset. The slot index is one high byte of the wire address —
|
||||
// two values on byte-addressed chips (the & ~1), bits 16:9 re-packed on
|
||||
// the large ones.
|
||||
spm::flash_address_t address;
|
||||
std::uint8_t page_high;
|
||||
if constexpr (word_flash) {
|
||||
// Pages are aligned, so one page never crosses a 64 KiB boundary:
|
||||
// RAMPZ is a per-page constant and the fill cursor is a 16-bit Z
|
||||
// whose low byte is the whole in-page offset (256-byte pages). The
|
||||
// slot index is simply the wire word address's high byte.
|
||||
const std::uint8_t rampz = static_cast<std::uint8_t>(wire_address >> 15);
|
||||
const std::uint16_t z0 = static_cast<std::uint16_t>(wire_address << 1);
|
||||
std::uint16_t z = z0;
|
||||
do {
|
||||
std::uint8_t low = link::rx();
|
||||
std::uint8_t high = link::rx();
|
||||
spm::fill<off>((static_cast<spm::flash_address_t>(rampz) << 16) | z,
|
||||
static_cast<std::uint16_t>(low | (high << 8)));
|
||||
z += 2;
|
||||
} while (static_cast<std::uint8_t>(z));
|
||||
address = (static_cast<spm::flash_address_t>(rampz) << 16) | z0;
|
||||
page_high = static_cast<std::uint8_t>(wire_address >> 8) & 0xfe;
|
||||
} else {
|
||||
address = static_cast<spm::flash_address_t>(wire_address);
|
||||
do {
|
||||
std::uint8_t low = link::rx();
|
||||
std::uint8_t high = link::rx();
|
||||
spm::fill<off>(address, static_cast<std::uint16_t>(low | (high << 8)));
|
||||
address += 2;
|
||||
} while (static_cast<std::uint8_t>(address) & (page - 1));
|
||||
address -= 2; // back inside the page — erase and write ignore the word bits
|
||||
page_high = static_cast<std::uint8_t>(address >> 8) & 0xfe;
|
||||
}
|
||||
if (page_high != slot_high) {
|
||||
// The tinies halt the CPU through the erase and the write, so only
|
||||
// the megas — running on while their RWW section programs — wait.
|
||||
spm::erase_page<off>(address);
|
||||
if constexpr (boot_section)
|
||||
spm::wait();
|
||||
spm::write_page<off>(address);
|
||||
if constexpr (boot_section) {
|
||||
spm::wait();
|
||||
spm::rww_enable<off>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The four fuse/lock bytes in the hardware's own Z order: low, lock,
|
||||
// extended, high. Writing fuses is not a thing self-programming can do on
|
||||
// AVR — SPM reaches flash (and boot lock bits) only.
|
||||
void send_fuses()
|
||||
{
|
||||
std::uint8_t which = 0;
|
||||
do
|
||||
link::tx(spm::read_fuse<off>(static_cast<spm::fuse>(which)));
|
||||
while (++which & 3);
|
||||
}
|
||||
|
||||
[[noreturn]] void run()
|
||||
{
|
||||
// A watchdog reset belongs to the application (whose watchdog stays
|
||||
// forced on until it clears WDRF) — no activation window in its way.
|
||||
// The flag register is MCUSR, or the classic megas' MCUCSR.
|
||||
if (avr::hw::field_impl<wdrf_field()>::test())
|
||||
run_app();
|
||||
|
||||
link::init();
|
||||
|
||||
// The high byte of the 512-byte-aligned base this copy runs at: the
|
||||
// return address is a word address, whose high byte is the 256-word slot
|
||||
// index — on byte-addressed chips doubled back into byte terms.
|
||||
// program_flash refuses this one slot and the info block is addressed
|
||||
// from it, so both follow wherever the code was flashed.
|
||||
const std::uint16_t ra_words = reinterpret_cast<std::uint16_t>(__builtin_return_address(0));
|
||||
const std::uint8_t slot_high = word_flash ? static_cast<std::uint8_t>(ra_words >> 8) & 0xfe
|
||||
: static_cast<std::uint8_t>((ra_words >> 8) << 1);
|
||||
|
||||
// The knock: 'p' then 'b', each under a fresh window; any other byte is
|
||||
// line noise and waits again. Falling out of a window runs the app.
|
||||
while (rx_deadline() != 'p' || rx_deadline() != 'b') {
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
// No prompt while an EEPROM write runs: a pending write blocks SPM
|
||||
// and fuse reads (§26.2.1), and the ack tells the host all is done.
|
||||
ee::wait();
|
||||
link::tx(ack);
|
||||
const std::uint8_t command = link::rx();
|
||||
switch (command) {
|
||||
case 'b': { // info block, read relative to the running slot
|
||||
// The block sits in the image's first 256 bytes (the build lint
|
||||
// asserts it), and slots are 512-aligned — so the low byte of its
|
||||
// link address (in wire units: bytes, or words on the large
|
||||
// chips) is its offset in any slot, and the high byte of its
|
||||
// runtime address is the running slot's. Built as a byte pair so
|
||||
// no absolute address is ever materialized.
|
||||
const auto link_low = reinterpret_cast<std::uint16_t>(info_data.data());
|
||||
const std::uint8_t low =
|
||||
word_flash ? static_cast<std::uint8_t>(link_low >> 1) : static_cast<std::uint8_t>(link_low);
|
||||
send_flash(std::bit_cast<std::uint16_t>(std::array{low, slot_high}),
|
||||
static_cast<std::uint8_t>(info_data.size()));
|
||||
break;
|
||||
}
|
||||
case 'J': { // jump to a wire word address: hand-over and staging transfer
|
||||
auto target = reinterpret_cast<void (*)()>(rx16());
|
||||
link::tx(ack);
|
||||
link::drain();
|
||||
jump(target);
|
||||
}
|
||||
case 'R': // read flash: addr16, n8 (0 = 256)
|
||||
case 'r': // read EEPROM: addr16, n8
|
||||
case 'w': { // write EEPROM: addr16, n8, then n bytes each acked
|
||||
std::uint16_t address = rx16();
|
||||
std::uint8_t count = link::rx();
|
||||
if (command == 'R')
|
||||
send_flash(address, count);
|
||||
else if (command == 'r')
|
||||
send_eeprom(address, count);
|
||||
else
|
||||
store_eeprom(address, count);
|
||||
break;
|
||||
}
|
||||
case 'W': // program one flash page: addr16, page bytes
|
||||
program_flash(rx16(), slot_high);
|
||||
break;
|
||||
case 'F': // fuse and lock bytes
|
||||
send_fuses();
|
||||
break;
|
||||
default: // unknown bytes are ignored; the loop re-acks
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace pureboot
|
||||
|
||||
template struct avr::startup::entry<pureboot::run>;
|
||||
@@ -1,942 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""pureboot host tool — the smart half of the pureboot protocol (README.md).
|
||||
|
||||
The device exposes primitives; this tool composes them: image loading (raw
|
||||
binary or Intel HEX), flash programming with read-back verification, erase as
|
||||
writing 0xff, EEPROM programming, fuse and info readout, the hand-over jump,
|
||||
and — on chips without a hardware boot section — the reset-vector surgery
|
||||
that re-homes the application's entry through the trampoline word below the
|
||||
loader. Page 0 and the trampoline are written first, so every interruption
|
||||
point of a flash leaves the chip reset-recoverable into the loader.
|
||||
|
||||
It also updates the loader itself (--update-loader): pureboot's image is
|
||||
position-independent, so the tool installs the identical binary one 512-byte
|
||||
slot below the resident loader, jumps into that staging copy, lets it rewrite
|
||||
the resident slot, and restores what the staging slot held — resumable at
|
||||
every phase from the flash state plus a host-side state file carrying the
|
||||
saved bytes.
|
||||
|
||||
Python standard library only; the serial port is driven with termios on POSIX
|
||||
and the Win32 serial API (through ctypes) on Windows, so any tty or COM port
|
||||
works — a USB adapter as well as a simavr pty.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
else:
|
||||
import select
|
||||
import termios
|
||||
|
||||
PROMPT = b"+"
|
||||
PROTOCOL_VERSION = 1
|
||||
SLOT = 512 # the loader slot on byte-addressed chips; word-addressed ones (>64 KiB) use 1 KiB — their own smallest boot sector
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- serial ---
|
||||
|
||||
|
||||
class PosixPort:
|
||||
"""A raw serial port with deadline-based reads, over termios."""
|
||||
|
||||
def __init__(self, path, baud):
|
||||
self.fd = os.open(path, os.O_RDWR | os.O_NOCTTY)
|
||||
attrs = termios.tcgetattr(self.fd)
|
||||
attrs[0] = 0 # iflag
|
||||
attrs[1] = 0 # oflag
|
||||
attrs[2] = termios.CREAD | termios.CLOCAL | termios.CS8 # cflag
|
||||
attrs[3] = 0 # lflag
|
||||
try:
|
||||
speed = getattr(termios, f"B{baud}")
|
||||
except AttributeError:
|
||||
raise Error(f"unsupported baud rate {baud}") from None
|
||||
attrs[4] = attrs[5] = speed
|
||||
attrs[6][termios.VMIN] = 0
|
||||
attrs[6][termios.VTIME] = 0
|
||||
termios.tcsetattr(self.fd, termios.TCSANOW, attrs)
|
||||
|
||||
def close(self):
|
||||
os.close(self.fd)
|
||||
|
||||
def write(self, data):
|
||||
os.write(self.fd, data)
|
||||
|
||||
def flush_input(self):
|
||||
termios.tcflush(self.fd, termios.TCIFLUSH)
|
||||
|
||||
def read_available(self, wait):
|
||||
"""Everything that arrives within `wait` seconds of quiet start."""
|
||||
ready, _, _ = select.select([self.fd], [], [], wait)
|
||||
return os.read(self.fd, 4096) if ready else b""
|
||||
|
||||
def read_exact(self, count, timeout):
|
||||
data = b""
|
||||
deadline = time.monotonic() + timeout
|
||||
while len(data) < count:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise Error(f"timeout: got {len(data)} of {count} bytes")
|
||||
ready, _, _ = select.select([self.fd], [], [], remaining)
|
||||
if ready:
|
||||
data += os.read(self.fd, count - len(data))
|
||||
return data
|
||||
|
||||
|
||||
if os.name == "nt":
|
||||
# The same port, over the Win32 serial API — kernel32 through ctypes, so
|
||||
# the tool stays standard-library only. Timeouts live in the driver
|
||||
# (COMMTIMEOUTS) rather than in a readiness call: Windows has no select()
|
||||
# for a COM handle, so each read asks the driver for its own deadline.
|
||||
|
||||
_GENERIC_READ, _GENERIC_WRITE = 0x80000000, 0x40000000
|
||||
_OPEN_EXISTING, _PURGE_RXCLEAR = 3, 0x0008
|
||||
_INVALID_HANDLE = wintypes.HANDLE(-1).value
|
||||
# A gap this long ends a read_available(): longer than the coalescing a
|
||||
# USB-serial adapter's latency timer imposes (16 ms on FTDI parts), so a
|
||||
# burst is not split, short enough to stay responsive.
|
||||
_GAP_MS = 30
|
||||
|
||||
class _DCB(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("DCBlength", wintypes.DWORD),
|
||||
("BaudRate", wintypes.DWORD),
|
||||
("fBits", wintypes.DWORD), # the packed flag bitfield, set below
|
||||
("wReserved", wintypes.WORD),
|
||||
("XonLim", wintypes.WORD),
|
||||
("XoffLim", wintypes.WORD),
|
||||
("ByteSize", wintypes.BYTE),
|
||||
("Parity", wintypes.BYTE),
|
||||
("StopBits", wintypes.BYTE),
|
||||
("XonChar", ctypes.c_char),
|
||||
("XoffChar", ctypes.c_char),
|
||||
("ErrorChar", ctypes.c_char),
|
||||
("EofChar", ctypes.c_char),
|
||||
("EvtChar", ctypes.c_char),
|
||||
("wReserved1", wintypes.WORD),
|
||||
]
|
||||
|
||||
class _COMMTIMEOUTS(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("ReadIntervalTimeout", wintypes.DWORD),
|
||||
("ReadTotalTimeoutMultiplier", wintypes.DWORD),
|
||||
("ReadTotalTimeoutConstant", wintypes.DWORD),
|
||||
("WriteTotalTimeoutMultiplier", wintypes.DWORD),
|
||||
("WriteTotalTimeoutConstant", wintypes.DWORD),
|
||||
]
|
||||
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_LPDWORD = ctypes.POINTER(wintypes.DWORD)
|
||||
# Declared, not inferred: a HANDLE is a pointer, and a defaulted int
|
||||
# return would truncate it on 64-bit.
|
||||
_k32.CreateFileW.restype = wintypes.HANDLE
|
||||
_k32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
|
||||
wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
||||
_k32.ReadFile.argtypes = [wintypes.HANDLE, wintypes.LPVOID, wintypes.DWORD, _LPDWORD, wintypes.LPVOID]
|
||||
_k32.WriteFile.argtypes = [wintypes.HANDLE, wintypes.LPCVOID, wintypes.DWORD, _LPDWORD, wintypes.LPVOID]
|
||||
_k32.GetCommState.argtypes = [wintypes.HANDLE, ctypes.POINTER(_DCB)]
|
||||
_k32.SetCommState.argtypes = [wintypes.HANDLE, ctypes.POINTER(_DCB)]
|
||||
_k32.SetCommTimeouts.argtypes = [wintypes.HANDLE, ctypes.POINTER(_COMMTIMEOUTS)]
|
||||
_k32.PurgeComm.argtypes = [wintypes.HANDLE, wintypes.DWORD]
|
||||
_k32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
|
||||
def _fail(what):
|
||||
code = ctypes.get_last_error()
|
||||
raise Error(f"{what}: {ctypes.FormatError(code).strip()} (Windows error {code})")
|
||||
|
||||
class WindowsPort:
|
||||
"""A raw serial port with deadline-based reads, over Win32."""
|
||||
|
||||
def __init__(self, path, baud):
|
||||
# Win32 takes the rate as a plain integer, so unlike termios any
|
||||
# rate the hardware can divide down to is available — but a driver
|
||||
# may also accept one it cannot produce (an FT232R takes a baud of
|
||||
# 3, reports it back, and goes on using the previous divisor).
|
||||
# Only obvious nonsense is refusable; the rest is the driver's word.
|
||||
if baud < 50:
|
||||
raise Error(f"unsupported baud rate {baud}")
|
||||
# \\.\COM6: the device-namespace form. A bare COMn resolves only
|
||||
# for n < 10, and double-digit ports are routine on Windows.
|
||||
if path.lower().startswith("com") and path[3:].isdigit():
|
||||
path = rf"\\.\{path}"
|
||||
self.handle = _k32.CreateFileW(
|
||||
path, _GENERIC_READ | _GENERIC_WRITE, 0, None, _OPEN_EXISTING, 0, None
|
||||
)
|
||||
if self.handle == _INVALID_HANDLE:
|
||||
_fail(f"cannot open {path}")
|
||||
self.timeouts = None
|
||||
try:
|
||||
dcb = _DCB()
|
||||
dcb.DCBlength = ctypes.sizeof(_DCB)
|
||||
if not _k32.GetCommState(self.handle, ctypes.byref(dcb)):
|
||||
_fail(f"cannot read the state of {path}")
|
||||
dcb.BaudRate, dcb.ByteSize, dcb.Parity, dcb.StopBits = baud, 8, 0, 0 # 8N1
|
||||
# fBinary, and DTR/RTS asserted (fDtrControl and fRtsControl,
|
||||
# two bits each, = _ENABLE); every other flag clear, so no
|
||||
# parity and no flow control. Raising both matches what opening
|
||||
# a POSIX tty does — including the reset pulse on the boards
|
||||
# that wire DTR to it.
|
||||
dcb.fBits = 0x1 | (1 << 4) | (1 << 12)
|
||||
if not _k32.SetCommState(self.handle, ctypes.byref(dcb)):
|
||||
_fail(f"cannot configure {path} for {baud} baud 8N1")
|
||||
# Arm them once here too: reads re-arm per call, but the write
|
||||
# timeout would otherwise stay at the driver's default — which
|
||||
# may be "wait forever" — until the first read.
|
||||
self._deadline(_GAP_MS, 1000)
|
||||
except Error:
|
||||
# An open port outlives the exception otherwise, and a COM
|
||||
# handle is exclusive: the next attempt would meet its own
|
||||
# leftover as "Access is denied".
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
_k32.CloseHandle(self.handle)
|
||||
|
||||
def _deadline(self, interval, total):
|
||||
"""Arm the driver's read timeouts: `interval` ms of quiet ends a
|
||||
read once bytes have arrived, `total` ms ends it regardless."""
|
||||
if self.timeouts == (interval, total):
|
||||
return
|
||||
spec = _COMMTIMEOUTS()
|
||||
spec.ReadIntervalTimeout = interval
|
||||
spec.ReadTotalTimeoutConstant = total
|
||||
spec.WriteTotalTimeoutConstant = 5000
|
||||
if not _k32.SetCommTimeouts(self.handle, ctypes.byref(spec)):
|
||||
_fail("cannot set the port timeouts")
|
||||
self.timeouts = (interval, total)
|
||||
|
||||
def _read(self, count):
|
||||
buffer = ctypes.create_string_buffer(count)
|
||||
got = wintypes.DWORD()
|
||||
if not _k32.ReadFile(self.handle, buffer, count, ctypes.byref(got), None):
|
||||
_fail("read failed")
|
||||
return buffer.raw[: got.value]
|
||||
|
||||
def write(self, data):
|
||||
written = wintypes.DWORD()
|
||||
if not _k32.WriteFile(self.handle, data, len(data), ctypes.byref(written), None):
|
||||
_fail("write failed")
|
||||
if written.value != len(data):
|
||||
raise Error(f"short write: {written.value} of {len(data)} bytes")
|
||||
|
||||
def flush_input(self):
|
||||
if not _k32.PurgeComm(self.handle, _PURGE_RXCLEAR):
|
||||
_fail("cannot flush the input buffer")
|
||||
|
||||
def read_available(self, wait):
|
||||
"""Everything that arrives within `wait` seconds of quiet start."""
|
||||
# A zero total means *no* timeout to the driver, so never round
|
||||
# down to it — the same trap on the deadline below.
|
||||
self._deadline(_GAP_MS, max(1, round(wait * 1000)))
|
||||
return self._read(4096)
|
||||
|
||||
def read_exact(self, count, timeout):
|
||||
data = b""
|
||||
deadline = time.monotonic() + timeout
|
||||
while len(data) < count:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise Error(f"timeout: got {len(data)} of {count} bytes")
|
||||
# No interval timeout here: only the count or the deadline
|
||||
# ends the read, so a gap mid-reply is simply waited out.
|
||||
self._deadline(0, max(1, round(remaining * 1000)))
|
||||
data += self._read(count - len(data))
|
||||
return data
|
||||
|
||||
|
||||
Port = WindowsPort if os.name == "nt" else PosixPort
|
||||
|
||||
|
||||
# -------------------------------------------------------------- protocol ---
|
||||
|
||||
|
||||
class Info:
|
||||
"""The 12-byte info block."""
|
||||
|
||||
def __init__(self, raw):
|
||||
if len(raw) != 12 or raw[0:2] != b"PB":
|
||||
raise Error(f"bad info block: {raw.hex()}")
|
||||
if raw[2] != PROTOCOL_VERSION:
|
||||
raise Error(f"protocol version {raw[2]}, tool speaks {PROTOCOL_VERSION}")
|
||||
self.raw = bytes(raw)
|
||||
self.signature = raw[3:6]
|
||||
self.page = raw[6] or 256 # the wire count convention: 0 means 256
|
||||
self.patch_vector = bool(raw[11] & 1)
|
||||
# Large chips speak word addresses for flash (bit 1); the host keeps
|
||||
# every address in bytes and converts at the wire.
|
||||
self.word_flash = bool(raw[11] & 2)
|
||||
scale = 2 if self.word_flash else 1
|
||||
self.base = (raw[7] | (raw[8] << 8)) * scale
|
||||
self.eeprom_size = raw[9] | (raw[10] << 8)
|
||||
self.slot = 1024 if self.word_flash else SLOT
|
||||
self.flash_size = self.base + self.slot
|
||||
self.stage = self.base - self.slot # where a staging copy of the loader goes
|
||||
# The hand-over target, as the word address 'J' takes: the trampoline
|
||||
# below the loader (tinies), or word 0 (mega — the application's own
|
||||
# reset vector; BOOTRST re-vectors a reset into the loader instead).
|
||||
self.app_entry_word = (self.base - 2) // 2 if self.patch_vector else 0
|
||||
|
||||
def describe(self):
|
||||
sig = " ".join(f"{b:02x}" for b in self.signature)
|
||||
vector = "host-patched reset vector" if self.patch_vector else "hardware boot section"
|
||||
return (
|
||||
f"signature {sig}, page {self.page} B, "
|
||||
f"app flash {self.base} B (loader at {self.base:#06x}), "
|
||||
f"EEPROM {self.eeprom_size} B, {vector}"
|
||||
)
|
||||
|
||||
|
||||
class Loader:
|
||||
"""A pureboot session. Between commands the loader has prompted `+` and
|
||||
awaits a command byte; every method restores that invariant — except
|
||||
jump(), after which the target must be knocked afresh."""
|
||||
|
||||
def __init__(self, port):
|
||||
self.port = port
|
||||
self.info = None
|
||||
|
||||
def connect(self, wait):
|
||||
"""Knock until the activation window answers, then read the info
|
||||
block. Also converges when the loader already sits in its command
|
||||
loop: the knock bytes are ignored-or-executed there, and the drain
|
||||
absorbs whatever they produced."""
|
||||
self.port.flush_input()
|
||||
deadline = time.monotonic() + wait
|
||||
while True:
|
||||
self.port.write(b"pb")
|
||||
if PROMPT in self.port.read_available(0.4):
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
raise Error("no answer — reset the device within its activation window")
|
||||
while self.port.read_available(0.3):
|
||||
pass
|
||||
self.port.write(b"b")
|
||||
self.info = Info(self.port.read_exact(12, 2.0))
|
||||
self._expect_prompt()
|
||||
return self.info
|
||||
|
||||
def _expect_prompt(self, timeout=2.0):
|
||||
byte = self.port.read_exact(1, timeout)
|
||||
if byte != PROMPT:
|
||||
raise Error(f"expected prompt, got {byte.hex()}")
|
||||
|
||||
def _command(self, tx, reply_len=0, timeout=2.0):
|
||||
self.port.write(tx)
|
||||
reply = self.port.read_exact(reply_len, timeout) if reply_len else b""
|
||||
self._expect_prompt(timeout)
|
||||
return reply
|
||||
|
||||
def _stream_read(self, command, address, count, address_scale=1):
|
||||
data = b""
|
||||
while count:
|
||||
chunk = min(count, 256)
|
||||
wire = address // address_scale
|
||||
head = bytes((ord(command), wire & 0xFF, wire >> 8, chunk & 0xFF))
|
||||
data += self._command(head, chunk, 5.0)
|
||||
address += chunk
|
||||
count -= chunk
|
||||
return data
|
||||
|
||||
def read_flash(self, address, count):
|
||||
if not self.info.word_flash:
|
||||
return self._stream_read("R", address, count)
|
||||
# Word-addressed wire: widen to even bounds and never let one read
|
||||
# cross a 64 KiB boundary (the device holds RAMPZ for a whole run).
|
||||
start = address & ~1
|
||||
span = (address + count + 1 & ~1) - start
|
||||
data = b""
|
||||
at = start
|
||||
remaining = span
|
||||
while remaining:
|
||||
chunk = min(remaining, 0x10000 - (at & 0xFFFF))
|
||||
data += self._stream_read("R", at, chunk, address_scale=2)
|
||||
at += chunk
|
||||
remaining -= chunk
|
||||
return data[address - start : address - start + count]
|
||||
|
||||
def read_eeprom(self, address, count):
|
||||
return self._stream_read("r", address, count)
|
||||
|
||||
def write_page(self, address, data):
|
||||
assert len(data) == self.info.page and address % self.info.page == 0
|
||||
wire = address // (2 if self.info.word_flash else 1)
|
||||
head = bytes((ord("W"), wire & 0xFF, wire >> 8))
|
||||
self._command(head + data, 0, 2.0)
|
||||
|
||||
def write_eeprom(self, address, data):
|
||||
offset = 0
|
||||
while offset < len(data):
|
||||
chunk = data[offset : offset + 256]
|
||||
head = bytes((ord("w"), address & 0xFF, address >> 8, len(chunk) & 0xFF))
|
||||
self.port.write(head)
|
||||
for byte in chunk:
|
||||
self.port.write(bytes((byte,)))
|
||||
self._expect_prompt() # per-byte ack: the write has begun
|
||||
self._expect_prompt() # the next command prompt
|
||||
address += len(chunk)
|
||||
offset += len(chunk)
|
||||
|
||||
def read_fuses(self):
|
||||
return self._command(b"F", 4, 2.0)
|
||||
|
||||
def jump(self, word_address):
|
||||
"""'J': the device acks, then execution continues at the word
|
||||
address — a loader slot's base (whose copy must then be knocked
|
||||
afresh) or the application entry."""
|
||||
self.port.write(bytes((ord("J"), word_address & 0xFF, word_address >> 8)))
|
||||
self._expect_prompt()
|
||||
|
||||
def enter_copy(self, byte_address, wait):
|
||||
"""Jump into the loader copy at `byte_address` and knock it. Ending
|
||||
up in the copy addressed is guaranteed by construction: a jump to a
|
||||
slot base lands in that slot's entry stub."""
|
||||
self.jump(byte_address // 2)
|
||||
return self.connect(wait)
|
||||
|
||||
def run_application(self):
|
||||
self.jump(self.info.app_entry_word)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- images ---
|
||||
|
||||
|
||||
def load_image(path):
|
||||
"""Raw binary, or Intel HEX by extension (.hex/.ihx/.ihex)."""
|
||||
data = open(path, "rb").read()
|
||||
if not path.lower().endswith((".hex", ".ihx", ".ihex")):
|
||||
if not data:
|
||||
raise Error(f"{path}: empty image")
|
||||
return data
|
||||
memory = {}
|
||||
for number, line in enumerate(data.decode("ascii", "replace").splitlines(), 1):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
if not line.startswith(":"):
|
||||
raise Error(f"{path}:{number}: not an Intel HEX record")
|
||||
record = bytes.fromhex(line[1:])
|
||||
if sum(record) & 0xFF:
|
||||
raise Error(f"{path}:{number}: checksum mismatch")
|
||||
count, address, kind = record[0], (record[1] << 8) | record[2], record[3]
|
||||
payload = record[4 : 4 + count]
|
||||
if kind == 0:
|
||||
for i, byte in enumerate(payload):
|
||||
memory[address + i] = byte
|
||||
elif kind == 1:
|
||||
break
|
||||
elif kind in (2, 4) and not any(payload):
|
||||
continue # a zero base extends nothing
|
||||
elif kind in (3, 5):
|
||||
continue # start address: irrelevant, reset is the entry
|
||||
else:
|
||||
raise Error(f"{path}:{number}: record type {kind} reaches beyond the 16-bit space")
|
||||
if not memory:
|
||||
raise Error(f"{path}: empty image")
|
||||
return bytes(memory.get(i, 0xFF) for i in range(max(memory) + 1))
|
||||
|
||||
|
||||
# --------------------------------------------------------------- surgery ---
|
||||
|
||||
|
||||
def rjmp_target(word_address, opcode, flash_words):
|
||||
return (word_address + 1 + (opcode & 0x0FFF)) % flash_words
|
||||
|
||||
|
||||
def rjmp_to(word_address, destination, flash_words):
|
||||
return 0xC000 | ((destination - word_address - 1) % flash_words % 0x1000)
|
||||
|
||||
|
||||
def plan_flash(image, info):
|
||||
"""The pages to program, as {page_address: bytes}, already carrying the
|
||||
reset-vector surgery where the chip needs it."""
|
||||
page = info.page
|
||||
limit = info.base - (2 if info.patch_vector else 0)
|
||||
if len(image) > limit:
|
||||
raise Error(f"image is {len(image)} B, application flash ends at {limit}")
|
||||
final = bytearray(image) + bytearray([0xFF] * (-len(image) % page))
|
||||
|
||||
if info.patch_vector:
|
||||
flash_words = info.flash_size // 2
|
||||
word0 = final[0] | (final[1] << 8)
|
||||
if word0 & 0xF000 != 0xC000:
|
||||
raise Error(
|
||||
"the image's reset vector is not an rjmp — pureboot's vector "
|
||||
"surgery cannot re-home it (crt-less entry at address 0?)"
|
||||
)
|
||||
entry = rjmp_target(0, word0, flash_words)
|
||||
if entry >= info.base // 2:
|
||||
raise Error(
|
||||
"the image's reset vector already targets the loader — this "
|
||||
"is a read-back of a patched image; flash the original"
|
||||
)
|
||||
trampoline_word = (info.base - 2) // 2
|
||||
patch = rjmp_to(0, info.base // 2, flash_words)
|
||||
final[0], final[1] = patch & 0xFF, patch >> 8
|
||||
trampoline_page = info.base - page
|
||||
if len(final) < trampoline_page + page:
|
||||
final += bytearray([0xFF] * (trampoline_page + page - len(final)))
|
||||
jump = rjmp_to(trampoline_word, entry, flash_words)
|
||||
final[info.base - 2], final[info.base - 1] = jump & 0xFF, jump >> 8
|
||||
|
||||
pages = {a: bytes(final[a : a + page]) for a in range(0, len(final), page)}
|
||||
return pages
|
||||
|
||||
|
||||
def covered(pages, info, skip_blank):
|
||||
"""Pages in programming order; optionally dropping all-0xff pages (sound
|
||||
only over erased flash) — never a load-bearing one.
|
||||
|
||||
With a patched vector (tinies), the patched page 0 goes first and the
|
||||
trampoline page second: from the first write on, a reset lands in the
|
||||
loader and the loader's own fall-through lands on the application entry,
|
||||
so every interruption point of the flash is recoverable. With a hardware
|
||||
boot section a reset re-vectors to the loader regardless; ascending
|
||||
order, page 0 last, maximizes what an interrupted image retains."""
|
||||
trampoline_page = info.base - info.page if info.patch_vector else None
|
||||
first = [0, trampoline_page] if info.patch_vector else []
|
||||
rest = [a for a in sorted(pages) if a not in first]
|
||||
if skip_blank:
|
||||
rest = [a for a in rest if pages[a].count(0xFF) != len(pages[a])]
|
||||
order = [a for a in first if a in pages] + rest
|
||||
if not info.patch_vector:
|
||||
order = [a for a in order if a != 0] + ([0] if 0 in pages else [])
|
||||
return order
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- fuses ---
|
||||
|
||||
|
||||
# Per-chip boot fuse geometry, keyed by the signature's family/part bytes:
|
||||
# which byte of the 'F' reply (low, lock, extended, high) carries BOOTSZ/
|
||||
# BOOTRST, and the BOOTSZ->words ladder. Sources: Atmel-2486/2466/2503
|
||||
# (HIGH fuse), Atmel-8271 (m168A: EXTENDED; m328P: HIGH), Atmel-42719.
|
||||
BOOT_FUSE = {
|
||||
bytes((0x93, 0x07)): (3, {0b11: 128, 0b10: 256, 0b01: 512, 0b00: 1024}), # m8/8A
|
||||
bytes((0x94, 0x03)): (3, {0b11: 128, 0b10: 256, 0b01: 512, 0b00: 1024}), # m16
|
||||
bytes((0x95, 0x02)): (3, {0b11: 256, 0b10: 512, 0b01: 1024, 0b00: 2048}), # m32/32A
|
||||
bytes((0x94, 0x06)): (2, {0b11: 128, 0b10: 256, 0b01: 512, 0b00: 1024}), # m168A
|
||||
bytes((0x95, 0x0F)): (3, {0b11: 256, 0b10: 512, 0b01: 1024, 0b00: 2048}), # m328P
|
||||
bytes((0x97, 0x05)): (3, {0b11: 512, 0b10: 1024, 0b01: 2048, 0b00: 4096}), # 1284P
|
||||
}
|
||||
|
||||
|
||||
def mega_boot(info, fuse_bytes):
|
||||
"""Decode a mega's boot configuration from its fuses (the byte and the
|
||||
BOOTSZ ladder are per chip): BOOTSZ1:0 in bits 2:1 select the
|
||||
boot-section words, BOOTRST in bit 0 (programmed = 0) re-vectors reset
|
||||
to its start. Returns (bootrst_programmed, boot_section_start_byte)."""
|
||||
entry = BOOT_FUSE.get(bytes(info.signature[1:3]))
|
||||
if entry is None:
|
||||
raise Error(f"unknown mega signature {info.signature.hex()} — no boot fuse map")
|
||||
which, ladder = entry
|
||||
fuse = fuse_bytes[which]
|
||||
words = ladder[(fuse >> 1) & 0x03]
|
||||
return (fuse & 1) == 0, info.flash_size - words * 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------- loader update ---
|
||||
|
||||
|
||||
def image_info(image):
|
||||
"""The info block embedded in a pureboot binary, or None."""
|
||||
at = image.find(b"PB" + bytes((PROTOCOL_VERSION,)))
|
||||
return Info(image[at : at + 12]) if 0 <= at <= len(image) - 12 else None
|
||||
|
||||
|
||||
def loader_image(path):
|
||||
"""A loader update image, as the slot's own content. A raw binary is that
|
||||
already; an Intel HEX links the loader at its base inside an otherwise
|
||||
blank flash image, and load_image() anchors every image at zero, so the
|
||||
blank below the base is dropped here. The base comes from the image's own
|
||||
info block rather than the device's, so an image built for somewhere else
|
||||
survives intact and the preflight can say so."""
|
||||
image = load_image(path)
|
||||
embedded = image_info(image)
|
||||
if embedded and len(image) > embedded.base:
|
||||
image = image[embedded.base :]
|
||||
return image
|
||||
|
||||
|
||||
def staging_content(image, info):
|
||||
"""The 512-byte staging-slot content: the image, padding, and — on
|
||||
chips whose hand-over jumps through the word below the resident loader —
|
||||
that word, which for a staging copy is the slot's own last word: an rjmp
|
||||
to the resident base. The staging copy's fall-through and 'J'-free exit
|
||||
both land in a loader instead of garbage."""
|
||||
slot = info.slot
|
||||
if len(image) > (slot - 2 if info.patch_vector else slot):
|
||||
raise Error(f"loader image is {len(image)} B, the slot holds {slot - 2 if info.patch_vector else slot}")
|
||||
content = bytearray(image) + bytearray([0xFF] * (slot - len(image)))
|
||||
if info.patch_vector:
|
||||
through = rjmp_to((info.base - 2) // 2, info.base // 2, info.flash_size // 2)
|
||||
content[slot - 2], content[slot - 1] = through & 0xFF, through >> 8
|
||||
return bytes(content)
|
||||
|
||||
|
||||
def update_preflight(image, info, fuse_bytes):
|
||||
"""Errors and warnings before any flash is touched. Returns warnings."""
|
||||
embedded = image_info(image)
|
||||
if embedded is None:
|
||||
raise Error("no pureboot info block in the update image — not a pureboot binary?")
|
||||
if embedded.raw[3:] != info.raw[3:]:
|
||||
raise Error(
|
||||
f"update image is for another target: it declares "
|
||||
f"[{embedded.describe()}], the device says [{info.describe()}]"
|
||||
)
|
||||
warnings = []
|
||||
if not info.patch_vector:
|
||||
if fuse_bytes is None:
|
||||
raise Error("a loader update on this chip needs its fuses — unreadable? pass --assume-fuses")
|
||||
bootrst, bls_start = mega_boot(info, fuse_bytes)
|
||||
if info.stage < bls_start:
|
||||
raise Error(
|
||||
f"cannot self-update: the staging slot {info.stage:#06x} lies below the "
|
||||
f"boot section ({bls_start:#06x}) where SPM is disabled "
|
||||
f"— a boot section of at least two slots ({2 * info.slot} B, BOOTSZ) is "
|
||||
f"required, and only an external programmer can change fuses"
|
||||
)
|
||||
if not bootrst:
|
||||
warnings.append(
|
||||
"BOOTRST unprogrammed: reset boots the application throughout the update; "
|
||||
"an interruption is recovered by re-running this update"
|
||||
)
|
||||
elif bls_start == info.stage:
|
||||
warnings.append(
|
||||
"BOOTRST targets the staging slot: brief unrecoverable windows exist while "
|
||||
"the staging copy itself is being installed or retired (page-write scale)"
|
||||
)
|
||||
else:
|
||||
warnings.append(
|
||||
f"BOOTRST targets {bls_start:#06x}, inside application flash: reset reaches a "
|
||||
f"loader only across erased flash from there"
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
class UpdateState:
|
||||
"""The host-side memory of an update in flight: what the staging slot
|
||||
held (and page 0, where the update repoints it). Losing this file after
|
||||
the staging slot was overwritten loses those saved bytes — the update
|
||||
still completes, but the staging region can then only be restored by
|
||||
reflashing the application."""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self.data = None
|
||||
|
||||
def load_or_save(self, loader):
|
||||
info = loader.info
|
||||
if os.path.exists(self.path):
|
||||
self.data = json.load(open(self.path))
|
||||
if bytes.fromhex(self.data["signature"]) != info.signature or self.data["base"] != info.base:
|
||||
raise Error(f"{self.path} belongs to a different device — remove it to start over")
|
||||
return
|
||||
self.data = {
|
||||
"signature": info.signature.hex(),
|
||||
"base": info.base,
|
||||
"staging": loader.read_flash(info.stage, info.slot).hex(),
|
||||
"page0": loader.read_flash(0, info.page).hex() if info.patch_vector else "",
|
||||
}
|
||||
with open(self.path, "w") as f:
|
||||
json.dump(self.data, f)
|
||||
|
||||
@property
|
||||
def staging(self):
|
||||
return bytes.fromhex(self.data["staging"])
|
||||
|
||||
@property
|
||||
def page0(self):
|
||||
return bytes.fromhex(self.data["page0"])
|
||||
|
||||
def discard(self):
|
||||
os.unlink(self.path)
|
||||
|
||||
|
||||
def write_differing(loader, base, content, order=None):
|
||||
"""Program the pages of `content` at `base` that differ from flash —
|
||||
idempotent, so a resumed phase redoes only what an interruption left."""
|
||||
page = loader.info.page
|
||||
offsets = order if order is not None else range(0, len(content), page)
|
||||
written = 0
|
||||
for offset in offsets:
|
||||
want = content[offset : offset + page]
|
||||
if loader.read_flash(base + offset, page) != want:
|
||||
loader.write_page(base + offset, want)
|
||||
written += 1
|
||||
for at in range(0, len(content), 256):
|
||||
if loader.read_flash(base + at, min(256, len(content) - at)) != content[at : at + 256]:
|
||||
raise Error(f"verify failed at {base + at:#06x} after programming")
|
||||
return written
|
||||
|
||||
|
||||
def patch_word0(loader, page0, target_base):
|
||||
"""Rewrite page 0 with its word 0 re-aimed at `target_base` — the
|
||||
resume insurance around rewriting a loader slot the reset path uses."""
|
||||
info = loader.info
|
||||
patched = bytearray(page0)
|
||||
word = rjmp_to(0, target_base // 2, info.flash_size // 2)
|
||||
patched[0], patched[1] = word & 0xFF, word >> 8
|
||||
write_differing(loader, 0, bytes(patched))
|
||||
return bytes(patched)
|
||||
|
||||
|
||||
def op_update_loader(loader, wait, path, state_path, fuse_bytes):
|
||||
"""Replace the resident loader with `path`, using the loader itself as
|
||||
its own staging loader. Every phase is idempotent and keyed off the
|
||||
actual flash state, so a re-run after any interruption resumes; the
|
||||
state file carries the bytes the staging slot held."""
|
||||
info = loader.info
|
||||
image = loader_image(path)
|
||||
for warning in update_preflight(image, info, fuse_bytes):
|
||||
print(f"note: {warning}")
|
||||
staged = staging_content(image, info)
|
||||
resident = bytes(image) + bytes([0xFF] * (info.slot - len(image)))
|
||||
page = info.page
|
||||
|
||||
state = UpdateState(state_path)
|
||||
state.load_or_save(loader)
|
||||
|
||||
# Install the staging copy. On a chip whose staging slot starts at
|
||||
# address 0 (the 1 KB tiny13A), its first page carries the reset vector:
|
||||
# written last, so any earlier interruption still resets into the old
|
||||
# resident, and from then on resets enter the staging copy.
|
||||
order = list(range(0, info.slot, page))
|
||||
if info.stage == 0:
|
||||
order = order[1:] + [0]
|
||||
if write_differing(loader, info.stage, staged, order):
|
||||
print(f"staging copy installed at {info.stage:#06x}")
|
||||
|
||||
# Enter it and let it rewrite the resident slot. Where a patched reset
|
||||
# vector routes through the resident (a tiny with the staging slot away
|
||||
# from page 0), word 0 is re-aimed at the staging copy around the
|
||||
# rewrite, so a power failure mid-rewrite still resets into a loader.
|
||||
loader.enter_copy(info.stage, wait)
|
||||
redirect = info.patch_vector and info.stage != 0
|
||||
if redirect:
|
||||
patch_word0(loader, state.page0, info.stage)
|
||||
if write_differing(loader, info.base, resident):
|
||||
print(f"resident loader rewritten at {info.base:#06x}")
|
||||
|
||||
# Enter the new resident and put the staging region back: page 0 first
|
||||
# where it lives in that region (word 0 then points at the new resident
|
||||
# for the rest of the restore), the saved trampoline with the rest.
|
||||
loader.enter_copy(info.base, wait)
|
||||
if redirect:
|
||||
write_differing(loader, 0, state.page0)
|
||||
order = list(range(0, info.slot, page))
|
||||
if info.stage == 0:
|
||||
order = [0] + order[1:]
|
||||
write_differing(loader, info.stage, state.staging, order)
|
||||
|
||||
state.discard()
|
||||
print(f"loader updated: {len(image)} B at {info.base:#06x}, staging region restored")
|
||||
|
||||
|
||||
def check_walk_region(pages, info, fuse_bytes, force):
|
||||
"""With BOOTRST programmed but targeting below the loader, reset reaches
|
||||
the loader only by walking across erased flash from the boot-section
|
||||
start; application data in that span would divert reset into itself.
|
||||
Only checkable when the fuses are known (--fuses or --assume-fuses)."""
|
||||
if info.patch_vector or fuse_bytes is None:
|
||||
return
|
||||
bootrst, bls_start = mega_boot(info, fuse_bytes)
|
||||
if not bootrst or bls_start >= info.base:
|
||||
return
|
||||
overlap = [a for a in sorted(pages) if a >= bls_start and pages[a].count(0xFF) != len(pages[a])]
|
||||
if overlap and not force:
|
||||
raise Error(
|
||||
f"the image writes {overlap[0]:#06x}.. inside the reset walk region "
|
||||
f"[{bls_start:#06x}, {info.base:#06x}) (BOOTRST programmed): reset could no "
|
||||
f"longer reach the loader — --force to flash it anyway"
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------ operations ---
|
||||
|
||||
|
||||
def op_erase_flash(loader):
|
||||
"""0xff over the whole application area. Descending on a patched-vector
|
||||
chip: page 0 — the patched reset vector — goes last, so an interrupted
|
||||
erase still resets into the loader, and once it is gone the whole area
|
||||
is erased and the reset walk reaches the loader anyway."""
|
||||
blank = bytes([0xFF] * loader.info.page)
|
||||
addresses = range(0, loader.info.base, loader.info.page)
|
||||
for address in reversed(addresses) if loader.info.patch_vector else addresses:
|
||||
loader.write_page(address, blank)
|
||||
print(f"erase: {loader.info.base // loader.info.page} pages")
|
||||
|
||||
|
||||
def op_erase_eeprom(loader):
|
||||
loader.write_eeprom(0, bytes([0xFF] * loader.info.eeprom_size))
|
||||
print(f"erase: {loader.info.eeprom_size} B of EEPROM")
|
||||
|
||||
|
||||
def op_flash(loader, path, erase, verify, fuse_bytes=None, force=False):
|
||||
image = load_image(path)
|
||||
pages = plan_flash(image, loader.info)
|
||||
check_walk_region(pages, loader.info, fuse_bytes, force)
|
||||
if erase:
|
||||
op_erase_flash(loader)
|
||||
order = covered(pages, loader.info, skip_blank=erase)
|
||||
for address in order:
|
||||
loader.write_page(address, pages[address])
|
||||
print(f"flash: {path}: {len(order)} pages")
|
||||
if verify:
|
||||
verify_pages(loader, pages)
|
||||
|
||||
|
||||
def verify_pages(loader, pages):
|
||||
for address in sorted(pages):
|
||||
got = loader.read_flash(address, loader.info.page)
|
||||
if got != pages[address]:
|
||||
first = next(i for i in range(len(got)) if got[i] != pages[address][i])
|
||||
raise Error(
|
||||
f"verify failed at {address + first:#06x}: "
|
||||
f"wrote {pages[address][first]:02x}, read {got[first]:02x}"
|
||||
)
|
||||
print(f"verify: {len(pages)} pages ok")
|
||||
|
||||
|
||||
def op_verify_flash(loader, path):
|
||||
verify_pages(loader, plan_flash(load_image(path), loader.info))
|
||||
|
||||
|
||||
def op_read_flash(loader, path):
|
||||
data = loader.read_flash(0, loader.info.base)
|
||||
open(path, "wb").write(data)
|
||||
print(f"read flash: {len(data)} B -> {path}")
|
||||
|
||||
|
||||
def op_eeprom(loader, path, erase, verify):
|
||||
image = load_image(path)
|
||||
if len(image) > loader.info.eeprom_size:
|
||||
raise Error(f"EEPROM image is {len(image)} B, device has {loader.info.eeprom_size}")
|
||||
if erase:
|
||||
op_erase_eeprom(loader)
|
||||
loader.write_eeprom(0, image)
|
||||
print(f"eeprom: {path}: {len(image)} B")
|
||||
if verify:
|
||||
got = loader.read_eeprom(0, len(image))
|
||||
if got != image:
|
||||
first = next(i for i in range(len(got)) if got[i] != image[i])
|
||||
raise Error(f"verify failed at EEPROM {first:#06x}: wrote {image[first]:02x}, read {got[first]:02x}")
|
||||
print(f"verify: {len(image)} B ok")
|
||||
|
||||
|
||||
def op_verify_eeprom(loader, path):
|
||||
image = load_image(path)
|
||||
got = loader.read_eeprom(0, len(image))
|
||||
if got != image:
|
||||
first = next(i for i in range(len(got)) if got[i] != image[i])
|
||||
raise Error(f"verify failed at EEPROM {first:#06x}: expected {image[first]:02x}, read {got[first]:02x}")
|
||||
print(f"verify: {len(image)} B of EEPROM ok")
|
||||
|
||||
|
||||
def op_read_eeprom(loader, path):
|
||||
data = loader.read_eeprom(0, loader.info.eeprom_size)
|
||||
open(path, "wb").write(data)
|
||||
print(f"read EEPROM: {len(data)} B -> {path}")
|
||||
|
||||
|
||||
def op_fuses(loader):
|
||||
low, lock, extended, high = loader.read_fuses()
|
||||
print(f"fuses: low {low:02x} high {high:02x} extended {extended:02x} lock {lock:02x}")
|
||||
return bytes((low, lock, extended, high))
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- cli ---
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="pureboot host tool", epilog="operations run in the order listed above"
|
||||
)
|
||||
parser.add_argument("--port", required=True, help="serial device: COM6, /dev/ttyUSB0, or a simavr pty")
|
||||
parser.add_argument("--baud", type=int, default=115200, help="115200 mega, 57600 tinies")
|
||||
parser.add_argument("--wait", type=float, default=30.0, help="seconds to keep knocking")
|
||||
parser.add_argument("--info", action="store_true", help="print the device info block")
|
||||
parser.add_argument("--fuses", action="store_true", help="read the fuse and lock bytes")
|
||||
parser.add_argument("--update-loader", metavar="FILE", help="replace the loader with this pureboot binary")
|
||||
parser.add_argument("--state", metavar="FILE", help="update state file (default: FILE.pbstate)")
|
||||
parser.add_argument("--assume-fuses", metavar="HEX8", help="fuse bytes low,lock,ext,high as 8 hex digits "
|
||||
"(overrides reading them — e.g. under a simulator that cannot)")
|
||||
parser.add_argument("--erase-flash", action="store_true", help="0xff over the application flash")
|
||||
parser.add_argument("--flash", metavar="FILE", help="program an application (bin or ihex)")
|
||||
parser.add_argument("--no-verify", action="store_true", help="skip read-back after writes")
|
||||
parser.add_argument("--read-flash", metavar="FILE", help="dump the application flash")
|
||||
parser.add_argument("--verify-flash", metavar="FILE", help="compare flash against an image")
|
||||
parser.add_argument("--erase-eeprom", action="store_true", help="0xff over the EEPROM")
|
||||
parser.add_argument("--eeprom", metavar="FILE", help="program the EEPROM (bin or ihex)")
|
||||
parser.add_argument("--read-eeprom", metavar="FILE", help="dump the EEPROM")
|
||||
parser.add_argument("--verify-eeprom", metavar="FILE", help="compare EEPROM against an image")
|
||||
parser.add_argument("--force", action="store_true", help="override refusable safety checks")
|
||||
parser.add_argument("--stay", action="store_true", help="leave the loader in its session")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.update_loader and (args.flash or args.erase_flash):
|
||||
parser.error("--update-loader does not combine with application flash operations")
|
||||
fuse_override = None
|
||||
if args.assume_fuses:
|
||||
try:
|
||||
fuse_override = bytes.fromhex(args.assume_fuses)
|
||||
assert len(fuse_override) == 4
|
||||
except (ValueError, AssertionError):
|
||||
parser.error("--assume-fuses takes 8 hex digits: low,lock,extended,high")
|
||||
|
||||
port = Port(args.port, args.baud)
|
||||
try:
|
||||
loader = Loader(port)
|
||||
info = loader.connect(args.wait)
|
||||
if args.info:
|
||||
print(f"device: {info.describe()}")
|
||||
fuse_bytes = fuse_override
|
||||
if args.fuses or (args.update_loader and not info.patch_vector and fuse_bytes is None):
|
||||
read = op_fuses(loader)
|
||||
if fuse_bytes is None:
|
||||
fuse_bytes = read
|
||||
if args.update_loader:
|
||||
state = args.state or args.update_loader + ".pbstate"
|
||||
op_update_loader(loader, args.wait, args.update_loader, state, fuse_bytes)
|
||||
if args.flash:
|
||||
op_flash(loader, args.flash, args.erase_flash, not args.no_verify, fuse_bytes, args.force)
|
||||
elif args.erase_flash:
|
||||
op_erase_flash(loader)
|
||||
if args.read_flash:
|
||||
op_read_flash(loader, args.read_flash)
|
||||
if args.verify_flash:
|
||||
op_verify_flash(loader, args.verify_flash)
|
||||
if args.eeprom:
|
||||
op_eeprom(loader, args.eeprom, args.erase_eeprom, not args.no_verify)
|
||||
elif args.erase_eeprom:
|
||||
op_erase_eeprom(loader)
|
||||
if args.read_eeprom:
|
||||
op_read_eeprom(loader, args.read_eeprom)
|
||||
if args.verify_eeprom:
|
||||
op_verify_eeprom(loader, args.verify_eeprom)
|
||||
if args.stay:
|
||||
print("loader stays in its session (reset to leave)")
|
||||
else:
|
||||
loader.run_application()
|
||||
print("application running")
|
||||
finally:
|
||||
port.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Error as error:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(130)
|
||||
@@ -1,53 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Position-independence lint for the pureboot image.
|
||||
|
||||
The self-staging design lets the identical binary run from any 512-byte
|
||||
slot, which holds only if nothing in the image addresses itself absolutely.
|
||||
Two link-time facts guarantee it, both asserted here from the built ELF:
|
||||
|
||||
1. No absolute jmp/call opcodes — all control flow is PC-relative
|
||||
(rjmp/rcall/ijmp/icall). -mrelax normally guarantees this; a code
|
||||
change that grows a branch out of relaxation range would break it
|
||||
silently.
|
||||
2. The info block sits within the image's first 256 bytes: the 'b'
|
||||
command rebuilds its address as (running slot high byte : low byte of
|
||||
the link address), which needs the offset to fit that low byte.
|
||||
|
||||
Usage: check_pi.py <objdump> <nm> <elf> <text_start_hex>
|
||||
"""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
objdump, nm, elf, text_start = sys.argv[1:]
|
||||
text_start = int(text_start, 0)
|
||||
|
||||
listing = subprocess.run([objdump, "-d", elf], capture_output=True, text=True, check=True).stdout
|
||||
absolute = [
|
||||
line
|
||||
for line in listing.splitlines()
|
||||
if re.search(r"\t(jmp|call)\t", line)
|
||||
]
|
||||
if absolute:
|
||||
print("FAIL: absolute control flow in the image:")
|
||||
print("\n".join(absolute))
|
||||
sys.exit(1)
|
||||
|
||||
symbols = subprocess.run([nm, "-C", elf], capture_output=True, text=True, check=True).stdout
|
||||
info = [line for line in symbols.splitlines() if "info_data" in line]
|
||||
if len(info) != 1:
|
||||
print(f"FAIL: expected one info-block storage symbol, found {len(info)}")
|
||||
sys.exit(1)
|
||||
offset = int(info[0].split()[0], 16) - text_start
|
||||
if not 0 <= offset < 256:
|
||||
print(f"FAIL: info block at image offset {offset:#x}, must sit in the first 256 bytes")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"PI lint: control flow PC-relative, info block at offset {offset:#x}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -4,6 +4,9 @@ if(NOT _res EQUAL 0)
|
||||
endif()
|
||||
# avr-size line 2 is "<text> <data> <bss> <dec> <hex> <file>".
|
||||
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})
|
||||
if(_text GREATER LIMIT)
|
||||
message(FATAL_ERROR ".text is ${_text} bytes, over the ${LIMIT}-byte boot section")
|
||||
|
||||
@@ -7,103 +7,122 @@
|
||||
// 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
|
||||
// what the client read back through the bootloader.
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <array>
|
||||
#include <csignal>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <print>
|
||||
|
||||
#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 "sim_avr.h"
|
||||
#include "sim_elf.h"
|
||||
#include "uart_pty.h"
|
||||
}
|
||||
|
||||
static avr_t *avr;
|
||||
static uart_pty_t uart_pty;
|
||||
static const char *dump_path;
|
||||
namespace {
|
||||
|
||||
static void finish(int sig)
|
||||
avr_t *avr;
|
||||
uart_pty_t uart_pty;
|
||||
const char *dump_path;
|
||||
|
||||
[[noreturn]] void finish(int)
|
||||
{
|
||||
(void)sig;
|
||||
if (dump_path) {
|
||||
FILE *f = fopen(dump_path, "wb");
|
||||
std::FILE *f = std::fopen(dump_path, "wb");
|
||||
if (f) {
|
||||
fwrite(avr->flash, 1, avr->flashend + 1, f);
|
||||
fclose(f);
|
||||
std::fwrite(avr->flash, 1, avr->flashend + 1, f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
uart_pty_stop(&uart_pty);
|
||||
_exit(0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
if (argc < 3) {
|
||||
fprintf(stderr, "usage: %s <tsb.elf> <boot_base_hex> [flash_dump.bin]\n", argv[0]);
|
||||
std::println(stderr, "usage: {} <tsb.elf> <boot_base_hex> [flash_dump.bin]", argv[0]);
|
||||
return 2;
|
||||
}
|
||||
uint32_t boot_base = (uint32_t)strtoul(argv[2], NULL, 0);
|
||||
dump_path = argc >= 4 ? argv[3] : NULL;
|
||||
auto boot_base = static_cast<std::uint32_t>(std::strtoul(argv[2], nullptr, 0));
|
||||
dump_path = argc >= 4 ? argv[3] : nullptr;
|
||||
|
||||
avr = avr_make_mcu_by_name("atmega328p");
|
||||
if (!avr) {
|
||||
fprintf(stderr, "device: no ATmega328P core\n");
|
||||
std::println(stderr, "device: no ATmega328P core");
|
||||
return 1;
|
||||
}
|
||||
avr_init(avr);
|
||||
avr->frequency = 16000000;
|
||||
// Real flash powers up erased (0xff); the app region must look erased
|
||||
// before the bootloader programs it.
|
||||
memset(avr->flash, 0xff, avr->flashend + 1);
|
||||
std::memset(avr->flash, 0xff, avr->flashend + 1);
|
||||
|
||||
// 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
|
||||
// section base ourselves and enter there (BOOTRST is not modelled).
|
||||
elf_firmware_t fw = {0};
|
||||
elf_firmware_t fw{};
|
||||
if (elf_read_firmware(argv[1], &fw) != 0) {
|
||||
fprintf(stderr, "device: cannot read %s\n", argv[1]);
|
||||
std::println(stderr, "device: cannot read {}", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
memcpy(avr->flash + boot_base, fw.flash, fw.flashsize);
|
||||
// An image that runs past flash end cannot execute on hardware, and a
|
||||
// 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->codeend = avr->flashend;
|
||||
|
||||
// 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.
|
||||
// Layout: [appjump lo][appjump hi][timeout][password...][0xff].
|
||||
const char *cfg = getenv("TSB_CONFIG");
|
||||
const char *cfg = std::getenv("TSB_CONFIG");
|
||||
if (cfg) {
|
||||
uint32_t app_end = boot_base - 128; // config page sits directly below the boot code
|
||||
std::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) {
|
||||
char b[3] = {cfg[i], cfg[i + 1], 0};
|
||||
avr->flash[app_end + i / 2] = (uint8_t)strtoul(b, NULL, 16);
|
||||
const std::array pair{cfg[i], cfg[i + 1], '\0'};
|
||||
avr->flash[app_end + i / 2] = static_cast<std::uint8_t>(std::strtoul(pair.data(), nullptr, 16));
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
// in real time, distorting protocol timing. Clear it so the loader runs at
|
||||
// true cycle speed.
|
||||
uint32_t uflags = 0;
|
||||
std::uint32_t uflags = 0;
|
||||
avr_ioctl(avr, AVR_IOCTL_UART_GET_FLAGS('0'), &uflags);
|
||||
uflags &= ~AVR_UART_FLAG_POLL_SLEEP;
|
||||
avr_ioctl(avr, AVR_IOCTL_UART_SET_FLAGS('0'), &uflags);
|
||||
|
||||
uart_pty_init(avr, &uart_pty);
|
||||
uart_pty_connect(&uart_pty, '0');
|
||||
printf("TSB_PTY %s\n", uart_pty.pty.slavename);
|
||||
fflush(stdout);
|
||||
std::println("TSB_PTY {}", uart_pty.pty.slavename);
|
||||
std::fflush(stdout);
|
||||
|
||||
signal(SIGTERM, finish);
|
||||
signal(SIGINT, finish);
|
||||
std::signal(SIGTERM, finish);
|
||||
std::signal(SIGINT, finish);
|
||||
|
||||
for (;;) {
|
||||
int state = avr_run(avr);
|
||||
if (state == cpu_Done || state == cpu_Crashed)
|
||||
if (state == cpu_Done || state == cpu_Crashed) {
|
||||
break;
|
||||
}
|
||||
finish(0);
|
||||
return 0;
|
||||
}
|
||||
finish(0);
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
// Test-fixture application for the pureboot protocol tests: prints "APP" on
|
||||
// the chip's serial link (the same link the loader uses) — the proof that
|
||||
// the loader's hand-over, and on the tinies the host's reset-vector
|
||||
// surgery, actually launched it. Linked normally (crt, vectors at 0); on
|
||||
// the tinies its reset vector is the rjmp the host re-homes.
|
||||
//
|
||||
// On the mega it then listens, and an 'L' makes it jump into the resident
|
||||
// loader — the application-owned loader entry a BOOTRST-unprogrammed mega
|
||||
// relies on (reset always boots the application there), exercised by the
|
||||
// self-update tests. The tinies idle: reset reaches their loader through
|
||||
// the patched vector, so the application owes it nothing.
|
||||
#include <libavr/libavr.hpp>
|
||||
|
||||
using namespace avr::literals;
|
||||
|
||||
namespace {
|
||||
|
||||
consteval avr::hertz_t clock()
|
||||
{
|
||||
if (avr::hw::db.name == "ATtiny13A")
|
||||
return 9.6_MHz;
|
||||
if (avr::hw::db.name == "ATtiny85")
|
||||
return 8_MHz;
|
||||
return 16_MHz;
|
||||
}
|
||||
|
||||
using dev = avr::device<{.clock = clock()}>;
|
||||
|
||||
template <avr::hertz_t C,
|
||||
bool Hardware = avr::hw::db.has_instance("USART0") || avr::hw::db.has_instance("USART")>
|
||||
struct link {
|
||||
using tx_t = avr::uart::usart0<C, {.baud = 115200_Bd, .max_baud_error = 2.5_pct}>;
|
||||
static void tx(char c)
|
||||
{
|
||||
tx_t::write(static_cast<std::uint8_t>(c));
|
||||
}
|
||||
[[noreturn]] static void idle()
|
||||
{
|
||||
// 'L' hands back to the loader at the top slot — 512 bytes, or the
|
||||
// 1 KiB the >64 KiB chips use.
|
||||
constexpr std::uint32_t slot = avr::hw::db.mem.flash_size > 65536 ? 1024 : 512;
|
||||
for (;;)
|
||||
if (tx_t::read_blocking() == 'L')
|
||||
reinterpret_cast<void (*)()>(static_cast<std::uint16_t>((avr::hw::db.mem.flash_size - slot) / 2))();
|
||||
}
|
||||
};
|
||||
|
||||
template <avr::hertz_t C>
|
||||
struct link<C, false> {
|
||||
using tx_t = avr::uart::software_tx<C, avr::pb1, 57600_Bd>;
|
||||
static void tx(char c)
|
||||
{
|
||||
tx_t::write(static_cast<std::uint8_t>(c));
|
||||
}
|
||||
[[noreturn]] static void idle()
|
||||
{
|
||||
while (true) {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
avr::init<typename link<dev::clock>::tx_t>();
|
||||
link<dev::clock>::tx('A');
|
||||
link<dev::clock>::tx('P');
|
||||
link<dev::clock>::tx('P');
|
||||
link<dev::clock>::idle();
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Position-independence acceptance test: the identical pureboot binary,
|
||||
flashed one slot below the resident loader, must serve the complete command
|
||||
set from there. The resident installs it (through-word composed by the host
|
||||
layer), 'J' transfers control, and every command is exercised against the
|
||||
staged copy — the info block must come back byte-identical, the write guard
|
||||
must protect the staged copy's own slot and permit the resident's, and the
|
||||
staged copy must be able to rewrite the resident slot verbatim.
|
||||
|
||||
Usage: pbreloc.py <device_bin> <pureboot_elf> <mcu> <hz> <base_hex> <page>
|
||||
<baud> <tool_py> <workdir>
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def fail(message):
|
||||
print(f"FAIL: {message}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main():
|
||||
device_bin, elf, mcu, hz, base_hex, page, baud, tool, workdir = sys.argv[1:]
|
||||
base, page, baud = int(base_hex, 0), int(page), int(baud)
|
||||
stage = None # derived from the device's own info (slot-sized) below
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(tool)))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import pbsim
|
||||
import pureboot as pb
|
||||
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
objcopy = os.environ.get("PB_OBJCOPY", "avr-objcopy")
|
||||
image_path = os.path.join(workdir, "pureboot.bin")
|
||||
subprocess.run([objcopy, "-O", "binary", elf, image_path], check=True)
|
||||
image = open(image_path, "rb").read()
|
||||
|
||||
device = pbsim.Device(device_bin, elf, mcu, hz, base_hex, page, baud, os.path.join(workdir, "dump.bin"))
|
||||
try:
|
||||
port = pb.Port(device.pty, baud)
|
||||
loader = pb.Loader(port)
|
||||
info = loader.connect(25)
|
||||
if info.base != base:
|
||||
fail(f"info reports base {info.base:#06x}")
|
||||
resident_info = info.raw
|
||||
|
||||
# Install the staging copy exactly as the update flow would.
|
||||
stage = info.stage
|
||||
staged = pb.staging_content(image, info)
|
||||
pb.write_differing(loader, stage, staged)
|
||||
|
||||
# Enter it; from here on, every command runs in the relocated copy.
|
||||
staged_info = loader.enter_copy(stage, 25)
|
||||
if staged_info.raw != resident_info:
|
||||
fail(f"staged info {staged_info.raw.hex()} != resident info {resident_info.hex()}")
|
||||
|
||||
# 'R' from the staged copy already proved itself in the install
|
||||
# verify; 'F' must answer 4 bytes (values are unmodeled in simavr).
|
||||
if len(loader.read_fuses()) != 4:
|
||||
fail("fuse read from the staged copy")
|
||||
|
||||
# EEPROM round-trip through the staged copy.
|
||||
pattern = bytes(range(0x50, 0x60))
|
||||
loader.write_eeprom(0, pattern)
|
||||
if loader.read_eeprom(0, len(pattern)) != pattern:
|
||||
fail("EEPROM round-trip through the staged copy")
|
||||
|
||||
# The guard, both ways: its own slot refused (drained, unchanged),
|
||||
# the resident slot writable.
|
||||
before = loader.read_flash(stage, page)
|
||||
loader.write_page(stage, bytes(page))
|
||||
if loader.read_flash(stage, page) != before:
|
||||
fail("the staged copy's guard let its own slot change")
|
||||
marker = bytes((i * 3) & 0xFF for i in range(page))
|
||||
loader.write_page(base, marker)
|
||||
if loader.read_flash(base, page) != marker:
|
||||
fail("the staged copy could not write the resident slot")
|
||||
|
||||
# Restore the resident image through the staged copy, then 'J' back
|
||||
# into it and prove it lives.
|
||||
resident = image + b"\xff" * (info.slot - len(image))
|
||||
pb.write_differing(loader, base, resident)
|
||||
back_info = loader.enter_copy(base, 25)
|
||||
if back_info.raw != resident_info:
|
||||
fail("the restored resident does not serve its info block")
|
||||
port.close()
|
||||
finally:
|
||||
device.stop()
|
||||
print("pbreloc: the relocated copy serves the full command set")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,61 +0,0 @@
|
||||
"""Shared simavr harness for the pureboot tests: spawn the device runner,
|
||||
hand out its pty, restart it from a flash dump (the power-fail path), and
|
||||
keep its chatter out of undrained pipes."""
|
||||
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
|
||||
|
||||
class Device:
|
||||
def __init__(self, binary, elf, mcu, hz, base_hex, page, baud, dump, reset_hex=None, resume=None):
|
||||
cmd = [binary, elf, mcu, hz, base_hex, str(page), str(baud), dump]
|
||||
if reset_hex is not None or resume is not None:
|
||||
cmd.append(reset_hex if reset_hex is not None else ("0" if not mcu.startswith("atmega") else base_hex))
|
||||
if resume is not None:
|
||||
cmd.append(resume)
|
||||
self.log = open(dump + ".log", "a")
|
||||
self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self.log, text=True)
|
||||
self.dump = dump
|
||||
self.pty = None
|
||||
for _ in range(50):
|
||||
line = self.proc.stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
if line.startswith("PB_PTY"):
|
||||
self.pty = line.split()[1]
|
||||
break
|
||||
if not self.pty:
|
||||
self.stop()
|
||||
raise RuntimeError("device did not report a pty")
|
||||
|
||||
def reset(self):
|
||||
"""The external reset line: SIGUSR1 re-enters at the reset vector."""
|
||||
self.proc.send_signal(signal.SIGUSR1)
|
||||
|
||||
def power_fail(self):
|
||||
"""SIGTERM: the runner dumps its flash and exits — the image a
|
||||
restart resumes from."""
|
||||
self.stop()
|
||||
return self.dump
|
||||
|
||||
def stop(self):
|
||||
self.proc.terminate()
|
||||
try:
|
||||
self.proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
self.log.close()
|
||||
|
||||
|
||||
def run_tool(tool, pty, baud, *args, timeout=180):
|
||||
result = subprocess.run(
|
||||
[os.environ.get("PYTHON", "python3"), tool, "--port", pty, "--baud", str(baud), "--wait", "25", *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
print(result.stdout, end="")
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"tool exited {result.returncode}: {result.stderr.strip()}")
|
||||
return result.stdout
|
||||
181
test/pbtest.py
181
test/pbtest.py
@@ -1,181 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end pureboot protocol test: spawn the simavr device, then drive it
|
||||
with the real host tool (pureboot.py, as a subprocess over the device's pty)
|
||||
through flash + EEPROM + fuse + hand-over scenarios, and cross-check
|
||||
the tool's view against the simulator's ground-truth memory dumps.
|
||||
|
||||
Usage: pbtest.py <device_bin> <pureboot_elf> <mcu> <hz> <base_hex> <page>
|
||||
<baud> <eeprom_size> <app_bin> <tool_py> <workdir>
|
||||
Exits 0 if every scenario passes.
|
||||
"""
|
||||
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def fail(message):
|
||||
print(f"FAIL: {message}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def rjmp_decode(word, at, flash_words):
|
||||
"""Where an rjmp word at word-address `at` lands — deliberately written
|
||||
against the instruction-set definition (12-bit signed offset), not with
|
||||
the host tool's encoder, so an encoding bug cannot verify itself."""
|
||||
if word & 0xF000 != 0xC000:
|
||||
fail(f"word at {at * 2:#06x} is {word:#06x}, not an rjmp")
|
||||
offset = word & 0x0FFF
|
||||
if offset >= 0x800:
|
||||
offset -= 0x1000
|
||||
return (at + 1 + offset) % flash_words
|
||||
|
||||
|
||||
class Device:
|
||||
def __init__(self, binary, elf, mcu, hz, base, page, baud, dump):
|
||||
self.proc = subprocess.Popen(
|
||||
[binary, elf, mcu, hz, base, str(page), str(baud), dump],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
self.dump = dump
|
||||
self.pty = None
|
||||
deadline = time.time() + 5
|
||||
while time.time() < deadline:
|
||||
line = self.proc.stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
if line.startswith("PB_PTY"):
|
||||
self.pty = line.split()[1]
|
||||
break
|
||||
if not self.pty:
|
||||
self.stop()
|
||||
raise RuntimeError("device did not report a pty")
|
||||
|
||||
def stop(self):
|
||||
self.proc.terminate()
|
||||
try:
|
||||
self.proc.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
|
||||
|
||||
def run_tool(tool, pty, baud, *args):
|
||||
result = subprocess.run(
|
||||
[sys.executable, tool, "--port", pty, "--baud", str(baud), "--wait", "20", *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
print(result.stdout, end="")
|
||||
if result.returncode != 0:
|
||||
fail(f"tool exited {result.returncode}: {result.stderr.strip()}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def main():
|
||||
(device_bin, elf, mcu, hz, base_hex, page, baud, eeprom_size, app_bin, tool, workdir) = sys.argv[1:]
|
||||
base, page, baud, eeprom_size = int(base_hex, 0), int(page), int(baud), int(eeprom_size)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(tool)))
|
||||
import pureboot as pb
|
||||
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
ee_image = bytes(range(0xA0, 0xB0))
|
||||
ee_path = os.path.join(workdir, "ee.bin")
|
||||
open(ee_path, "wb").write(ee_image)
|
||||
dump = os.path.join(workdir, "flash_dump.bin")
|
||||
read_flash = os.path.join(workdir, "readback_flash.bin")
|
||||
read_eeprom = os.path.join(workdir, "readback_eeprom.bin")
|
||||
|
||||
# The geometry the host will discover, for computing the expected image:
|
||||
# megas carry a boot section (no vector surgery), the large ones speak
|
||||
# word addresses, and the page byte is the wire's 0-means-256.
|
||||
mega = mcu.startswith("atmega")
|
||||
word_flash = base + 512 > 0x10000
|
||||
wire_base = base // 2 if word_flash else base
|
||||
flags = (0 if mega else 1) | (2 if word_flash else 0)
|
||||
info = pb.Info(
|
||||
bytes([ord("P"), ord("B"), 1, 0, 0, 0, page & 0xFF])
|
||||
+ bytes([wire_base & 0xFF, wire_base >> 8, eeprom_size & 0xFF, eeprom_size >> 8])
|
||||
+ bytes([flags])
|
||||
)
|
||||
|
||||
device = Device(device_bin, elf, mcu, hz, base_hex, page, baud, dump)
|
||||
try:
|
||||
# Session 1: knock from reset, identify, program everything, stay.
|
||||
out = run_tool(tool, device.pty, baud, "--info", "--fuses", "--flash", app_bin,
|
||||
"--eeprom", ee_path, "--stay")
|
||||
for needed in ("device: signature", "fuses:", "verify:", "stays"):
|
||||
if needed not in out:
|
||||
fail(f"session 1 output lacks {needed!r}")
|
||||
|
||||
# Session 2: reconnect into the live session, verify, dump, hand over
|
||||
# is deferred — the pty must be reopened for the APP banner first.
|
||||
out = run_tool(tool, device.pty, baud, "--verify-flash", app_bin, "--verify-eeprom", ee_path,
|
||||
"--read-flash", read_flash, "--read-eeprom", read_eeprom, "--stay")
|
||||
if out.count("verify:") != 2:
|
||||
fail("session 2 did not verify both memories")
|
||||
|
||||
eeprom_back = open(read_eeprom, "rb").read()
|
||||
if eeprom_back[: len(ee_image)] != ee_image:
|
||||
fail("EEPROM read-back mismatch")
|
||||
|
||||
# The expected post-surgery flash, straight from the tool's planner.
|
||||
pages = pb.plan_flash(open(app_bin, "rb").read(), info)
|
||||
flash_back = open(read_flash, "rb").read()
|
||||
for address, data in pages.items():
|
||||
if flash_back[address : address + page] != data:
|
||||
fail(f"flash read-back mismatch in page {address:#06x}")
|
||||
|
||||
# An external reset re-enters through the patched word 0 (tinies; the
|
||||
# runner resets them to address 0 like silicon) or BOOTRST (mega).
|
||||
# The loader must answer a fresh knock, and the 'J' hand-over must
|
||||
# land in the application, which banners on the same link.
|
||||
device.proc.send_signal(signal.SIGUSR1)
|
||||
port = pb.Port(device.pty, baud)
|
||||
try:
|
||||
loader = pb.Loader(port)
|
||||
loader.connect(15)
|
||||
loader.run_application()
|
||||
banner = port.read_exact(3, 5.0)
|
||||
if banner != b"APP":
|
||||
fail(f"application banner was {banner!r}")
|
||||
finally:
|
||||
port.close()
|
||||
finally:
|
||||
device.stop()
|
||||
|
||||
# Ground truth: the simulator's own memories, against the host's view.
|
||||
flash_true = open(dump, "rb").read()
|
||||
if flash_true[:base] != flash_back:
|
||||
fail("host flash read-back differs from the simulator's flash")
|
||||
if flash_true[base] == 0xFF and flash_true[base + 1] == 0xFF:
|
||||
fail("loader region looks erased in the ground-truth dump")
|
||||
|
||||
# The surgery, decoded independently: the patched vector must land on the
|
||||
# loader, the trampoline on the application's own entry (tinies only —
|
||||
# the megas' word 0 stays the application's).
|
||||
if not mega:
|
||||
flash_words = (base + 512) // 2
|
||||
app = open(app_bin, "rb").read()
|
||||
word0 = flash_true[0] | (flash_true[1] << 8)
|
||||
if rjmp_decode(word0, 0, flash_words) != base // 2:
|
||||
fail("patched reset vector does not land on the loader base")
|
||||
trampoline = flash_true[base - 2] | (flash_true[base - 1] << 8)
|
||||
original = app[0] | (app[1] << 8)
|
||||
if rjmp_decode(trampoline, (base - 2) // 2, flash_words) != rjmp_decode(original, 0, flash_words):
|
||||
fail("trampoline does not land on the application's own entry")
|
||||
ee_true_path = dump + ".eeprom"
|
||||
if os.path.exists(ee_true_path):
|
||||
ee_true = open(ee_true_path, "rb").read()
|
||||
if ee_true[: len(ee_image)] != ee_image:
|
||||
fail("ground-truth EEPROM does not match what was programmed")
|
||||
|
||||
print("pbtest: all scenarios pass")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
223
test/pbupdate.py
223
test/pbupdate.py
@@ -1,223 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Self-update end-to-end: an application is flashed, then the loader
|
||||
replaces itself with a re-timed build through the host tool's
|
||||
--update-loader — and the power-fail phases of that update are rehearsed by
|
||||
killing the simulated device mid-write, restarting it from its flash dump,
|
||||
and letting a re-run complete the update.
|
||||
|
||||
The mega runs the BOOTRST-unprogrammed profile (reset boots the application;
|
||||
the fixture application's 'L' jump is the application-owned loader entry),
|
||||
with --assume-fuses standing in for the fuse read simavr cannot model. The
|
||||
tinies reset into a loader at every phase by construction — the t13a because
|
||||
its staging slot carries the reset vector itself, the t85 through the word-0
|
||||
redirect the tool plants around the resident rewrite.
|
||||
|
||||
Usage: pbupdate.py <device_bin> <pureboot_elf> <update_elf> <mcu> <hz>
|
||||
<base_hex> <page> <baud> <app_bin> <tool_py> <workdir>
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def fail(message):
|
||||
print(f"FAIL: {message}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def rjmp_decode(word, at, flash_words):
|
||||
"""Written against the instruction-set definition, not with the tool's
|
||||
encoder, so an encoding bug cannot verify itself."""
|
||||
if word & 0xF000 != 0xC000:
|
||||
fail(f"word at {at * 2:#06x} is {word:#06x}, not an rjmp")
|
||||
offset = word & 0x0FFF
|
||||
if offset >= 0x800:
|
||||
offset -= 0x1000
|
||||
return (at + 1 + offset) % flash_words
|
||||
|
||||
|
||||
class PowerFail(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def assumed_fuses(pb, image):
|
||||
"""Synthetic 'F' bytes for --assume-fuses: the smallest boot section
|
||||
covering both the resident and the staging slot (two slots — what a
|
||||
self-update needs), BOOTRST unprogrammed — the per-chip BOOTSZ ladder
|
||||
and fuse byte come from the tool's own table, keyed by the update
|
||||
image's embedded signature."""
|
||||
info = pb.image_info(image)
|
||||
which, ladder = pb.BOOT_FUSE[bytes(info.signature[1:3])]
|
||||
bits = min((b for b in ladder if ladder[b] * 2 >= 2 * info.slot), key=lambda b: ladder[b])
|
||||
fuses = bytearray((0xFF, 0xFF, 0xFF, 0xFF))
|
||||
fuses[which] = 0xF8 | (bits << 1) | 1
|
||||
return bytes(fuses)
|
||||
|
||||
|
||||
def make_fault_loader(pb, base, slot, kill_region, kill_hits, device):
|
||||
"""A Loader whose write_page kills the device (or, with device=None,
|
||||
just the host) at the Nth write into a region; the sequence
|
||||
stage->resident->stage distinguishes the install from the restore."""
|
||||
|
||||
class FaultLoader(pb.Loader):
|
||||
def __init__(self, port):
|
||||
super().__init__(port)
|
||||
self.seen_resident = False
|
||||
self.hits = 0
|
||||
|
||||
def write_page(self, address, data):
|
||||
if address >= base:
|
||||
phase = "resident"
|
||||
self.seen_resident = True
|
||||
elif address >= base - slot:
|
||||
phase = "stage_restore" if self.seen_resident else "stage"
|
||||
else:
|
||||
phase = "app"
|
||||
if phase == kill_region:
|
||||
self.hits += 1
|
||||
if self.hits == kill_hits:
|
||||
if device is not None:
|
||||
device.power_fail()
|
||||
raise PowerFail(f"{kill_region} write {kill_hits}")
|
||||
super().write_page(address, data)
|
||||
|
||||
return FaultLoader
|
||||
|
||||
|
||||
def main():
|
||||
(device_bin, elf, update_elf, mcu, hz, base_hex, page, baud, app_bin, tool, workdir) = sys.argv[1:]
|
||||
base, page, baud = int(base_hex, 0), int(page), int(baud)
|
||||
mega = mcu.startswith("atmega")
|
||||
slot = 1024 if base + 1024 > 0x10000 and mega else 512 # word-addressed chips use the 1 KiB slot
|
||||
reset_hex = "0" if mega else None # the mega runs BOOTRST-unprogrammed here
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(tool)))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import pbsim
|
||||
import pureboot as pb
|
||||
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
objcopy = os.environ.get("PB_OBJCOPY", "avr-objcopy")
|
||||
images = {}
|
||||
for name, source in (("v0", elf), ("v9", update_elf)):
|
||||
path = os.path.join(workdir, name + ".bin")
|
||||
subprocess.run([objcopy, "-O", "binary", source, path], check=True)
|
||||
images[name] = open(path, "rb").read()
|
||||
if images["v0"] == images["v9"]:
|
||||
fail("the update image is byte-identical to the resident build")
|
||||
dump = os.path.join(workdir, "dump.bin")
|
||||
state = os.path.join(workdir, "update.pbstate")
|
||||
fuses = assumed_fuses(pb, images["v0"]) if mega else None
|
||||
|
||||
def connect(device):
|
||||
port = pb.Port(device.pty, baud)
|
||||
if mega:
|
||||
# Reset boots the application here; its 'L' is the loader entry.
|
||||
# To a live loader the same byte is an ignored command.
|
||||
port.read_available(0.5)
|
||||
port.write(b"L")
|
||||
loader = pb.Loader(port)
|
||||
loader.connect(25)
|
||||
return port, loader
|
||||
|
||||
def padded(image):
|
||||
return image + b"\xff" * (slot - len(image))
|
||||
|
||||
def resident_bytes(loader):
|
||||
return loader.read_flash(base, slot)
|
||||
|
||||
def assert_state(loader, image, app_pages):
|
||||
if resident_bytes(loader) != padded(image):
|
||||
fail("resident loader does not match the update image")
|
||||
stage = base - slot
|
||||
got = loader.read_flash(stage, slot)
|
||||
for address, data in app_pages.items():
|
||||
if stage <= address < base:
|
||||
if got[address - stage : address - stage + page] != data:
|
||||
fail(f"staging region page {address:#06x} not restored")
|
||||
|
||||
device = pbsim.Device(device_bin, elf, mcu, hz, base_hex, page, baud, dump, reset_hex=reset_hex)
|
||||
final = "v0"
|
||||
try:
|
||||
# The application first — its planner output is the restore truth.
|
||||
pbsim.run_tool(tool, device.pty, baud, "--flash", app_bin, "--stay")
|
||||
port, loader = connect(device)
|
||||
app_pages = pb.plan_flash(open(app_bin, "rb").read(), loader.info)
|
||||
port.close()
|
||||
|
||||
# A clean CLI update, resident -> v9.
|
||||
args = ["--update-loader", os.path.join(workdir, "v9.bin"), "--state", state, "--stay"]
|
||||
if mega:
|
||||
args += ["--assume-fuses", fuses.hex()]
|
||||
out = pbsim.run_tool(tool, device.pty, baud, *args)
|
||||
if "loader updated" not in out:
|
||||
fail("update did not report success")
|
||||
if os.path.exists(state):
|
||||
fail("state file survived a completed update")
|
||||
port, loader = connect(device)
|
||||
assert_state(loader, images["v9"], app_pages)
|
||||
loader.run_application()
|
||||
if port.read_exact(3, 5.0) != b"APP":
|
||||
fail("application does not banner after the update")
|
||||
port.close()
|
||||
final = "v9"
|
||||
print("clean update: resident replaced, staging restored, application intact")
|
||||
|
||||
# Power-fail rehearsal: kill mid-phase, restart from the dump,
|
||||
# re-run, and the update must still complete. Each round flips the
|
||||
# direction so the flash is never already at its target. The mega's
|
||||
# mid-resident-rewrite loss is exercised as a host crash instead:
|
||||
# with BOOTRST unprogrammed and the resident mid-erase, a power loss
|
||||
# there has no reset path into the staging copy — the documented
|
||||
# cost of that profile (README).
|
||||
for kill_region, kill_hits, kill_device in (
|
||||
("stage", 2, True),
|
||||
("resident", 1, not mega),
|
||||
("stage_restore", 2, True),
|
||||
):
|
||||
device.reset() # the previous round left the application running
|
||||
port, loader = connect(device)
|
||||
target = "v9" if resident_bytes(loader) == padded(images["v0"]) else "v0"
|
||||
image_path = os.path.join(workdir, target + ".bin")
|
||||
injected = make_fault_loader(pb, base, slot, kill_region, kill_hits, device if kill_device else None)(port)
|
||||
injected.info = loader.info
|
||||
try:
|
||||
pb.op_update_loader(injected, 25, image_path, state, fuses)
|
||||
fail(f"{kill_region}: fault never triggered")
|
||||
except PowerFail as event:
|
||||
print(f"power fail injected: {event}")
|
||||
port.close()
|
||||
if kill_device:
|
||||
device = pbsim.Device(device_bin, elf, mcu, hz, base_hex, page, baud, dump,
|
||||
reset_hex=reset_hex, resume=dump)
|
||||
port, loader = connect(device)
|
||||
pb.op_update_loader(loader, 25, image_path, state, fuses)
|
||||
assert_state(loader, images[target], app_pages)
|
||||
loader.run_application()
|
||||
if port.read_exact(3, 5.0) != b"APP":
|
||||
fail(f"{kill_region}: application lost after the resumed update")
|
||||
port.close()
|
||||
final = target
|
||||
print(f"resumed after {kill_region} loss: update completed, application intact")
|
||||
finally:
|
||||
device.stop()
|
||||
|
||||
# Ground truth: the simulator's own flash against the final state, and
|
||||
# on the tinies an independent decode of the reset routing.
|
||||
flash = open(dump, "rb").read()
|
||||
if flash[base : base + slot] != padded(images[final]):
|
||||
fail("ground-truth resident region does not match the final image")
|
||||
if not mega:
|
||||
flash_words = (base + slot) // 2
|
||||
word0 = flash[0] | (flash[1] << 8)
|
||||
if rjmp_decode(word0, 0, flash_words) != base // 2:
|
||||
fail("ground-truth reset vector does not land on the loader")
|
||||
app = open(app_bin, "rb").read()
|
||||
trampoline = flash[base - 2] | (flash[base - 1] << 8)
|
||||
if rjmp_decode(trampoline, (base - 2) // 2, flash_words) != rjmp_decode(app[0] | (app[1] << 8), 0, flash_words):
|
||||
fail("ground-truth trampoline does not land on the application entry")
|
||||
print("pbupdate: clean update + all power-fail phases recovered")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,390 +0,0 @@
|
||||
// simavr "device" for the pureboot protocol tests, all three chips. Loads
|
||||
// the boot-linked ELF at the loader base, starts execution there (BOOTRST /
|
||||
// the patched vector are not what is under test), and exposes the loader's
|
||||
// serial link as a pty for the real host tool:
|
||||
//
|
||||
// - Megas: the hardware USART through simavr's uart_pty.
|
||||
// - Tinies: an 8N1 bridge between a pty and the GPIO software UART
|
||||
// (drives PB0, the loader's RX; decodes PB1, its TX), timed against the
|
||||
// simulated cycle counter.
|
||||
//
|
||||
// simavr's tiny cores decode the SPM opcode but attach no NVM module — SPM
|
||||
// is a silent no-op (the mega's boot section has one, avr_flash). The
|
||||
// missing module is supplied here: the SPM ioctl reads SPMCSR/Z/r1:r0 and
|
||||
// implements buffer fill, page erase, page write, and CTPB, completing
|
||||
// instantly. RFLB's LPM diversion (fuse readout) stays unmodeled, so the
|
||||
// 'F' command answers with flash bytes — the tests assert transport only.
|
||||
//
|
||||
// On exit (or SIGTERM) the flash and EEPROM are dumped to files for a
|
||||
// ground-truth cross-check against what the host read back.
|
||||
#include <fcntl.h>
|
||||
#include <pty.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "avr_eeprom.h"
|
||||
#include "avr_flash.h"
|
||||
#include "avr_ioport.h"
|
||||
#include "avr_uart.h"
|
||||
#include "sim_avr.h"
|
||||
#include "sim_elf.h"
|
||||
#include "sim_io.h"
|
||||
#include "uart_pty.h"
|
||||
|
||||
static avr_t *avr;
|
||||
static uart_pty_t uart_pty;
|
||||
static int use_uart_pty;
|
||||
static const char *dump_path;
|
||||
static uint32_t reset_pc;
|
||||
static volatile sig_atomic_t reset_requested;
|
||||
|
||||
// simavr 1.6's avr_flash PGERS handler erases spm_pagesize bytes starting at
|
||||
// Z & ~1 instead of the page containing Z (its PGWRT path masks correctly) —
|
||||
// hardware ignores the in-page bits (§26.8.1), so an erase issued with Z
|
||||
// anywhere inside the page wipes half the neighbouring page in simulation
|
||||
// only. Wrap the mega's registered flash ioctl and re-dispatch page erases
|
||||
// with Z forced to the page boundary; everything else passes through.
|
||||
static avr_flash_t *mega_flash;
|
||||
static int (*mega_flash_ioctl)(avr_io_t *io, uint32_t ctl, void *param);
|
||||
|
||||
static int fixed_flash_ioctl(avr_io_t *io, uint32_t ctl, void *param)
|
||||
{
|
||||
if (ctl == AVR_IOCTL_FLASH_SPM && avr_regbit_get(io->avr, mega_flash->pgers)) {
|
||||
uint16_t z = (uint16_t)(io->avr->data[30] | (io->avr->data[31] << 8));
|
||||
uint16_t masked = (uint16_t)(z & ~(mega_flash->spm_pagesize - 1));
|
||||
io->avr->data[30] = (uint8_t)masked;
|
||||
io->avr->data[31] = (uint8_t)(masked >> 8);
|
||||
int result = mega_flash_ioctl(io, ctl, param);
|
||||
io->avr->data[30] = (uint8_t)z;
|
||||
io->avr->data[31] = (uint8_t)(z >> 8);
|
||||
return result;
|
||||
}
|
||||
return mega_flash_ioctl(io, ctl, param);
|
||||
}
|
||||
|
||||
static void fix_mega_flash_erase(void)
|
||||
{
|
||||
for (avr_io_t *io = avr->io_port; io; io = io->next) {
|
||||
if (io->kind && strcmp(io->kind, "flash") == 0) {
|
||||
mega_flash = (avr_flash_t *)io;
|
||||
mega_flash_ioctl = io->ioctl;
|
||||
io->ioctl = fixed_flash_ioctl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
fprintf(stderr, "device: no flash module to fix — SPM page erases may misalign\n");
|
||||
}
|
||||
|
||||
static void request_reset(int sig)
|
||||
{
|
||||
(void)sig;
|
||||
reset_requested = 1;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- tiny NVM ---
|
||||
|
||||
typedef struct {
|
||||
avr_io_t io;
|
||||
uint8_t buffer[128];
|
||||
uint8_t used[128]; // a buffer word loads once until erased — like silicon
|
||||
unsigned page;
|
||||
} tiny_nvm_t;
|
||||
|
||||
static tiny_nvm_t nvm;
|
||||
|
||||
static int nvm_ioctl(avr_io_t *io, uint32_t ctl, void *param)
|
||||
{
|
||||
(void)param;
|
||||
if (ctl != AVR_IOCTL_FLASH_SPM)
|
||||
return -1;
|
||||
tiny_nvm_t *n = (tiny_nvm_t *)io;
|
||||
avr_t *mcu = io->avr;
|
||||
uint8_t command = mcu->data[0x57] & 0x1f; // SPMCSR, both tinies
|
||||
uint16_t z = (uint16_t)(mcu->data[30] | (mcu->data[31] << 8));
|
||||
uint32_t page_base = (uint32_t)(z & ~(n->page - 1)) % (mcu->flashend + 1);
|
||||
if (command == 0x01) { // SPMEN alone: buffer fill from r1:r0
|
||||
unsigned offset = z & (n->page - 1) & ~1u;
|
||||
if (!n->used[offset]) { // first write wins until the buffer clears
|
||||
n->buffer[offset] = mcu->data[0];
|
||||
n->buffer[offset + 1] = mcu->data[1];
|
||||
n->used[offset] = 1;
|
||||
}
|
||||
} else if (command == 0x03) { // PGERS
|
||||
memset(mcu->flash + page_base, 0xff, n->page);
|
||||
} else if (command == 0x05) { // PGWRT: programming only clears bits
|
||||
for (unsigned i = 0; i < n->page; i++)
|
||||
mcu->flash[page_base + i] &= n->buffer[i];
|
||||
memset(n->buffer, 0xff, n->page);
|
||||
memset(n->used, 0, n->page);
|
||||
} else if (command == 0x11) { // CTPB
|
||||
memset(n->buffer, 0xff, n->page);
|
||||
memset(n->used, 0, n->page);
|
||||
}
|
||||
mcu->data[0x57] &= (uint8_t)~0x1f; // the operation completes instantly
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- GPIO bridge ---
|
||||
|
||||
static int pty_master = -1;
|
||||
static avr_irq_t *rx_pin; // the loader's RX (PB0), driven from the pty
|
||||
static avr_cycle_count_t bit_cycles;
|
||||
|
||||
static int tx_level = 1, tx_active, tx_bit;
|
||||
static uint8_t tx_shift;
|
||||
|
||||
static avr_cycle_count_t tx_sample(avr_t *mcu, avr_cycle_count_t when, void *param)
|
||||
{
|
||||
(void)mcu;
|
||||
(void)param;
|
||||
tx_shift = (uint8_t)((tx_shift >> 1) | (tx_level ? 0x80 : 0));
|
||||
if (++tx_bit < 8)
|
||||
return when + bit_cycles;
|
||||
if (write(pty_master, &tx_shift, 1) != 1)
|
||||
fprintf(stderr, "device: pty write lost a byte\n");
|
||||
tx_active = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void tx_hook(avr_irq_t *irq, uint32_t value, void *param)
|
||||
{
|
||||
(void)irq;
|
||||
(void)param;
|
||||
int level = value & 1;
|
||||
if (!tx_active && tx_level == 1 && level == 0) { // start edge
|
||||
tx_active = 1;
|
||||
tx_bit = 0;
|
||||
avr_cycle_timer_register(avr, bit_cycles + bit_cycles / 2, tx_sample, NULL);
|
||||
}
|
||||
tx_level = level;
|
||||
}
|
||||
|
||||
static uint8_t rx_queue[8192];
|
||||
static unsigned rx_head, rx_tail; // ring: head = next to send
|
||||
static int rx_active, rx_bit;
|
||||
static uint8_t rx_byte;
|
||||
|
||||
static void rx_start_next(void);
|
||||
|
||||
static avr_cycle_count_t rx_step(avr_t *mcu, avr_cycle_count_t when, void *param)
|
||||
{
|
||||
(void)mcu;
|
||||
(void)param;
|
||||
if (rx_bit < 8) {
|
||||
avr_raise_irq(rx_pin, (rx_byte >> rx_bit) & 1);
|
||||
rx_bit++;
|
||||
return when + bit_cycles;
|
||||
}
|
||||
if (rx_bit == 8) { // stop bit, plus one idle bit of margin
|
||||
avr_raise_irq(rx_pin, 1);
|
||||
rx_bit++;
|
||||
return when + 2 * bit_cycles;
|
||||
}
|
||||
rx_active = 0;
|
||||
rx_start_next();
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void rx_start_next(void)
|
||||
{
|
||||
if (rx_active || rx_head == rx_tail)
|
||||
return;
|
||||
rx_byte = rx_queue[rx_head];
|
||||
rx_head = (rx_head + 1) % sizeof(rx_queue);
|
||||
rx_active = 1;
|
||||
rx_bit = 0;
|
||||
avr_raise_irq(rx_pin, 0); // start bit
|
||||
avr_cycle_timer_register(avr, bit_cycles, rx_step, NULL);
|
||||
}
|
||||
|
||||
// A reset abandons whatever the bridge was mid-transfer: bytes still queued
|
||||
// for a chip that no longer has the context to receive them meaningfully,
|
||||
// and a decode in progress on a TX line the reset may have already changed.
|
||||
// The pending cycle timers must go with the state: avr_reset drops the TX
|
||||
// output latch, whose falling edge starts a spurious decode before this
|
||||
// runs, and a stale tx_sample would then interleave with the loader's first
|
||||
// real answer through the shared shift state, corrupting it.
|
||||
static void bridge_reset(void)
|
||||
{
|
||||
avr_cycle_timer_cancel(avr, tx_sample, NULL);
|
||||
avr_cycle_timer_cancel(avr, rx_step, NULL);
|
||||
rx_head = rx_tail = 0;
|
||||
rx_active = 0;
|
||||
tx_active = 0;
|
||||
tx_level = 1;
|
||||
avr_raise_irq(rx_pin, 1); // idle line
|
||||
}
|
||||
|
||||
static void poll_pty(void)
|
||||
{
|
||||
uint8_t chunk[256];
|
||||
ssize_t got = read(pty_master, chunk, sizeof(chunk));
|
||||
for (ssize_t i = 0; i < got; i++) {
|
||||
unsigned next = (rx_tail + 1) % sizeof(rx_queue);
|
||||
if (next == rx_head)
|
||||
break; // full: the host will retry on timeout
|
||||
rx_queue[rx_tail] = chunk[i];
|
||||
rx_tail = next;
|
||||
}
|
||||
if (got > 0)
|
||||
rx_start_next();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ main ---
|
||||
|
||||
static void finish(int sig)
|
||||
{
|
||||
(void)sig;
|
||||
if (dump_path) {
|
||||
FILE *f = fopen(dump_path, "wb");
|
||||
if (f) {
|
||||
fwrite(avr->flash, 1, avr->flashend + 1, f);
|
||||
fclose(f);
|
||||
}
|
||||
avr_eeprom_desc_t ee = {.ee = NULL, .offset = 0, .size = 0};
|
||||
if (avr_ioctl(avr, AVR_IOCTL_EEPROM_GET, &ee) == 0 && ee.ee && ee.size) {
|
||||
char path[512];
|
||||
snprintf(path, sizeof(path), "%s.eeprom", dump_path);
|
||||
f = fopen(path, "wb");
|
||||
if (f) {
|
||||
fwrite(ee.ee, 1, ee.size, f);
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (use_uart_pty)
|
||||
uart_pty_stop(&uart_pty);
|
||||
_exit(0);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
if (argc < 8 || argc > 10) {
|
||||
fprintf(stderr,
|
||||
"usage: %s <pureboot.elf> <mcu> <hz> <base_hex> <page> <baud> <flash_dump>"
|
||||
" [reset_hex] [resume_flash]\n"
|
||||
" reset_hex: reset vector (default: base on the mega, 0 on the tinies)\n"
|
||||
" resume_flash: raw full-flash image loaded instead of the ELF — a prior\n"
|
||||
" run's dump, for power-fail resume tests\n",
|
||||
argv[0]);
|
||||
return 2;
|
||||
}
|
||||
const char *mcu_name = argv[2];
|
||||
uint32_t base = (uint32_t)strtoul(argv[4], NULL, 0);
|
||||
unsigned page = (unsigned)atoi(argv[5]);
|
||||
unsigned baud = (unsigned)atoi(argv[6]);
|
||||
dump_path = argv[7];
|
||||
use_uart_pty = strncmp(mcu_name, "atmega", 6) == 0; // every mega links over its hardware USART
|
||||
|
||||
avr = avr_make_mcu_by_name(mcu_name);
|
||||
if (!avr) {
|
||||
fprintf(stderr, "device: no %s core\n", mcu_name);
|
||||
return 1;
|
||||
}
|
||||
avr_init(avr);
|
||||
avr->frequency = (uint32_t)strtoul(argv[3], NULL, 0);
|
||||
memset(avr->flash, 0xff, avr->flashend + 1); // real flash powers up erased
|
||||
|
||||
if (argc > 9) {
|
||||
// Resume: the full flash image of an interrupted prior run.
|
||||
FILE *f = fopen(argv[9], "rb");
|
||||
if (!f || fread(avr->flash, 1, avr->flashend + 1, f) == 0) {
|
||||
fprintf(stderr, "device: cannot read %s\n", argv[9]);
|
||||
return 1;
|
||||
}
|
||||
fclose(f);
|
||||
} else {
|
||||
elf_firmware_t fw = {0};
|
||||
if (elf_read_firmware(argv[1], &fw) != 0) {
|
||||
fprintf(stderr, "device: cannot read %s\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
memcpy(avr->flash + base, fw.flash, fw.flashsize);
|
||||
}
|
||||
// The mega enters the loader in hardware (BOOTRST, not modeled — the
|
||||
// argument picks the modeled fuse's target); the tinies reset to word 0
|
||||
// like silicon — erased flash walks up into the loader, and after the
|
||||
// host's surgery the patched vector routes there.
|
||||
reset_pc = argc > 8 ? (uint32_t)strtoul(argv[8], NULL, 0) : (use_uart_pty ? base : 0);
|
||||
avr->pc = reset_pc;
|
||||
avr->codeend = avr->flashend;
|
||||
|
||||
// Erased EEPROM, as hardware powers up (simavr zeroes it).
|
||||
uint8_t blank[1024];
|
||||
memset(blank, 0xff, sizeof(blank));
|
||||
avr_eeprom_desc_t seed = {.ee = blank, .offset = 0, .size = 0};
|
||||
if (avr_ioctl(avr, AVR_IOCTL_EEPROM_GET, &seed) == 0 && seed.size <= sizeof(blank)) {
|
||||
seed.ee = blank;
|
||||
avr_ioctl(avr, AVR_IOCTL_EEPROM_SET, &seed);
|
||||
}
|
||||
|
||||
if (use_uart_pty) {
|
||||
fix_mega_flash_erase();
|
||||
// POLL_SLEEP paces an idle-polling loader in host real time (a
|
||||
// no-hardware CPU-saving hack); clear it so cycles run free.
|
||||
uint32_t flags = 0;
|
||||
avr_ioctl(avr, AVR_IOCTL_UART_GET_FLAGS('0'), &flags);
|
||||
flags &= ~AVR_UART_FLAG_POLL_SLEEP;
|
||||
avr_ioctl(avr, AVR_IOCTL_UART_SET_FLAGS('0'), &flags);
|
||||
uart_pty_init(avr, &uart_pty);
|
||||
uart_pty_connect(&uart_pty, '0');
|
||||
printf("PB_PTY %s\n", uart_pty.pty.slavename);
|
||||
} else {
|
||||
nvm.page = page;
|
||||
memset(nvm.buffer, 0xff, sizeof(nvm.buffer));
|
||||
nvm.io.kind = "tiny_nvm";
|
||||
nvm.io.ioctl = nvm_ioctl;
|
||||
avr_register_io(avr, &nvm.io);
|
||||
|
||||
bit_cycles = (avr->frequency + baud / 2) / baud; // matches uart.hpp's own rounding exactly
|
||||
rx_pin = avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('B'), 0);
|
||||
avr_irq_register_notify(avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('B'), 1), tx_hook, NULL);
|
||||
avr_raise_irq(rx_pin, 1); // idle line
|
||||
|
||||
int slave;
|
||||
struct termios raw;
|
||||
cfmakeraw(&raw);
|
||||
if (openpty(&pty_master, &slave, NULL, &raw, NULL) != 0) {
|
||||
fprintf(stderr, "device: openpty failed\n");
|
||||
return 1;
|
||||
}
|
||||
fcntl(pty_master, F_SETFL, O_NONBLOCK);
|
||||
printf("PB_PTY %s\n", ttyname(slave));
|
||||
}
|
||||
fflush(stdout);
|
||||
|
||||
signal(SIGTERM, finish);
|
||||
signal(SIGINT, finish);
|
||||
signal(SIGUSR1, request_reset); // an external reset line, for the tests
|
||||
|
||||
long since_poll = 0;
|
||||
for (;;) {
|
||||
int state = avr_run(avr);
|
||||
if (state == cpu_Done || state == cpu_Crashed)
|
||||
break;
|
||||
if (reset_requested) {
|
||||
reset_requested = 0;
|
||||
avr_reset(avr);
|
||||
avr->pc = reset_pc;
|
||||
if (use_uart_pty) { // reset restores the pacing hack; re-clear it
|
||||
uint32_t flags = 0;
|
||||
avr_ioctl(avr, AVR_IOCTL_UART_GET_FLAGS('0'), &flags);
|
||||
flags &= ~AVR_UART_FLAG_POLL_SLEEP;
|
||||
avr_ioctl(avr, AVR_IOCTL_UART_SET_FLAGS('0'), &flags);
|
||||
} else {
|
||||
bridge_reset();
|
||||
}
|
||||
}
|
||||
if (!use_uart_pty && ++since_poll >= 2000) {
|
||||
since_poll = 0;
|
||||
poll_pty();
|
||||
}
|
||||
}
|
||||
finish(0);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host-tool unit tests — the pure planning and policy logic, no simulator:
|
||||
the flash-programming orders and their recovery properties, the reset-vector
|
||||
surgery, the staging-slot composition, the mega boot-fuse decode, and the
|
||||
update preflight's error/warning matrix (fuse combinations simavr cannot
|
||||
model reach it here as synthetic bytes).
|
||||
|
||||
Usage: test_planner.py <tool_py>
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def fail(message):
|
||||
print(f"FAIL: {message}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def expect_error(what, fn, *needles):
|
||||
try:
|
||||
fn()
|
||||
except Exception as error:
|
||||
for needle in needles:
|
||||
if needle not in str(error):
|
||||
fail(f"{what}: error lacks {needle!r}: {error}")
|
||||
return
|
||||
fail(f"{what}: no error raised")
|
||||
|
||||
|
||||
def info_of(pb, base, page, patch, flash, signature=(0x1E, 0x93, 0x0B), word_flash=False):
|
||||
scale = 2 if word_flash else 1
|
||||
wire_base = base // scale
|
||||
flags = (1 if patch else 0) | (2 if word_flash else 0)
|
||||
raw = bytes((0x50, 0x42, 1, *signature, page & 0xFF, wire_base & 0xFF, wire_base >> 8,
|
||||
0, 2, flags))
|
||||
info = pb.Info(raw)
|
||||
assert info.flash_size == flash
|
||||
return info
|
||||
|
||||
|
||||
def rjmp_decode(word, at, flash_words):
|
||||
if word & 0xF000 != 0xC000:
|
||||
fail(f"not an rjmp: {word:#06x}")
|
||||
offset = word & 0x0FFF
|
||||
if offset >= 0x800:
|
||||
offset -= 0x1000
|
||||
return (at + 1 + offset) % flash_words
|
||||
|
||||
|
||||
def main():
|
||||
import os
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(sys.argv[1])))
|
||||
import pureboot as pb
|
||||
|
||||
tiny = info_of(pb, 0x1E00, 64, True, 0x2000)
|
||||
mega = info_of(pb, 0x7E00, 128, False, 0x8000, signature=(0x1E, 0x95, 0x0F))
|
||||
|
||||
# mega_boot: BOOTSZ words and the BOOTRST sense per chip — the fuse byte
|
||||
# index (HIGH everywhere but the m168A's EXTENDED) and the per-family
|
||||
# ladders (Atmel-2486/2466/2503/8271/42719). Synthetic 'F' replies: only
|
||||
# the boot byte carries meaning.
|
||||
cases = (
|
||||
((0x1E, 0x93, 0x07), 0x2000, 3, {0b11: 0x1F00, 0b10: 0x1E00, 0b01: 0x1C00, 0b00: 0x1800}), # m8
|
||||
((0x1E, 0x94, 0x03), 0x4000, 3, {0b11: 0x3F00, 0b10: 0x3E00, 0b01: 0x3C00, 0b00: 0x3800}), # m16
|
||||
((0x1E, 0x95, 0x02), 0x8000, 3, {0b11: 0x7E00, 0b10: 0x7C00, 0b01: 0x7800, 0b00: 0x7000}), # m32
|
||||
((0x1E, 0x94, 0x06), 0x4000, 2, {0b11: 0x3F00, 0b10: 0x3E00, 0b01: 0x3C00, 0b00: 0x3800}), # m168A
|
||||
((0x1E, 0x95, 0x0F), 0x8000, 3, {0b11: 0x7E00, 0b10: 0x7C00, 0b01: 0x7800, 0b00: 0x7000}), # m328P
|
||||
((0x1E, 0x97, 0x05), 0x20000, 3, {0b11: 0x1FC00, 0b10: 0x1F800, 0b01: 0x1F000, 0b00: 0x1E000}), # 1284P
|
||||
)
|
||||
for signature, flash, which, ladder in cases:
|
||||
# Word-addressed chips carry the 1 KiB slot (their smallest boot sector).
|
||||
slot = 1024 if flash > 0x10000 else 512
|
||||
chip = info_of(pb, flash - slot, 128 if flash < 0x20000 else 0, False, flash,
|
||||
signature=signature, word_flash=flash > 0x10000)
|
||||
for bits, start in ladder.items():
|
||||
fuses = bytearray((0xFF, 0xFF, 0xFF, 0xFF))
|
||||
fuses[which] = (0xF8 | (bits << 1)) & ~1
|
||||
prog, at = pb.mega_boot(chip, bytes(fuses))
|
||||
if not prog or at != start:
|
||||
fail(f"mega_boot {signature[1]:02x}{signature[2]:02x} BOOTSZ={bits:02b} programmed: {prog} {at:#07x}")
|
||||
fuses[which] |= 1
|
||||
prog, at = pb.mega_boot(chip, bytes(fuses))
|
||||
if prog or at != start:
|
||||
fail(f"mega_boot {signature[1]:02x}{signature[2]:02b} unprogrammed: {prog} {at:#07x}")
|
||||
|
||||
# Word-addressed info decode: the 1284P's base/page ride the wire scaled,
|
||||
# and its slot is 1 KiB.
|
||||
big = info_of(pb, 0x1FC00, 0, False, 0x20000, signature=(0x1E, 0x97, 0x05), word_flash=True)
|
||||
if big.page != 256 or big.base != 0x1FC00 or big.stage != 0x1F800 or big.slot != 1024:
|
||||
fail(f"word-addressed info decode: page {big.page}, base {big.base:#x}, stage {big.stage:#x}")
|
||||
|
||||
# Surgery: word 0 lands on the loader, the trampoline on the original
|
||||
# entry — checked with an independent decoder.
|
||||
app = bytes((0xC0 | 0x00, 0xC0)) + bytes((0x12,)) * 300 # rjmp .+0x00C0... entry word 0xC0C0
|
||||
entry = rjmp_decode(app[0] | (app[1] << 8), 0, tiny.flash_size // 2)
|
||||
pages = pb.plan_flash(app, tiny)
|
||||
word0 = pages[0][0] | (pages[0][1] << 8)
|
||||
if rjmp_decode(word0, 0, tiny.flash_size // 2) != tiny.base // 2:
|
||||
fail("surgery: patched word 0 misses the loader")
|
||||
tp = pages[tiny.base - 64]
|
||||
tramp = tp[62] | (tp[63] << 8)
|
||||
if rjmp_decode(tramp, (tiny.base - 2) // 2, tiny.flash_size // 2) != entry:
|
||||
fail("surgery: trampoline misses the original entry")
|
||||
expect_error("non-rjmp vector", lambda: pb.plan_flash(bytes((0x0C, 0x94)) + app[2:], tiny), "not an rjmp")
|
||||
looped = bytearray(app)
|
||||
word = pb.rjmp_to(0, tiny.base // 2, tiny.flash_size // 2)
|
||||
looped[0], looped[1] = word & 0xFF, word >> 8
|
||||
expect_error("read-back image", lambda: pb.plan_flash(bytes(looped), tiny), "read-back")
|
||||
expect_error("oversize image", lambda: pb.plan_flash(bytes(0x1DFF), tiny), "application flash ends")
|
||||
|
||||
# Ordering: patched vector puts page 0 first and the trampoline second;
|
||||
# a boot section puts page 0 last. Blank pages drop only when erased.
|
||||
order = pb.covered(pages, tiny, skip_blank=False)
|
||||
if order[0] != 0 or order[1] != tiny.base - 64:
|
||||
fail(f"tiny order starts {order[:2]}, want page 0 then trampoline page")
|
||||
if sorted(order[2:]) != order[2:]:
|
||||
fail("tiny order tail not ascending")
|
||||
mega_pages = pb.plan_flash(bytes((0xFF,)) * 600, mega)
|
||||
morder = pb.covered(mega_pages, mega, skip_blank=False)
|
||||
if morder[-1] != 0 or sorted(morder[:-1]) != morder[:-1]:
|
||||
fail(f"mega order {morder}, want ascending with page 0 last")
|
||||
blanky = {0: pages[0], 64: bytes((0xFF,)) * 64, 128: pages[128], tiny.base - 64: tp}
|
||||
slim = pb.covered(blanky, tiny, skip_blank=True)
|
||||
if 64 in slim or 0 not in slim or tiny.base - 64 not in slim:
|
||||
fail(f"skip_blank order wrong: {slim}")
|
||||
|
||||
# Staging content: the identical image plus the through-word on a
|
||||
# patched-vector chip; hard size clamps either way.
|
||||
image = bytes(range(256)) * 2 # 512 B — too big for a tiny slot
|
||||
expect_error("tiny staging size", lambda: pb.staging_content(image, tiny), "510")
|
||||
staged = pb.staging_content(image[:508], tiny)
|
||||
through = staged[510] | (staged[511] << 8)
|
||||
if rjmp_decode(through, (tiny.base - 2) // 2, tiny.flash_size // 2) != tiny.base // 2:
|
||||
fail("through-word misses the resident base")
|
||||
if pb.staging_content(image, mega) != image:
|
||||
fail("mega staging content should be the bare image")
|
||||
expect_error("mega staging size", lambda: pb.staging_content(image + b"!", mega), "512")
|
||||
|
||||
# The embedded info block: found in a synthetic binary, absent in noise.
|
||||
binary = bytes((0xAA,)) * 10 + tiny.raw + bytes((0xBB,)) * 10
|
||||
found = pb.image_info(binary)
|
||||
if found is None or found.raw != tiny.raw:
|
||||
fail("image_info misses the embedded block")
|
||||
if pb.image_info(bytes((0xAA,)) * 40) is not None:
|
||||
fail("image_info invents a block")
|
||||
|
||||
# Update preflight: the full fuse matrix, plus target mismatch.
|
||||
other = info_of(pb, 0x1E00, 32, True, 0x2000)
|
||||
expect_error("wrong-target image", lambda: pb.update_preflight(binary, other, None), "another target")
|
||||
expect_error("mega needs fuses", lambda: pb.update_preflight(bytes((0xAA,)) * 8 + mega.raw, mega, None),
|
||||
"--assume-fuses")
|
||||
mega_image = bytes((0xAA,)) * 8 + mega.raw
|
||||
|
||||
def fuses(high):
|
||||
return bytes((0xFF, 0xFF, 0xFF, high))
|
||||
|
||||
expect_error("BOOTSZ 512 B", lambda: pb.update_preflight(mega_image, mega, fuses(0xFE)),
|
||||
"cannot self-update", "BOOTSZ")
|
||||
notes = pb.update_preflight(mega_image, mega, fuses(0xFD)) # 1 KB, BOOTRST unprogrammed
|
||||
if not any("BOOTRST unprogrammed" in n for n in notes):
|
||||
fail(f"1K/unprogrammed notes: {notes}")
|
||||
notes = pb.update_preflight(mega_image, mega, fuses(0xFC)) # 1 KB, BOOTRST programmed
|
||||
if not any("staging slot" in n for n in notes):
|
||||
fail(f"1K/programmed notes: {notes}")
|
||||
notes = pb.update_preflight(mega_image, mega, fuses(0xFA)) # 2 KB, BOOTRST programmed
|
||||
if not any("application flash" in n for n in notes):
|
||||
fail(f"2K/programmed notes: {notes}")
|
||||
if pb.update_preflight(bytes((0xAA,)) * 8 + tiny.raw, tiny, None) != []:
|
||||
fail("tiny preflight should pass without fuses")
|
||||
|
||||
# The walk-region refusal: BOOTRST aimed below the loader plus app data
|
||||
# in the walk span errors without --force; erased spans and unprogrammed
|
||||
# BOOTRST pass.
|
||||
deep = {0x7800: bytes((1,)) * 128}
|
||||
expect_error("walk region", lambda: pb.check_walk_region(deep, mega, fuses(0xFA), False), "--force")
|
||||
pb.check_walk_region(deep, mega, fuses(0xFA), True)
|
||||
pb.check_walk_region(deep, mega, fuses(0xFB), False) # BOOTRST unprogrammed
|
||||
pb.check_walk_region({0x7800: bytes((0xFF,)) * 128}, mega, fuses(0xFA), False)
|
||||
pb.check_walk_region(deep, mega, None, False) # fuses unknown: no check
|
||||
|
||||
print("test_planner: all planner and policy checks pass")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -144,7 +144,7 @@ class Host:
|
||||
self._expect(CONFIRM, "C end")
|
||||
return echo
|
||||
|
||||
# Activation when the config page carries a password: 3×'@' then the
|
||||
# Activation when the config page carries a password: 3x'@' then the
|
||||
# password bytes, then the info block + mainloop '!'.
|
||||
def activate_password(self, password):
|
||||
self.s.reset_input_buffer()
|
||||
@@ -167,6 +167,20 @@ class Host:
|
||||
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):
|
||||
if not cond:
|
||||
raise AssertionError(msg)
|
||||
@@ -181,7 +195,7 @@ PW_BYTES = bytes([0x50, 0x57])
|
||||
|
||||
def scenario_roundtrip(host):
|
||||
"""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()
|
||||
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()})")
|
||||
@@ -219,6 +233,15 @@ def scenario_emergency(host):
|
||||
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():
|
||||
binary, elf, boot_base = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
failures = []
|
||||
@@ -229,6 +252,7 @@ def main():
|
||||
("round-trip", None, scenario_roundtrip),
|
||||
("password activation", PW_CONFIG, scenario_password),
|
||||
("emergency erase", PW_CONFIG, scenario_emergency),
|
||||
("wrong password", PW_CONFIG, scenario_wrong_password),
|
||||
]
|
||||
for name, config, fn in groups:
|
||||
print(f"--- {name} ---")
|
||||
|
||||
60
tools/check.sh
Executable file
60
tools/check.sh
Executable file
@@ -0,0 +1,60 @@
|
||||
#!/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"
|
||||
90
tools/make_presets.py
Executable file
90
tools/make_presets.py
Executable file
@@ -0,0 +1,90 @@
|
||||
#!/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())
|
||||
135
tsb/tsb_asm.cpp
135
tsb/tsb_asm.cpp
@@ -1,14 +1,15 @@
|
||||
// TinySafeBoot on libavr — tier 3: full feature parity in the 512-byte boot
|
||||
// TinySafeBoot on libavr - tier 3: full feature parity in the 512-byte boot
|
||||
// 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,
|
||||
// emergency erase, and config/flash/EEPROM read-write — at 510 bytes in the
|
||||
// 512-byte BOOTSZ=11 section the hand-written oracle occupies (500 B). This tier used to be one
|
||||
// monolithic inline-asm routine; it is now the tricks tier's C++ (same
|
||||
// register protocol, same structure — see tsb_tricks.cpp, including the
|
||||
// global-register miscompile rules) with exactly two routines kept in
|
||||
// assembly, the two whose remaining cost *is* the calling convention:
|
||||
// emergency erase, and config/flash/EEPROM read-write - inside the 512-byte
|
||||
// BOOTSZ=11 section the hand-written oracle occupies (oracle/README.md holds
|
||||
// what each tier measures, in one table rather than four). The
|
||||
// body is the tricks tier's C++ (same register protocol, same structure - see
|
||||
// tsb_tricks.cpp, including the global-register miscompile rules) with exactly
|
||||
// two routines kept in assembly, the two whose remaining cost *is* the calling
|
||||
// convention:
|
||||
//
|
||||
// rx the bounded receive: C++ must re-floor the timeout window on every
|
||||
// call (the global-register-store miscompile) and split it across
|
||||
@@ -16,12 +17,12 @@
|
||||
// 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
|
||||
// (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,
|
||||
// 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
|
||||
// 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.
|
||||
//
|
||||
@@ -41,10 +42,16 @@ namespace hw = avr::hw;
|
||||
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.
|
||||
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 request = '?';
|
||||
constexpr std::uint8_t knock = '@';
|
||||
@@ -57,28 +64,34 @@ 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).
|
||||
constexpr std::uint8_t act_min = 16;
|
||||
// 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>((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::detail::solve_baud(16_MHz, 115200_Bd);
|
||||
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
|
||||
[[gnu::progmem]] constexpr std::uint8_t info[16] = {
|
||||
[[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
|
||||
0x1E, 0x95, 0x0F, // ATmega328P signature
|
||||
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,
|
||||
eeprom_end & 0xFF, eeprom_end >> 8,
|
||||
0xAA, 0xAA,
|
||||
};
|
||||
});
|
||||
// clang-format on
|
||||
|
||||
register std::uint16_t g_addr asm("r28");
|
||||
@@ -94,7 +107,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
// Bounded byte receive (asm 1 of 2): release the one-wire line on a direction
|
||||
// change, poll RXC0 under the oracle's nested X-register countdown seeded from
|
||||
// g_window (floored against lockout), byte or 0-on-silence in r24. Z survives
|
||||
// — the property the store's word loop rides on.
|
||||
// - the property the store's word loop rides on.
|
||||
[[gnu::noinline, gnu::noclone]] std::uint8_t rx()
|
||||
{
|
||||
std::uint8_t byte;
|
||||
@@ -115,7 +128,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
" brne 3b \n\t"
|
||||
" sbiw r26, 1 \n\t"
|
||||
" brcc 2b \n\t"
|
||||
" clr %[b] \n\t" // silence → 0, which no compare accepts
|
||||
" clr %[b] \n\t" // silence -> 0, which no compare accepts
|
||||
" rjmp 5f \n\t"
|
||||
"4: lds %[b], %[udr0] \n\t"
|
||||
"5: \n\t"
|
||||
@@ -129,14 +142,13 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
// One-wire transmit: take the line (TXEN0 alone) on a direction change with a
|
||||
// turn-around guard, put the byte out, hold the line until the whole frame is
|
||||
// out (TXC0, not UDRE0), W1C TXC0 by storing the sampled status back (keeps
|
||||
// U2X0). Plain C++ — it compiles *smaller* than the oracle's routine.
|
||||
// U2X0). Plain C++ - it compiles *smaller* than the oracle's routine.
|
||||
[[gnu::noinline, gnu::noclone]] void tx(std::uint8_t byte)
|
||||
{
|
||||
if (g_receiving) {
|
||||
g_receiving = 0;
|
||||
hw::ucsr0b::write(hw::ucsr0b::txen0(1));
|
||||
for (std::uint8_t guard = 46; guard; --guard)
|
||||
;
|
||||
avr::delay::cycles<guard_cycles>();
|
||||
}
|
||||
hw::udr0::write(byte);
|
||||
std::uint8_t status;
|
||||
@@ -153,7 +165,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
return rx();
|
||||
}
|
||||
|
||||
// One flash byte ← [g_addr++] (the advance right before ret — the
|
||||
// One flash byte <- [g_addr++] (the advance right before ret - the
|
||||
// global-register rule, see tsb_tricks.cpp).
|
||||
[[gnu::noinline, gnu::noclone]] std::uint8_t sflash()
|
||||
{
|
||||
@@ -162,18 +174,18 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
return byte;
|
||||
}
|
||||
|
||||
// One EEPROM byte ← [g_addr++].
|
||||
// One EEPROM byte <- [g_addr++].
|
||||
[[gnu::noinline, gnu::noclone]] std::uint8_t eerd()
|
||||
{
|
||||
std::uint8_t byte = ee::read(g_addr);
|
||||
std::uint8_t byte = ee::read<no_spm>(g_addr);
|
||||
++g_addr;
|
||||
return byte;
|
||||
}
|
||||
|
||||
// One EEPROM byte → [g_addr++].
|
||||
// One EEPROM byte -> [g_addr++].
|
||||
[[gnu::noinline, gnu::noclone]] void eewr(std::uint8_t byte)
|
||||
{
|
||||
ee::write<off>(g_addr, byte);
|
||||
ee::write<off, no_spm>(g_addr, byte);
|
||||
++g_addr;
|
||||
}
|
||||
|
||||
@@ -185,7 +197,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
} while (--g_cnt);
|
||||
}
|
||||
|
||||
// Wait out a running SPM op, then re-open the RWW section — after every page
|
||||
// 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, gnu::noclone]] void settle()
|
||||
{
|
||||
@@ -201,12 +213,12 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
tsb_app();
|
||||
}
|
||||
|
||||
// Step g_addr one page down and erase that page (the decrement lives here —
|
||||
// Step g_addr one page down and erase that page (the decrement lives here -
|
||||
// the global-register rule).
|
||||
[[gnu::noinline, gnu::noclone]] void erase_below()
|
||||
{
|
||||
g_addr -= page;
|
||||
spm::erase_page<off>(g_addr);
|
||||
spm::command<off>(spm::op::erase, g_addr);
|
||||
settle();
|
||||
}
|
||||
|
||||
@@ -221,7 +233,7 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
}
|
||||
|
||||
// Stream one host page into the erased flash page at g_addr (asm 2 of 2): the
|
||||
// word pair stages in r0:r1 straight from rx (whose register set is known —
|
||||
// word pair stages in r0:r1 straight from rx (whose register set is known -
|
||||
// the cross-call liveness C++ cannot express), Z walks the page and PGWRT
|
||||
// programs it. g_addr is left at the next page base.
|
||||
[[gnu::noinline, gnu::noclone]] void store_flash()
|
||||
@@ -256,14 +268,15 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
{
|
||||
// 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())
|
||||
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
|
||||
// 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::reg<"UBRR0">::write(static_cast<std::uint8_t>(baud.ubrr));
|
||||
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
|
||||
@@ -271,13 +284,15 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
// same reason.
|
||||
g_receiving = 0;
|
||||
|
||||
// Activation: 3×'@', 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.
|
||||
// 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)
|
||||
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
|
||||
@@ -291,17 +306,19 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
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[0]);
|
||||
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)
|
||||
if (mask == 0) {
|
||||
continue;
|
||||
if (rcnf() != confirm || rcnf() != confirm)
|
||||
}
|
||||
if (rcnf() != confirm || rcnf() != confirm) {
|
||||
appjump();
|
||||
}
|
||||
erase_application(); // leaves g_addr = 0 for the EEPROM walk
|
||||
do {
|
||||
eewr(0xff);
|
||||
@@ -310,9 +327,10 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
erase_below();
|
||||
break;
|
||||
}
|
||||
if (got != expected)
|
||||
if (got != expected) {
|
||||
mask = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
tx(confirm); // Mainloop ready
|
||||
@@ -320,23 +338,27 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
switch (rx()) {
|
||||
case 'f': // read application flash, one page per host '!'
|
||||
for (;;) {
|
||||
if (rx() != confirm)
|
||||
if (rx() != confirm) {
|
||||
break;
|
||||
}
|
||||
g_cnt = page;
|
||||
sendf();
|
||||
if (g_addr >= app_end)
|
||||
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)
|
||||
while (rcnf() == confirm) {
|
||||
store_flash();
|
||||
}
|
||||
break;
|
||||
case 'e': // read EEPROM, one page per host '!', until the host stops
|
||||
for (;;) {
|
||||
if (rx() != confirm)
|
||||
if (rx() != confirm) {
|
||||
break;
|
||||
}
|
||||
g_cnt = page;
|
||||
do {
|
||||
tx(eerd());
|
||||
@@ -358,8 +380,9 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
sendf();
|
||||
break;
|
||||
case 'C': // replace the config page, then echo it back to verify
|
||||
if (rcnf() != confirm)
|
||||
if (rcnf() != confirm) {
|
||||
break;
|
||||
}
|
||||
g_addr = app_end + page;
|
||||
erase_below(); // leaves g_addr = app_end, the store target
|
||||
store_flash();
|
||||
@@ -373,14 +396,6 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
} // namespace
|
||||
} // namespace tsb
|
||||
|
||||
// Reset lands here: BOOTRST vectors to the boot section base and .vectors is
|
||||
// laid first, so this is the first instruction executed. No crt ran, so set
|
||||
// the stack pointer before anything is called.
|
||||
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
|
||||
{
|
||||
SP = RAMEND;
|
||||
// The one line of crt this loader needs: compiled code assumes
|
||||
// __zero_reg__ (r1) is 0, and power-on registers are undefined.
|
||||
asm volatile("clr __zero_reg__");
|
||||
tsb::run();
|
||||
}
|
||||
// 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>;
|
||||
|
||||
329
tsb/tsb_policy.cpp
Normal file
329
tsb/tsb_policy.cpp
Normal file
@@ -0,0 +1,329 @@
|
||||
// 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>;
|
||||
149
tsb/tsb_pure.cpp
149
tsb/tsb_pure.cpp
@@ -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
|
||||
// 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,
|
||||
// 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.
|
||||
// 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
|
||||
@@ -20,16 +20,29 @@ 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.
|
||||
using serial_t = dev::uart0<{.baud = 115200_Bd, .max_baud_error = 3_pct, .half_duplex = true}>;
|
||||
// 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
|
||||
// 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 = '?';
|
||||
@@ -50,26 +63,48 @@ constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20;
|
||||
// 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).
|
||||
// clang-format off
|
||||
inline constexpr std::array<std::uint8_t, 16> info_data = {
|
||||
inline constexpr auto info_data = std::to_array<std::uint8_t>({
|
||||
'T', 'S', 'B',
|
||||
build_date & 0xFF, build_date >> 8,
|
||||
0xF3, // status byte (native-UART fixed-baud lineage)
|
||||
0x1E, 0x95, 0x0F, // ATmega328P signature
|
||||
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
|
||||
using info = avr::flash_table<info_data>;
|
||||
|
||||
// Blocking byte read/write over the one-wire line: read() releases the line to
|
||||
// the receiver, write() takes it and holds it until the frame is out.
|
||||
// The lockout-proof floor for the receive window: the oracle's F_CPU/1MHz, so
|
||||
// it follows the clock rather than restating it.
|
||||
constexpr auto act_min = static_cast<std::uint8_t>(dev::clock.hz / 1'000'000);
|
||||
|
||||
// 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;
|
||||
|
||||
// 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()
|
||||
{
|
||||
return serial.read_blocking();
|
||||
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;
|
||||
}
|
||||
|
||||
// write() takes the line and holds it until the frame is out.
|
||||
void tx(std::uint8_t byte)
|
||||
{
|
||||
serial.write(byte);
|
||||
@@ -83,14 +118,16 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
// Stream `count` bytes to the host, from flash (LPM) or from EEPROM.
|
||||
void send_flash(std::uint16_t addr, std::uint8_t count)
|
||||
{
|
||||
while (count--)
|
||||
while (count--) {
|
||||
tx(avr::flash_load(flash_ptr(addr++)));
|
||||
}
|
||||
}
|
||||
|
||||
void send_eeprom(std::uint16_t addr, std::uint8_t count)
|
||||
{
|
||||
while (count--)
|
||||
tx(ee::read(addr++));
|
||||
while (count--) {
|
||||
tx(ee::read<no_spm>(addr++));
|
||||
}
|
||||
}
|
||||
|
||||
// Prompt the host with '?' and report whether it answered '!'.
|
||||
@@ -101,32 +138,33 @@ bool request_confirm()
|
||||
}
|
||||
|
||||
// Stream one page from the host straight into the already-erased flash page at
|
||||
// `addr`, filling the SPM word buffer low byte then high — no SRAM staging, so
|
||||
// `addr`, filling the SPM word buffer low byte then high - no SRAM staging, so
|
||||
// receiving and programming are the same loop.
|
||||
void store_flash_page(std::uint16_t addr)
|
||||
{
|
||||
const auto open = spm::page::begin<spm::from::boot_section, off>(addr);
|
||||
for (std::uint16_t i = 0; i < page; i += 2) {
|
||||
std::uint8_t lo = rx();
|
||||
std::uint8_t hi = rx();
|
||||
spm::fill<off>(addr + i, static_cast<std::uint16_t>(lo | (hi << 8)));
|
||||
spm::fill<off>(open, addr + i, static_cast<std::uint16_t>(lo | (hi << 8)));
|
||||
}
|
||||
spm::write_page<off>(addr);
|
||||
spm::wait();
|
||||
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.
|
||||
void store_eeprom_page(std::uint16_t addr)
|
||||
{
|
||||
for (std::uint16_t i = 0; i < page; ++i)
|
||||
ee::write<off>(addr + i, rx());
|
||||
for (std::uint16_t i = 0; i < page; ++i) {
|
||||
ee::write<off, no_spm>(addr + i, rx());
|
||||
}
|
||||
}
|
||||
|
||||
// Erase one flash page and wait it out — the erase step shared by the whole-app
|
||||
// erase, the config-page rewrite and the emergency wipe.
|
||||
// Erase one flash page, waited out by the blocking spelling - the erase step
|
||||
// shared by the whole-app erase, the config-page rewrite and the emergency
|
||||
// wipe.
|
||||
void erase_page(std::uint16_t addr)
|
||||
{
|
||||
spm::erase_page<off>(addr);
|
||||
spm::wait();
|
||||
spm::erase_page<spm::from::boot_section, off>(addr);
|
||||
}
|
||||
|
||||
// Erase the whole application, one page at a time, top-down as the reference
|
||||
@@ -157,8 +195,9 @@ extern "C" [[noreturn]] void tsb_app();
|
||||
void read_flash()
|
||||
{
|
||||
for (std::uint16_t a = 0; a < app_end; a += page) {
|
||||
if (rx() != confirm)
|
||||
if (rx() != confirm) {
|
||||
return;
|
||||
}
|
||||
send_flash(a, page);
|
||||
}
|
||||
}
|
||||
@@ -167,8 +206,9 @@ void read_flash()
|
||||
void read_eeprom()
|
||||
{
|
||||
for (std::uint16_t a = 0;; a += page) {
|
||||
if (rx() != confirm)
|
||||
if (rx() != confirm) {
|
||||
return;
|
||||
}
|
||||
send_eeprom(a, page);
|
||||
}
|
||||
}
|
||||
@@ -178,22 +218,25 @@ void read_eeprom()
|
||||
void write_flash()
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// 'E': take pages the host offers behind '?' into 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);
|
||||
}
|
||||
}
|
||||
|
||||
// 'C': replace the config page, then echo it back for the host to verify.
|
||||
void write_config()
|
||||
{
|
||||
if (!request_confirm())
|
||||
if (!request_confirm()) {
|
||||
return;
|
||||
}
|
||||
erase_page(app_end);
|
||||
store_flash_page(app_end);
|
||||
spm::rww_enable<off>();
|
||||
@@ -206,8 +249,9 @@ void write_config()
|
||||
void emergency_erase()
|
||||
{
|
||||
erase_application();
|
||||
for (std::uint16_t a = 0; a <= eeprom_end; ++a)
|
||||
ee::write<off>(a, 0xff);
|
||||
for (std::uint16_t a = 0; a <= eeprom_end; ++a) {
|
||||
ee::write<off, no_spm>(a, 0xff);
|
||||
}
|
||||
erase_page(app_end);
|
||||
spm::rww_enable<off>();
|
||||
}
|
||||
@@ -222,45 +266,54 @@ gate password_gate()
|
||||
{
|
||||
for (const std::uint8_t *pw = flash_ptr(app_end + 3);; ++pw) {
|
||||
std::uint8_t expected = avr::flash_load(pw);
|
||||
if (expected == 0xff)
|
||||
if (expected == 0xff) {
|
||||
return gate::pass;
|
||||
}
|
||||
std::uint8_t got = rx();
|
||||
if (got == 0)
|
||||
if (got == 0) {
|
||||
return gate::emergency;
|
||||
if (got != expected)
|
||||
for (;;)
|
||||
}
|
||||
if (got != expected) {
|
||||
for (;;) {
|
||||
rx();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[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())
|
||||
if (avr::hw::mcusr::wdrf.test()) {
|
||||
appjump();
|
||||
}
|
||||
|
||||
avr::init<serial_t>();
|
||||
|
||||
// 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
|
||||
// loader out). An idle port times out and boots the application.
|
||||
__uint24 idle = static_cast<__uint24>(avr::flash_load(flash_ptr(app_end + 2)) | 16) << 16;
|
||||
// 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
|
||||
// window then bounds every receive of the session.
|
||||
window = avr::flash_load(flash_ptr(app_end + 2)) | act_min;
|
||||
__uint24 idle = static_cast<__uint24>(window) << 16;
|
||||
std::uint8_t knocks = 0;
|
||||
while (knocks < 3) {
|
||||
if (auto byte = serial.read())
|
||||
if (auto byte = serial.read()) {
|
||||
knocks = *byte == knock ? knocks + 1 : 0;
|
||||
else if (--idle == 0)
|
||||
} else if (--idle == 0) {
|
||||
appjump();
|
||||
}
|
||||
}
|
||||
|
||||
switch (password_gate()) {
|
||||
case gate::pass:
|
||||
send_flash(reinterpret_cast<std::uint16_t>(info::storage.data()), info::size());
|
||||
break;
|
||||
case gate::emergency:
|
||||
if (!request_confirm() || !request_confirm())
|
||||
if (!request_confirm() || !request_confirm()) {
|
||||
appjump();
|
||||
}
|
||||
emergency_erase();
|
||||
break;
|
||||
}
|
||||
@@ -295,14 +348,6 @@ gate password_gate()
|
||||
} // namespace
|
||||
} // namespace tsb
|
||||
|
||||
// Reset lands here: BOOTRST vectors to the boot section base and .vectors is
|
||||
// laid first, so this is the first instruction executed. No crt ran, so set the
|
||||
// stack pointer before anything is called.
|
||||
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
|
||||
{
|
||||
SP = RAMEND;
|
||||
// The one line of crt this loader needs: compiled code assumes
|
||||
// __zero_reg__ (r1) is 0, and power-on registers are undefined.
|
||||
asm volatile("clr __zero_reg__");
|
||||
tsb::run();
|
||||
}
|
||||
// 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>;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
// TinySafeBoot on libavr — tier 2: C++ with compiler trickery, no assembly.
|
||||
// TinySafeBoot on libavr - tier 2: C++ with compiler trickery, no assembly.
|
||||
//
|
||||
// The full TinySafeBoot feature set — watchdog bail, one-wire half-duplex,
|
||||
// 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 — in pure C++, 526 bytes: 14 over the 512-byte
|
||||
// boot section the hand-written oracle fits, from 168 over at this tier's first
|
||||
// floor. The structure mirrors the oracle's: a handful of tiny noinline
|
||||
// config/flash/EEPROM read-write - in pure C++, a little over the 512-byte boot
|
||||
// section the hand-written oracle fits (oracle/README.md holds what each tier
|
||||
// measures). The structure mirrors the oracle's: a handful of tiny noinline
|
||||
// primitives sharing one whole-loader register allocation, expressed as global
|
||||
// register variables so no helper ever saves, spills, or reloads any of it.
|
||||
//
|
||||
// The register protocol (all call-saved, so calls preserve them by ABI):
|
||||
// Y (r28:r29) g_addr the walked flash/EEPROM address — adiw-able
|
||||
// r16 g_cnt byte countdown of the running block — ldi-able
|
||||
// Y (r28:r29) g_addr the walked flash/EEPROM address - adiw-able
|
||||
// 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)
|
||||
@@ -18,10 +18,10 @@
|
||||
// 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
|
||||
// local/scratch/probes/gcc-avr-globalreg-repro.cpp, lessons.md entry). Every
|
||||
// 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()
|
||||
// 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.
|
||||
//
|
||||
@@ -41,10 +41,16 @@ namespace hw = avr::hw;
|
||||
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.
|
||||
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 request = '?';
|
||||
constexpr std::uint8_t knock = '@';
|
||||
@@ -57,28 +63,34 @@ 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).
|
||||
constexpr std::uint8_t act_min = 16;
|
||||
// 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>((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::detail::solve_baud(16_MHz, 115200_Bd);
|
||||
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
|
||||
[[gnu::progmem]] constexpr std::uint8_t info[16] = {
|
||||
[[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
|
||||
0x1E, 0x95, 0x0F, // ATmega328P signature
|
||||
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,
|
||||
eeprom_end & 0xFF, eeprom_end >> 8,
|
||||
0xAA, 0xAA,
|
||||
};
|
||||
});
|
||||
// clang-format on
|
||||
|
||||
register std::uint16_t g_addr asm("r28");
|
||||
@@ -93,8 +105,8 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
|
||||
// Bounded byte receive, the oracle's shape: release the one-wire line on a
|
||||
// direction change, poll RXC0 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
|
||||
// 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.
|
||||
[[gnu::noinline, gnu::noclone]] std::uint8_t rx()
|
||||
{
|
||||
@@ -102,24 +114,25 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
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
|
||||
// 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 {
|
||||
std::uint8_t fine = 0;
|
||||
do {
|
||||
auto status = hw::ucsr0a::read();
|
||||
if (status & hw::ucsr0a::rxc0(1).value)
|
||||
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
|
||||
// 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
|
||||
// (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)
|
||||
@@ -127,8 +140,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
if (g_receiving) {
|
||||
g_receiving = 0;
|
||||
hw::ucsr0b::write(hw::ucsr0b::txen0(1));
|
||||
for (std::uint8_t guard = 46; guard; --guard)
|
||||
;
|
||||
avr::delay::cycles<guard_cycles>();
|
||||
}
|
||||
hw::udr0::write(byte);
|
||||
std::uint8_t status;
|
||||
@@ -145,7 +157,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
return rx();
|
||||
}
|
||||
|
||||
// One flash byte ← [g_addr++] (the advance right before ret — see header).
|
||||
// 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));
|
||||
@@ -153,18 +165,18 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
return byte;
|
||||
}
|
||||
|
||||
// One EEPROM byte ← [g_addr++].
|
||||
// One EEPROM byte <- [g_addr++].
|
||||
[[gnu::noinline, gnu::noclone]] std::uint8_t eerd()
|
||||
{
|
||||
std::uint8_t byte = ee::read(g_addr);
|
||||
std::uint8_t byte = ee::read<no_spm>(g_addr);
|
||||
++g_addr;
|
||||
return byte;
|
||||
}
|
||||
|
||||
// One EEPROM byte → [g_addr++].
|
||||
// One EEPROM byte -> [g_addr++].
|
||||
[[gnu::noinline, gnu::noclone]] void eewr(std::uint8_t byte)
|
||||
{
|
||||
ee::write<off>(g_addr, byte);
|
||||
ee::write<off, no_spm>(g_addr, byte);
|
||||
++g_addr;
|
||||
}
|
||||
|
||||
@@ -176,7 +188,7 @@ const std::uint8_t *flash_ptr(std::uint16_t addr)
|
||||
} while (--g_cnt);
|
||||
}
|
||||
|
||||
// Wait out a running SPM op, then re-open the RWW section — after every page
|
||||
// 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, gnu::noclone]] void settle()
|
||||
{
|
||||
@@ -198,12 +210,12 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
[[gnu::noinline, gnu::noclone]] void erase_below()
|
||||
{
|
||||
g_addr -= page;
|
||||
spm::erase_page<off>(g_addr);
|
||||
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
|
||||
// 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()
|
||||
{
|
||||
@@ -214,18 +226,19 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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>(g_addr, word);
|
||||
spm::fill<off>(open, g_addr, word);
|
||||
g_addr += 2;
|
||||
} while (--g_cnt);
|
||||
spm::write_page<off>(g_addr - page);
|
||||
spm::command<off>(spm::op::write, g_addr - page);
|
||||
settle();
|
||||
}
|
||||
|
||||
@@ -233,14 +246,15 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
{
|
||||
// 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())
|
||||
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
|
||||
// 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::reg<"UBRR0">::write(static_cast<std::uint8_t>(baud.ubrr));
|
||||
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
|
||||
@@ -248,13 +262,15 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
// same reason.
|
||||
g_receiving = 0;
|
||||
|
||||
// Activation: 3×'@', 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.
|
||||
// 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)
|
||||
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
|
||||
@@ -268,17 +284,19 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
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[0]);
|
||||
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)
|
||||
if (mask == 0) {
|
||||
continue;
|
||||
if (rcnf() != confirm || rcnf() != confirm)
|
||||
}
|
||||
if (rcnf() != confirm || rcnf() != confirm) {
|
||||
appjump();
|
||||
}
|
||||
erase_application(); // leaves g_addr = 0 for the EEPROM walk
|
||||
do {
|
||||
eewr(0xff);
|
||||
@@ -287,9 +305,10 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
erase_below();
|
||||
break;
|
||||
}
|
||||
if (got != expected)
|
||||
if (got != expected) {
|
||||
mask = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
tx(confirm); // Mainloop ready
|
||||
@@ -297,23 +316,27 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
switch (rx()) {
|
||||
case 'f': // read application flash, one page per host '!'
|
||||
for (;;) {
|
||||
if (rx() != confirm)
|
||||
if (rx() != confirm) {
|
||||
break;
|
||||
}
|
||||
g_cnt = page;
|
||||
sendf();
|
||||
if (g_addr >= app_end)
|
||||
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)
|
||||
while (rcnf() == confirm) {
|
||||
store_flash();
|
||||
}
|
||||
break;
|
||||
case 'e': // read EEPROM, one page per host '!', until the host stops
|
||||
for (;;) {
|
||||
if (rx() != confirm)
|
||||
if (rx() != confirm) {
|
||||
break;
|
||||
}
|
||||
g_cnt = page;
|
||||
do {
|
||||
tx(eerd());
|
||||
@@ -335,8 +358,9 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
sendf();
|
||||
break;
|
||||
case 'C': // replace the config page, then echo it back to verify
|
||||
if (rcnf() != confirm)
|
||||
if (rcnf() != confirm) {
|
||||
break;
|
||||
}
|
||||
g_addr = app_end + page;
|
||||
erase_below(); // leaves g_addr = app_end, the store target
|
||||
store_flash();
|
||||
@@ -350,14 +374,6 @@ extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --def
|
||||
} // namespace
|
||||
} // namespace tsb
|
||||
|
||||
// Reset lands here: BOOTRST vectors to the boot section base and .vectors is
|
||||
// laid first, so this is the first instruction executed. No crt ran, so set
|
||||
// the stack pointer before anything is called.
|
||||
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
|
||||
{
|
||||
SP = RAMEND;
|
||||
// The one line of crt this loader needs: compiled code assumes
|
||||
// __zero_reg__ (r1) is 0, and power-on registers are undefined.
|
||||
asm volatile("clr __zero_reg__");
|
||||
tsb::run();
|
||||
}
|
||||
// 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>;
|
||||
|
||||
Reference in New Issue
Block a user