Files
noahandClaude Opus 4.8 8d48e488bd a113d (Amlogic AXG/S21 Pro): .afw producer profile + double brick gate
Add the S21 Pro-class Amlogic A113D/AXG control board to the .afw producer
and the CI brick-prevention gate, matching the Zynq-7010 treatment.

- ci/afw_boards.py: a113d producer profile (arm64, preserve, buildable). Maps
  the 7-mtd layout, names nvdata (mtd6) the only image-bearing partition, and
  stages three images vmlinux.bin/devicetree.dtb/uramdisk.image.gz
  (arm64-image/fdt/uimage) into it.
- ci/afw_manifest.py: validate_a113d enforces exactly those three images, the
  formats, per-image ceilings, total <= nvdata usable, and that no
  bootloader/spl/fip/tpl member is present and no non-nvdata partition carries
  an image.
- ci/check-afw.py: the independent checker re-validates the produced bundle
  (arm64, preserve, no FIP member, three named images with formats/ceilings,
  total <= nvdata, mtd0-5 carry no image) and knows the arm64 Image magic.
- ci/test-afw.py: a113d bundle passes and installs all three into nvdata;
  non-arm64 kernel, oversize kernel, an added FIP member, and a preserved mtd
  made to carry an image are each refused.

All 37 afw tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
2026-11-06 21:01:56 -06:00

875 lines
33 KiB
Python
Executable File

