#include "FwUpdate.h" #include "FwPatch.h" #if defined(NRF52_PLATFORM) #include #include #include #include #include #ifndef FW_OTA_PUBKEY #error "FW_OTA_PUBKEY (64 hex chars) must be defined for FwUpdate" #endif #ifndef FW_OTA_TARGET #error "FW_OTA_TARGET (the env name) must be defined, tools/build_version.py does it" #endif // Roles with a console (repeater, room server, sensor) never mount ExtraFS, so // the whole space up to InternalFS is free. The companion would need 0xD4000. #ifndef FW_OTA_STAGE_END #define FW_OTA_STAGE_END 0xED000 #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 #define RING_SIZE (1u << RING_BITS) #define RING_MASK (RING_SIZE - 1) 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 = deflate full image, 2 = in-place delta (FwPatch) uint8_t reserved0[3]; uint32_t raw_size; uint32_t comp_size; uint8_t raw_sha[32]; uint8_t comp_sha[32]; char target[32]; char version[48]; 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"); // --- inflate ------------------------------------------------------------------ // A small RFC 1951 decoder in the style of zlib's contrib/puff. EVERYTHING it // touches during the copy must live in RAM, because the copy erases the flash // the firmware runs from: the functions are placed in .data (copied to RAM by // the startup code), the tables are non-const for the same reason, and no // library call (memset, memcpy) may be emitted -- `fw verify` runs the very same // code, and tools/ota_check_ramfunc.sh checks the disassembly for calls out. #define RAMFUNC \ __attribute__((section(".data.ramfunc"), noinline, long_call, optimize("no-tree-loop-distribute-patterns"))) // GCC moves a never-written static table to .rodata, i.e. flash, even when it // is not const (seen: lbase..clorder at 0x7b9fc). Pin the tables to RAM. #define RAMDATA __attribute__((section(".data.ramtab"))) typedef int (*FlushFn)(void *ctx, const uint8_t *data, uint32_t off, uint32_t len, uint32_t in_used); struct Inflate { const uint8_t *in; uint32_t inlen, incnt; uint32_t bitbuf, bitcnt; uint8_t *ring; uint32_t outcnt, outmax; FlushFn flush; void *ctx; }; struct Huff { int16_t count[16]; int16_t symbol[288]; }; RAMDATA static uint16_t lbase[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; RAMDATA static uint16_t lext[29] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; RAMDATA static uint16_t dbase[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; RAMDATA static uint16_t dext[30] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; RAMDATA static uint8_t clorder[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static Huff g_lencode, g_distcode; // .bss is RAM; static so the stack stays small static int16_t g_lengths[320]; RAMFUNC static int inf_bits(Inflate *s, int need, uint32_t *out) { uint32_t val = s->bitbuf; while (s->bitcnt < (uint32_t)need) { if (s->incnt == s->inlen) return -1; val |= (uint32_t)s->in[s->incnt++] << s->bitcnt; s->bitcnt += 8; } s->bitbuf = val >> need; s->bitcnt -= need; *out = val & ((1u << need) - 1); return 0; } RAMFUNC static int inf_put(Inflate *s, uint8_t b) { if (s->outcnt >= s->outmax) return -2; s->ring[s->outcnt & RING_MASK] = b; s->outcnt++; if ((s->outcnt % PAGE) == 0) { uint32_t off = s->outcnt - PAGE; return s->flush(s->ctx, &s->ring[off & RING_MASK], off, PAGE, s->incnt); } return 0; } RAMFUNC static int inf_decode(Inflate *s, const Huff *h, int *sym) { int code = 0, first = 0, index = 0; for (int len = 1; len < 16; len++) { uint32_t b; if (inf_bits(s, 1, &b)) return -1; code |= (int)b; int count = h->count[len]; if (code - count < first) { *sym = h->symbol[index + (code - first)]; return 0; } index += count; first += count; first <<= 1; code <<= 1; } return -3; } RAMFUNC static int inf_construct(Huff *h, const int16_t *length, int n) { int16_t offs[16]; for (int len = 0; len < 16; len++) h->count[len] = 0; for (int sym = 0; sym < n; sym++) h->count[length[sym]]++; if (h->count[0] == n) return 0; int left = 1; for (int len = 1; len < 16; len++) { left <<= 1; left -= h->count[len]; if (left < 0) return left; } offs[1] = 0; for (int len = 1; len < 15; len++) offs[len + 1] = offs[len] + h->count[len]; for (int sym = 0; sym < n; sym++) if (length[sym] != 0) h->symbol[offs[length[sym]]++] = sym; return left; } RAMFUNC static int inf_codes(Inflate *s, const Huff *lc, const Huff *dc) { int sym; do { if (inf_decode(s, lc, &sym)) return -4; if (sym < 256) { if (inf_put(s, (uint8_t)sym)) return -5; } else if (sym > 256) { sym -= 257; if (sym >= 29) return -6; uint32_t e; if (inf_bits(s, lext[sym], &e)) return -1; uint32_t len = lbase[sym] + e; if (inf_decode(s, dc, &sym)) return -4; if (sym >= 30) return -6; if (inf_bits(s, dext[sym], &e)) return -1; uint32_t dist = dbase[sym] + e; if (dist > s->outcnt || dist > RING_SIZE) return -7; while (len--) { if (inf_put(s, s->ring[(s->outcnt - dist) & RING_MASK])) return -5; } } } while (sym != 256); return 0; } RAMFUNC static int inf_stored(Inflate *s) { s->bitbuf = 0; s->bitcnt = 0; if (s->incnt + 4 > s->inlen) return -1; uint32_t len = s->in[s->incnt] | ((uint32_t)s->in[s->incnt + 1] << 8); uint32_t nlen = s->in[s->incnt + 2] | ((uint32_t)s->in[s->incnt + 3] << 8); s->incnt += 4; if (len != (~nlen & 0xffff)) return -8; if (s->incnt + len > s->inlen) return -1; while (len--) if (inf_put(s, s->in[s->incnt++])) return -5; return 0; } RAMFUNC static int inf_fixed(Inflate *s) { int sym = 0; for (; sym < 144; sym++) g_lengths[sym] = 8; for (; sym < 256; sym++) g_lengths[sym] = 9; for (; sym < 280; sym++) g_lengths[sym] = 7; for (; sym < 288; sym++) g_lengths[sym] = 8; inf_construct(&g_lencode, g_lengths, 288); for (sym = 0; sym < 30; sym++) g_lengths[sym] = 5; inf_construct(&g_distcode, g_lengths, 30); return inf_codes(s, &g_lencode, &g_distcode); } RAMFUNC static int inf_dynamic(Inflate *s) { uint32_t nlen, ndist, ncode, v; if (inf_bits(s, 5, &nlen)) return -1; nlen += 257; if (inf_bits(s, 5, &ndist)) return -1; ndist += 1; if (inf_bits(s, 4, &ncode)) return -1; ncode += 4; if (nlen > 286 || ndist > 30) return -9; uint32_t index; for (index = 0; index < ncode; index++) { if (inf_bits(s, 3, &v)) return -1; g_lengths[clorder[index]] = (int16_t)v; } for (; index < 19; index++) g_lengths[clorder[index]] = 0; if (inf_construct(&g_lencode, g_lengths, 19) != 0) return -10; index = 0; while (index < nlen + ndist) { int sym; if (inf_decode(s, &g_lencode, &sym)) return -4; if (sym < 16) { g_lengths[index++] = (int16_t)sym; } else { int16_t len = 0; uint32_t rep; if (sym == 16) { if (index == 0) return -11; len = g_lengths[index - 1]; if (inf_bits(s, 2, &rep)) return -1; rep += 3; } else if (sym == 17) { if (inf_bits(s, 3, &rep)) return -1; rep += 3; } else { if (inf_bits(s, 7, &rep)) return -1; rep += 11; } if (index + rep > nlen + ndist) return -12; while (rep--) g_lengths[index++] = len; } } if (g_lengths[256] == 0) return -13; int err = inf_construct(&g_lencode, g_lengths, nlen); if (err && (err < 0 || nlen != (uint32_t)(g_lencode.count[0] + g_lencode.count[1]))) return -14; err = inf_construct(&g_distcode, g_lengths + nlen, ndist); if (err && (err < 0 || ndist != (uint32_t)(g_distcode.count[0] + g_distcode.count[1]))) return -15; return inf_codes(s, &g_lencode, &g_distcode); } // Raw deflate stream -> flush() per 4 KB page, the last page short. RAMFUNC static int inf_run(Inflate *s) { uint32_t last, type; int err; do { if (inf_bits(s, 1, &last)) return -1; if (inf_bits(s, 2, &type)) return -1; if (type == 0) err = inf_stored(s); else if (type == 1) err = inf_fixed(s); else if (type == 2) err = inf_dynamic(s); else err = -16; if (err) return err; } while (!last); uint32_t tail = s->outcnt % PAGE; if (tail) { uint32_t off = s->outcnt - tail; return s->flush(s->ctx, &s->ring[off & RING_MASK], off, tail, s->incnt); } return 0; } // --- the copy, RAM only --------------------------------------------------------- struct CopyCtx { uint32_t stage_blob; // flash address of the compressed stream const uint32_t *settings; // RAM copy of the bootloader settings page }; RAMFUNC static void nvmc_wait() { while (NRF_NVMC->READY == NVMC_READY_READY_Busy) { } } RAMFUNC static void nvmc_erase(uint32_t addr) { NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een; nvmc_wait(); NRF_NVMC->ERASEPAGE = addr; nvmc_wait(); NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren; nvmc_wait(); } RAMFUNC static void nvmc_write(uint32_t addr, const uint8_t *src, uint32_t len) { NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen; nvmc_wait(); for (uint32_t i = 0; i < len; i += 4) { uint32_t w = 0xFFFFFFFFu; for (uint32_t b = 0; b < 4 && i + b < len; b++) { w &= ~((uint32_t)0xFF << (8 * b)); w |= (uint32_t)src[i + b] << (8 * b); } *(volatile uint32_t *)(addr + i) = w; nvmc_wait(); } NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren; nvmc_wait(); } RAMFUNC static void wdt_feed() { if (NRF_WDT->RUNSTATUS) NRF_WDT->RR[0] = WDT_RR_RR_Reload; } RAMFUNC static int copy_flush(void *vctx, const uint8_t *data, uint32_t off, uint32_t len, uint32_t in_used) { CopyCtx *c = (CopyCtx *)vctx; uint32_t addr = APP_START + off; // never overwrite compressed input that has not been read yet if (addr + PAGE > c->stage_blob + in_used) return -20; wdt_feed(); nvmc_erase(addr); nvmc_write(addr, data, len); return 0; } RAMFUNC static void copy_and_reset(Inflate *s, CopyCtx *c) { // 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 *)c->settings, PAGE); // 2) inflate over the running image inf_run(s); // 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 (;;) { } } // --- 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) { // Nordic crc16_compute (CRC-16-CCITT, init 0xFFFF), as the bootloader checks it for (uint32_t i = 0; i < len; i++) { crc = (uint16_t)((crc >> 8) | (crc << 8)); crc ^= p[i]; crc ^= (uint16_t)((crc & 0xFF) >> 4); crc ^= (uint16_t)((crc << 8) << 4); crc ^= (uint16_t)(((crc & 0xFF) << 4) << 1); } return crc; } static int hexval(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static bool pubkey(uint8_t out[32]) { const char *hex = FW_OTA_PUBKEY; if (strlen(hex) != 64) return false; for (int i = 0; i < 32; i++) { int hi = hexval(hex[2 * i]), lo = hexval(hex[2 * i + 1]); if (hi < 0 || lo < 0) return false; out[i] = (uint8_t)(hi << 4 | lo); } return true; } static int b64val(char c) { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+') return 62; if (c == '/') return 63; return -1; } static int b64decode(const char *in, uint8_t *out, int max) { int n = 0, bits = 0; uint32_t acc = 0; for (; *in && *in != '='; in++) { int v = b64val(*in); if (v < 0) return -1; acc = (acc << 6) | (uint32_t)v; bits += 6; if (bits >= 8) { bits -= 8; if (n >= max) return -1; out[n++] = (uint8_t)(acc >> bits); } } return n; } static uint32_t imageEnd() { uint32_t data_len = (uint32_t)&__data_end__ - (uint32_t)&__data_start__; return (uint32_t)&__etext + data_len; } struct VerifyCtx { SHA256 sha; uint16_t crc; uint32_t stage_blob; 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); v->crc = crc16_update(v->crc, data, len); if (APP_START + off + PAGE > v->stage_blob + in_used) v->overlap = true; return 0; } // --- commands ------------------------------------------------------------------- uint32_t FwUpdate::received() const { uint32_t n = (_total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK, have = 0; for (uint32_t i = 0; i < n; i++) if (_have[i >> 3] & (1 << (i & 7))) have++; return have; } uint16_t FwUpdate::battMinMv() { uint16_t mv = 0xFFFF; for (int i = 0; i < 5; i++) { uint16_t v = _board.getBattMilliVolts(); if (v < mv) mv = v; delay(100); } 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: { 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: if (_job == JOB_VERIFY) { strcpy(reply, "> verifying"); break; } sprintf(reply, "> rx %lu/%lu chunks, batt %umV", (unsigned long)received(), (unsigned long)n, mv); break; case READY: 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); break; } } void FwUpdate::cmdBegin(const char *arg, char *reply) { uint32_t total = strtoul(arg, NULL, 10); // 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; } if (stage + total > FW_OTA_STAGE_END) { sprintf(reply, "ERR: %lu B does not fit, %lu free", (unsigned long)total, (unsigned long)(FW_OTA_STAGE_END - stage)); return; } _stage = stage; _total = total; memset(_have, 0, sizeof(_have)); _state = RECEIVING; _manifest_ok = false; _format = 0; _job = JOB_NONE; _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); } void FwUpdate::cmdWrite(const char *arg, char *reply) { if (_state == FAILED) { sprintf(reply, "ERR: %s", _err); return; } if (_state != RECEIVING) { strcpy(reply, "ERR: not receiving"); return; } char *end; uint32_t off = strtoul(arg, &end, 10); while (*end == ' ') end++; uint8_t buf[FW_OTA_CHUNK]; int len = b64decode(end, buf, sizeof(buf)); if (len <= 0 || off % FW_OTA_CHUNK || off + len > _total || (len != FW_OTA_CHUNK && off + len != _total)) { strcpy(reply, "ERR: bad chunk"); return; } uint32_t idx = off / FW_OTA_CHUNK; if (!(_have[idx >> 3] & (1 << (idx & 7)))) { 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 && _job == JOB_NONE) _job = JOB_MANIFEST; // loop() checks it } strcpy(reply, "ok"); } void FwUpdate::cmdMissing(char *reply) { if (_state != RECEIVING) { strcpy(reply, "ERR: not receiving"); return; } uint32_t n = (_total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK; int pos = sprintf(reply, ">"); int listed = 0; for (uint32_t i = 0; i < n && pos < 140; i++) { if (!(_have[i >> 3] & (1 << (i & 7)))) { pos += sprintf(reply + pos, " %lu", (unsigned long)(i * FW_OTA_CHUNK)); listed++; } } if (!listed) strcpy(reply, "> none"); } void FwUpdate::cmdVerify(char *reply) { if (_state == READY || _state == FAILED || _job == JOB_VERIFY) { cmdStatus(reply); return; } if (_state != RECEIVING) { strcpy(reply, "ERR: nothing staged"); return; } uint32_t n = (_total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK; if (received() != n) { strcpy(reply, "ERR: incomplete, see fw missing"); return; } _job = JOB_VERIFY; // loop() runs it; poll `fw status` strcpy(reply, "> verifying"); } void FwUpdate::doVerify() { flash_nrf5x_flush(); _state = FAILED; const Manifest *m = (const Manifest *)_stage; 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; } { uint8_t h[32]; SHA256 sha; sha.update((const uint8_t *)(_stage + FW_OTA_MANIFEST_SIZE), m->comp_size); sha.finalize(h, 32); if (memcmp(h, m->comp_sha, 32) != 0) { strcpy(_err, "blob hash"); 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) { free(ring); delete v; strcpy(_err, "no RAM"); goto fail; } v->crc = 0xFFFF; v->stage_blob = _stage + FW_OTA_MANIFEST_SIZE; v->overlap = false; Inflate s = {}; s.in = (const uint8_t *)v->stage_blob; s.inlen = m->comp_size; s.ring = ring; s.outmax = m->raw_size; s.flush = verify_flush; s.ctx = v; int err = inf_run(&s); uint8_t h[32]; v->sha.finalize(h, 32); _crc = v->crc; bool overlap = v->overlap; free(ring); delete v; if (err) { sprintf(_err, "inflate %d", err); goto fail; } if (s.outcnt != m->raw_size || memcmp(h, m->raw_sha, 32) != 0) { strcpy(_err, "image hash"); goto fail; } if (overlap) { strcpy(_err, "image would overrun the package"); goto fail; } } _raw_size = m->raw_size; strncpy(_version, m->version, sizeof(_version) - 1); _version[sizeof(_version) - 1] = 0; _state = READY; return; fail: _state = FAILED; } void FwUpdate::cmdBootloader(char *reply) { const volatile uint16_t *s16 = (const volatile uint16_t *)BL_SETTINGS; const volatile uint32_t *s32 = (const volatile uint32_t *)BL_SETTINGS; sprintf(reply, "> bank0=%04X crc=%04X bank1=%04X size=%lu", s16[0], s16[1], s16[2], (unsigned long)s32[2]); } void FwUpdate::cmdApply(uint32_t sender_timestamp, const char *arg, char *reply) { if (_state != READY) { strcpy(reply, "ERR: nothing verified, fw verify first"); return; } bool force = strcmp(arg, "force") == 0; if (force && sender_timestamp != 0) { strcpy(reply, "ERR: force is local-only"); return; } uint16_t bank0 = *(const volatile uint16_t *)BL_SETTINGS; if (bank0 != 0x0001 && bank0 != 0xFFFF) { sprintf(reply, "ERR: unknown bootloader settings (bank0=%04X)", bank0); return; } uint16_t mv = battMinMv(); // USB VBUS present: the copy cannot run out of power, and a board without // a cell reads only ~3.7 V on VBAT (x4 on the bench), so the gate would // refuse a perfectly safe apply. bool ext = _board.isExternalPowered(); if (!force && !ext) { if (mv < 2000) { sprintf(reply, "ERR: battery unknown (%umV), fw apply force (local)", mv); return; } if (mv < FW_OTA_MIN_MV) { sprintf(reply, "ERR: batt %umV < %u", mv, FW_OTA_MIN_MV); return; } } _apply_at = millis() + 2000; // let the reply go out first sprintf(reply, "OK applying %s in 2 s (batt %umV%s), back in ~20 s", _version, mv, ext ? ", USB" : ""); } void FwUpdate::loop() { if (_job == JOB_MANIFEST) { _job = JOB_NONE; flash_nrf5x_flush(); if (checkManifest()) { _manifest_ok = true; } else { _state = FAILED; } } else if (_job == JOB_VERIFY) { _job = JOB_NONE; if (!_manifest_ok && !checkManifest()) { _state = FAILED; } else { doVerify(); } } if (_apply_at == 0 || (long)(millis() - _apply_at) < 0) return; _apply_at = 0; if (_state != READY) return; uint32_t *settings = (uint32_t *)malloc(PAGE); 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); if (_format != 2) free(ring); _state = FAILED; strcpy(_err, "no RAM for apply"); return; } memcpy(settings, (const void *)BL_SETTINGS, PAGE); uint16_t *s16 = (uint16_t *)settings; s16[0] = 0x0001; // BANK_VALID_APP s16[1] = _crc; // bank_0_crc 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)); s.in = (const uint8_t *)c.stage_blob; s.inlen = ((const Manifest *)_stage)->comp_size; s.ring = ring; s.outmax = _raw_size; s.flush = copy_flush; s.ctx = &c; Serial.flush(); NRF_USBD->USBPULLUP = 0; // a clean disconnect, see NodeMaintenance::dfuTick delay(100); uint8_t sd = 0; 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); } bool FwUpdate::handleCommand(uint32_t sender_timestamp, const char *command, char *reply) { if (memcmp(command, "fw", 2) != 0 || (command[2] != 0 && command[2] != ' ')) return false; const char *arg = command[2] ? &command[3] : ""; while (*arg == ' ') arg++; if (strncmp(arg, "w ", 2) == 0) cmdWrite(arg + 2, reply); else if (strcmp(arg, "status") == 0 || !*arg) cmdStatus(reply); else if (strncmp(arg, "begin ", 6) == 0) cmdBegin(arg + 6, reply); else if (strcmp(arg, "missing") == 0) cmdMissing(reply); else if (strcmp(arg, "verify") == 0) cmdVerify(reply); else if (strncmp(arg, "apply", 5) == 0) { const char *a = arg + 5; while (*a == ' ') a++; cmdApply(sender_timestamp, a, reply); } else if (strcmp(arg, "abort") == 0) { _state = IDLE; _apply_at = 0; strcpy(reply, "OK"); } else if (strcmp(arg, "bl") == 0) cmdBootloader(reply); else strcpy(reply, "ERR: fw status|begin|w|missing|verify|apply|abort|bl"); return true; } #else bool FwUpdate::handleCommand(uint32_t, const char *command, char *reply) { if (memcmp(command, "fw", 2) != 0 || (command[2] != 0 && command[2] != ' ')) return false; strcpy(reply, "ERR: not an nRF52 board"); return true; } void FwUpdate::loop() {} #endif