Build natively in an emulated arm64 VM on a remote build host

qemu-user cannot run cargo, so no Rust port (py-cryptography and its
dependents) can be cross-built. The build VM is now FreeBSD arm64 under
full-system emulation (qemu-system-aarch64, TCG), run by the new
release/vmhost.sh in a rootless podman container on the build host
GW_VMHOST. vm.sh drives it over ssh and reaches the VM's loopback-only
ssh port through the host (ProxyJump). Settings may live in
$GW_KEYDIR/vm.conf.

The image download probes its sources, resumes stalled transfers and
falls back to a mirror that keeps old releases; the checksum always comes
from FreeBSD itself.

build.sh builds the ports in chunks of PORTS_CHUNK (20) with timings, so
progress is visible and a failure costs one chunk, then runs the whole
list once more to bundle the set. ports_list evaluates ports.conf like
tools' list_config does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Karst 2026-11-18 23:42:04 -05:00
parent 3c3cd5e719
commit dcc4d129ab
5 changed files with 369 additions and 121 deletions

View file

@ -74,9 +74,9 @@ upstream OPNsense publishes no aarch64 packages at all. `release/build.sh`
drives [opnsense/tools](https://github.com/opnsense/tools) through base,
kernel, ports, plugins and core, builds the `mono-gateway` package from this
repository against the new kernel, signs everything and builds the eMMC image.
It runs on a FreeBSD host of the series' release (14.3 for 26.1, 15.1 for
26.7): the cross-building VM that `release/vm.sh` runs on a Linux
workstation, or a native aarch64 machine. See [RELEASE.md](RELEASE.md).
It runs on an aarch64 FreeBSD host of the series' release (14.3 for 26.1,
15.1 for 26.7): the emulated arm64 VM that `release/vm.sh` runs on a Linux
build host, or a native aarch64 machine. See [RELEASE.md](RELEASE.md).
To build only the board package on such a host after a release build:

View file

