Preserve Full USB packet logging and verify packaged firmware
This commit is contained in:
1 parent
d07537f6aa
commit
7c65314266
10 files changed
+508
-6
No files matched your search
@@ -595,6 +595,64 @@ while IFS= read -r env_name; do
|
||||
fi
|
||||
done < <(resolve_companion_firmwares)
|
||||
|
||||
# Full logging is a compiled and packaged contract, including when a legacy
|
||||
# observer recipe or DISABLE_DEBUG injects an inherited packet-logging -U.
|
||||
verify_full_logging_contract() {
|
||||
local env_name=$1
|
||||
local ESP32_FULL_BUILD=$2
|
||||
local PACKET_LOGGING_OVERRIDE=$3
|
||||
local DISABLE_DEBUG=$4
|
||||
local expected=$5
|
||||
local combined=$6
|
||||
local MESHDEBUG_OVERRIDE=off MQTT_BRIDGE_OVERRIDE="" MQTT_DEBUG_OVERRIDE=""
|
||||
local FIRMWARE_FILENAME_INFIX=""
|
||||
local BUILD_PROFILE_FOR_TARGET=full
|
||||
local -a BUILD_CAPABILITIES=() BUILD_EXPECTATIONS=() BUILD_APPLICATION_EXPECTATIONS=()
|
||||
local expectations
|
||||
|
||||
configure_unified_full_infrastructure_output "$env_name"
|
||||
if requires_full_usb_packet_logging "$env_name"; then
|
||||
[ "$expected" = yes ] || fail "$env_name unexpectedly requires USB logging"
|
||||
else
|
||||
[ "$expected" = no ] || fail "$env_name omitted its Full USB logging contract"
|
||||
fi
|
||||
declare_build_capability_contract "$env_name" "${PIO_ENV_PLATFORM_BY_NAME[$env_name]}"
|
||||
expectations=" ${BUILD_APPLICATION_EXPECTATIONS[*]} "
|
||||
if [ "$expected" = yes ]; then
|
||||
[[ "$expectations" == *"logging.usb.packets="* ]] \
|
||||
|| fail "$env_name does not check packet logging in the packaged application"
|
||||
[[ "$expectations" == *"logging.usb.control="* ]] \
|
||||
|| fail "$env_name does not check working USB logging controls"
|
||||
else
|
||||
[[ "$expectations" != *"logging.usb."* ]] \
|
||||
|| fail "$env_name promises logging after it was explicitly omitted"
|
||||
fi
|
||||
if [ "$combined" = yes ]; then
|
||||
[[ "$expectations" == *"logging.usb.output=OK - logging.output %s (saved)"* ]] \
|
||||
|| fail "$env_name does not verify its combined output selector"
|
||||
else
|
||||
[[ "$expectations" != *"logging.usb.output="* ]] \
|
||||
|| fail "$env_name unexpectedly promises a combined output selector"
|
||||
fi
|
||||
}
|
||||
|
||||
for logging_target in Station_G2_repeater_observer_mqtt \
|
||||
Station_G2_room_server_observer_mqtt heltec_v4_repeater_observer_mqtt \
|
||||
heltec_v4_r8_room_server_observer_mqtt; do
|
||||
verify_full_logging_contract "$logging_target" 1 "" 0 yes yes
|
||||
verify_full_logging_contract "$logging_target" 1 off 1 yes yes
|
||||
verify_full_logging_contract "$logging_target" 0 "" 0 no no
|
||||
done
|
||||
for logging_target in Station_G2_repeater_bridge_espnow heltec_v4_sensor; do
|
||||
verify_full_logging_contract "$logging_target" 1 "" 0 yes no
|
||||
verify_full_logging_contract "$logging_target" 1 on 1 yes no
|
||||
verify_full_logging_contract "$logging_target" 1 off 0 no no
|
||||
verify_full_logging_contract "$logging_target" 1 "" 1 no no
|
||||
done
|
||||
for logging_target in Station_G2_companion_radio_full RAK_4631_companion_radio_full; do
|
||||
verify_full_logging_contract "$logging_target" 0 off 1 yes no
|
||||
done
|
||||
|
||||
# Synthetic inventory: one ESP32 target qualified for expanded Full and one
|
||||
# nRF52 target which must attempt complete LoRa OTA in its current partition.
|
||||
SUPPORTED_PIO_ENVS=(
|
||||
|
||||
@@ -75,6 +75,60 @@ class FirmwareCapabilityCheckerTest(unittest.TestCase):
|
||||
self.assertFalse(manifest["verified"])
|
||||
self.assertIn("promised", result.stderr)
|
||||
|
||||
def test_application_gate_rejects_elf_only_logging_evidence(self):
|
||||
# Debug/symbol strings in the ELF must not qualify an image whose
|
||||
# uploadable binary has had the implementation compiled or linked out.
|
||||
result, manifest = self.run_checker(
|
||||
b"USB logger", "--expect-application", "logging.usb.packets=USB logger",
|
||||
artifacts={"firmware-bin": b"no logging implementation"})
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertFalse(manifest["verified"])
|
||||
self.assertIn("packaged application", result.stderr)
|
||||
|
||||
def test_application_gate_accepts_packaged_code_without_elf_marker(self):
|
||||
result, manifest = self.run_checker(
|
||||
b"stripped symbols", "--expect-application", "logging.usb.packets=USB logger",
|
||||
artifacts={"firmware-bin": b"USB logger"})
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue(manifest["verified"])
|
||||
self.assertIn("logging.usb.packets", manifest["capabilities"])
|
||||
self.assertEqual(manifest["verification"][0]["source"], "packaged application")
|
||||
|
||||
def test_full_logging_requires_packet_code_as_well_as_the_setting(self):
|
||||
expectations = ["--expect-application", "logging.usb.control=usb.logging",
|
||||
"--expect-application", "logging.usb.packets=packet logger"]
|
||||
for body, accepted in [(b"usb.logging debug logger", False),
|
||||
(b"packet logger", False),
|
||||
(b"usb.logging packet logger", True)]:
|
||||
with self.subTest(body=body):
|
||||
result, manifest = self.run_checker(b"", *expectations,
|
||||
artifacts={"firmware-bin": body})
|
||||
self.assertEqual(result.returncode, 0 if accepted else 1, result.stderr)
|
||||
self.assertEqual(manifest["verified"], accepted)
|
||||
|
||||
def test_application_checks_require_the_installable_artifact(self):
|
||||
result, manifest = self.run_checker(
|
||||
b"USB logger", "--expect-application", "logging.usb.packets=USB logger")
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertFalse(manifest["verified"])
|
||||
self.assertIn("require --firmware-bin or --dfu-package", result.stderr)
|
||||
|
||||
def test_nrf52_logging_is_checked_inside_the_dfu_application(self):
|
||||
for body, accepted in [(b"packet logger", True), (b"no logger", False)]:
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, "w") as package:
|
||||
package.writestr("manifest.json", json.dumps({"manifest": {
|
||||
"application": {"bin_file": "app.bin"}}}))
|
||||
package.writestr("app.bin", body)
|
||||
# A marker elsewhere in the ZIP is not proof of running code.
|
||||
package.writestr("notes.txt", "packet logger")
|
||||
result, manifest = self.run_checker(
|
||||
b"packet logger", "--platform", "NRF52_PLATFORM",
|
||||
"--expect-application", "logging.usb.packets=packet logger",
|
||||
artifacts={"dfu-package": archive.getvalue()})
|
||||
self.assertEqual(result.returncode, 0 if accepted else 1, result.stderr)
|
||||
self.assertEqual(manifest["verified"], accepted)
|
||||
|
||||
def ota_artifacts(self, *, second_slot=True, image_size=48):
|
||||
def entry(kind, subtype, address, size):
|
||||
return struct.pack("<HBBII16sI", 0x50AA, kind, subtype,
|
||||
|
||||
@@ -37,12 +37,13 @@ def flatten(values):
|
||||
return [token for value in values for token in shlex.split(str(value))]
|
||||
|
||||
|
||||
def apply_policy(flags, overlay, *, full=True, companion=True):
|
||||
def apply_policy(flags, overlay, *, full=True, companion=True, logging=False):
|
||||
environment = FakeEnvironment(flags)
|
||||
output = io.StringIO()
|
||||
variables = {
|
||||
"MESHCORE_ESP32_FULL_BUILD": "1" if full else "0",
|
||||
"MESHCORE_COMPANION_RADIO_FULL": "1" if companion else "0",
|
||||
"MESHCORE_REQUIRE_PACKET_LOGGING": "1" if logging else "0",
|
||||
"PLATFORMIO_BUILD_FLAGS": overlay,
|
||||
}
|
||||
with mock.patch.dict(os.environ, variables, clear=False):
|
||||
@@ -58,6 +59,33 @@ def apply_policy(flags, overlay, *, full=True, companion=True):
|
||||
|
||||
|
||||
class FullBuildFlagDedupTest(unittest.TestCase):
|
||||
def test_required_packet_logging_removes_all_conflicting_forms(self):
|
||||
for disable in ["-UMESH_PACKET_LOGGING", "-U MESH_PACKET_LOGGING",
|
||||
"-DMESH_PACKET_LOGGING=0", "-D MESH_PACKET_LOGGING=0"]:
|
||||
for before in (True, False):
|
||||
with self.subTest(disable=disable, before=before):
|
||||
enable = "-DMESH_PACKET_LOGGING=1"
|
||||
flags = [disable, enable] if before else [enable, disable]
|
||||
env, _, _ = apply_policy(flags, enable, logging=True)
|
||||
self.assertEqual(flatten(env.values["BUILD_FLAGS"]), [enable])
|
||||
|
||||
def test_required_logging_preserves_other_macros_and_quoted_inputs(self):
|
||||
flags = ["-UMESH_DEBUG -D MESH_PACKET_LOGGING_COMPACT=0 "
|
||||
"-I 'include path' -include 'forced header.h' "
|
||||
"-D LABEL='\"USB logging Full\"' -U MESH_PACKET_LOGGING"]
|
||||
env, _, ns = apply_policy(flags, "", logging=True)
|
||||
actual = ns["logical_flags"](env.values["BUILD_FLAGS"])
|
||||
expected = ns["logical_flags"](flags)[:-1] + [("-DMESH_PACKET_LOGGING=1",)]
|
||||
self.assertEqual(actual, expected)
|
||||
|
||||
def test_without_logging_contract_explicit_disables_remain(self):
|
||||
flags = ["-UMESH_PACKET_LOGGING -DMESH_PACKET_LOGGING=0"]
|
||||
env, _, _ = apply_policy(flags, "", logging=False)
|
||||
self.assertEqual(env.values["BUILD_FLAGS"], flags)
|
||||
# A stale external variable cannot turn a standard image into Full.
|
||||
env, _, _ = apply_policy(flags, "", full=False, logging=True)
|
||||
self.assertEqual(env.values["BUILD_FLAGS"], flags)
|
||||
|
||||
def test_repeated_extends_overlay_keeps_last_exact_occurrence(self):
|
||||
overlay = (
|
||||
"-DFEATURE=1 -UFEATURE -DFEATURE=1 "
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise real PlatformIO flag ordering through a host compiler (no board).
|
||||
|
||||
Requires PlatformIO and its tool-scons package, installed by the native tests
|
||||
in CI. This deliberately uses ProcessFlags, not a reimplementation of it.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
try:
|
||||
import SCons.Script
|
||||
except ImportError:
|
||||
core = Path(os.environ.get("PLATFORMIO_CORE_DIR", Path.home() / ".platformio"))
|
||||
for path in sorted((core / "packages" / "tool-scons").glob("scons-local-*"), reverse=True):
|
||||
sys.path.insert(0, str(path))
|
||||
import SCons.Script
|
||||
|
||||
from platformio.builder.tools.piobuild import ParseFlagsExtended, ProcessFlags
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPT = ROOT / "scripts" / "deduplicate_full_build_flags.py"
|
||||
SOURCE = """
|
||||
#if !defined(MESH_PACKET_LOGGING) || MESH_PACKET_LOGGING != 1
|
||||
#error Full image lost USB packet logging
|
||||
#endif
|
||||
#if defined(MESH_DEBUG)
|
||||
#error Packet logging must not reenable disabled debug logging
|
||||
#endif
|
||||
int logging_contract(void) { return MESH_PACKET_LOGGING; }
|
||||
"""
|
||||
|
||||
|
||||
class FullLoggingCompilerTest(unittest.TestCase):
|
||||
def compile(self, flags, *, required):
|
||||
self.assertIsNotNone(shutil.which("gcc"), "Install gcc to run the compiler regression")
|
||||
env = SCons.Script.Environment(tools=["gcc"], BUILD_FLAGS=flags)
|
||||
env.AddMethod(ParseFlagsExtended)
|
||||
env.AddMethod(ProcessFlags)
|
||||
with mock.patch.dict(os.environ, {
|
||||
"MESHCORE_ESP32_FULL_BUILD": "1",
|
||||
"MESHCORE_COMPANION_RADIO_FULL": "0",
|
||||
"MESHCORE_REQUIRE_PACKET_LOGGING": "1" if required else "0",
|
||||
"PLATFORMIO_BUILD_FLAGS": "-DMESH_PACKET_LOGGING=1",
|
||||
}), contextlib.redirect_stdout(io.StringIO()):
|
||||
runpy.run_path(str(SCRIPT), init_globals={"Import": lambda _: None, "env": env})
|
||||
env.ProcessFlags(env["BUILD_FLAGS"])
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source, target = Path(directory) / "probe.c", Path(directory) / "probe.o"
|
||||
source.write_text(SOURCE)
|
||||
command = env.subst_list("$CCCOM", source=env.File(str(source)), target=env.File(str(target)))[0]
|
||||
result = subprocess.run([str(item) for item in command], text=True, capture_output=True)
|
||||
return result, [str(item) for item in command]
|
||||
|
||||
def test_reproduces_the_published_station_g2_failure(self):
|
||||
result, command = self.compile(
|
||||
["-UMESH_DEBUG -UMESH_PACKET_LOGGING", "-DMESH_PACKET_LOGGING=1"], required=False)
|
||||
self.assertGreater(command.index("-UMESH_PACKET_LOGGING"), command.index("-DMESH_PACKET_LOGGING=1"))
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("Full image lost USB packet logging", result.stderr)
|
||||
|
||||
def test_full_contract_survives_real_platformio_preprocessing(self):
|
||||
for disable in ("-UMESH_PACKET_LOGGING", "-U MESH_PACKET_LOGGING",
|
||||
"-DMESH_PACKET_LOGGING=0", "-D MESH_PACKET_LOGGING=0"):
|
||||
for before in (True, False):
|
||||
with self.subTest(disable=disable, before=before):
|
||||
flags = ["-DMESH_PACKET_LOGGING=1", "-UMESH_DEBUG", disable]
|
||||
if before:
|
||||
flags.reverse()
|
||||
result, _ = self.compile(flags, required=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A previously passing RAM/capability manifest cannot bypass a new contract."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class FullLoggingResumeTest(unittest.TestCase):
|
||||
def check_cached(self, source, *, packet_present=True, logging_required=True):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)
|
||||
stem = "Station_G2_repeater_observer_mqtt-full-usb-wifi-ota-vtest"
|
||||
checks = [{"capability": "logging.usb.control", "evidence": "USB control", "present": True},
|
||||
{"capability": "logging.usb.packets", "evidence": "packet logger", "present": packet_present}]
|
||||
if source is not None:
|
||||
for check in checks:
|
||||
check["source"] = source
|
||||
manifest = {"schema_version": 2, "verified": True, "verification": checks}
|
||||
(directory / (stem + ".capabilities.json")).write_text(json.dumps(manifest))
|
||||
(directory / (stem + ".bin")).write_bytes(b"firmware")
|
||||
(directory / (stem + "-merged.bin")).write_bytes(b"merged firmware")
|
||||
proof = dict(schema_version=1, passed=True, available_internal_bytes=80000,
|
||||
required_heap_bytes=50000, largest_internal_region_bytes=80000,
|
||||
required_contiguous_bytes=5120, elf_sha256="a" * 64,
|
||||
files={p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in directory.iterdir()})
|
||||
(directory / (stem + ".memory.json")).write_text(json.dumps(proof))
|
||||
command = '''
|
||||
source build.sh
|
||||
OUTPUT_DIR="$1"
|
||||
BUILD_APPLICATION_EXPECTATIONS=()
|
||||
if [ "$3" = yes ]; then
|
||||
BUILD_APPLICATION_EXPECTATIONS=('logging.usb.control=USB control' 'logging.usb.packets=packet logger')
|
||||
fi
|
||||
build_artifacts_exist ESP32_PLATFORM "$2"
|
||||
'''
|
||||
return subprocess.run(["bash", "-c", command, "resume-test", str(directory), stem,
|
||||
"yes" if logging_required else "no"], cwd=ROOT,
|
||||
text=True, capture_output=True)
|
||||
|
||||
def test_old_and_elf_only_manifests_force_a_rebuild(self):
|
||||
for source in (None, "linked image"):
|
||||
with self.subTest(source=source):
|
||||
result = self.check_cached(source)
|
||||
self.assertNotEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
def test_verified_packaged_logger_can_resume(self):
|
||||
result = self.check_cached("packaged application")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_missing_packet_logger_cannot_resume(self):
|
||||
result = self.check_cached("packaged application", packet_present=False)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
|
||||
def test_other_profiles_keep_their_existing_resume_policy(self):
|
||||
result = self.check_cached(None, logging_required=False)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user