Scan the image dataset by dataset; report silent failures

finish's scan imported the image's pool with every dataset mounted under
an altroot. The pool's own dataset needs a mountpoint inside the read-only
root, so nothing was mounted, find scanned an empty directory, and the
export then failed with "pool is busy". The pool is now imported without
mounting, and each dataset is mounted read-only by itself. The root must
have /bin/sh, so an empty scan cannot pass. The export is retried, since
the pool stays busy for a while after the import and after an unmount.

build.sh now says when set -e stops it, and vm.sh sign returns finish's
exit status, not tee's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Karst 2026-11-22 16:40:09 -05:00
parent f5fa1360bf
commit 1d27c40b84
4 changed files with 209 additions and 8 deletions

View file

@ -229,7 +229,10 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
build-only dependencies are not kept and get rebuilt. A port that
fails is recorded and the step goes on with the others, then fails at the
end. Tools stops at the first failure only when its step is given an
argument, and `build` gives none.
argument, and `build` gives none. Once the failures are fixed, run `build`
again. Finished sets are reused, and the ports step skips every package
it has built. It does rebuild the build-only dependencies of the ports it
still has to build.
- After each port, tools ran `make clean` to remove its work directories
and its dependencies'. That clean runs each dependency's clean with the
port's own flavor, so a dependency with another flavor, or with none,
@ -304,8 +307,13 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
3. Builds the 5 GB ZFS eMMC image (`mk-image.sh`). On a cross-building
host the xtools set is moved aside first, because tools would otherwise
overlay amd64 toolchain files onto the image.
4. Imports the image's pool read-only and fails if any non-aarch64 ELF file
is found.
4. Imports the image's pool read-only, without mounting it, and mounts each
dataset read-only by itself. Mounting them all at import does not work:
the pool's own dataset needs a mountpoint inside the read-only root, and
the import then leaves nothing mounted (2026-11-22). Fails if any
non-aarch64 ELF file is found (firmware blobs aside), if a dataset cannot
be mounted, or if the root dataset has no `/bin/sh`, so an empty scan
cannot pass.
5. Compresses and signs the image.
**To time a few ports** before a first full build of a series:

View file

