Add zynq-7010 toolkit flash module (tier-2 update, offset writes, BOOT.bin guard)

The toolkit now flashes the Zynq update path through the CLI like am335x/cv1835.
- boards/zynq.rs: ZynqPlan::from_afw (validates the zynq-7010 .afw: armv7, preserve,
  the kernel/dtb/rootfs image set, zimage/fdt/cpio-gzip formats, size ceilings,
  rejects any bootloader/spl/BOOT.bin member and a non-zImage kernel), preflight
  (alkane source, root, flash tools, mtd0/mtd1, BOOT.bin-preserve guard), install
  (OFFSET-AWARE: nanddump/flash_erase/nandwrite --start at the device-relative
  slot offset - kernel 0x2200000, dtb 0x2700000 in /dev/mtd0, rootfs in /dev/mtd1
  - with per-region backup + md5 readback), and a hard guard that refuses any
  /dev/mtd0 write below BOOTBIN_PRESERVE so BOOT.bin can never be clobbered.
- alkane-artifacts: add the strict 'zimage' image format (magic 0x016f2818 at 0x24).
- alkane-cli: route zynq-7010 through afw plan/preflight/install.
- 6 module tests (good plan, non-zImage, oversize, bootloader member, wrong
  board/arch, every-mtd0-target-above-BOOT.bin). Full flash suite 47 green,
  artifacts green; the real bundle renders its plan through the CLI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