@ -13,7 +13,7 @@ built from source here, signed with our own key, and served from
```
code.karsttech.com/claude/{opnsense-src,opnsense-deps} github.com/opnsense/{tools,core,ports,plugins}
\ / (release tags)
release/build.sh in the build VM (FreeBSD amd64, cross-building aarch64)
release/build.sh in the build VM (FreeBSD arm64, emulated on the build host)
| unsigned sets -> sign (key in VM memory only) -> image
release/vm.sh pull-out -> /scratch/mono-opnsense/out/<series>/
|
@ -98,8 +98,10 @@ two names in a directory that differ only in case.
- **Private key:** `~/.config/gwmirror/repo.key` on the workstation (RSA
4096, mode 0600). It is never stored in git, in `/scratch`, on the share or
on a VM disk. **Keep an offline backup:** anyone holding it can install
code as root on the gateway.
on a VM disk. `vm.sh sign` copies it over ssh, through the build host, into
a memory file system in the build VM and removes it when signing ends.
**Keep an offline backup:** anyone holding it can install code as root on
the gateway.
- **Public key:** `keys/opnsense.karsttech.com.20261117.pub`.
- **Fingerprint:** `sha256(repo.pub)` =
`5fc1e2bf74e0386a2ea1ee60d085d683735a9d7cd8090647be0f476c779c0dc3`, shipped
@ -126,30 +128,50 @@ two names in a directory that differ only in case.
### Build host
Builds run in a FreeBSD amd64 VM on the workstation (QEMU/KVM, as the normal
user). It cross-builds aarch64:
- base, kernel and the board package use the cross compiler;
- ports run in an aarch64 chroot under qemu-user emulation, sped up by
tools' native "xtools" toolchain.
Builds run natively in a FreeBSD arm64 VM that QEMU emulates (TCG) inside a
rootless podman container on a build host: ours is the HTPC (Bazzite, Ryzen
AI Max+ 395, 16 cores), `GW_VMHOST=htpc`. The build host needs podman, curl,
sha256sum and xz, and no root. `release/vm.sh` runs `release/vmhost.sh`
there over ssh; that script builds the container image (QEMU and the arm64
UEFI firmware, from Debian) on first use and keeps the VM's files in
`~/gwbuild-vm/<osrel>`. The VM's ssh port listens on the build host's
loopback only, and vm.sh reaches it through the build host (ProxyJump).
Why emulated, not cross-built: on 2026-11-18 an amd64 VM cross-built base,
kernel and xtools in 64 minutes, but tools builds ports in an aarch64 chroot
under qemu's user-mode emulation, and no qemu-user-static available for
FreeBSD 14 can run cargo there (3.1.0 jumps into unmapped memory; 6.2.50
cannot start FreeBSD 14 programs at all). Every Rust port, py-cryptography
included, failed. Full-system emulation runs a real FreeBSD kernel: slow
(roughly a tenth of native speed), but faithful.
The VM's FreeBSD release must match the series: 14.3 for 26.1, 15.1 for
26.7 (`OS` in tools' `config/<series>/build.conf`). A native aarch64 FreeBSD
machine works with the same `build.sh` and no changes.
```sh
sudo apt install qemu-system-x86 qemu-utils genisoimage # once
release/vm.sh create 14.3 # official image, checksum verified, grown to 100G
release/vm.sh start 14.3 # first boot applies freebsd-update patches: ~20 minutes
# ~/.config/gwmirror/vm.conf, sourced by vm.sh
GW_VMHOST=htpc # ~/.ssh/config alias of the build host
GW_VM_CPUS=24
GW_VM_MEM=16G
release/vm.sh create 14.3 # on the build host: official image, checksum verified, grown to 100G
release/vm.sh start 14.3 # first boot applies freebsd-update patches: an hour or more emulated
release/vm.sh setup 14.3 # build.sh setup: host packages, ZFS settings
release/vm.sh sync 14.3 # this repository (with .git) -> /usr/deps
```
- **Disk:** the VM disk lives under `/scratch/mono-opnsense/vm` and uses ZFS
with zstd compression and autotrim. Only one series at a time fits in
`/scratch`'s free space.
- **Setup:** `setup` installs git, python3, rsync, qemu-user-static and
aarch64-binutils. They come from the frozen package set of exactly that
FreeBSD release.
- **Image:** the checksums come from download.freebsd.org or, for an old
release, archive.freebsd.org; the image itself from the first of those or
a mirror that has it (archive.freebsd.org at times stops sending).
Stalled transfers are resumed.
- **Disk:** ZFS with zstd compression and autotrim, in a qcow2 file with
copy-on-write disabled (the HTPC's home is btrfs).
- **Setup:** `setup` installs git, python3 and rsync from the frozen package
set of exactly that FreeBSD release.
- **Restarts:** the VM does not start with the build host. After a reboot,
`vm.sh start` it and run `build` again: finished sets are reused, and the
ports are built in chunks (below), so at most one chunk is lost.
### Build, sign, collect
@ -188,22 +210,29 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
port's `checksum` target then verifies the SHA256, so only the original
bytes are accepted. A distfile that still cannot be fetched stops the
build with the port's name.
5. Builds ports, plugins, core and the packages set.
6. Builds the board package against the base set's headers and our libxml2,
5. Builds the ports in chunks of `PORTS_CHUNK` (default 20) ports. Tools
adds the packages it built to the packages set only when a ports step
ends, and every run starts from that set, so a single step of several days
would lose everything to a reboot of the build host; a chunk loses only
itself. The list is tools' `ports.conf`, read the way tools reads it. A
chunk in which a port fails still saves the others, then stops the build.
A final whole ports step builds whatever the chunks missed and prunes.
6. Builds plugins, core and the packages set.
7. Builds the board package against the base set's headers and our libxml2,
and puts it into the packages set.
**`finish`:**
1. Checks the key against `keys/fingerprints/trusted`.
2. Signs base, kernel, packages and aux. Signing the packages set regenerates
the catalogue, so it includes `mono-gateway`.
3. Builds the 5 GB ZFS eMMC image (`mk-image.sh`) with the xtools set moved
aside, because tools would otherwise overlay amd64 toolchain files onto
the image.
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.
5. Compresses and signs the image.
**Before a first full build of a series**, measure the cross-build:
**To time a few ports** before a first full build of a series:
```sh
release/vm.sh run 14.3 pilot 26.1 26.1.11 security/suricata databases/py-duckdb@py313

View file