#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Offline tests for the .afw producer and the CI brick-prevention gate."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tarfile
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
MAKE = ROOT / "ci" / "make-afw.sh"
CHECK = ROOT / "ci" / "check-afw.py"
REVISION = "0" * 40
P1 = 16 * 1024 * 1024
def run(command, **kwargs):
return subprocess.run(command, text=True, capture_output=True, **kwargs)
def fixture_input(directory):
directory.mkdir(parents=True, exist_ok=True)
image = bytearray(4096)
image[0x38:0x3C] = b"ARMd"
image[0x08:0x10] = (0x200000).to_bytes(8, "little")
(directory / "Image").write_bytes(image)
dtb = bytearray(1024)
dtb[0:4] = b"\xd0\x0d\xfe\xed"
(directory / "cv-alkane.dtb").write_bytes(dtb)
(directory / "rootfs.cpio.gz").write_bytes(b"\x1f\x8b" + b"rootfs" + b"\0" * 64)
fit = bytearray(P1)
fit[0:4] = b"\xd0\x0d\xfe\xed"
marker = b"config@cv1835_miner_emmc"
fit[0x100 : 0x100 + len(marker)] = marker
(directory / "alkane-cv1835-p1.fit").write_bytes(fit)
return directory
def build_afw(work, input_dir, name="good.afw", extra=()):
output = work / "dist"
result = run(
[
"bash",
str(MAKE),
"--board",
"cv1835",
"--version",
"0.1.0",
"--input",
str(input_dir),
"--output",
str(output),
"--sdk-revision",
REVISION,
"--os-revision",
REVISION,
"--allow-unsigned",
*extra,
]
)
if result.returncode != 0:
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
files = list(output.glob("*.afw"))
if len(files) != 1:
raise AssertionError(f"expected one bundle, found {files}")
return files[0]
def pack_members(directory, members, output):
listing = output.with_suffix(".list")
listing.write_text("\n".join(members) + "\n")
result = run(
[
"tar",
"--format=ustar",
"--owner=0",
"--group=0",
"--numeric-owner",
"--create",
"--file",
str(output),
"-C",
str(directory),
"-T",
str(listing),
]
)
if result.returncode != 0:
raise AssertionError(result.stderr)
listing.unlink()
return output
def rewrite_bundle(source, destination, edit_manifest=None, flip_payload=None):
"""Unpack a bundle, edit the manifest or payload, and repack it strictly."""
work = destination.parent / (destination.name + ".unpack")
if work.exists():
shutil.rmtree(work)
work.mkdir()
with tarfile.open(source, "r:") as archive:
names = archive.getnames()
archive.extractall(work)
manifest_path = work / "manifest.json"
manifest = json.loads(manifest_path.read_text())
if edit_manifest is not None:
edit_manifest(manifest, work)
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
members = ["manifest.json"]
if manifest["signature"]["member"]:
members.append(manifest["signature"]["member"])
members.extend(image["file"] for image in manifest["images"])
if flip_payload:
for member in members:
if member in ("manifest.json", "manifest.json.sig"):
continue
path = work / member
if path.is_file():
data = bytearray(path.read_bytes())
if data:
data[len(data) // 2] ^= 0x01
path.write_bytes(data)
break
pack_members(work, members, destination)
shutil.rmtree(work)
return destination
class AfwTests(unittest.TestCase):
def setUp(self):
self.temp = Path(tempfile.mkdtemp(prefix="afw-test."))
self.input = fixture_input(self.temp / "sdk-out")
def tearDown(self):
shutil.rmtree(self.temp, ignore_errors=True)
def check(self, path, *extra):
return run([sys.executable, str(CHECK), str(path), *extra])
def test_good_bundle_passes_and_reports_install(self):
bundle = build_afw(self.temp, self.input)
result = self.check(bundle, "--allow-unsigned", "--expect-board", "cv1835")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("afw: OK", result.stdout)
self.assertIn("install p1 -> p1", result.stdout)
result = self.check(bundle, "--allow-unsigned", "--json")
self.assertEqual(result.returncode, 0, result.stderr)
summary = json.loads(result.stdout)
self.assertEqual(summary["board"], "cv1835")
self.assertEqual(summary["arch"], "arm64")
self.assertEqual(summary["install"][0]["size"], P1)
def test_unsigned_bundle_needs_the_flag(self):
bundle = build_afw(self.temp, self.input)
result = self.check(bundle)
self.assertNotEqual(result.returncode, 0)
self.assertIn("unsigned", result.stderr)
def test_one_byte_tampered_payload_fails(self):
bundle = build_afw(self.temp, self.input)
tampered = rewrite_bundle(bundle, self.temp / "tampered.afw", flip_payload=True)
result = self.check(tampered, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("sha256 mismatch", result.stderr)
def test_wrong_board_is_refused(self):
bundle = build_afw(self.temp, self.input)
result = self.check(bundle, "--allow-unsigned", "--expect-board", "zynq-7010")
self.assertNotEqual(result.returncode, 0)
self.assertIn("expected zynq-7010", result.stderr)
def test_manifest_cannot_claim_a_different_arch(self):
bundle = build_afw(self.temp, self.input)
def edit(manifest, _work):
manifest["arch"] = "armv7"
wrong = rewrite_bundle(bundle, self.temp / "wrong-arch.afw", edit_manifest=edit)
result = self.check(wrong, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("must use arm64", result.stderr)
def test_truncated_tar_fails(self):
bundle = build_afw(self.temp, self.input)
truncated = self.temp / "truncated.afw"
truncated.write_bytes(bundle.read_bytes()[:100])
result = self.check(truncated, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("truncated", result.stderr)
def test_traversal_member_fails(self):
stage = self.temp / "traversal"
stage.mkdir()
(stage / "manifest.json").write_text("{}\n")
(stage / "payload").mkdir()
(stage / "payload" / "p1.fit").write_bytes(b"\xd0\x0d\xfe\xed")
bundle = self.temp / "traversal.afw"
import io
with tarfile.open(bundle, "w", format=tarfile.USTAR_FORMAT) as archive:
for name, data in (
("manifest.json", b"{}\n"),
("payload/../escape", b"x"),
):
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
result = self.check(bundle, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("traversal", result.stderr)
def test_oversize_fit_is_refused_by_producer(self):
fit = self.input / "alkane-cv1835-p1.fit"
data = fit.read_bytes()
fit.write_bytes(data + b"\0")
result = run(
[
"bash",
str(MAKE),
"--board",
"cv1835",
"--version",
"0.1.0",
"--input",
str(self.input),
"--output",
str(self.temp / "dist"),
"--sdk-revision",
REVISION,
"--os-revision",
REVISION,
"--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("larger than", result.stderr)
def test_oversize_fit_is_refused_by_checker(self):
bundle = build_afw(self.temp, self.input)
def edit(manifest, work):
manifest["images"][-1]["size"] = P1 + 1
manifest["images"][-1]["sha256"] = "0" * 64
path = work / manifest["images"][-1]["file"]
path.write_bytes(path.read_bytes() + b"\0")
oversize = rewrite_bundle(bundle, self.temp / "oversize.afw", edit_manifest=edit)
result = self.check(oversize, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("exceeds partition", result.stderr)
def test_bootloader_member_under_preserve_is_refused(self):
bundle = build_afw(self.temp, self.input)
def edit(manifest, work):
manifest["images"].append(
{
"name": "u-boot",
"file": "payload/u-boot.img",
"role": "bootloader",
"format": "uimage",
"size": 4,
"sha256": "0" * 64,
"partition": None,
"install": False,
}
)
(work / "payload" / "u-boot.img").write_bytes(b"\x27\x05\x19\x56")
wrong = rewrite_bundle(bundle, self.temp / "bootloader.afw", edit_manifest=edit)
result = self.check(wrong, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("preserve", result.stderr)
def test_hash_mismatch_fails(self):
bundle = build_afw(self.temp, self.input)
def edit(manifest, _work):
manifest["images"][0]["sha256"] = "1" * 64
wrong = rewrite_bundle(bundle, self.temp / "hash.afw", edit_manifest=edit)
result = self.check(wrong, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("sha256 mismatch", result.stderr)
def test_missing_image_fails_producer(self):
(self.input / "Image").unlink()
result = run(
[
"bash",
str(MAKE),
"--board",
"cv1835",
"--version",
"0.1.0",
"--input",
str(self.input),
"--output",
str(self.temp / "dist"),
"--sdk-revision",
REVISION,
"--os-revision",
REVISION,
"--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("required image is missing", result.stderr)
def test_plan_size_cross_check(self):
bundle = build_afw(self.temp, self.input)
plan = self.temp / "plan.json"
plan.write_text(json.dumps({
"board": "cv1835",
"arch": "arm64",
"bootloader_policy": "preserve",
"partitions": [{"name": "p1", "size": P1}],
}))
result = self.check(bundle, "--allow-unsigned", "--plan", plan)
self.assertEqual(result.returncode, 0, result.stderr)
plan.write_text(json.dumps({
"board": "cv1835",
"arch": "arm64",
"bootloader_policy": "preserve",
"partitions": [{"name": "p1", "size": P1 - 1}],
}))
result = self.check(bundle, "--allow-unsigned", "--plan", plan)
self.assertNotEqual(result.returncode, 0)
self.assertIn("differs from the manifest", result.stderr)
def test_unknown_board_fails(self):
result = run(
[
"bash",
str(MAKE),
"--board",
"whatsminer-h6",
"--version",
"0.1.0",
"--input",
str(self.input),
"--output",
str(self.temp / "dist"),
"--sdk-revision",
REVISION,
"--os-revision",
REVISION,
"--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("unknown board family", result.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)
AM_KERNEL_MAX = 0x500000
AM_ROOT_MAX = 0x1400000
def uimage_header(kind, payload=b"payload"):
header = bytearray(64)
header[0:4] = b"\x27\x05\x19\x56"
header[12:16] = len(payload).to_bytes(4, "big")
header[29] = 2 # ARM
header[30] = kind # 2 kernel, 3 ramdisk
header[31] = 0 if kind == 2 else 1
header[32:48] = b"alkane-am335x\0\0\0"
return bytes(header) + payload
def am_fixture_input(directory):
directory.mkdir(parents=True, exist_ok=True)
(directory / "alkane-am335x.uImage").write_bytes(uimage_header(2, b"kernel"))
dtb = bytearray(2048)
dtb[0:4] = b"\xd0\x0d\xfe\xed"
(directory / "am335x-alkane.dtb").write_bytes(dtb)
(directory / "alkane-am335x-ramdisk.uImage").write_bytes(
uimage_header(3, b"ramdisk")
)
return directory
def build_am_afw(work, input_dir, extra=()):
output = work / "dist-am"
result = run(
[
"bash",
str(MAKE),
"--board",
"am335x",
"--version",
"0.1.0",
"--input",
str(input_dir),
"--output",
str(output),
"--sdk-revision",
REVISION,
"--os-revision",
REVISION,
"--allow-unsigned",
*extra,
]
)
if result.returncode != 0:
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
files = list(output.glob("*.afw"))
if len(files) != 1:
raise AssertionError(f"expected one bundle, found {files}")
return files[0]
class Am335xAfwTests(unittest.TestCase):
def setUp(self):
self.temp = Path(tempfile.mkdtemp(prefix="am335x-afw-test."))
self.input = am_fixture_input(self.temp / "sdk-out")
def tearDown(self):
shutil.rmtree(self.temp, ignore_errors=True)
def check(self, path, *extra):
return run([sys.executable, str(CHECK), str(path), *extra])
def test_good_bundle_passes_and_reports_three_installs(self):
bundle = build_am_afw(self.temp, self.input)
result = self.check(bundle, "--allow-unsigned", "--expect-board", "am335x")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("afw: OK", result.stdout)
self.assertIn("board am335x arch arm", result.stdout)
self.assertIn("bootloader preserve", result.stdout)
result = self.check(bundle, "--allow-unsigned", "--json")
self.assertEqual(result.returncode, 0, result.stderr)
summary = json.loads(result.stdout)
installs = {item["image"]: item["partition"] for item in summary["install"]}
self.assertEqual(
installs, {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
)
def test_oversize_kernel_is_refused_by_producer(self):
path = self.input / "alkane-am335x.uImage"
path.write_bytes(path.read_bytes() + b"\0" * (AM_KERNEL_MAX + 1))
result = run(
[
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / "dist"),
"--sdk-revision", REVISION, "--os-revision", REVISION,
"--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("larger than", result.stderr)
def test_oversize_root_is_refused_by_producer(self):
path = self.input / "alkane-am335x-ramdisk.uImage"
path.write_bytes(path.read_bytes() + b"\0" * (AM_ROOT_MAX + 1))
result = run(
[
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / "dist"),
"--sdk-revision", REVISION, "--os-revision", REVISION,
"--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("larger than", result.stderr)
def test_u_boot_member_under_preserve_is_refused(self):
bundle = build_am_afw(self.temp, self.input)
def edit(manifest, work):
manifest["images"].append(
{
"name": "u-boot",
"file": "payload/u-boot.img",
"role": "component",
"format": "uimage",
"size": 4,
"sha256": __import__("hashlib").sha256(b"boot").hexdigest(),
"partition": None,
"install": False,
}
)
(work / "payload" / "u-boot.img").write_bytes(b"boot")
bad = rewrite_bundle(bundle, self.temp / "uboot.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("u-boot", result.stderr)
def test_manifest_cannot_claim_arm64(self):
bundle = build_am_afw(self.temp, self.input)
def edit(manifest, _work):
manifest["arch"] = "arm64"
bad = rewrite_bundle(bundle, self.temp / "wrong-arch.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("must use arm", result.stderr)
def test_mtd4_write_target_is_refused(self):
bundle = build_am_afw(self.temp, self.input)
def edit(manifest, _work):
for part in manifest["partitions"]:
if part["name"] == "mtd4":
part["write_order"] = 1
part["image"] = "kernel"
part["secure"] = False
bad = rewrite_bundle(bundle, self.temp / "mtd4.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("mtd4", result.stderr)
def test_offset_in_the_0x780000_hole_is_refused(self):
bundle = build_am_afw(self.temp, self.input)
def edit(manifest, _work):
for part in manifest["partitions"]:
if part["name"] == "mtd8":
part["offset"] = 0x780000
bad = rewrite_bundle(bundle, self.temp / "hole.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("hole", result.stderr)
def test_ramdisk_must_be_type_3(self):
(self.input / "alkane-am335x-ramdisk.uImage").write_bytes(
uimage_header(2, b"not-a-ramdisk")
)
result = run(
[
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / "dist"),
"--sdk-revision", REVISION, "--os-revision", REVISION,
"--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("type-3 ramdisk", result.stderr)
def test_truncated_tar_fails(self):
bundle = build_am_afw(self.temp, self.input)
truncated = self.temp / "truncated.afw"
truncated.write_bytes(bundle.read_bytes()[:100])
result = self.check(truncated, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("truncated", result.stderr)
def test_traversal_member_fails(self):
import io
bundle = self.temp / "traversal.afw"
with tarfile.open(bundle, "w", format=tarfile.USTAR_FORMAT) as archive:
for name, data in (
("manifest.json", b"{}\n"),
("payload/../escape", b"x"),
):
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
result = self.check(bundle, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("traversal", result.stderr)
def test_plan_json_cross_check(self):
sdk = Path("/home/noah/projects/alkane-sdk")
plan_yaml = sdk / "install" / "plans" / "am335x.yaml"
if not plan_yaml.is_file():
self.skipTest("alkane-sdk am335x plan not present")
plan_json = self.temp / "am335x-plan.json"
result = run(
[
sys.executable, str(sdk / "ci" / "check-plans.py"),
"--plan", str(plan_yaml), "--emit-json", str(plan_json),
]
)
self.assertEqual(result.returncode, 0, result.stderr)
bundle = build_am_afw(
self.temp, self.input, extra=("--plan", str(plan_json))
)
result = self.check(
bundle, "--allow-unsigned", "--plan", str(plan_json)
)
self.assertEqual(result.returncode, 0, result.stderr)
def am_stock_fixture_input(directory):
"""The tier-3 from-stock input: adds our U-Boot (firmware uImage, type 5)
alongside the kernel/dtb/ramdisk."""
am_fixture_input(directory)
(directory / "alkane-am335x-uboot-mtd4.uImage").write_bytes(
uimage_header(5, b"u-boot")
)
return directory
def build_am_stock_afw(work, input_dir, extra=()):
output = work / "dist-am-stock"
result = run(
[
"bash", str(MAKE), "--board", "am335x-stock", "--version", "0.1.0",
"--input", str(input_dir), "--output", str(output),
"--sdk-revision", REVISION, "--os-revision", REVISION,
"--allow-unsigned", *extra,
]
)
if result.returncode != 0:
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
files = list(output.glob("*.afw"))
if len(files) != 1:
raise AssertionError(f"expected one bundle, found {files}")
return files[0]
class Am335xStockAfwTests(unittest.TestCase):
"""Tier-3 from-stock bundle: writes U-Boot to mtd4 but must still refuse
every SPL write and a wrongly-typed U-Boot member."""
def setUp(self):
self.temp = Path(tempfile.mkdtemp(prefix="am335x-stock-afw-test."))
self.input = am_stock_fixture_input(self.temp / "sdk-out")
def tearDown(self):
shutil.rmtree(self.temp, ignore_errors=True)
def check(self, path, *extra):
return run([sys.executable, str(CHECK), str(path), *extra])
def test_good_stock_bundle_passes_with_four_installs(self):
bundle = build_am_stock_afw(self.temp, self.input)
result = self.check(bundle, "--allow-unsigned", "--expect-board", "am335x-stock")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("afw: OK", result.stdout)
self.assertIn("bootloader include", result.stdout)
result = self.check(bundle, "--allow-unsigned", "--json")
self.assertEqual(result.returncode, 0, result.stderr)
installs = {item["image"]: item["partition"] for item in json.loads(result.stdout)["install"]}
self.assertEqual(
installs, {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
)
def test_u_boot_member_must_be_firmware_type(self):
# A U-Boot payload wrongly built as a type-2 kernel uImage must be caught.
(self.input / "alkane-am335x-uboot-mtd4.uImage").write_bytes(uimage_header(2, b"u-boot"))
result = run(
[
"bash", str(MAKE), "--board", "am335x-stock", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / "dist"),
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned",
]
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("firmware", result.stderr + result.stdout)
def test_making_an_spl_copy_a_write_target_is_refused(self):
bundle = build_am_stock_afw(self.temp, self.input)
def edit(manifest, _work):
for part in manifest["partitions"]:
if part["name"] == "mtd0":
part["secure"] = False
part["write_order"] = 5
part["image"] = "u-boot"
bad = rewrite_bundle(bundle, self.temp / "spl-write.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("mtd0", result.stderr)
def zimage_blob(payload=b"zkernel"):
# ARM zImage: magic 0x016f2818 (LE) at offset 0x24.
b = bytearray(64)
b[0x24:0x28] = b"\x18\x28\x6f\x01"
return bytes(b) + payload
def zynq_fixture_input(directory):
directory.mkdir(parents=True, exist_ok=True)
(directory / "zImage").write_bytes(zimage_blob())
dtb = bytearray(1024); dtb[0:4] = b"\xd0\x0d\xfe\xed"
(directory / "zynq-alkane.dtb").write_bytes(dtb)
(directory / "rootfs.cpio.gz").write_bytes(b"\x1f\x8b" + b"rootfs")
return directory
def build_zynq_afw(work, input_dir, extra=()):
output = work / "dist-zynq"
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
"--input", str(input_dir), "--output", str(output),
"--sdk-revision", REVISION, "--os-revision", REVISION,
"--allow-unsigned", *extra])
if result.returncode != 0:
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
files = list(output.glob("*.afw"))
if len(files) != 1:
raise AssertionError(f"expected one bundle, found {files}")
return files[0]
class ZynqAfwTests(unittest.TestCase):
"""zynq-7010 tier-2 bundle: kernel(zImage)/dtb/rootfs, BOOT.bin preserved."""
def setUp(self):
self.temp = Path(tempfile.mkdtemp(prefix="zynq-afw-test."))
self.input = zynq_fixture_input(self.temp / "sdk-out")
def tearDown(self):
shutil.rmtree(self.temp, ignore_errors=True)
def check(self, path, *extra):
return run([sys.executable, str(CHECK), str(path), *extra])
def test_good_zynq_bundle_passes(self):
bundle = build_zynq_afw(self.temp, self.input)
result = self.check(bundle, "--allow-unsigned", "--expect-board", "zynq-7010")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("afw: OK", result.stdout)
self.assertIn("bootloader preserve", result.stdout)
def test_non_zimage_kernel_is_refused(self):
(self.input / "zImage").write_bytes(b"\x00" * 4096) # no zImage magic
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / "d"),
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
self.assertNotEqual(result.returncode, 0)
self.assertIn("zImage", result.stderr + result.stdout)
def test_oversize_kernel_is_refused(self):
(self.input / "zImage").write_bytes(zimage_blob(b"\x00" * (0x500000 + 1)))
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / "d"),
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
self.assertNotEqual(result.returncode, 0)
self.assertIn("ceiling", result.stderr + result.stdout)
def test_bootloader_member_is_refused(self):
bundle = build_zynq_afw(self.temp, self.input)
def edit(manifest, work):
manifest["images"].append({
"name": "u-boot", "file": "payload/BOOT.bin", "role": "bootloader",
"format": "raw", "size": 4,
"sha256": __import__("hashlib").sha256(b"boot").hexdigest(),
"partition": None, "install": False,
})
(work / "payload" / "BOOT.bin").write_bytes(b"boot")
bad = rewrite_bundle(bundle, self.temp / "bl.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
def arm64_image_blob(payload=b"a64kernel"):
# arm64 Linux Image: ASCII "ARMd" at offset 0x38.
b = bytearray(64)
b[0x38:0x3C] = b"ARMd"
b[0x08:0x10] = (0x200000).to_bytes(8, "little") # text_offset / image_size hint
return bytes(b) + payload
def uramdisk_blob(payload=b"ramdisk"):
# legacy uImage ramdisk (magic 0x27051956); a113d does not enforce arch/type.
b = bytearray(64)
b[0:4] = b"\x27\x05\x19\x56"
b[12:16] = len(payload).to_bytes(4, "big")
return bytes(b) + payload
def a113d_fixture_input(directory):
directory.mkdir(parents=True, exist_ok=True)
(directory / "vmlinux.bin").write_bytes(arm64_image_blob())
dtb = bytearray(2048); dtb[0:4] = b"\xd0\x0d\xfe\xed"
(directory / "devicetree.dtb").write_bytes(bytes(dtb))
(directory / "uramdisk.image.gz").write_bytes(uramdisk_blob())
return directory
def build_a113d_afw(work, input_dir, extra=()):
output = work / "dist-a113d"
result = run(["bash", str(MAKE), "--board", "a113d", "--version", "0.1.0",
"--input", str(input_dir), "--output", str(output),
"--sdk-revision", REVISION, "--os-revision", REVISION,
"--allow-unsigned", *extra])
if result.returncode != 0:
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
files = list(output.glob("*.afw"))
if len(files) != 1:
raise AssertionError(f"expected one bundle, found {files}")
return files[0]
class A113dAfwTests(unittest.TestCase):
"""a113d tier-2 bundle: kernel/dtb/rootfs staged into nvdata; FIP + mtd0-5 preserved."""
def setUp(self):
self.temp = Path(tempfile.mkdtemp(prefix="a113d-afw-test."))
self.input = a113d_fixture_input(self.temp / "sdk-out")
def tearDown(self):
shutil.rmtree(self.temp, ignore_errors=True)
def check(self, path, *extra):
return run([sys.executable, str(CHECK), str(path), *extra])
def make(self, outdir="d"):
return run(["bash", str(MAKE), "--board", "a113d", "--version", "0.1.0",
"--input", str(self.input), "--output", str(self.temp / outdir),
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
def test_good_a113d_bundle_passes_and_preserves(self):
bundle = build_a113d_afw(self.temp, self.input)
result = self.check(bundle, "--allow-unsigned", "--expect-board", "a113d")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("afw: OK", result.stdout)
self.assertIn("bootloader preserve", result.stdout)
# all three images install into the nvdata UBI, never a raw mtd0-5 write
self.assertEqual(result.stdout.count("-> nvdata"), 3)
def test_non_arm64_kernel_is_refused(self):
(self.input / "vmlinux.bin").write_bytes(b"\x00" * 4096) # no ARMd magic
result = self.make()
self.assertNotEqual(result.returncode, 0)
self.assertIn("arm64", (result.stderr + result.stdout).lower())
def test_oversize_kernel_is_refused(self):
(self.input / "vmlinux.bin").write_bytes(arm64_image_blob(b"\x00" * (0x4000000 + 1)))
result = self.make()
self.assertNotEqual(result.returncode, 0)
self.assertIn("ceiling", (result.stderr + result.stdout).lower())
def test_fip_member_is_refused(self):
bundle = build_a113d_afw(self.temp, self.input)
def edit(manifest, work):
manifest["images"].append({
"name": "fip", "file": "payload/fip.bin", "role": "bootloader",
"format": "raw", "size": 4,
"sha256": __import__("hashlib").sha256(b"fip!").hexdigest(),
"partition": None, "install": False,
})
(work / "payload" / "fip.bin").write_bytes(b"fip!")
bad = rewrite_bundle(bundle, self.temp / "fip.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("fip", (result.stderr + result.stdout).lower())
def test_preserved_mtd_carrying_an_image_is_refused(self):
bundle = build_a113d_afw(self.temp, self.input)
def edit(manifest, work):
for partition in manifest["partitions"]:
if partition["name"] != "nvdata":
partition["image"] = "kernel" # try to aim a write at the FIP side
break
bad = rewrite_bundle(bundle, self.temp / "pre.afw", edit_manifest=edit)
result = self.check(bad, "--allow-unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("preserved", (result.stderr + result.stdout).lower())