This commit is contained in:
2026-11-06 20:13:38 -06:00
co-authored by Claude Opus 4.8
parent b1316b2bd9
commit cce24b6880
4 changed files with 656 additions and 1 deletions
+8 -1
View File
@@ -42,7 +42,7 @@ const AM335X_CEILINGS: &[(&str, u64, &str)] = &[
];
const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"];
const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "fdt", "cpio-gzip", "uimage", "raw"];
const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "zimage", "fdt", "cpio-gzip", "uimage", "raw"];
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
@@ -700,6 +700,7 @@ fn check_image_format(
match image.format.as_str() {
"fit" => "not a FIT or missing the board config",
"arm64-image" => "not an arm64 Image",
"zimage" => "not an ARM zImage",
"fdt" => "not an FDT",
"cpio-gzip" => "not gzip-compressed",
"uimage" => "not a legacy uImage",
@@ -732,6 +733,12 @@ fn check_image_format(
return Err(fail());
}
}
"zimage" => {
// ARM zImage magic 0x016f2818 (little-endian) at offset 0x24.
if data.len() < 0x28 || &data[0x24..0x28] != b"\x18\x28\x6f\x01" {
return Err(fail());
}
}
"cpio-gzip" => {
if !data.starts_with(b"\x1f\x8b") {
return Err(fail());
+49
View File
@@ -12,6 +12,7 @@ use alkane_flash::boards::am335x::{
self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions,
};
use alkane_flash::boards::cv1835::Cv1835Plan;
use alkane_flash::boards::zynq::{self, ZynqInstallOptions, ZynqOutcome, ZynqPlan};
use alkane_flash::install::{
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
};
@@ -344,6 +345,12 @@ fn run_plan(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
println!("plan is read-only; no write performed");
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
println!("{}", plan.render());
println!("plan is read-only; no write performed (run preflight/install with --host)");
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
@@ -399,6 +406,15 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
let report = zynq::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
print!("{}", report.render());
if !report.ok() {
return Err("preflight failed; do not write".into());
}
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let held_backup = opts.value("held-backup").map(PathBuf::from);
let report = preflight(
@@ -495,6 +511,39 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
println!("{}", plan.render());
let install_options = ZynqInstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
match zynq::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
ZynqOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no board erase or write was performed.");
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
println!("Re-run with --confirm FLASH to write {targets} (BOOT.bin preserved).");
}
ZynqOutcome::Installed(receipt) => {
for backup in &receipt.backups {
println!(
"held {} {} offset 0x{:x} md5 {}",
backup.image_name, backup.path.display(), backup.offset, backup.md5
);
}
println!("all read-backs matched before reboot; BOOT.bin never touched");
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
} else {
println!("reboot skipped (--no-reboot)");
}
}
}
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let install_options = InstallOptions {
dry_run: opts.flag("dry-run"),
+1
View File
@@ -4,3 +4,4 @@
pub mod am335x;
pub mod cv1835;
pub mod zynq;
+598
View File
@@ -0,0 +1,598 @@
// SPDX-License-Identifier: MIT
//! Zynq-7010 board module: tier-2 network UPDATE of a board already running
//! alkane (installed from stock via the dsh-owned RSA-gate path - that first
//! install is not this module). It writes our kernel (zImage) into the mtd0
//! kernel slot, the dtb, and the rootfs into mtd1, and PRESERVES BOOT.bin
//! (FSBL + FPGA bitstream + stock U-Boot) at the front of mtd0.
//!
//! The write offsets are DEVICE-RELATIVE and authoritative here (like the
//! am335x MTD_MAP): kernel at 0x2200000 and dtb at 0x2700000 within /dev/mtd0,
//! rootfs at 0 within /dev/mtd1. The module REFUSES to erase or write /dev/mtd0
//! below BOOTBIN_PRESERVE, so a bad offset can never clobber BOOT.bin.
use crate::md5::md5_hex;
use crate::preflight::{classify, parse_digest};
use crate::transport::{Remote, RemoteError};
use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use thiserror::Error;
pub const BOARD: &str = "zynq-7010";
pub const ARCH: &str = "armv7";
/// mtd0 0x0..0x2200000 is BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) and is
/// NEVER erased or written by this module.
pub const BOOTBIN_PRESERVE: u64 = 0x2200000;
/// Authoritative write targets: (image, device, device-relative offset, ceiling, format).
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a new
/// rootfs under an old kernel.
const TARGETS: [(&str, &str, u64, u64, &str); 3] = [
("rootfs", "/dev/mtd1", 0x0, 0x2000000, "cpio-gzip"),
("dtb", "/dev/mtd0", 0x2700000, 0x20000, "fdt"),
("kernel", "/dev/mtd0", 0x2200000, 0x500000, "zimage"),
];
#[derive(Debug, Error)]
pub enum ZynqPlanError {
#[error("bundle is for {0}, not zynq-7010")]
WrongBoard(String),
#[error("bundle arch is {0}, zynq-7010 needs armv7")]
WrongArch(String),
#[error("zynq-7010 requires bootloader_policy preserve")]
BootloaderPolicy,
#[error("zynq-7010 bundle carries a bootloader/spl/BOOT.bin member: {0}")]
BootloaderMember(String),
#[error("manifest is not an OS payload")]
PayloadType,
#[error("manifest marker is empty")]
Marker,
#[error("zynq-7010 must install exactly kernel, dtb and rootfs")]
InstallCount,
#[error("zynq-7010 is missing the {0} image")]
MissingImage(String),
#[error("zynq-7010 {image} format is {actual}, expected {expected}")]
ImageFormat { image: String, actual: String, expected: &'static str },
#[error("zynq-7010 {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
ImageTooLarge { image: String, size: u64, ceiling: u64 },
#[error("zynq-7010 {image} is not an ARM zImage")]
NotZImage { image: String },
#[error("zynq-7010 refuses to place {image} at 0x{offset:x} on {device}: below BOOT.bin (0x{bootbin:x})")]
WouldClobberBootbin { image: String, device: String, offset: u64, bootbin: u64 },
}
#[derive(Clone, Debug)]
pub struct ZynqTarget {
pub image_name: String,
pub device: String,
pub offset: u64,
pub size: u64,
pub data: Vec<u8>,
pub expected_md5: String,
}
#[derive(Clone, Debug)]
pub struct ZynqPlan {
pub targets: Vec<ZynqTarget>,
pub marker: String,
pub kernel_version: String,
pub sdk_revision: String,
pub os_revision: String,
pub afw_sha256: String,
pub min_free_bytes: u64,
}
fn is_bootloaderish(image: &AfwImage) -> bool {
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
image.role == "bootloader"
|| lowered.contains("spl")
|| lowered.contains("u-boot")
|| lowered.contains("uboot")
|| lowered.contains("boot.bin")
}
impl ZynqPlan {
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, ZynqPlanError> {
let manifest = &afw.manifest;
if manifest.board != BOARD {
return Err(ZynqPlanError::WrongBoard(manifest.board.clone()));
}
if manifest.arch != ARCH {
return Err(ZynqPlanError::WrongArch(manifest.arch.clone()));
}
if manifest.payload_type != "os" {
return Err(ZynqPlanError::PayloadType);
}
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
return Err(ZynqPlanError::BootloaderPolicy);
}
if manifest.marker.is_empty() {
return Err(ZynqPlanError::Marker);
}
// BOOT.bin / bootloader members are never allowed - we reuse the board's.
for image in &manifest.images {
if is_bootloaderish(image) {
return Err(ZynqPlanError::BootloaderMember(image.file.clone()));
}
}
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
if installs.len() != TARGETS.len() {
return Err(ZynqPlanError::InstallCount);
}
let mut targets = Vec::with_capacity(TARGETS.len());
for (image_name, device, offset, ceiling, expected_format) in TARGETS {
let image = manifest
.images
.iter()
.find(|i| i.name == image_name && i.install)
.ok_or_else(|| ZynqPlanError::MissingImage(image_name.to_owned()))?;
if image.format != expected_format {
return Err(ZynqPlanError::ImageFormat {
image: image_name.to_owned(),
actual: image.format.clone(),
expected: expected_format,
});
}
if image.size > ceiling {
return Err(ZynqPlanError::ImageTooLarge {
image: image_name.to_owned(),
size: image.size,
ceiling,
});
}
// The one hard brick guard: a write on /dev/mtd0 must sit entirely
// above BOOT.bin.
if device == "/dev/mtd0" && offset < BOOTBIN_PRESERVE {
return Err(ZynqPlanError::WouldClobberBootbin {
image: image_name.to_owned(),
device: device.to_owned(),
offset,
bootbin: BOOTBIN_PRESERVE,
});
}
let data = afw
.image(image_name)
.map(|(_, data)| data)
.ok_or_else(|| ZynqPlanError::MissingImage(image_name.to_owned()))?;
if expected_format == "zimage"
&& !(data.len() >= 0x28 && data[0x24..0x28] == [0x18, 0x28, 0x6f, 0x01])
{
return Err(ZynqPlanError::NotZImage { image: image_name.to_owned() });
}
targets.push(ZynqTarget {
image_name: image_name.to_owned(),
device: device.to_owned(),
offset,
size: image.size,
expected_md5: md5_hex(data),
data: data.to_vec(),
});
}
Ok(Self {
targets,
marker: manifest.marker.clone(),
kernel_version: manifest.kernel_version.clone(),
sdk_revision: manifest.sdk_revision.clone(),
os_revision: manifest.os_revision.clone(),
afw_sha256: afw.archive_sha256.clone(),
min_free_bytes: manifest
.preflight
.get("min_free_bytes")
.and_then(|v| v.as_u64())
.unwrap_or(16 * 1024 * 1024),
})
}
pub fn render(&self) -> String {
let mut out = format!("board {BOARD} arch {ARCH}\n");
out.push_str(&format!(
"tier 2 update: write the kernel slot + mtd1; BOOT.bin (mtd0 0..0x{:x}) preserved, never written\n",
BOOTBIN_PRESERVE
));
out.push_str("image format kernel=zImage, dtb=fdt, rootfs=cpio-gzip\n");
for target in &self.targets {
out.push_str(&format!(
"write {} {} offset 0x{:x} size {} B md5 {}\n",
target.image_name, target.device, target.offset, target.size, target.expected_md5
));
}
out.push_str(&format!(
"marker {} kernel {} sdk {} os {}",
self.marker,
self.kernel_version,
short(&self.sdk_revision),
short(&self.os_revision),
));
out
}
}
fn short(rev: &str) -> &str {
rev.get(..12).unwrap_or(rev)
}
#[derive(Debug, Error)]
pub enum ZynqError {
#[error("preflight failed:\n{0}")]
Preflight(String),
#[error("--confirm FLASH is required to write")]
Confirm,
#[error("refusing to write {device} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
BootbinGuard { device: String, offset: u64, bootbin: u64 },
#[error("{0} staged md5 differs from the verified bundle")]
StageMismatch(String),
#[error("{0} read-back md5 mismatch; do not reboot")]
Readback(String),
#[error(transparent)]
Remote(#[from] RemoteError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[derive(Clone, Debug)]
pub struct ZynqCheck {
pub name: String,
pub ok: bool,
pub detail: String,
}
#[derive(Clone, Debug)]
pub struct ZynqPreflight {
pub host: String,
pub checks: Vec<ZynqCheck>,
}
impl ZynqPreflight {
pub fn ok(&self) -> bool {
self.checks.iter().all(|c| c.ok)
}
pub fn render(&self) -> String {
let mut out = format!("preflight {}\n", self.host);
for c in &self.checks {
out.push_str(&format!("check {} {}: {}\n", c.name, if c.ok { "ok" } else { "FAIL" }, c.detail));
}
out.push_str(&format!("result {}", if self.ok() { "PASS" } else { "FAIL (do not write)" }));
out
}
}
pub fn preflight(
plan: &ZynqPlan,
remote: &mut dyn Remote,
host: &str,
) -> Result<ZynqPreflight, ZynqError> {
let mut checks = Vec::new();
let fingerprint = remote.user_command(
"uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \
echo __RELEASE__; cat /etc/os-release 2>/dev/null; cat /etc/alkane-release 2>/dev/null \
|| true",
Duration::from_secs(20),
)?;
let text = String::from_utf8_lossy(&fingerprint).into_owned();
let mut it = text.split("__MODEL__");
let kernel = it.next().unwrap_or("").trim().to_owned();
let rest = it.next().unwrap_or("");
let mut it2 = rest.split("__RELEASE__");
let _model = it2.next().unwrap_or("");
let release = it2.next().unwrap_or("");
let source = classify(&kernel, release, &text);
checks.push(ZynqCheck {
name: "source-os".to_owned(),
ok: source == "alkane",
detail: format!("{source} (update path requires alkane)"),
});
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(ZynqCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
let tools = remote.user_command(
"for c in /usr/sbin/flash_erase /usr/sbin/nandwrite /usr/sbin/nanddump md5sum sync; do \
command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
Duration::from_secs(15),
)?;
let missing: Vec<String> = String::from_utf8_lossy(&tools)
.lines()
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
.collect();
checks.push(ZynqCheck {
name: "commands".to_owned(),
ok: missing.is_empty(),
detail: if missing.is_empty() { "flash tools present".to_owned() } else { format!("missing {}", missing.join(", ")) },
});
let mtd = String::from_utf8_lossy(&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?).into_owned();
let have_mtd01 = mtd.contains("mtd0:") && mtd.contains("mtd1:");
checks.push(ZynqCheck {
name: "mtd".to_owned(),
ok: have_mtd01,
detail: if have_mtd01 { "mtd0 (BOOT.bin+kernel) and mtd1 present".to_owned() } else { format!("mtd0/mtd1 not found: {mtd}") },
});
// The guard, asserted again at preflight: no target writes mtd0 below BOOT.bin.
let guard_ok = plan
.targets
.iter()
.all(|t| !(t.device == "/dev/mtd0" && t.offset < BOOTBIN_PRESERVE));
checks.push(ZynqCheck {
name: "preserve-bootbin".to_owned(),
ok: guard_ok,
detail: format!("no write on /dev/mtd0 below 0x{BOOTBIN_PRESERVE:x}"),
});
Ok(ZynqPreflight { host: host.to_owned(), checks })
}
#[derive(Clone, Debug)]
pub struct ZynqInstallOptions {
pub dry_run: bool,
pub confirm: Option<String>,
pub no_reboot: bool,
pub backup_dir: PathBuf,
}
#[derive(Clone, Debug)]
pub struct ZynqBackup {
pub image_name: String,
pub device: String,
pub offset: u64,
pub path: PathBuf,
pub md5: String,
pub size: u64,
}
#[derive(Clone, Debug)]
pub struct ZynqReceipt {
pub backups: Vec<ZynqBackup>,
pub rebooted: bool,
}
pub enum ZynqOutcome {
DryRun(Box<ZynqPreflight>),
Installed(ZynqReceipt),
}
/// flash_erase/nandwrite erase-block count that covers `size` bytes at a 128 KiB
/// erase block (the Zynq pl35x-nand block size).
fn erase_blocks(size: u64) -> u64 {
const BLOCK: u64 = 0x20000;
size.div_ceil(BLOCK)
}
pub fn install(
plan: &ZynqPlan,
remote: &mut dyn Remote,
options: &ZynqInstallOptions,
host: &str,
) -> Result<ZynqOutcome, ZynqError> {
let report = preflight(plan, remote, host)?;
if !report.ok() {
return Err(ZynqError::Preflight(report.render()));
}
if options.dry_run {
return Ok(ZynqOutcome::DryRun(Box::new(report)));
}
if options.confirm.as_deref() != Some("FLASH") {
return Err(ZynqError::Confirm);
}
fs::create_dir_all(&options.backup_dir)?;
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
let mut backups = Vec::new();
for target in &plan.targets {
// Hard guard, right before touching NAND: never below BOOT.bin on mtd0.
if target.device == "/dev/mtd0" && target.offset < BOOTBIN_PRESERVE {
return Err(ZynqError::BootbinGuard {
device: target.device.clone(),
offset: target.offset,
bootbin: BOOTBIN_PRESERVE,
});
}
let name = &target.image_name;
let device = &target.device;
let offset = target.offset;
// Back up the region we are about to overwrite, offset-aware.
let remote_backup = format!("/tmp/.alkane-z-{name}-backup.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_backup} {device}",
target.size
),
Duration::from_secs(300),
)?;
let local = options.backup_dir.join(format!("{name}-{epoch}.img"));
remote.pull(&remote_backup, &local, Duration::from_secs(300))?;
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
let data = fs::read(&local)?;
let md5 = md5_hex(&data);
backups.push(ZynqBackup {
image_name: name.clone(),
device: device.clone(),
offset,
path: local,
md5,
size: target.size,
});
// Stage the verified payload and prove its remote md5 before writing.
let mut staged = tempfile::NamedTempFile::new()?;
staged.write_all(&target.data)?;
staged.flush()?;
let remote_stage = format!("/tmp/.alkane-z-{name}-stage.img");
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
let staged_md5 = parse_digest(
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
if staged_md5 != target.expected_md5 {
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
return Err(ZynqError::StageMismatch(name.clone()));
}
// Erase and write exactly the region at its offset. flash_erase takes an
// offset + block count, so BOOT.bin (below the offset) is never touched.
let blocks = erase_blocks(target.size);
remote.root_command(
&format!("/usr/sbin/flash_erase {device} 0x{offset:x} {blocks}"),
Duration::from_secs(300),
)?;
remote.root_command(
&format!("/usr/sbin/nandwrite -p --start=0x{offset:x} {device} {remote_stage} && sync"),
Duration::from_secs(300),
)?;
// Read back exactly what we wrote and compare.
let remote_readback = format!("/tmp/.alkane-z-{name}-readback.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_readback} {device}",
target.size
),
Duration::from_secs(300),
)?;
let readback = parse_digest(
&remote.root_command(&format!("md5sum {remote_readback}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
let _ = remote.root_command(
&format!("rm -f {remote_stage} {remote_readback}"),
Duration::from_secs(15),
);
if readback != target.expected_md5 {
return Err(ZynqError::Readback(name.clone()));
}
}
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(ZynqOutcome::Installed(ZynqReceipt { backups, rebooted }))
}
pub fn owns_board(board: &str) -> bool {
board == BOARD
}
#[cfg(test)]
mod tests {
use super::*;
use alkane_artifacts::afw::{AfwManifest, AfwMember};
use sha2::{Digest, Sha256};
use serde_json::json;
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
fn zimage(payload: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 64];
b[0x24..0x28].copy_from_slice(&[0x18, 0x28, 0x6f, 0x01]);
b.extend_from_slice(payload);
b
}
fn afw(kernel: Vec<u8>, dtb: Vec<u8>, rootfs: Vec<u8>) -> VerifiedAfw {
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "x", "install": true})
};
let value = json!({
"schema": 2, "format": "afw", "board": "zynq-7010", "arch": "armv7",
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
"bootloader_policy": "preserve",
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
"partitions": [],
"images": [
image("kernel", "payload/zImage", "kernel", "zimage", &kernel),
image("dtb", "payload/zynq-alkane.dtb", "dtb", "fdt", &dtb),
image("rootfs", "payload/rootfs.cpio.gz", "rootfs", "cpio-gzip", &rootfs),
],
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
});
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/zImage".to_owned(), data: kernel },
AfwMember { name: "payload/zynq-alkane.dtb".to_owned(), data: dtb },
AfwMember { name: "payload/rootfs.cpio.gz".to_owned(), data: rootfs },
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
}
}
fn dtb() -> Vec<u8> {
let mut b = vec![0u8; 1024];
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
b
}
#[test]
fn accepts_a_good_plan_and_places_above_bootbin() {
let plan = ZynqPlan::from_afw(&afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec())).unwrap();
assert_eq!(plan.targets.len(), 3);
// write order rootfs, dtb, kernel
assert_eq!(plan.targets[0].image_name, "rootfs");
assert_eq!(plan.targets[2].image_name, "kernel");
for t in &plan.targets {
if t.device == "/dev/mtd0" {
assert!(t.offset >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name);
}
}
assert!(plan.render().contains("BOOT.bin"));
}
#[test]
fn refuses_a_non_zimage_kernel() {
let result = ZynqPlan::from_afw(&afw(vec![0u8; 64], dtb(), b"\x1f\x8brf".to_vec()));
assert!(matches!(result, Err(ZynqPlanError::NotZImage { .. })));
}
#[test]
fn refuses_an_oversize_kernel() {
let big = zimage(&vec![0u8; 0x500000]);
let result = ZynqPlan::from_afw(&afw(big, dtb(), b"\x1f\x8brf".to_vec()));
assert!(matches!(result, Err(ZynqPlanError::ImageTooLarge { .. })));
}
#[test]
fn refuses_a_bootloader_member() {
let mut verified = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
verified.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(ZynqPlan::from_afw(&verified), Err(ZynqPlanError::BootloaderMember(_))));
}
#[test]
fn wrong_board_and_arch_are_refused() {
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
v.manifest.board = "am335x".to_owned();
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongBoard(_))));
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
v.manifest.arch = "arm".to_owned();
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongArch(_))));
}
#[test]
fn every_mtd0_target_is_above_bootbin() {
// Compile-time-ish guarantee from the TARGETS table.
for (image, device, offset, _ceiling, _fmt) in TARGETS {
if device == "/dev/mtd0" {
assert!(offset >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin");
}
}
}
}