# SPDX-License-Identifier: MIT # SCons script: `Import` and `env` are SCons builtins (as in build_version.py). # ruff: noqa: F821 # mypy: disable-error-code="name-defined" """PlatformIO extra script: run src/helpers/FwPatch.cpp from RAM (nRF52 envs). [nrf52_base] extra_scripts = ... pre:tools/ota_ramlib.py `fw apply` with a delta package rewrites the flash the firmware executes from, so the patch applier (FwPatch.cpp with the vendored detools + heatshrink inside) must not have a single instruction or constant table in flash. The vendored code stays unmodified; instead the compiled object is post-processed: * every .text*/.rodata* section is renamed to .data.fwp* -- the nRF52 linker script collects .data* into RAM and the startup code copies it there, exactly like the RAMFUNC attribute in FwUpdate.cpp does for single functions; * memcpy/memset/memmove references become fwp_memcpy/... (RAM copies defined in FwPatch.cpp), because the compiler emits those calls on its own; * the RAM copies carry optimize("no-tree-loop-distribute-patterns") in FwPatch.cpp itself, otherwise GCC turns their bodies back into memcpy calls. It runs as a pre-action of the LINK, on whatever FwPatch.cpp.o goes into it, and is idempotent. A post-action of the compile (the first version) silently did not run when the object was rebuilt because it was missing rather than because the source changed -- and the image then had its applier in flash. tools/ota_check_ramfunc.sh verifies the result on the linked ELF. """ import subprocess import sys if __name__ == "__main__": # run by hand: just the help print(__doc__) sys.exit(0) Import("env") # SCons builtins, see the ruff exemption at the top TARGET = "helpers/FwPatch.cpp" REDEFINE = ("memcpy", "memset", "memmove") def _ramify(target, source, env): obj = target[0].get_abspath() objcopy = env.subst("$OBJCOPY") objdump = objcopy[: -len("objcopy")] + "objdump" heads = subprocess.run( [objdump, "-h", obj], check=True, capture_output=True, text=True ).stdout args = [] for line in heads.splitlines(): parts = line.split() if len(parts) >= 2 and parts[0].isdigit(): name = parts[1] if name.startswith((".text", ".rodata")): args += ["--rename-section", f"{name}=.data.fwp{name}"] for sym in REDEFINE: args += ["--redefine-sym", f"{sym}=fwp_{sym}"] subprocess.run([objcopy, *args, obj], check=True) print( f"ota_ramlib: {len(args) // 2 - len(REDEFINE)} sections of FwPatch.cpp moved to RAM" ) def _prelink(target, source, env): hits = [ n for n in source if n.get_path().replace("\\", "/").endswith(TARGET + ".o") ] for obj in hits: _ramify([obj], [], env) if not hits: print("ota_ramlib: FwPatch.cpp.o not in this link (no FwUpdate here)") env.AddPreAction("$BUILD_DIR/${PROGNAME}.elf", _prelink)