diff --git a/platformio.ini b/platformio.ini index 9d0c7599..e4248679 100644 --- a/platformio.ini +++ b/platformio.ini @@ -124,6 +124,8 @@ platform_packages = ; U flashované desky je to podmínka, ne komfort (AGENTS.md). extra_scripts = create-uf2.py pre:tools/build_version.py +; FwPatch.cpp (delta OTA applier) runs from RAM, see the script's header. + pre:tools/ota_ramlib.py build_flags = ${arduino_base.build_flags} -D NRF52_PLATFORM -D LFS_NO_ASSERT=1 @@ -207,12 +209,11 @@ test_framework = googletest build_flags = -std=c++17 -I src -I test/mocks - -I src/helpers/fwpatch/detools/heatshrink test_build_src = yes test_ignore = test_kiss_modem build_src_filter = -<*> - +<../src/helpers/FwPatch.c> + +<../src/helpers/FwPatch.cpp> +<../src/Utils.cpp> +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> @@ -231,7 +232,6 @@ test_framework = googletest build_flags = -std=c++17 -I src -I test/mocks - -I src/helpers/fwpatch/detools/heatshrink -fsanitize=address,undefined # Bez -fno-sanitize-recover UBSan nalez jen VYPISE a test dobehne uspesne -- # takze z te poloviny sanitizeru byla jen ozdoba. ASAN abortuje sam. @@ -259,7 +259,7 @@ test_ignore = ; jednotka. build_src_filter = -<*> - +<../src/helpers/FwPatch.c> + +<../src/helpers/FwPatch.cpp> +<../src/Utils.cpp> +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> diff --git a/src/helpers/FwPatch.c b/src/helpers/FwPatch.cpp similarity index 88% rename from src/helpers/FwPatch.c rename to src/helpers/FwPatch.cpp index ad9cf893..f859ea5e 100644 --- a/src/helpers/FwPatch.c +++ b/src/helpers/FwPatch.cpp @@ -1,5 +1,10 @@ // CUSTOM (TeTeHacko): in-place delta update, see FwPatch.h. // +// C++ file on purpose: `helpers/*.cpp` is in every nRF52 env's build_src_filter, +// a .c file would need a filter entry in each of them. detools compiles as C++ +// unchanged. Only nRF52 and the native test build it (ARDUINO without +// NRF52_PLATFORM = ESP32/RP2040/STM32, nothing to do there). +// // This translation unit compiles the vendored detools + heatshrink decoder // (src/helpers/fwpatch/detools, unmodified, see README.tth.md there) together // with the driver below. On the node tools/ota_ramlib.py moves the whole object @@ -7,6 +12,8 @@ // single instruction or table of the real run lives in the flash it rewrites // (tools/ota_check_ramfunc.sh checks the result). +#if defined(NRF52_PLATFORM) || !defined(ARDUINO) + // --- vendored code, configured here instead of editing it ------------------------ #define HEATSHRINK_CONFIG_H // skip the vendored config, these values win #define HEATSHRINK_DYNAMIC_ALLOC 0 @@ -29,12 +36,15 @@ // --- driver -------------------------------------------------------------------- +// keeps GCC from turning these byte loops back into memcpy/memset calls +#define FWP_NOLIBC __attribute__((optimize("no-tree-loop-distribute-patterns"))) + static uint8_t g_page[FWP_PAGE]; static struct detools_apply_patch_in_place_t g_dt; #define NO_PAGE ((uintptr_t)-1) -static void fwp_copy(uint8_t *d, const uint8_t *s, uint32_t n) { +FWP_NOLIBC static void fwp_copy(uint8_t *d, const uint8_t *s, uint32_t n) { while (n--) *d++ = *s++; } @@ -168,23 +178,24 @@ int fwp_run(fwp_job *j) { return 0; } -// --- RAM copies of the two libc calls the compiler and detools emit ----------- +extern "C" { +// --- RAM copies of the libc calls the compiler and detools emit ----------- // tools/ota_ramlib.py renames memcpy/memset/memmove in this object to these, so // the real run never jumps back into flash libc. -void *fwp_memcpy(void *d, const void *s, size_t n) { +FWP_NOLIBC void *fwp_memcpy(void *d, const void *s, size_t n) { uint8_t *dd = (uint8_t *)d; const uint8_t *ss = (const uint8_t *)s; while (n--) *dd++ = *ss++; return d; } -void *fwp_memset(void *d, int c, size_t n) { +FWP_NOLIBC void *fwp_memset(void *d, int c, size_t n) { uint8_t *dd = (uint8_t *)d; while (n--) *dd++ = (uint8_t)c; return d; } -void *fwp_memmove(void *d, const void *s, size_t n) { +FWP_NOLIBC void *fwp_memmove(void *d, const void *s, size_t n) { uint8_t *dd = (uint8_t *)d; const uint8_t *ss = (const uint8_t *)s; if (dd < ss) { @@ -198,3 +209,6 @@ void *fwp_memmove(void *d, const void *s, size_t n) { } return d; } +} // extern "C" + +#endif diff --git a/src/helpers/FwUpdate.cpp b/src/helpers/FwUpdate.cpp index f4f3a58f..d9315c00 100644 --- a/src/helpers/FwUpdate.cpp +++ b/src/helpers/FwUpdate.cpp @@ -1,4 +1,5 @@ #include "FwUpdate.h" +#include "FwPatch.h" #if defined(NRF52_PLATFORM) @@ -22,6 +23,7 @@ #endif #define APP_START 0x27000 // S140 7.x, all our nRF52840 boards +#define PATCH_LO (FW_OTA_STAGE_END - FW_OTA_PATCH_AREA) // delta packages live here #define PAGE 4096u #define BL_SETTINGS 0xFF000u // sdk11 bootloader_settings_t, nRF52840 #define RING_BITS 15 @@ -33,7 +35,7 @@ extern "C" uint32_t __etext, __data_start__, __data_end__; // --- manifest (tools/ota_pack.py writes the same layout) ---------------------- struct __attribute__((packed)) Manifest { char magic[4]; // "MCFW" - uint8_t format; // 1 + uint8_t format; // 1 = deflate full image, 2 = in-place delta (FwPatch) uint8_t reserved0[3]; uint32_t raw_size; uint32_t comp_size; @@ -41,7 +43,7 @@ struct __attribute__((packed)) Manifest { uint8_t comp_sha[32]; char target[32]; char version[48]; - uint8_t reserved1[32]; + uint8_t base_sha[32]; // format 2: sha256 of the image the delta applies to uint8_t signature[64]; // Ed25519 over bytes 0..191 }; static_assert(sizeof(Manifest) == FW_OTA_MANIFEST_SIZE, "manifest layout"); @@ -354,6 +356,45 @@ RAMFUNC static void copy_and_reset(Inflate *s, CopyCtx *c) { } } +// --- delta apply (format 2) ------------------------------------------------------ +// The applier itself (FwPatch.cpp, detools) is moved to RAM by tools/ota_ramlib.py; +// these are its flash callbacks and the entry point, all RAM as well. + +RAMFUNC static void fwp_erase_page(uintptr_t a) { + wdt_feed(); + nvmc_erase((uint32_t)a); +} + +RAMFUNC static void fwp_write_page(uintptr_t a, const uint8_t *src, uint32_t n) { + nvmc_write((uint32_t)a, src, n); +} + +RAMFUNC static void fwp_tick() { + wdt_feed(); +} + +RAMFUNC static void patch_and_reset(fwp_job *j, const uint32_t *settings) { + // 1) the bootloader learns the new CRC before a single app byte changes + wdt_feed(); + nvmc_erase(BL_SETTINGS); + nvmc_write(BL_SETTINGS, (const uint8_t *)settings, PAGE); + // 2) patch the running image in place + fwp_run(j); + // 3) whatever happened, reset; a CRC mismatch keeps the node in the bootloader + wdt_feed(); + __DSB(); + SCB->AIRCR = (0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk; + __DSB(); + for (;;) { + } +} + +// An env without tools/ota_ramlib.py would leave the applier in flash, which the +// real run erases under itself. Refuse delta packages there. +static bool deltaInRam() { + return (uintptr_t)&fwp_run >= 0x20000000u; +} + // --- helpers -------------------------------------------------------------------- static uint16_t crc16_update(uint16_t crc, const uint8_t *p, uint32_t len) { @@ -424,6 +465,12 @@ struct VerifyCtx { bool overlap; }; +static void delta_sink(void *vctx, const uint8_t *data, uint32_t len) { + VerifyCtx *v = (VerifyCtx *)vctx; + v->sha.update(data, len); + v->crc = crc16_update(v->crc, data, len); +} + static int verify_flush(void *vctx, const uint8_t *data, uint32_t off, uint32_t len, uint32_t in_used) { VerifyCtx *v = (VerifyCtx *)vctx; v->sha.update(data, len); @@ -451,19 +498,75 @@ uint16_t FwUpdate::battMinMv() { return mv; } +const uint8_t *FwUpdate::baseSha() { + if (!_base_known) { + SHA256 sha; + sha.update((const uint8_t *)APP_START, imageEnd() - APP_START); + sha.finalize(_base_sha, 32); + _base_known = true; + } + return _base_sha; +} + +bool FwUpdate::checkManifest() { + const Manifest *m = (const Manifest *)_stage; + uint8_t key[32]; + if (memcmp(m->magic, "MCFW", 4) != 0 || (m->format != 1 && m->format != 2)) { + strcpy(_err, "not a package"); + return false; + } + if (!pubkey(key)) { + strcpy(_err, "bad FW_OTA_PUBKEY"); + return false; + } + if (!ed25519_verify(m->signature, (const uint8_t *)m, offsetof(Manifest, signature), key)) { + strcpy(_err, "bad signature"); + return false; + } + if (strncmp(m->target, FW_OTA_TARGET, sizeof(m->target)) != 0) { + strcpy(_err, "wrong target"); + return false; + } + if (FW_OTA_MANIFEST_SIZE + m->comp_size != _total) { + strcpy(_err, "size mismatch"); + return false; + } + if (m->format == 2) { + if (!deltaInRam()) { + strcpy(_err, "no delta support in this build"); + return false; + } + if (_stage != PATCH_LO) { + strcpy(_err, "delta too big for the patch area"); + return false; + } + if (memcmp(m->base_sha, baseSha(), 32) != 0) { + strcpy(_err, "wrong base image"); + return false; + } + } + _format = m->format; + return true; +} + void FwUpdate::cmdStatus(char *reply) { uint16_t mv = _board.getBattMilliVolts(); uint32_t n = (_total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK; switch (_state) { case IDLE: - sprintf(reply, "> idle, batt %umV (min %u), free %lu B", mv, FW_OTA_MIN_MV, - (unsigned long)(FW_OTA_STAGE_END - ((imageEnd() + PAGE - 1) & ~(PAGE - 1)))); + { + const uint8_t *b = baseSha(); + sprintf(reply, "> idle, batt %umV (min %u), free %lu B, base %lu %02x%02x%02x%02x%s", mv, FW_OTA_MIN_MV, + (unsigned long)(FW_OTA_STAGE_END - ((imageEnd() + PAGE - 1) & ~(PAGE - 1))), + (unsigned long)(imageEnd() - APP_START), b[0], b[1], b[2], b[3], deltaInRam() ? ", delta" : ""); + } break; case RECEIVING: sprintf(reply, "> rx %lu/%lu chunks, batt %umV", (unsigned long)received(), (unsigned long)n, mv); break; case READY: - sprintf(reply, "> ready %s, %lu B, crc %04X, batt %umV", _version, (unsigned long)_raw_size, _crc, mv); + sprintf(reply, "> ready %s%s, %lu B, crc %04X, batt %umV", _version, _format == 2 ? " (delta)" : "", + (unsigned long)_raw_size, _crc, mv); break; case FAILED: sprintf(reply, "> failed: %s", _err); @@ -473,7 +576,9 @@ void FwUpdate::cmdStatus(char *reply) { void FwUpdate::cmdBegin(const char *arg, char *reply) { uint32_t total = strtoul(arg, NULL, 10); - uint32_t stage = (imageEnd() + PAGE - 1) & ~(PAGE - 1); + // small = delta: top of the free flash, out of reach of the in-place shift; + // big = full image: right above the running one, as before + uint32_t stage = total <= FW_OTA_PATCH_AREA ? PATCH_LO : (imageEnd() + PAGE - 1) & ~(PAGE - 1); if (total <= FW_OTA_MANIFEST_SIZE) { strcpy(reply, "ERR: fw begin "); return; @@ -487,6 +592,8 @@ void FwUpdate::cmdBegin(const char *arg, char *reply) { _total = total; memset(_have, 0, sizeof(_have)); _state = RECEIVING; + _manifest_ok = false; + _format = 0; _apply_at = 0; sprintf(reply, "OK %lu chunks of %u at %05lX", (unsigned long)((total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK), FW_OTA_CHUNK, (unsigned long)stage); @@ -512,6 +619,22 @@ void FwUpdate::cmdWrite(const char *arg, char *reply) { flash_nrf5x_write(_stage + off, buf, len); _have[idx >> 3] |= (1 << (idx & 7)); } + if (!_manifest_ok) { + // as soon as the manifest is complete: refuse a package for another board or + // another base before the rest of it is sent + bool all = true; + for (uint32_t i = 0; i * FW_OTA_CHUNK < FW_OTA_MANIFEST_SIZE; i++) + if (!(_have[i >> 3] & (1 << (i & 7)))) all = false; + if (all) { + flash_nrf5x_flush(); + if (!checkManifest()) { + _state = FAILED; + sprintf(reply, "ERR: %s", _err); + return; + } + _manifest_ok = true; + } + } strcpy(reply, "ok"); } @@ -550,28 +673,8 @@ void FwUpdate::cmdVerify(char *reply) { _state = FAILED; const Manifest *m = (const Manifest *)_stage; - uint8_t key[32]; - if (memcmp(m->magic, "MCFW", 4) != 0 || m->format != 1) { - strcpy(_err, "not a package"); - goto fail; - } - if (!pubkey(key)) { - strcpy(_err, "bad FW_OTA_PUBKEY"); - goto fail; - } - if (!ed25519_verify(m->signature, (const uint8_t *)m, offsetof(Manifest, signature), key)) { - strcpy(_err, "bad signature"); - goto fail; - } - if (strncmp(m->target, FW_OTA_TARGET, sizeof(m->target)) != 0) { - strcpy(_err, "wrong target"); - goto fail; - } - if (FW_OTA_MANIFEST_SIZE + m->comp_size != _total) { - strcpy(_err, "size mismatch"); - goto fail; - } - if (APP_START + m->raw_size > FW_OTA_STAGE_END) { + if (!checkManifest()) goto fail; + if (APP_START + m->raw_size > (m->format == 2 ? PATCH_LO : FW_OTA_STAGE_END)) { strcpy(_err, "image too big"); goto fail; } @@ -585,7 +688,39 @@ void FwUpdate::cmdVerify(char *reply) { goto fail; } } - { + if (m->format == 2) { + // dry run of the very code `fw apply` runs: no flash touched, the new image + // streamed through sha256 + the bootloader's CRC16 + VerifyCtx *v = new VerifyCtx(); + if (!v) { + strcpy(_err, "no RAM"); + goto fail; + } + v->crc = 0xFFFF; + fwp_job j; + memset(&j, 0, sizeof(j)); + j.mem_base = APP_START; + j.mem_size = PATCH_LO - APP_START; + j.from_size = imageEnd() - APP_START; + j.patch = (const uint8_t *)(_stage + FW_OTA_MANIFEST_SIZE); + j.patch_size = m->comp_size; + j.dry = 1; + j.sink = delta_sink; + j.sink_ctx = v; + int err = fwp_run(&j); + uint8_t h[32]; + v->sha.finalize(h, 32); + _crc = v->crc; + delete v; + if (err) { + sprintf(_err, "delta %d/%d", err, j.detools_err); + goto fail; + } + if (j.to_size != m->raw_size || memcmp(h, m->raw_sha, 32) != 0) { + strcpy(_err, "image hash"); + goto fail; + } + } else { uint8_t *ring = (uint8_t *)malloc(RING_SIZE); VerifyCtx *v = new VerifyCtx(); if (!ring || !v) { @@ -680,12 +815,12 @@ void FwUpdate::loop() { if (_state != READY) return; uint32_t *settings = (uint32_t *)malloc(PAGE); - uint8_t *ring = (uint8_t *)malloc(RING_SIZE); + uint8_t *ring = _format == 2 ? (uint8_t *)1 : (uint8_t *)malloc(RING_SIZE); // delta needs no ring static Inflate s; static CopyCtx c; if (!settings || !ring) { free(settings); - free(ring); + if (_format != 2) free(ring); _state = FAILED; strcpy(_err, "no RAM for apply"); return; @@ -698,6 +833,18 @@ void FwUpdate::loop() { s16[2] = 0x00FF; // bank_1 = BANK_INVALID_APP settings[2] = _raw_size; // bank_0_size + static fwp_job j; + if (_format == 2) { + memset(&j, 0, sizeof(j)); + j.mem_base = APP_START; + j.mem_size = PATCH_LO - APP_START; + j.from_size = imageEnd() - APP_START; + j.patch = (const uint8_t *)(_stage + FW_OTA_MANIFEST_SIZE); + j.patch_size = ((const Manifest *)_stage)->comp_size; + j.erase = fwp_erase_page; + j.write = fwp_write_page; + j.tick = fwp_tick; + } c.stage_blob = _stage + FW_OTA_MANIFEST_SIZE; c.settings = settings; memset(&s, 0, sizeof(s)); @@ -715,6 +862,7 @@ void FwUpdate::loop() { sd_softdevice_is_enabled(&sd); if (sd) sd_softdevice_disable(); __disable_irq(); + if (_format == 2) patch_and_reset(&j, settings); copy_and_reset(&s, &c); } diff --git a/src/helpers/FwUpdate.h b/src/helpers/FwUpdate.h index 87898d89..2fb99d23 100644 --- a/src/helpers/FwUpdate.h +++ b/src/helpers/FwUpdate.h @@ -3,8 +3,14 @@ // CUSTOM (TeTeHacko): firmware update pushed by an admin, no bootloader change. // Design and the reasons behind it: docs/ota-admin.md. // -// The node stores a signed, deflate-compressed image in the free flash above the -// running one, checks it completely (signature, hashes, a dry-run inflate), and +// Two package formats, one signed 256 B manifest: +// 1 deflate-compressed full image, staged in the free flash above the running +// one, inflated over it by a RAM routine; +// 2 detools in-place DELTA against the running image (FwPatch.cpp), staged in +// the top FW_OTA_PATCH_AREA below InternalFS. The manifest names the base +// (sha256 of the running image) and the node refuses a package for another +// base as soon as the manifest chunks arrive. +// For both, the node checks it completely (signature, hashes, a dry-run inflate), and // only then, on an explicit `fw apply`, disables the SoftDevice and runs a copy // routine from RAM that inflates the image over itself. The bootloader settings // page gets the CRC of the new image FIRST, so a power cut mid-copy leaves a @@ -30,6 +36,10 @@ #define FW_OTA_MIN_MV 3800 // ~50 % of a Li-ion cell at rest #endif +#ifndef FW_OTA_PATCH_AREA +#define FW_OTA_PATCH_AREA 0x10000 // delta packages (manifest + patch) up to 64 kB +#endif + #define FW_OTA_MANIFEST_SIZE 256 class FwUpdate { @@ -52,6 +62,8 @@ private: void cmdBootloader(char *reply); uint16_t battMinMv(); uint32_t received() const; + bool checkManifest(); // signature, target, base; sets _err + const uint8_t *baseSha(); // sha256 of the running image, computed once mesh::MainBoard &_board; State _state = IDLE; @@ -59,6 +71,10 @@ private: uint32_t _total = 0; // package size (manifest + blob) uint32_t _raw_size = 0; uint16_t _crc = 0; + uint8_t _format = 0; + bool _manifest_ok = false; + bool _base_known = false; + uint8_t _base_sha[32]; char _version[48] = { 0 }; char _err[48] = { 0 }; unsigned long _apply_at = 0; diff --git a/src/helpers/fwpatch/detools/README.tth.md b/src/helpers/fwpatch/detools/README.tth.md index fb935a53..39e8da94 100644 --- a/src/helpers/fwpatch/detools/README.tth.md +++ b/src/helpers/fwpatch/detools/README.tth.md @@ -5,7 +5,7 @@ files `c/detools.{c,h}` and `c/heatshrink/*`, copied **unmodified**. Licences: detools BSD-2-Clause (`LICENSE`, includes bsdiff/sais notices), heatshrink ISC (`heatshrink/README.rst`). -Used only by `src/helpers/FwPatch.c`, which `#include`s both `.c` files and +Used only by `src/helpers/FwPatch.cpp`, which `#include`s both `.c` files and configures them there (heatshrink 11/10 static, heatshrink-only detools, no file I/O) -- so nothing in this directory needs editing. Nothing here is in any `build_src_filter` on its own. diff --git a/src/helpers/fwpatch/detools/heatshrink_decoder.h b/src/helpers/fwpatch/detools/heatshrink_decoder.h new file mode 100644 index 00000000..a29a3fdf --- /dev/null +++ b/src/helpers/fwpatch/detools/heatshrink_decoder.h @@ -0,0 +1,4 @@ +// CUSTOM (TeTeHacko): forwarding header, not part of detools. detools.h includes +// "heatshrink_decoder.h" expecting it on the include path; this keeps every env +// free of an extra -I flag. See README.tth.md. +#include "heatshrink/heatshrink_decoder.h"