Update MeshCore features and OTA layout handling
This commit is contained in:
1 parent
0c4619bcc3
commit
47993d178e
74 files changed
+1696
-1169
No files matched your search
+87
-2
@@ -54,10 +54,25 @@ APPROVAL_YES = b"APRV" # 41 50 52 56 = approved
|
||||
|
||||
DEFAULT_BLOCK_SIZE = 1024
|
||||
|
||||
# nRF52840 OTAFIX's detools in-place workspace. A firmware image (including EndF) must fit here, and
|
||||
# the staged .mota must begin above it. Keep in sync with OtaFlashLayout_nrf52.h / the OTAFIX bootloader.
|
||||
# Conservative fallback for firmware built before the layout record below existed. Keep in sync with
|
||||
# OtaFlashLayout_nrf52.h and motatool's format.rs.
|
||||
NRF52_INPLACE_MEMORY = 0x00098000
|
||||
|
||||
NRF52_APP_BASE_S140_V6 = 0x00026000
|
||||
NRF52_APP_BASE_S140_V7 = 0x00027000
|
||||
NRF52_EXTRAFS_START = 0x000D4000
|
||||
NRF52_APP_END = 0x000ED000
|
||||
NRF52_FLASH_PAGE = 4096
|
||||
|
||||
# A validated nRF52 firmware carries this record immediately before EndF. It lets an offline packager
|
||||
# derive the actual app base and staging ceiling from the built artifact, without a board-name allowlist.
|
||||
# magic(8) | version(1) | flags(1) | record_len(2) | app_base(4) | linked_app_end(4) | stage_ceiling(4)
|
||||
NRF52_LAYOUT_MAGIC = b"mOTALay1"
|
||||
NRF52_LAYOUT_VERSION = 1
|
||||
NRF52_LAYOUT_LEN = 24
|
||||
NRF52_LAYOUT_FLAG_SD = 0x01
|
||||
NRF52_LAYOUT_FLAG_INTERNAL_EXTRAFS = 0x02
|
||||
|
||||
# MeshTower V2's SD-backed OTA target keeps the staged .mota off-chip, so the application may use the
|
||||
# complete S140 v6 application region up to InternalFS instead of leaving room for internal staging.
|
||||
# This is deliberately target-specific: other nRF52 OTA builds still need NRF52_INPLACE_MEMORY above.
|
||||
@@ -154,6 +169,76 @@ class FwIdent:
|
||||
hw_id: str = "" # readable hardware tag (brick-safety), e.g. "RAK4631"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Nrf52Layout:
|
||||
"""Resolved flash geometry embedded immediately before an nRF52 firmware's EndF trailer."""
|
||||
app_base: int
|
||||
linked_app_end: int
|
||||
stage_ceiling: int
|
||||
flags: int = 0
|
||||
|
||||
@property
|
||||
def sd_backed(self) -> bool:
|
||||
return bool(self.flags & NRF52_LAYOUT_FLAG_SD)
|
||||
|
||||
|
||||
def nrf52_stage_ceiling_for_layout(linked_app_end: int, uses_internal_extrafs: bool) -> int:
|
||||
"""Select a safe staging ceiling from linker geometry and actual secondary-storage type."""
|
||||
if uses_internal_extrafs:
|
||||
return NRF52_EXTRAFS_START
|
||||
if linked_app_end in (NRF52_EXTRAFS_START, NRF52_APP_END):
|
||||
return NRF52_APP_END
|
||||
return NRF52_EXTRAFS_START
|
||||
|
||||
|
||||
def build_nrf52_layout(layout: Nrf52Layout) -> bytes:
|
||||
if layout.app_base not in (NRF52_APP_BASE_S140_V6, NRF52_APP_BASE_S140_V7):
|
||||
raise ValueError(f"unsupported nRF52 app base 0x{layout.app_base:X}")
|
||||
if layout.linked_app_end not in (NRF52_EXTRAFS_START, NRF52_APP_END):
|
||||
raise ValueError(f"unsupported nRF52 linked app end 0x{layout.linked_app_end:X}")
|
||||
if layout.stage_ceiling not in (NRF52_EXTRAFS_START, NRF52_APP_END):
|
||||
raise ValueError(f"unsupported nRF52 staging ceiling 0x{layout.stage_ceiling:X}")
|
||||
if not (layout.app_base < layout.linked_app_end <= NRF52_APP_END):
|
||||
raise ValueError("invalid nRF52 app region")
|
||||
if layout.flags & ~(NRF52_LAYOUT_FLAG_SD | NRF52_LAYOUT_FLAG_INTERNAL_EXTRAFS):
|
||||
raise ValueError(f"unsupported nRF52 layout flags 0x{layout.flags:X}")
|
||||
expected_ceiling = (NRF52_APP_END if layout.sd_backed else
|
||||
nrf52_stage_ceiling_for_layout(
|
||||
layout.linked_app_end,
|
||||
bool(layout.flags & NRF52_LAYOUT_FLAG_INTERNAL_EXTRAFS)))
|
||||
if layout.stage_ceiling != expected_ceiling:
|
||||
raise ValueError(f"nRF52 staging ceiling 0x{layout.stage_ceiling:X} is inconsistent with layout flags")
|
||||
return struct.pack("<8sBBHIII", NRF52_LAYOUT_MAGIC, NRF52_LAYOUT_VERSION, layout.flags,
|
||||
NRF52_LAYOUT_LEN, layout.app_base, layout.linked_app_end,
|
||||
layout.stage_ceiling)
|
||||
|
||||
|
||||
def ensure_nrf52_layout(body: bytes, layout: Nrf52Layout) -> bytes:
|
||||
"""Append or replace the fixed layout record on an EndF-free firmware body."""
|
||||
record = build_nrf52_layout(layout)
|
||||
if len(body) >= NRF52_LAYOUT_LEN and body[-NRF52_LAYOUT_LEN:-NRF52_LAYOUT_LEN + 8] == NRF52_LAYOUT_MAGIC:
|
||||
body = body[:-NRF52_LAYOUT_LEN]
|
||||
return body + record
|
||||
|
||||
|
||||
def parse_nrf52_layout(image: bytes) -> Optional[Nrf52Layout]:
|
||||
"""Read a validated layout record from an EndF-trailed firmware; old firmware returns None."""
|
||||
if not has_endf(image) or len(image) < ENDF_LEN + NRF52_LAYOUT_LEN:
|
||||
return None
|
||||
record = image[-ENDF_LEN - NRF52_LAYOUT_LEN:-ENDF_LEN]
|
||||
try:
|
||||
magic, version, flags, record_len, app_base, linked_end, ceiling = struct.unpack(
|
||||
"<8sBBHIII", record)
|
||||
if magic != NRF52_LAYOUT_MAGIC or version != NRF52_LAYOUT_VERSION or record_len != NRF52_LAYOUT_LEN:
|
||||
return None
|
||||
layout = Nrf52Layout(app_base, linked_end, ceiling, flags)
|
||||
if build_nrf52_layout(layout) != record:
|
||||
return None
|
||||
return layout
|
||||
except (ValueError, struct.error):
|
||||
return None
|
||||
|
||||
|
||||
def build_endf(body: bytes, ident: Optional["FwIdent"] = None) -> bytes:
|
||||
"""The fixed 56-byte EndF trailer for a firmware BODY (identity zero-filled if not given)."""
|
||||
ident = ident or FwIdent()
|
||||
|
||||
+45
-20
@@ -66,6 +66,24 @@ def _board_maximum_size(build_env):
|
||||
return None
|
||||
|
||||
|
||||
def _source_filter_text():
|
||||
"""Resolved source-filter text for detecting code that is actually part of this environment."""
|
||||
srcf = ""
|
||||
for getter in (lambda: env.GetProjectOption("build_src_filter", ""), # noqa: F821
|
||||
lambda: env.GetProjectOption("src_filter", ""), # noqa: F821
|
||||
lambda: env.get("SRC_FILTER", "")): # noqa: F821
|
||||
try:
|
||||
value = getter()
|
||||
srcf += " " + (" ".join(map(str, value)) if isinstance(value, (list, tuple)) else str(value))
|
||||
except Exception:
|
||||
pass
|
||||
return srcf
|
||||
|
||||
|
||||
def _builds_companion_radio() -> bool:
|
||||
return "examples/companion_radio" in _source_filter_text().replace("\\", "/")
|
||||
|
||||
|
||||
def _version_from_headers():
|
||||
"""FIRMWARE_VERSION is a header ``#define`` in the example (upstream MeshCore convention), not a -D, so
|
||||
_cppdef() can't see it and the EndF version would otherwise default to 0. Read it from the source WITHOUT
|
||||
@@ -90,15 +108,7 @@ def _version_from_headers():
|
||||
return vals
|
||||
|
||||
# 1) restrict to the example(s) this env compiles (build_src_filter -> examples/<name>)
|
||||
srcf = ""
|
||||
for getter in (lambda: env.GetProjectOption("build_src_filter", ""), # noqa: F821
|
||||
lambda: env.GetProjectOption("src_filter", ""), # noqa: F821
|
||||
lambda: env.get("SRC_FILTER", "")): # noqa: F821
|
||||
try:
|
||||
v = getter()
|
||||
srcf += " " + (" ".join(map(str, v)) if isinstance(v, (list, tuple)) else str(v))
|
||||
except Exception:
|
||||
pass
|
||||
srcf = _source_filter_text()
|
||||
ex_dirs = set(re.findall(r"examples[/\\]([A-Za-z0-9_]+)", srcf))
|
||||
hdrs = []
|
||||
for d in ex_dirs:
|
||||
@@ -155,33 +165,48 @@ def _append_endf_hex(source, target, env): # Intel-HEX path (nRF52: app f
|
||||
if not segs:
|
||||
print("EndF: empty .hex, skipping"); return
|
||||
app_start, app_end = segs[0] # first (lowest) segment = the application image
|
||||
body = bytes(ih.tobinarray(start=app_start, size=app_end - app_start))
|
||||
raw_body = bytes(ih.tobinarray(start=app_start, size=app_end - app_start))
|
||||
if ml.has_endf(raw_body):
|
||||
print(f"EndF: already present in {os.path.basename(path)} (no change)"); return
|
||||
|
||||
app_region_size = _board_maximum_size(env)
|
||||
if app_region_size is None:
|
||||
raise RuntimeError("nRF52 linked application region is unavailable")
|
||||
linked_app_end = app_start + app_region_size
|
||||
internal_extrafs = (_cppdef("EXTRAFS") is not None and _cppdef("QSPIFLASH") is None
|
||||
and _builds_companion_radio())
|
||||
sd_backed = _cppdef("OTA_SD_STORE") is not None
|
||||
stage_ceiling = (ml.NRF52_APP_END if sd_backed else
|
||||
ml.nrf52_stage_ceiling_for_layout(linked_app_end, internal_extrafs))
|
||||
layout_flags = ((ml.NRF52_LAYOUT_FLAG_SD if sd_backed else 0) |
|
||||
(ml.NRF52_LAYOUT_FLAG_INTERNAL_EXTRAFS if internal_extrafs else 0))
|
||||
layout = ml.Nrf52Layout(app_start, linked_app_end, stage_ceiling, layout_flags)
|
||||
body = ml.ensure_nrf52_layout(raw_body, layout)
|
||||
ident = _firmware_ident()
|
||||
out, h8 = ml.ensure_endf(body, ident)
|
||||
sd_backed = _cppdef("OTA_SD_STORE") is not None
|
||||
seeder_only = _cppdef("OTA_SEEDER_ONLY") is not None
|
||||
if seeder_only:
|
||||
# A source-only full Companion never stages or applies an update to
|
||||
# itself, so it does not need to fit in OTAFIX's in-place workspace.
|
||||
# It must still fit the board/env's resolved flash application region.
|
||||
image_limit = _board_maximum_size(env)
|
||||
if image_limit is None:
|
||||
raise RuntimeError("nRF52 seeder-only application limit is unavailable")
|
||||
image_limit = app_region_size
|
||||
limit_name = "application"
|
||||
else:
|
||||
image_limit = ml.NRF52_SD_APP_MEMORY if sd_backed else ml.NRF52_INPLACE_MEMORY
|
||||
limit_name = "SD application" if sd_backed else "in-place"
|
||||
# Dynamic in-place patches carry their own memory_size and are checked against the staged
|
||||
# container before approval. The firmware itself only needs to remain inside both its linked
|
||||
# application region and the selected filesystem-safe ceiling.
|
||||
image_limit = min(linked_app_end, stage_ceiling) - app_start
|
||||
limit_name = "nRF52 OTA application"
|
||||
if image_limit is not None and len(out) > image_limit:
|
||||
raise RuntimeError(f"nRF52 OTA image is {len(out)} bytes; {limit_name} limit is "
|
||||
f"{image_limit} bytes")
|
||||
if len(out) == len(body):
|
||||
print(f"EndF: already present in {os.path.basename(path)} (no change)"); return
|
||||
trailer = out[len(body):] # the EndF trailer (56 bytes with identity)
|
||||
for i, b in enumerate(trailer):
|
||||
suffix = out[len(raw_body):] # layout record + EndF identity trailer
|
||||
for i, b in enumerate(suffix):
|
||||
ih[app_end + i] = b # write it right after the app's last byte
|
||||
ih.write_hex_file(path)
|
||||
print(f"EndF: appended to {os.path.basename(path)} at 0x{app_end:X} "
|
||||
f"(app=0x{app_start:X}.. body_len={len(body)} body_hash={h8.hex()} "
|
||||
f"stage=0x{stage_ceiling:X} "
|
||||
f"target={ident.target_id:#010x} hw='{ident.hw_id}' fw={ident.fw_version:#010x})")
|
||||
|
||||
|
||||
|
||||
@@ -105,6 +105,38 @@ def test_endf_identity():
|
||||
assert len(z) == len(body) + ml.ENDF_LEN and ml.parse_endf_ident(z) == ml.FwIdent(0, 0, "")
|
||||
|
||||
|
||||
def test_nrf52_layout_record_roundtrip_and_policy():
|
||||
assert (ml.nrf52_stage_ceiling_for_layout(ml.NRF52_APP_END, True)
|
||||
== ml.NRF52_EXTRAFS_START)
|
||||
assert ml.nrf52_stage_ceiling_for_layout(ml.NRF52_APP_END, False) == ml.NRF52_APP_END
|
||||
assert (ml.nrf52_stage_ceiling_for_layout(ml.NRF52_EXTRAFS_START, True)
|
||||
== ml.NRF52_EXTRAFS_START)
|
||||
assert (ml.nrf52_stage_ceiling_for_layout(ml.NRF52_EXTRAFS_START, False)
|
||||
== ml.NRF52_APP_END)
|
||||
assert ml.nrf52_stage_ceiling_for_layout(0xE0000, False) == ml.NRF52_EXTRAFS_START
|
||||
|
||||
layout = ml.Nrf52Layout(ml.NRF52_APP_BASE_S140_V7, ml.NRF52_EXTRAFS_START,
|
||||
ml.NRF52_APP_END, 0)
|
||||
body = ml.ensure_nrf52_layout(_fw(4, 2048), layout)
|
||||
image, _ = ml.ensure_endf(body, ml.FwIdent(hw_id="Xiao_nrf52"))
|
||||
assert ml.parse_nrf52_layout(image) == layout
|
||||
# Re-running the record step replaces the tail instead of duplicating it.
|
||||
assert ml.ensure_nrf52_layout(body, layout) == body
|
||||
assert ml.parse_nrf52_layout(ml.ensure_endf(_fw(5, 2048))[0]) is None
|
||||
internal = ml.Nrf52Layout(
|
||||
ml.NRF52_APP_BASE_S140_V7, ml.NRF52_EXTRAFS_START,
|
||||
ml.NRF52_EXTRAFS_START, ml.NRF52_LAYOUT_FLAG_INTERNAL_EXTRAFS)
|
||||
internal_image, _ = ml.ensure_endf(ml.ensure_nrf52_layout(_fw(6, 2048), internal))
|
||||
assert ml.parse_nrf52_layout(internal_image) == internal
|
||||
try:
|
||||
ml.build_nrf52_layout(ml.Nrf52Layout(
|
||||
ml.NRF52_APP_BASE_S140_V7, ml.NRF52_EXTRAFS_START,
|
||||
ml.NRF52_EXTRAFS_START, 0))
|
||||
assert False, "inconsistent layout record accepted"
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
# --- merkle ----------------------------------------------------------------
|
||||
|
||||
def test_merkle_single_block():
|
||||
|
||||
Reference in new issue
Block a user