@ -134,6 +134,70 @@ host_pkg()
fi
}
# ports_list: the ports of tools' config/SERIES/ports.conf, read as tools' list_config
# reads them: comments skipped, each origin expanded with the PRODUCT_* values tools'
# Makefile gives its scripts, and lines dropped whose quirks name our target,
# architecture or SSL flavour
ports_list()
{
# one value per line, in this order; some may be empty
_vals=$(${TOOLS} -V ARCH -V APACHE -V LUA -V PERL -V PHP -V PYTHON -V RUBY -V SSL)
[ "$(echo "${_vals}" | wc -l)" -eq 8 ] || die "cannot read the PRODUCT values from tools"
{
read -r _arch
read -r PRODUCT_APACHE
read -r PRODUCT_LUA
read -r PRODUCT_PERL
read -r PRODUCT_PHP
read -r PRODUCT_PYTHON
read -r PRODUCT_RUBY
read -r PRODUCT_SSL
} <<EOF
${_vals}
EOF
_target=${_arch%%:*}
_arch=${_arch##*:}
set -f
while read -r _origin _quirks; do
case ${_origin} in
'' | '#'*) continue ;;
esac
eval "_origin=${_origin}"
for _q in $(echo "${_quirks}" | tr ',' ' '); do
if [ "${_q}" = "${_target}" ] || [ "${_q}" = "${_arch}" ] || [ "${_q}" = "${PRODUCT_SSL}" ]; then
continue 2
fi
done
echo "${_origin}"
done < "/usr/tools/config/${SERIES}/ports.conf"
set +f
}
# build_ports: tools' ports step, in chunks of PORTS_CHUNK (20) ports. Tools adds
# the packages it built to the packages set only when a ports step ends, and the
# next run starts from that set, so one long step loses days of work to a reboot of
# the build host; a chunk loses at most itself. A chunk with a failed port still
# saves the others, then stops the build. A last, whole ports step builds whatever
# the chunks missed (nothing, unless ports_list and tools disagree) and prunes.
build_ports()
{
_list=$(ports_list)
_total=$(echo "${_list}" | wc -l | tr -d ' ')
_done=0
# shellcheck disable=SC2086
echo "${_list}" | xargs -n "${PORTS_CHUNK:-20}" echo | while read -r _chunk; do
_t0=$(date +%s)
_done=$((_done + $(echo "${_chunk}" | wc -w)))
step "ports ${_done}/${_total}: ${_chunk}"
# "gwchunk" names no package: nothing is removed for a rebuild
${TOOLS} ${UNSIGNED} ports-gwchunk PORTSLIST="${_chunk}" PORTSENV="DEPEND=no PRUNE=no"
step "ports ${_done}/${_total} took $((($(date +%s) - _t0) / 60)) minutes"
done
step "ports: whole list"
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} ports-gwchunk
}
# fetch_distfiles [PORTSLIST=...]: tools' distfiles step, which fetches every distfile
# of the ports (and their dependencies) into the distfiles set. Some no longer download
# as recorded in distinfo, chiefly patches GitHub generates on the fly; the failed ports
@ -246,9 +310,10 @@ build()
step "mono-gateway kernel modules (early check against the new kernel)"
make -C "${DEPS}" -j"$(sysctl -n hw.ncpu)" modules OPS_SETTINGS="${SERIES}"
fetch_distfiles
step "ports plugins core packages"
build_ports
step "plugins core packages"
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} ports plugins core packages
${TOOLS} ${UNSIGNED} plugins core packages
sysroot_libxml2
step "mono-gateway package"
make -C "${DEPS}" -j"$(sysctl -n hw.ncpu)" package OPS_SETTINGS="${SERIES}" OPS_VERSION="${VERSION}"

View file