@ -26,6 +26,8 @@
# SPDX-License-Identifier: BSD-2-Clause
set -eu
# set -e stops at the first failed command without a word: say so (die has said why)
trap '_rc=$?; [ "${_rc}" -eq 0 ] || [ -n "${DIED:-}" ] || echo "build.sh: stopped by a failed command (exit ${_rc})" >&2' EXIT
FORGE=${FORGE:-https://code.karsttech.com/claude}
UPSTREAM=${UPSTREAM:-https://github.com/opnsense}
@ -45,6 +47,7 @@ PORTS_RUN=/var/tmp/gwbuild-ports.run
die()
{
echo "build.sh: $*" >&2
DIED=yes
exit 1
}
@ -56,6 +59,7 @@ step()
usage()
{
sed -n '3,24p' "${0}" >&2
DIED=yes
exit 2
}
@ -483,16 +487,37 @@ pilot()
}
# scan_image IMAGE: no amd64 (or other non-aarch64) ELF file may end up in the image
# (firmware blobs aside). The image's pool is imported read-only without mounting
# anything, and each dataset is mounted read-only by itself: mounting them all at
# import (zpool import -R) needs mountpoints the read-only root lacks, and leaves
# nothing mounted. The root dataset must have /bin/sh, so an empty mount cannot pass.
scan_image()
{
step "scanning $(basename "${1}") for foreign ELF files"
_md=$(mdconfig -a -t vnode -o readonly -f "${1}")
_mnt=$(mktemp -d /tmp/gwimage.XXXXXX)
_bad=${_mnt}.bad
if zpool import -o readonly=on -R "${_mnt}" -d "/dev/${_md}p2" pool0 gwscan; then
find "${_mnt}" -type f -size +0 -print0 | xargs -0 file -N | grep ': ELF' |
grep -v -e 'ARM aarch64' -e '/firmware/' > "${_bad}" || true
zpool export gwscan
_root=
: > "${_bad}"
if zpool import -N -o readonly=on -R "${_mnt}" -d "/dev/${_md}p2" pool0 gwscan; then
for _ds in $(zfs list -H -r -t filesystem -o name gwscan); do
if ! mount -t zfs -o ro "${_ds}" "${_mnt}"; then
echo "cannot mount ${_ds}" >> "${_bad}"
continue
fi
[ "${_ds}" != gwscan/ROOT/default ] || [ ! -f "${_mnt}/bin/sh" ] || _root=yes
find "${_mnt}" -xdev -type f -size +0 -print0 | xargs -0 file -N | grep ': ELF' |
grep -v -e 'ARM aarch64' -e '/firmware/' | sed "s|^${_mnt}|${_ds}:|" >> "${_bad}" || true
umount "${_mnt}"
done
[ -n "${_root}" ] || echo "no /bin/sh in gwscan/ROOT/default" >> "${_bad}"
# right after the import, and after an unmount, the pool is "busy" for a while
_try=1
until zpool export gwscan; do
[ "${_try}" -lt 10 ] || die "cannot export the image's pool gwscan"
_try=$((_try + 1))
sleep 3
done
else
echo "cannot import the image's pool" > "${_bad}"
fi

View file

@ -1134,5 +1134,171 @@ class PortsCleanTest(unittest.TestCase):
self.assertEqual(out, text)
class ScanImageTest(unittest.TestCase):
"""build.sh's scan_image: every ELF file in the image's datasets is aarch64."""
DATASETS = ["gwscan", "gwscan/ROOT", "gwscan/ROOT/default", "gwscan/usr", "gwscan/usr/home"]
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="gw-scan-")
self.addCleanup(shutil.rmtree, self.tmp)
self.fx = Fixture(self.tmp)
self.ds = os.path.join(self.tmp, "datasets")
self.work = os.path.join(self.tmp, "work")
os.makedirs(self.work)
self.listing = os.path.join(self.tmp, "zfs-list")
self.set_datasets(self.DATASETS)
self.add("gwscan/ROOT/default", "bin/sh", "ELF-arm")
self.add("gwscan/ROOT/default", "usr/lib/libc.so.7", "ELF-arm")
self.add("gwscan/ROOT/default", "etc/rc.conf", "text")
self.add("gwscan/ROOT/default", "empty", "")
for ds in self.DATASETS:
os.makedirs(os.path.join(self.ds, ds.replace("/", "_")), exist_ok=True)
fake = self.fx.make_fake
fake("mdconfig", 'case "$1" in -a) echo md7;; esac')
# export: "busy" the first FAKE_BUSY times
fake("zpool", """case "$1" in
import) exit ${FAKE_IMPORT_RC:-0};;
export) n=$(cat "$FAKE_LOG.busy" 2>/dev/null || echo 0); echo $((n + 1)) > "$FAKE_LOG.busy"
[ "$n" -ge "${FAKE_BUSY:-0}" ] || { echo "cannot export 'gwscan': pool is busy" >&2; exit 1; };;
esac""")
fake("sleep", "exit 0")
fake("zfs", 'cat "$FAKE_LISTING"')
# mount -t zfs -o ro DATASET DIR: the dataset's fixture tree appears at DIR
fake("mount", 'src="$FAKE_DS/$(echo "$5" | tr / _)"; [ -d "$src" ] || exit 1; cp -R "$src/." "$6/"')
fake("umount", 'find "$1" -mindepth 1 -delete')
fake("file", """[ "$1" = -N ] && shift
for f; do
case "$(head -c 7 "$f")" in
ELF-arm) echo "$f: ELF 64-bit LSB pie executable, ARM aarch64, for FreeBSD 14.3";;
ELF-x86) echo "$f: ELF 64-bit LSB executable, x86-64, for FreeBSD 14.3";;
*) echo "$f: ASCII text";;
esac
done""")
self.func = (build_function("die") + build_function("scan_image", [("/tmp/gwimage", f"{self.work}/gwimage")]))
def set_datasets(self, names):
with open(self.listing, "w") as f:
f.write("".join(n + "\n" for n in names))
def add(self, ds, rel, content):
p = os.path.join(self.ds, ds.replace("/", "_"), rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w") as f:
f.write(content)
def scan(self, released=True, **env):
e = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log,
"FAKE_DS": self.ds, "FAKE_LISTING": self.listing}
e.update(env)
r = subprocess.run(["sh", "-c", 'set -eu; step() { echo ">>> $*"; }\n' + self.func + '\nscan_image "$1"',
"sh", "/images/OPNsense-26.1.11-arm-aarch64-GATEWAY.img"],
env=e, capture_output=True, text=True)
# the pool is let go of and nothing is left behind, whatever the outcome
calls = self.fx.calls()
if released:
self.assertIn("mdconfig -d -u md7", calls)
self.assertEqual(os.listdir(self.work), [])
return r, calls
def test_busy_pool_exported_once_free(self):
r, calls = self.scan(FAKE_BUSY="2")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(calls.count("zpool export gwscan"), 3)
def test_pool_that_stays_busy(self):
r, calls = self.scan(released=False, FAKE_BUSY="100")
self.assertNotEqual(r.returncode, 0)
self.assertEqual(calls.count("zpool export gwscan"), 10)
self.assertIn("build.sh: cannot export the image's pool gwscan", r.stderr)
def test_clean_image(self):
r, calls = self.scan()
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("zpool import -N -o readonly=on -R", "\n".join(calls))
self.assertIn("zpool export gwscan", calls)
mounted = [c.split()[5] for c in calls if c.startswith("mount ")]
self.assertEqual(mounted, self.DATASETS)
self.assertEqual(len([c for c in calls if c.startswith("umount ")]), len(self.DATASETS))
def test_foreign_elf_named_with_its_dataset(self):
self.add("gwscan/usr/home", "user/a.out", "ELF-x86")
r, calls = self.scan()
self.assertNotEqual(r.returncode, 0)
self.assertIn("gwscan/usr/home:/user/a.out: ELF 64-bit LSB executable, x86-64", r.stderr)
self.assertIn("non-aarch64", r.stderr)
self.assertIn("zpool export gwscan", calls)
def test_foreign_elf_in_root(self):
self.add("gwscan/ROOT/default", "usr/local/bin/tool", "ELF-x86")
r, _ = self.scan()
self.assertNotEqual(r.returncode, 0)
self.assertIn("gwscan/ROOT/default:/usr/local/bin/tool", r.stderr)
def test_firmware_blobs_allowed(self):
self.add("gwscan/ROOT/default", "boot/firmware/sdma.bin", "ELF-x86")
r, _ = self.scan()
self.assertEqual(r.returncode, 0, r.stderr)
def test_empty_root_fails(self):
# the failure this replaces: nothing mounted, nothing scanned, a clean pass
shutil.rmtree(os.path.join(self.ds, "gwscan_ROOT_default"))
os.makedirs(os.path.join(self.ds, "gwscan_ROOT_default"))
r, _ = self.scan()
self.assertNotEqual(r.returncode, 0)
self.assertIn("no /bin/sh in gwscan/ROOT/default", r.stderr)
def test_no_root_dataset_fails(self):
self.set_datasets(["gwscan", "gwscan/usr", "gwscan/usr/home"])
r, _ = self.scan()
self.assertNotEqual(r.returncode, 0)
self.assertIn("no /bin/sh in gwscan/ROOT/default", r.stderr)
def test_unmountable_dataset_fails(self):
self.set_datasets(self.DATASETS + ["gwscan/var"])
r, calls = self.scan()
self.assertNotEqual(r.returncode, 0)
self.assertIn("cannot mount gwscan/var", r.stderr)
self.assertIn("zpool export gwscan", calls)
def test_import_failure(self):
r, calls = self.scan(FAKE_IMPORT_RC="1")
self.assertNotEqual(r.returncode, 0)
self.assertIn("cannot import the image's pool", r.stderr)
self.assertFalse([c for c in calls if c.startswith("mount ")])
class ExitTrapTest(unittest.TestCase):
"""build.sh says when set -e stops it, but not again after die."""
def run_body(self, body):
with open(BUILD) as f:
trap = [ln for ln in f.read().splitlines() if ln.startswith("trap ")]
self.assertEqual(len(trap), 1)
return subprocess.run(["sh", "-c", "set -eu\n" + trap[0] + "\n" + build_function("die") + body],
capture_output=True, text=True)
def test_failed_command_reported(self):
r = self.run_body("false\necho not reached\n")
self.assertEqual(r.returncode, 1)
self.assertEqual(r.stdout, "")
self.assertEqual(r.stderr, "build.sh: stopped by a failed command (exit 1)\n")
def test_die_reported_once(self):
r = self.run_body('die "no set"\n')
self.assertEqual(r.returncode, 1)
self.assertEqual(r.stderr, "build.sh: no set\n")
def test_success_silent(self):
r = self.run_body("true\n")
self.assertEqual((r.returncode, r.stderr), (0, ""))
def test_usage_not_reported_as_failure(self):
r = subprocess.run(["sh", BUILD], capture_output=True, text=True)
self.assertEqual(r.returncode, 2)
self.assertNotIn("stopped by a failed command", r.stderr)
self.assertIn("build.sh build SERIES VERSION", r.stderr)
if __name__ == "__main__":
unittest.main()

View file

@ -172,7 +172,9 @@ sign()
trap 'vssh "umount -f /root/gwkey" || echo "vm.sh: WARNING: unmount /root/gwkey in the VM by hand" >&2' EXIT
# shellcheck disable=SC2086
scp -q ${SSH_OPTS} "${KEYDIR}/repo.key" "${KEYDIR}/repo.pub" root@127.0.0.1:/root/gwkey/
vssh "sh /usr/deps/release/build.sh finish $1 $2 /root/gwkey 2>&1 | tee -a /root/gwbuild.log"
# the exit status of finish, not of tee
vssh "{ sh /usr/deps/release/build.sh finish $1 $2 /root/gwkey 2>&1; echo \$? > /root/gwfinish.rc; } |
tee -a /root/gwbuild.log; exit \$(cat /root/gwfinish.rc)"
}
pull_out()