@ -1,9 +1,15 @@
#!/bin/sh
#
# vm.sh: the FreeBSD amd64 build VM on this Linux workstation (QEMU/KVM, no root).
# vm.sh: the FreeBSD arm64 build VM, driven from this workstation. The VM runs on the
# build host GW_VMHOST (an ssh destination; empty: this machine), emulated by QEMU in
# a rootless podman container (release/vmhost.sh, which vm.sh runs there). Its ssh
# port listens on the build host's loopback only; vm.sh reaches it through the build
# host (ProxyJump). The build is native: base, kernel, ports and image are all built
# on arm64. Emulation makes it slow, not unreliable: qemu's user-mode emulation of a
# cross build cannot even run cargo.
#
# vm.sh create OSREL download and verify the official FreeBSD OSREL image,
# grow it, and make the first-boot seed ISO
# vm.sh create OSREL download and verify the official FreeBSD OSREL arm64
# image on the build host, grow it, make the seed
# vm.sh start | stop | status OSREL
# vm.sh ssh OSREL [COMMAND...]
# vm.sh setup OSREL install the build host packages (build.sh setup)
@ -19,9 +25,11 @@
# OSREL is the FreeBSD release the OPNsense series is built on: 14.3 for 26.1,
# 15.1 for 26.7 (the OS line of tools' config/<series>/build.conf).
#
# Environment: GW_VMROOT (default /scratch/mono-opnsense/vm), GW_OUT (default
# Settings come from the environment or from $GW_KEYDIR/vm.conf (sourced): GW_VMHOST,
# GW_VMROOT (the VM directory on the build host; vmhost.sh's default ~/gwbuild-vm),
# GW_VM_CPUS (8), GW_VM_MEM (16G), GW_VM_DISK (100G), GW_OUT (default
# /scratch/mono-opnsense/out), GW_KEYDIR (default ~/.config/gwmirror, holding repo.key,
# repo.pub and the VM's SSH key), GW_VM_CPUS (6), GW_VM_MEM (20G), GW_VM_DISK (100G).
# repo.pub and the VM's ssh key).
#
# Copyright 2026 Karst Tech
# SPDX-License-Identifier: BSD-2-Clause
@ -29,12 +37,11 @@
set -eu
HERE=$(cd "$(dirname "$0")/.." && pwd)
VMROOT=${GW_VMROOT:-/scratch/mono-opnsense/vm}
OUT=${GW_OUT:-/scratch/mono-opnsense/out}
KEYDIR=${GW_KEYDIR:-${HOME}/.config/gwmirror}
CPUS=${GW_VM_CPUS:-6}
MEM=${GW_VM_MEM:-20G}
DISKSIZE=${GW_VM_DISK:-100G}
# shellcheck disable=SC1091
[ ! -f "${KEYDIR}/vm.conf" ] || . "${KEYDIR}/vm.conf"
VMHOST=${GW_VMHOST:-}
OUT=${GW_OUT:-/scratch/mono-opnsense/out}
SSHKEY=${KEYDIR}/vm_ed25519
die()
@ -45,7 +52,7 @@ die()
usage()
{
sed -n '3,26p' "${0}" >&2
sed -n '3,33p' "${0}" >&2
exit 2
}
@ -55,16 +62,14 @@ OSREL=${2}
shift 2
echo "${OSREL}" | grep -Eqx '1[4-9]\.[0-9]' || die "bad FreeBSD release '${OSREL}'"
VMDIR=${VMROOT}/${OSREL}
DISK=${VMDIR}/disk.qcow2
SEED=${VMDIR}/seed.iso
PIDFILE=${VMDIR}/qemu.pid
PORT=$((2200 + ${OSREL%.*}))
SSH_OPTS="-p ${PORT} -i ${SSHKEY} -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=${VMDIR}/known_hosts -o ConnectTimeout=10 -o ServerAliveInterval=60"
KNOWN=${KEYDIR}/vm_known_hosts-${OSREL}
SSH_OPTS="-o Port=${PORT} -o IdentityFile=${SSHKEY} -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=${KNOWN} -o ConnectTimeout=20 -o ServerAliveInterval=60"
[ -z "${VMHOST}" ] || SSH_OPTS="${SSH_OPTS} -o ProxyJump=${VMHOST}"
running()
{
[ -f "${PIDFILE}" ] && kill -0 "$(cat "${PIDFILE}")" 2>/dev/null
vssh true 2> /dev/null
}
vssh()
@ -77,97 +82,60 @@ vssh()
safe_words()
{
for w; do
echo "${w}" | grep -Eqx '[A-Za-z0-9][A-Za-z0-9._/,@-]*' || die "unsafe argument '${w}'"
echo "${w}" | grep -Eqx '[A-Za-z0-9][A-Za-z0-9._/,@+=-]*' || die "unsafe argument '${w}'"
done
}
# vmhost COMMAND [ARG...]: release/vmhost.sh on the build host, with the VM settings
vmhost()
{
safe_words "$@"
_env=
for _v in GW_VMROOT GW_VM_CPUS GW_VM_MEM GW_VM_DISK; do
eval "_val=\${${_v}:-}"
[ -z "${_val}" ] || { safe_words "${_val}"; _env="${_env} ${_v}=${_val}"; }
done
if [ -n "${VMHOST}" ]; then
# shellcheck disable=SC2029
ssh -o BatchMode=yes "${VMHOST}" "env${_env} sh -s -- $*" < "${HERE}/release/vmhost.sh"
else
# shellcheck disable=SC2086
env${_env} sh "${HERE}/release/vmhost.sh" "$@"
fi
}
create()
{
[ ! -e "${DISK}" ] || die "${DISK} exists (vm.sh destroy ${OSREL} first)"
for tool in qemu-system-x86_64 qemu-img genisoimage xz curl sha256sum ssh-keygen; do
command -v ${tool} > /dev/null || die "${tool} is missing (sudo apt install qemu-system-x86 qemu-utils genisoimage xz-utils)"
done
[ -r /dev/kvm ] && [ -w /dev/kvm ] || die "no access to /dev/kvm"
mkdir -p "${VMDIR}" "${KEYDIR}"
mkdir -p "${KEYDIR}"
[ -f "${SSHKEY}" ] || ssh-keygen -q -t ed25519 -N '' -C gwmirror-build-vm -f "${SSHKEY}"
IMG=FreeBSD-${OSREL}-RELEASE-amd64-BASIC-CLOUDINIT-zfs.qcow2.xz
BASE=
for b in https://download.freebsd.org/releases/VM-IMAGES https://archive.freebsd.org/old-releases/VM-IMAGES; do
if curl -fsS -o /dev/null -I "${b}/${OSREL}-RELEASE/amd64/Latest/${IMG}" 2>/dev/null; then
BASE=${b}/${OSREL}-RELEASE/amd64/Latest
break
fi
done
[ -n "${BASE}" ] || die "no ${IMG} on download.freebsd.org or archive.freebsd.org"
echo ">>> downloading ${BASE}/${IMG}"
curl -fsS --proto =https -o "${VMDIR}/CHECKSUM.SHA256" "${BASE}/CHECKSUM.SHA256"
curl -fS --proto =https -o "${VMDIR}/${IMG}" "${BASE}/${IMG}"
WANT=$(sed -n "s/^SHA256 (${IMG}) = \([0-9a-f]\{64\}\)\$/\1/p" "${VMDIR}/CHECKSUM.SHA256")
HAVE=$(sha256sum "${VMDIR}/${IMG}" | cut -d' ' -f1)
[ -n "${WANT}" ] && [ "${WANT}" = "${HAVE}" ] || die "checksum mismatch for ${IMG}"
xz -d "${VMDIR}/${IMG}"
mv "${VMDIR}/${IMG%.xz}" "${DISK}"
qemu-img resize -q "${DISK}" "${DISKSIZE}"
# nuageinit runs a user-data file that is not "#cloud-config" as a root
# script on first boot: install our key for root and nothing else.
SEEDDIR=${VMDIR}/seed
mkdir -p "${SEEDDIR}"
printf 'instance-id: gwbuild-%s\nlocal-hostname: gwbuild-%s\n' "${OSREL}" "$(echo "${OSREL}" | tr . -)" > "${SEEDDIR}/meta-data"
cat > "${SEEDDIR}/user-data" <<EOF
#!/bin/sh
mkdir -p /root/.ssh
chmod 700 /root/.ssh
echo '$(cat "${SSHKEY}.pub")' > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
sysrc sshd_enable=YES ifconfig_DEFAULT=SYNCDHCP growfs_enable=YES
printf 'PermitRootLogin prohibit-password\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n' >> /etc/ssh/sshd_config
EOF
chmod 755 "${SEEDDIR}/user-data"
genisoimage -quiet -output "${SEED}" -volid cidata -rational-rock -joliet "${SEEDDIR}/user-data" "${SEEDDIR}/meta-data"
echo ">>> created ${DISK}; next: vm.sh start ${OSREL}"
# shellcheck disable=SC2046
vmhost create "${OSREL}" $(cut -d' ' -f1-3 "${SSHKEY}.pub")
rm -f "${KNOWN}"
echo ">>> next: vm.sh start ${OSREL}"
}
start()
{
running && die "already running (pid $(cat "${PIDFILE}"))"
[ -f "${DISK}" ] || die "no ${DISK} (vm.sh create ${OSREL})"
qemu-system-x86_64 -name "gwbuild-${OSREL}" -machine q35,accel=kvm -cpu host \
-smp "${CPUS}" -m "${MEM}" \
-drive "file=${DISK},if=virtio,cache=none,discard=unmap" \
-drive "file=${SEED},media=cdrom,readonly=on" \
-netdev "user,id=n0,hostfwd=tcp:127.0.0.1:${PORT}-:22" -device virtio-net-pci,netdev=n0 \
-display none -serial "file:${VMDIR}/console.log" \
-daemonize -pidfile "${PIDFILE}"
vmhost start "${OSREL}"
# the first boot applies freebsd-update patches and reboots before sshd
# starts, which takes a while
echo ">>> waiting for ssh on 127.0.0.1:${PORT} (console: ${VMDIR}/console.log)"
# starts, which takes long under emulation
echo ">>> waiting for ssh (up to 4 hours)"
i=0
until vssh true 2>/dev/null; do
until running; do
i=$((i + 1))
[ ${i} -lt 270 ] || die "no ssh after 45 minutes; see ${VMDIR}/console.log"
running || die "qemu exited; see ${VMDIR}/console.log"
sleep 10
[ ${i} -lt 480 ] || die "no ssh after 4 hours; see console.log in the VM directory on the build host"
if [ $((i % 10)) = 0 ] && [ "$(vmhost status "${OSREL}")" = stopped ]; then
die "the VM stopped; see console.log in the VM directory on the build host"
fi
sleep 30
done
echo ">>> up: vm.sh ssh ${OSREL}"
}
stop()
{
running || { echo ">>> not running"; return 0; }
vssh shutdown -p now 2>/dev/null || true
i=0
while running; do
i=$((i + 1))
if [ ${i} -gt 60 ]; then
kill "$(cat "${PIDFILE}")"
break
fi
sleep 2
done
rm -f "${PIDFILE}"
echo ">>> stopped"
vssh shutdown -p now 2> /dev/null || true
vmhost stop "${OSREL}"
}
sync_deps()
@ -200,8 +168,7 @@ sign()
vssh 'umount /root/gwkey 2>/dev/null; mkdir -p /root/gwkey && mount -t tmpfs -o size=1m,mode=0700 tmpfs /root/gwkey'
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 -P ${PORT} -i "${SSHKEY}" -o IdentitiesOnly=yes -o UserKnownHostsFile="${VMDIR}/known_hosts" \
"${KEYDIR}/repo.key" "${KEYDIR}/repo.pub" root@127.0.0.1:/root/gwkey/
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"
}
@ -222,7 +189,7 @@ case "${CMD}" in
create) [ $# -eq 0 ] || usage; create ;;
start) start ;;
stop) stop ;;
status) running && echo "running (pid $(cat "${PIDFILE}"), ssh port ${PORT})" || echo "stopped" ;;
status) vmhost status "${OSREL}" ;;
ssh) vssh "$@" ;;
setup) running || die "not running"; vssh sh -s setup < "${HERE}/release/build.sh" ;;
sync) sync_deps ;;
@ -230,6 +197,6 @@ run) run_build "$@" ;;
log) vssh tail -n 200 -F /root/gwbuild.log ;;
sign) sign "$@" ;;
pull-out) pull_out "$@" ;;
destroy) stop; rm -rf "${VMDIR}"; echo ">>> removed ${VMDIR}" ;;
destroy) stop; vmhost destroy "${OSREL}"; rm -f "${KNOWN}" ;;
*) usage ;;
esac

187
release/vmhost.sh Normal file
View file

@ -0,0 +1,187 @@
#!/bin/sh
#
# vmhost.sh: the FreeBSD arm64 build VM, on the host that runs this script. QEMU
# emulates the VM (TCG: any x86_64 or arm64 Linux host, no KVM, no root) inside a
# rootless podman container, so the host needs only podman, curl, sha256sum and xz.
# vm.sh runs this script on the build host over ssh, or here without a build host.
#
# vmhost.sh create OSREL KEYTYPE KEY COMMENT
# download and verify the official FreeBSD OSREL arm64 image,
# grow it, and make the first-boot seed that lets root log in
# with the given ssh public key
# vmhost.sh start OSREL boot the VM; its ssh port is 127.0.0.1:(2200 + OS major)
# vmhost.sh stop OSREL wait for the VM to power off (vm.sh shuts it down first),
# then remove its container
# vmhost.sh status | destroy OSREL
#
# Environment: GW_VMROOT (default ~/gwbuild-vm), GW_VM_CPUS (8), GW_VM_MEM (16G),
# GW_VM_DISK (100G).
#
# Copyright 2026 Karst Tech
# SPDX-License-Identifier: BSD-2-Clause
set -eu
VMROOT=${GW_VMROOT:-${HOME}/gwbuild-vm}
CPUS=${GW_VM_CPUS:-8}
MEM=${GW_VM_MEM:-16G}
DISKSIZE=${GW_VM_DISK:-100G}
IMAGE=localhost/gwbuild-qemu:1
die()
{
echo "vmhost.sh: $*" >&2
exit 1
}
[ $# -ge 2 ] || die "usage: vmhost.sh create|start|stop|status|destroy OSREL"
CMD=${1}
OSREL=${2}
shift 2
echo "${OSREL}" | grep -Eqx '1[4-9]\.[0-9]' || die "bad FreeBSD release '${OSREL}'"
echo "${CPUS}" | grep -Eqx '[1-9][0-9]{0,2}' || die "bad GW_VM_CPUS '${CPUS}'"
for v in "${MEM}" "${DISKSIZE}"; do
echo "${v}" | grep -Eqx '[1-9][0-9]*[MG]' || die "bad size '${v}'"
done
VMDIR=${VMROOT}/${OSREL}
NAME=gwbuild-${OSREL}
PORT=$((2200 + ${OSREL%.*}))
running()
{
[ "$(podman inspect -f '{{.State.Running}}' "${NAME}" 2>/dev/null)" = true ]
}
# QEMU, its arm64 UEFI firmware and the image tools, from Debian
build_image()
{
podman image exists "${IMAGE}" && return 0
_ctx=$(mktemp -d)
cat > "${_ctx}/Containerfile" <<'EOF'
FROM docker.io/library/debian:trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends qemu-system-arm qemu-efi-aarch64 qemu-utils genisoimage \
&& rm -rf /var/lib/apt/lists/*
EOF
podman build -q -t "${IMAGE}" "${_ctx}" > /dev/null
rm -rf "${_ctx}"
}
# the VM's directory is shared ("z") with the running VM's container
in_image()
{
podman run --rm -v "${VMDIR}:/vm:z" "${IMAGE}" "$@"
}
create()
{
[ $# -eq 3 ] || die "create needs the ssh public key (type, key, comment)"
[ "${1}" = ssh-ed25519 ] && echo "${2}" | grep -Eqx '[A-Za-z0-9+/]{40,}={0,2}' &&
echo "${3}" | grep -Eqx '[A-Za-z0-9._@-]+' || die "bad ssh public key"
[ ! -e "${VMDIR}/disk.qcow2" ] || die "${VMDIR}/disk.qcow2 exists (vm.sh destroy ${OSREL} first)"
for t in podman curl sha256sum xz; do
command -v ${t} > /dev/null || die "${t} is missing"
done
mkdir -p "${VMDIR}"
# no copy-on-write under a disk image (btrfs; elsewhere this does nothing)
chattr +C "${VMDIR}" 2> /dev/null || true
build_image
IMG=FreeBSD-${OSREL}-RELEASE-arm64-aarch64-BASIC-CLOUDINIT-zfs.qcow2.xz
REL=${OSREL}-RELEASE/aarch64/Latest
# The checksums come from FreeBSD itself; the image from the first source that
# has it, including a mirror that keeps old releases (archive.freebsd.org, the
# only official home of an old release, at times stops answering). Transfers
# that stall for a minute are resumed, many times.
OFFICIAL="https://download.freebsd.org/releases/VM-IMAGES https://archive.freebsd.org/old-releases/VM-IMAGES"
SOURCES="${OFFICIAL} https://mirror.math.princeton.edu/pub/FreeBSD/releases/VM-IMAGES"
_probe="curl -fsS -o /dev/null -I --proto =https --connect-timeout 30 --max-time 60"
_curl="curl -fsS --proto =https --connect-timeout 30 --speed-limit 1024 --speed-time 60 --retry 30 --retry-delay 20 --retry-all-errors -C -"
_sum()
{
sed -n "s/^SHA256 (${IMG}) = \([0-9a-f]\{64\}\)\$/\1/p" "${VMDIR}/CHECKSUM.SHA256" 2> /dev/null || true
}
WANT=$(_sum)
for b in ${OFFICIAL}; do
[ -z "${WANT}" ] || break
${_probe} "${b}/${REL}/CHECKSUM.SHA256" 2> /dev/null || continue
rm -f "${VMDIR}/CHECKSUM.SHA256.new"
${_curl} -o "${VMDIR}/CHECKSUM.SHA256.new" "${b}/${REL}/CHECKSUM.SHA256" || continue
mv "${VMDIR}/CHECKSUM.SHA256.new" "${VMDIR}/CHECKSUM.SHA256"
WANT=$(_sum)
done
[ -n "${WANT}" ] || die "no checksum for ${IMG} from download.freebsd.org or archive.freebsd.org"
HAVE=
for b in ${SOURCES}; do
${_probe} "${b}/${REL}/${IMG}" 2> /dev/null || continue
echo ">>> downloading ${b}/${REL}/${IMG}"
${_curl} -o "${VMDIR}/${IMG}" "${b}/${REL}/${IMG}" || continue
HAVE=$(sha256sum "${VMDIR}/${IMG}" | cut -d' ' -f1)
[ "${HAVE}" = "${WANT}" ] && break
echo ">>> checksum mismatch for the image from ${b}" >&2
rm -f "${VMDIR}/${IMG}"
done
[ "${HAVE}" = "${WANT}" ] || die "could not download ${IMG} with the published checksum"
xz -d "${VMDIR}/${IMG}"
mv "${VMDIR}/${IMG%.xz}" "${VMDIR}/disk.qcow2"
in_image qemu-img resize -q /vm/disk.qcow2 "${DISKSIZE}"
in_image cp /usr/share/AAVMF/AAVMF_VARS.fd /vm/efivars.fd
# nuageinit runs a user-data file that is not "#cloud-config" as a root
# script on first boot: install the key for root and nothing else.
mkdir -p "${VMDIR}/seed"
printf 'instance-id: gwbuild-%s\nlocal-hostname: gwbuild-%s\n' "${OSREL}" "$(echo "${OSREL}" | tr . -)" \
> "${VMDIR}/seed/meta-data"
cat > "${VMDIR}/seed/user-data" <<EOF
#!/bin/sh
mkdir -p /root/.ssh
chmod 700 /root/.ssh
echo '${1} ${2} ${3}' > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
sysrc sshd_enable=YES ifconfig_DEFAULT=SYNCDHCP growfs_enable=YES
printf 'PermitRootLogin prohibit-password\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n' >> /etc/ssh/sshd_config
EOF
chmod 755 "${VMDIR}/seed/user-data"
in_image genisoimage -quiet -output /vm/seed.iso -volid cidata -rational-rock -joliet \
/vm/seed/user-data /vm/seed/meta-data
echo ">>> created ${VMDIR}"
}
start()
{
running && die "already running"
[ -f "${VMDIR}/disk.qcow2" ] || die "no ${VMDIR}/disk.qcow2 (vm.sh create ${OSREL})"
build_image
podman rm -f "${NAME}" > /dev/null 2>&1 || true
# neoverse-n1: ARMv8.2 with LSE atomics, without the costly emulation of SVE
# and pointer authentication. The ssh port is on the host's loopback only.
podman run -d --name "${NAME}" --network host -v "${VMDIR}:/vm:z" "${IMAGE}" \
qemu-system-aarch64 -name "${NAME}" -machine virt,gic-version=3 -cpu neoverse-n1 \
-accel tcg,thread=multi -smp "${CPUS}" -m "${MEM}" \
-drive if=pflash,format=raw,readonly=on,file=/usr/share/AAVMF/AAVMF_CODE.fd \
-drive if=pflash,format=raw,file=/vm/efivars.fd \
-drive file=/vm/disk.qcow2,if=virtio,format=qcow2,discard=unmap \
-drive file=/vm/seed.iso,if=virtio,format=raw,readonly=on \
-netdev "user,id=n0,hostfwd=tcp:127.0.0.1:${PORT}-:22" -device virtio-net-pci,netdev=n0 \
-display none -serial file:/vm/console.log > /dev/null
echo ">>> started ${NAME}: ${CPUS} CPUs, ${MEM}, ssh on 127.0.0.1:${PORT}, console ${VMDIR}/console.log"
}
stop()
{
if running; then
timeout 300 podman wait "${NAME}" > /dev/null 2>&1 || podman stop -t 30 "${NAME}" > /dev/null
fi
podman rm -f "${NAME}" > /dev/null 2>&1 || true
echo ">>> stopped ${NAME}"
}
case "${CMD}" in
create) create "$@" ;;
start) start ;;
stop) stop ;;
status) running && echo "running (ssh 127.0.0.1:${PORT} on this host)" || echo "stopped" ;;
destroy) stop; rm -rf "${VMDIR}"; echo ">>> removed ${VMDIR}" ;;
*) die "unknown command '${CMD}'" ;;
esac