Skip to content

XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)

C

Linux host scripts: boot reports failed and ended runs as they ended, the service survives a kernel update, remove undoes both services, relative paths, dnsmasq restarts, hcmd, the first rebuild on a new host; tests/scripts and CI

Fred Nix2bdab9a9d455
diff --git a/scripts/build-host.sh b/scripts/build-host.sh
index 2faaf98..48eb492 100755
--- a/scripts/build-host.sh
+++ b/scripts/build-host.sh
@@ -2,7 +2,7 @@
# SPDX-License-Identifier: GPL-2.0-only
# Build the arm64 host Linux (4K pages like the UniXNU 4K XNU machine layer, 48-bit VA, user PAC) with the FKI patch, plus a busybox initramfs.
set -euo pipefail
-P=$(cd "$(dirname "$0")/.." && pwd); W=${W:?W: a work directory holding src/linux (a Linux tree); the build goes to $W/out/linux}; L=$W/src/linux; O=$W/out/linux; mkdir -p $O
+P=$(cd "$(dirname "$0")/.." && pwd); W=${W:?W: a work directory holding src/linux (a Linux tree); the build goes to $W/out/linux}; W=$(cd "$W" && pwd); L=$W/src/linux; O=$W/out/linux; mkdir -p $O
cd $L
git checkout -q -- drivers/Kconfig drivers/Makefile
rsync -a $P/linux/ ./
diff --git a/scripts/console-send-file.sh b/scripts/console-send-file.sh
index 85d3a6c..7e1afdd 100755
--- a/scripts/console-send-file.sh
+++ b/scripts/console-send-file.sh
@@ -2,9 +2,10 @@
# SPDX-License-Identifier: GPL-2.0-only
# console-send-file.sh LOCAL REMOTE: types LOCAL into the hosted macOS console shell as short base64 lines (one every
# 0.3 s, so the tty input queue never overflows: one long typed line gets mangled by the line editor), decoded to REMOTE.
-cd "$(dirname "$0")/.."
+P=$(cd "$(dirname "$0")/.." && pwd) # no cd there: LOCAL is a path of the caller's
f=$1; r=$2
+[ -f "$f" ] || { echo "$f: no such file" >&2; exit 1; } # before anything is typed: the lines below remove REMOTE
{ echo "rm -f $r.b64"
base64 < "$f" | tr -d '\n' | fold -w 100 | while read -r l || [ -n "$l" ]; do echo "echo $l >> $r.b64"; done
echo "base64 -D -i $r.b64 -o $r"
-} | bash scripts/vm.sh 'while IFS= read -r l; do printf "%s\n" "$l" >> /var/tmp/console-in; sleep 0.3; done'
+} | bash "$P/scripts/vm.sh" 'while IFS= read -r l; do printf "%s\n" "$l" >> /var/tmp/console-in; sleep 0.3; done'
diff --git a/scripts/free-kc/build.sh b/scripts/free-kc/build.sh
index e8d1112..2c280f2 100755
--- a/scripts/free-kc/build.sh
+++ b/scripts/free-kc/build.sh
@@ -13,6 +13,7 @@
set -euo pipefail
POC=$(cd "$(dirname "$0")/../.." && pwd)
DVM=${DVM:-$HOME/w/dvm}; W=${FREE_KC_WORK:-$HOME/w/free-kc}; OUT=${OUT:-/lib/firmware/xnu/kc-free.bin}
+mkdir -p $W; W=$(cd $W && pwd); DVM=$(cd $DVM && pwd) # every step below runs in another directory: no relative names
PD_URL=https://github.com/AFK-surf/PureDarwin PD_REV=b3b4b2812fdd1c5c251dc3089b5a1a9e00d29970
MBEDTLS_URL=https://github.com/Mbed-TLS/mbedtls MBEDTLS_REV=$(sed -n 's/^MBEDTLS_REV=//p' $POC/kexts/free/corecrypto/mbedtls.rev)
export DVM NETINC=${NETINC:-$POC/build/netinc}
diff --git a/scripts/install-service.sh b/scripts/install-service.sh
index f0f6e28..795242f 100755
--- a/scripts/install-service.sh
+++ b/scripts/install-service.sh
@@ -4,9 +4,26 @@
# macOS as a system service. It starts at boot, is stopped cleanly (its disk synced) when the VM shuts down, and is
# started again after a panic or a run that ended by itself; each run's kernel log is in /var/log/xnulinux/.
# sudo systemctl status xnulinux journalctl -u xnulinux settings: /etc/xnulinux.conf (then: systemctl restart xnulinux)
+# scripts/install-service.sh remove stop the hosted system (its disk synced first) and take the service away again
set -euo pipefail
P=$(cd "$(dirname "$0")/.." && pwd)
+if [ "${1:-}" = remove ]; then
+ # stopped through the unit while there is one (its ExecStop is xnulinux-boot.sh stop); a system started by hand the same way
+ if [ -f /etc/systemd/system/xnulinux.service ]; then sudo systemctl disable --now xnulinux.service; fi
+ [ ! -d /sys/module/xnu ] || (cd "$P" && scripts/xnulinux-boot.sh stop)
+ sudo rm -f /etc/systemd/system/xnulinux.service
+ sudo systemctl daemon-reload
+ echo "removed: xnulinux.service (kept: /etc/xnulinux.conf, the logs in /var/log/xnulinux, the disk; fki.ko and the memory set aside for it: scripts/vm-install-fki-service.sh remove)"
+ exit 0
+fi
U=$(id -un)
+# The service runs xnulinux-boot.sh as this user with no terminal: every sudo in it has to work without a password
+# (-k: not on the strength of one typed a moment ago). Said here, not by a unit that fails at the next boot.
+[ "$(id -u)" = 0 ] || sudo -k -n true 2>/dev/null || {
+ echo "$U cannot use sudo without a password, and the service runs scripts/xnulinux-boot.sh as $U with no terminal to ask on:" >&2
+ echo "give $U a NOPASSWD rule (sudo visudo -f /etc/sudoers.d/xnulinux: '$U ALL=(ALL) NOPASSWD:ALL') or run this as root" >&2
+ exit 1
+}
# the disk's UUIDs, where the service's xnulinux-boot.sh will look for them: MAC_CONF of /etc/xnulinux.conf (a PureDarwin
# disk's pd.conf, say), /var/tmp/mac.conf without one
M=$(unset MAC_CONF; [ -f /etc/xnulinux.conf ] && . /etc/xnulinux.conf >/dev/null; echo "${MAC_CONF:-/var/tmp/mac.conf}")
@@ -21,12 +38,14 @@ GPU=${GPU:-auto} # auto: the host GPU when the VM has a render node; off: CPU re
#XNU_ARGS="model=VirtualMac2,1"
#BOOTARGS="amfi_get_out_of_my_way=1 lp-sip0=2050 bt-transport-override=10"
CONF
+# Wants=, not Requires=, the unit that loads fki.ko at boot: after a kernel update that load fails (fki.ko is still the old
+# kernel's), and a required unit that failed keeps this one from ever starting. xnulinux-boot.sh builds both modules for
+# the running kernel and loads fki.ko itself when it is not loaded, with that unit's arguments.
sudo tee /etc/systemd/system/xnulinux.service >/dev/null <<UNIT
[Unit]
Description=xnulinux: the hosted macOS
After=xnulinux-fki.service network-online.target
-Wants=network-online.target
-Requires=xnulinux-fki.service
+Wants=xnulinux-fki.service network-online.target
StartLimitIntervalSec=600
StartLimitBurst=5
diff --git a/scripts/vm-install-fki-service.sh b/scripts/vm-install-fki-service.sh
index 54b6289..8331915 100755
--- a/scripts/vm-install-fki-service.sh
+++ b/scripts/vm-install-fki-service.sh
@@ -6,10 +6,22 @@
# regions and loads the Linux kernel image (nokaslr: see below). A CMA area was not enough: one page Linux pins in it
# during the boot (a buffer-head page of the block device) splits it, and the 8 GB block does not fit.
# A VM with more memory: LINUX_MEM=15G CARVE_BASE=0x400000000 for 24 GB.
+# scripts/vm-install-fki-service.sh remove give the memory back: the command line and the unit as they were before (after
+# scripts/install-service.sh remove; Linux has all of its RAM again after a reboot)
set -euo pipefail
P=$(cd "$(dirname "$0")/.." && pwd)
LINUX_MEM=${LINUX_MEM:-7G}; CARVE_BASE=${CARVE_BASE:-0x200000000}; CARVE_MB=${CARVE_MB:-8156}
G=/etc/default/grub.d/99-xnulinux.cfg
+if [ "${1:-}" = remove ]; then
+ [ ! -d /sys/module/xnu ] || { echo "a hosted system is running: scripts/install-service.sh remove (or scripts/xnulinux-boot.sh stop) first" >&2; exit 1; }
+ if [ -f /etc/systemd/system/xnulinux-fki.service ]; then sudo systemctl disable --now xnulinux-fki.service; fi
+ sudo rm -f /etc/systemd/system/xnulinux-fki.service "$G"
+ sudo systemctl daemon-reload
+ sudo update-grub >/dev/null 2>&1
+ if [ -d /sys/module/fki ]; then sudo systemctl stop xnudrmd 2>/dev/null || true; sudo rmmod fki; fi # (xnudrmd holds its /dev/xnu-hostcall)
+ echo "removed: xnulinux-fki.service and the mem= command line ($G); fki.ko is unloaded, and after a reboot Linux has all of the machine's memory again"
+ exit 0
+fi
# nokaslr: arm64's EFI stub randomises the Linux kernel's physical load address across all EFI memory before mem=
# takes effect, which otherwise places the kernel image inside the carve-out on some boots (fki then refuses to map it).
echo "GRUB_CMDLINE_LINUX=\"\$GRUB_CMDLINE_LINUX mem=$LINUX_MEM nokaslr log_buf_len=128M\"" | sudo tee $G >/dev/null
diff --git a/scripts/vm-net-up.sh b/scripts/vm-net-up.sh
index 62bc877..3350cc1 100755
--- a/scripts/vm-net-up.sh
+++ b/scripts/vm-net-up.sh
@@ -11,8 +11,10 @@ sudo sysctl -q -w net.ipv4.ip_forward=1
# the default route's interface: the word after "dev", wherever it is ("default dev wg0 scope link" has no gateway before
# it, and a multipath route names its interfaces on the next-hop lines)
up=$(ip route show default | awk '{ for (i = 1; i < NF; i++) if ($i == "dev") { print $(i + 1); exit } }')
-sudo iptables -t nat -C POSTROUTING -s 192.168.77.0/24 -o "$up" -j MASQUERADE 2>/dev/null ||
- sudo iptables -t nat -A POSTROUTING -s 192.168.77.0/24 -o "$up" -j MASQUERADE
+if [ -n "$up" ]; then
+ sudo iptables -t nat -C POSTROUTING -s 192.168.77.0/24 -o "$up" -j MASQUERADE 2>/dev/null ||
+ sudo iptables -t nat -A POSTROUTING -s 192.168.77.0/24 -o "$up" -j MASQUERADE
+fi
sudo iptables -C FORWARD -i xnu0 -j ACCEPT 2>/dev/null || sudo iptables -I FORWARD -i xnu0 -j ACCEPT
sudo iptables -C FORWARD -o xnu0 -m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null ||
sudo iptables -I FORWARD -o xnu0 -m state --state RELATED,ESTABLISHED -j ACCEPT
@@ -28,9 +30,21 @@ if command -v ethtool >/dev/null && ethtool -k "$up" 2>/dev/null | grep -q '^rx-
sudo ethtool -K "$up" rx-gro-hw off && echo "vm-net-up: hardware GRO off on $up (its packets cannot be forwarded to xnu0)"
fi
command -v dnsmasq >/dev/null || sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q dnsmasq-base >/dev/null 2>&1
+D=no
if command -v dnsmasq >/dev/null; then
+ # pkill does not wait for the one it ended, which holds 192.168.77.1's ports a moment longer. A dnsmasq started in that
+ # moment fails ("Address already in use") and then there is none: every second start of the hosted system had no DHCP
+ # and no DNS. Waited for by process id, taken before the kill: a process that is ending has no command line to be
+ # found by any more while it still has its sockets.
+ OLD=$(pgrep -f 'dnsmasq.*xnu0' || true)
sudo pkill -f 'dnsmasq.*xnu0' 2>/dev/null
- sudo dnsmasq --interface=xnu0 --bind-interfaces --except-interface=lo --dhcp-range=192.168.77.2,192.168.77.50,12h \
+ for _ in $(seq 1 50); do
+ left=; for p in $OLD; do ! sudo kill -0 "$p" 2>/dev/null || left=1; done
+ [ -n "$left" ] || break; sleep 0.1
+ done
+ if sudo dnsmasq --interface=xnu0 --bind-interfaces --except-interface=lo --dhcp-range=192.168.77.2,192.168.77.50,12h \
--dhcp-option=3,192.168.77.1 --dhcp-option=6,192.168.77.1 --pid-file=/run/dnsmasq-xnu0.pid
+ then D=yes; else D="DID NOT START (the hosted system gets no address and no DNS)"; fi
fi
-echo "vm-net-up: xnu0 192.168.77.1/24 up, NAT via $up, dnsmasq: $(command -v dnsmasq >/dev/null && echo yes || echo no)"
+[ -n "$up" ] && N="via $up" || N="none (this host has no default route)"
+echo "vm-net-up: xnu0 192.168.77.1/24 up, NAT $N, dnsmasq: $D"
diff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.sh
index 66947e4..5a729ab 100755
--- a/scripts/vm-xnu-rebuild.sh
+++ b/scripts/vm-xnu-rebuild.sh
@@ -1,8 +1,8 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-only
-# Inside the VM: apply xnulinux's XNU patches to the k27 tree, rebuild the kernel incrementally, and (when the macOS 27.2
-# kernelcache is there) relink the kernel collection with Apple's kexts. The kernel's segment slots inside the collection
-# (k27/segaddrs.sh) follow the kernel's size: when kc27-layout.py moves them, the kernel is linked again.
+# Inside the VM: apply xnulinux's XNU patches to the k27 tree, rebuild the kernel incrementally, build xnulinux's kexts,
+# and (when the macOS 27.2 kernelcache is there) relink the kernel collection with Apple's kexts. The kernel's segment slots
+# inside the collection (k27/segaddrs.sh) follow the kernel's size: when kc27-layout.py moves them, the kernel is linked again.
set -e -o pipefail # a failed kernel build stops here: never repackage the previous kernel
POC=${POC:-$(cd "$(dirname "$0")/.." && pwd)} # this repository: its patches, kexts and linker
cd ~/w/dvm
@@ -35,35 +35,44 @@ rm -rf $T/osfmk/corecrypto $T/osfmk/arm64/corecrypto
mirror "$P"/corecrypto/include/corecrypto $T/EXTERNAL_HEADERS/corecrypto
mirror "$P"/corecrypto/kernel $T/osfmk/xnulinux_crypto
t=$SECONDS; JOBS=12 bash k27/build-kernel27.sh 2>&1 | tail -15; echo "kernel: $((SECONDS - t)) s"
+sudo mkdir -p /lib/firmware/xnu # where xnu.ko takes the kernel and the collection from: a new host has none
+cp k27/segaddrs.sh /tmp/segaddrs.before
if [ -e out/kc/kc27.bin ]; then
- cp k27/segaddrs.sh /tmp/segaddrs.before
python3 k27/kc27-layout.py out/kc/kc27.bin out/k27/kernel-k27.macho --write k27/segaddrs.sh | tail -2
- if ! cmp -s /tmp/segaddrs.before k27/segaddrs.sh; then
- echo "kernel slots moved: linking the kernel again"
- JOBS=12 bash k27/build-kernel27.sh 2>&1 | tail -3
- fi
- # xnulinux's own kexts (kexts/*/NAME.json + NAME.cpp), built against the k27 kernel's objects and linked into the collection
- NATIVE=()
- # IONetworkingFamily's kernel headers (IOKit/network/*.h) for XnuEthernet: Apple's open source IONetworkingFamily-188 (APSL,
- # fetched here, not kept in the repository), whose __PRIVATE_SPI__ declarations name the reserved slots 2-5 the shipped family
- # uses (the SDK's headers leave slot 5 a reserved stub the collection does not export)
- NETINC="$POC/build/netinc"; NETSRC="$POC/build/IONetworkingFamily-188"; mkdir -p "$NETINC/IOKit"
- [ -e "$NETSRC/IOEthernetController.h" ] || git clone -q --depth 1 --branch IONetworkingFamily-188 https://github.com/apple-oss-distributions/IONetworkingFamily.git "$NETSRC"
- ln -sfn "$NETSRC" "$NETINC/IOKit/network"
- # IOHIDFamily's kernel headers (IOKit/hid/*.h) for XnuInput and IOStorageFamily's (IOKit/storage/*.h) for XnuDisk: the SDK's
- # Kernel.framework has them
- for h in toolchains/sdks/*.sdk/System/Library/Frameworks/Kernel.framework/Headers/IOKit/hid; do
- [ -e $h/IOHIDDevice.h ] && { ln -sfn $PWD/$h "$NETINC/IOKit/hid"; ln -sfn $PWD/$h/../hidsystem "$NETINC/IOKit/hidsystem"; ln -sfn $PWD/$h/../graphics "$NETINC/IOKit/graphics"; ln -sfn $PWD/$h/../storage "$NETINC/IOKit/storage"
- ln -sfn $PWD/${h%%/System/*}/usr/include/TargetConditionals.h "$NETINC/TargetConditionals.h"
- ln -sfn $PWD/$h/../../HIDDriverKit "$NETINC/HIDDriverKit"; break; } # IOHIDDevice.h includes HIDDriverKit/IOHIDDevice.h
- done
- for j in "$POC"/kexts/*/*.json; do
- [ -e "$j" ] || continue
- n=$(basename "$j" .json)
- # a kext that does not build is left out of the collection (reported), not the whole rebuild
- python3 scripts/build-native-kext.py $n "$(dirname "$j")/$n.cpp" -I "$NETINC" --obj ${KEXT_OBJ:-k27-obj} || { echo "kext $n failed to build: left out"; continue; }
- NATIVE+=("$j")
- done
+elif [ -e "$POC"/scripts/free-kc/kernel-slots.py ]; then
+ # no kernelcache to lay the kernel's slots out by: the same slots from layout numbers (scripts/free-kc/layout.json).
+ # Without this the kernel kept macOS-DroidVM's committed slots, too small for it: __TEXT_EXEC was linked over __KLD
+ python3 "$POC"/scripts/free-kc/kernel-slots.py "$POC"/scripts/free-kc/layout.json out/k27/kernel-k27.macho --write k27/segaddrs.sh | tail -1
+fi
+if ! cmp -s /tmp/segaddrs.before k27/segaddrs.sh; then
+ echo "kernel slots moved: linking the kernel again"
+ JOBS=12 bash k27/build-kernel27.sh 2>&1 | tail -3
+fi
+# xnulinux's own kexts (kexts/*/NAME.json + NAME.cpp), built against the k27 kernel's objects. With or without Apple's
+# kernelcache: the collection without Apple's kexts (scripts/free-kc/build.sh) links XnuCPU, XnuDisk and XnuDrm too,
+# and compiles its kexts against build/netinc; with the kernelcache they are linked into the collection below
+NATIVE=()
+# IONetworkingFamily's kernel headers (IOKit/network/*.h) for XnuEthernet: Apple's open source IONetworkingFamily-188 (APSL,
+# fetched here, not kept in the repository), whose __PRIVATE_SPI__ declarations name the reserved slots 2-5 the shipped family
+# uses (the SDK's headers leave slot 5 a reserved stub the collection does not export)
+NETINC="$POC/build/netinc"; NETSRC="$POC/build/IONetworkingFamily-188"; mkdir -p "$NETINC/IOKit"
+[ -e "$NETSRC/IOEthernetController.h" ] || git clone -q --depth 1 --branch IONetworkingFamily-188 https://github.com/apple-oss-distributions/IONetworkingFamily.git "$NETSRC"
+ln -sfn "$NETSRC" "$NETINC/IOKit/network"
+# IOHIDFamily's kernel headers (IOKit/hid/*.h) for XnuInput and IOStorageFamily's (IOKit/storage/*.h) for XnuDisk: the SDK's
+# Kernel.framework has them
+for h in toolchains/sdks/*.sdk/System/Library/Frameworks/Kernel.framework/Headers/IOKit/hid; do
+ [ -e $h/IOHIDDevice.h ] && { ln -sfn $PWD/$h "$NETINC/IOKit/hid"; ln -sfn $PWD/$h/../hidsystem "$NETINC/IOKit/hidsystem"; ln -sfn $PWD/$h/../graphics "$NETINC/IOKit/graphics"; ln -sfn $PWD/$h/../storage "$NETINC/IOKit/storage"
+ ln -sfn $PWD/${h%%/System/*}/usr/include/TargetConditionals.h "$NETINC/TargetConditionals.h"
+ ln -sfn $PWD/$h/../../HIDDriverKit "$NETINC/HIDDriverKit"; break; } # IOHIDDevice.h includes HIDDriverKit/IOHIDDevice.h
+done
+for j in "$POC"/kexts/*/*.json; do
+ [ -e "$j" ] || continue
+ n=$(basename "$j" .json)
+ # a kext that does not build is left out of the collection (reported), not the whole rebuild
+ python3 scripts/build-native-kext.py $n "$(dirname "$j")/$n.cpp" -I "$NETINC" --obj ${KEXT_OBJ:-k27-obj} || { echo "kext $n failed to build: left out"; continue; }
+ NATIVE+=("$j")
+done
+if [ -e out/kc/kc27.bin ]; then
printf '%s\n' "${NATIVE[@]}" > out/k27/natives.txt # the kexts of ours in this collection, for scripts/apple-kc/package.sh
# the collection (scripts/kclink): the kernel, xnulinux's kexts, and the Apple kexts of scripts/apple-kc/keep.txt from
# macOS 27.2's kernelcache
diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.sh
index 59585a2..18dae65 100755
--- a/scripts/xnulinux-boot.sh
+++ b/scripts/xnulinux-boot.sh
@@ -16,20 +16,30 @@
# FB_DUMP (/var/tmp/xnu-fb.raw) KEYSTORE (/var/tmp/xnu-keystore.bin) TRUSTCACHE (xnu/trustcache-mac.bin; empty: none)
# IMAGE (xnu/kc.bin: the kernel collection under /lib/firmware) GPU (auto|off) CPUS (1: the hosted system's CPUs, 32 at most) XNU_ARGS (more xnu.ko parameters)
set -euo pipefail
+# a relative MAC_CONF or DISK in the environment is a file where the caller is (docs/free-kc.md: MAC_CONF=pd.conf DISK=pd.img)
+for v in MAC_CONF DISK; do [[ ${!v:-/} = /* ]] || printf -v "$v" %s "$PWD/${!v}"; done
cd "$(dirname "$0")/.."
[ -f /etc/xnulinux.conf ] && . /etc/xnulinux.conf # for stop as well: the sync is typed into this system's CONSOLE_IN
+irqs_back() { # Linux's device interrupts back on the CPUs they had before the start took them off XNU's (/run: gone at a reboot, as they are)
+ local f v; [ -s /run/xnu-irq-affinity ] || return 0
+ while read -r f v; do [ -n "$v" ] && [ -e "$f" ] && echo "$v" | sudo tee "$f" >/dev/null 2>&1 || true; done < /run/xnu-irq-affinity
+ sudo rm -f /run/xnu-irq-affinity
+}
if [ "${1:-}" = stop ]; then # end the running hosted system (its disk synced first) and remove xnu.ko
if [ ! -d /sys/module/xnu ]; then
sudo systemctl stop xnudrmd 2>/dev/null || true
+ irqs_back
echo "no hosted system is running"; exit 0
fi
printf 'sync\n' >> "${CONSOLE_IN:-/var/tmp/console-in}"; sleep 3
echo 1 | sudo tee /sys/module/xnu/parameters/stop_run >/dev/null
# every XNU CPU sees the stop at its next host call; one in a long one (disk I/O while the VM shuts down) takes a while
for _ in $(seq 1 600); do pgrep -f "insmod xnu-ko/xnu.ko" >/dev/null || break; sleep 0.2; done
- if [ -d /sys/module/xnu ]; then sudo rmmod xnu; fi
+ # (under systemd --wait's collect unloads it too, and may get there between this test and the rmmod: not a failed stop)
+ if [ -d /sys/module/xnu ]; then e=$(sudo rmmod xnu 2>&1) || [ ! -d /sys/module/xnu ] || { echo "$e" >&2; exit 1; }; fi
sudo systemctl stop xnudrmd 2>/dev/null || true
for f in /sys/devices/system/cpu/cpu*/cpuidle/state[1-9]*/disable; do [ -e "$f" ] && echo 0 | sudo tee "$f" >/dev/null 2>&1 || true; done # XNU's CPUs are Linux's again
+ irqs_back
echo "hosted system stopped"
exit
fi
@@ -51,11 +61,19 @@ build() { # a module; on failure its compiler errors, modpost's, and what make s
build fki-ko
build xnu-ko "KBUILD_EXTRA_SYMBOLS=$PWD/fki-ko/Module.symvers"
# XNU prints a lot (console lines, kprintf): to the ring buffer only (journalctl -k, scripts/vm-dmesg-shell.sh), not the
-# VM console, where a CPU printing waits for the console with interrupts off
-sudo dmesg -n "${CONLEVEL:-1}"
+# VM console, where a CPU printing waits for the console with interrupts off. Level 2, not 1: the console takes what is
+# below its level, and fki_log_alert's lines (an XNU panic, an XNU CPU gone silent) are KERN_ALERT (1)
+sudo dmesg -n "${CONLEVEL:-2}"
# fki has the hosted kernel's DRAM from its load at boot (scripts/vm-install-fki-service.sh): reload it only when it changed,
# with the same carve-out
CARVE="carve_base=$(cat /sys/module/fki/parameters/carve_base 2>/dev/null || echo 0x200000000) carve_mb=$(cat /sys/module/fki/parameters/carve_mb 2>/dev/null || echo 8156)"
+# Not loaded at all: its load at boot failed (after a kernel update fki.ko was still the old kernel's, until the build
+# above). Then with what xnulinux-fki.service loads it with, which is where a host's own carve-out is written down.
+if [ ! -d /sys/module/fki ]; then
+ # (no such unit on a host where fki.ko is loaded by hand: sed's failure must not end the script here, under set -e)
+ UNIT_ARGS=$(sed -n 's|^ExecStart=.*/fki-ko/fki\.ko *||p' /etc/systemd/system/xnulinux-fki.service 2>/dev/null | head -1 || true)
+ [ -z "$UNIT_ARGS" ] || CARVE=$UNIT_ARGS
+fi
# (an fki.ko from before cpu_list has none: set -e must not stop here)
CPULIST=$(tr -d '\n' 2>/dev/null < /sys/module/fki/parameters/cpu_list || true); [ -z "$CPULIST" ] || CARVE="$CARVE cpu_list=$CPULIST"
if [ "$(cat /sys/module/fki/srcversion 2>/dev/null)" != "$(modinfo -F srcversion fki-ko/fki.ko)" ]; then
@@ -87,6 +105,8 @@ m = (1 << $NCPU) - 1
for c in l: m &= ~(1 << c)
h = format(m, 'x') # Linux reads a CPU mask in comma-separated groups of 32 bits
print(','.join(reversed([h[max(i - 8, 0):i] for i in range(len(h), 0, -8)])))")
+ # what they were, for the stop or the end of the run to give back (kept when a start finds it there: the values are the first start's)
+ [ -s /run/xnu-irq-affinity ] || for f in /proc/irq/default_smp_affinity /proc/irq/*/smp_affinity; do echo "$f $(cat "$f" 2>/dev/null)"; done | sudo tee /run/xnu-irq-affinity >/dev/null
echo "$MASK" | sudo tee /proc/irq/default_smp_affinity >/dev/null 2>&1 || true
for f in /proc/irq/*/smp_affinity; do echo "$MASK" | sudo tee "$f" >/dev/null 2>&1 || true; done
HOSTCPUS=$(python3 -c "print(','.join(str(c) for c in range($NCPU) if 0x${MASK//,/} >> c & 1))")
@@ -161,8 +181,23 @@ for try in 1 2 3 4 5 6 7 8 9; do
fi
echo "no contiguous memory for XNU yet: trying again in 20 s"; sleep 20
done
-echo "booting: console scripts/xnu-console.sh, screen tools/hosted/fb2png.py $FB_DUMP"
-[ $WAIT = 1 ] || exit 0
+# insmod gone and no xnu.ko: it did not load (no disk or collection, a parameter out of range)
+if ! pgrep -f "insmod xnu-ko/xnu.ko" >/dev/null && [ ! -d /sys/module/xnu ]; then
+ # with what xnu.ko itself said last: insmod only has the error number's words, and for a file xnu.ko did not find (the
+ # collection, the trust cache, the disk: -2) those are "Unknown symbol in module"
+ echo "xnu.ko did not load: $(cat /var/tmp/xnu-insmod.log)" >&2
+ # (xnu.ko said nothing when Linux itself refused the load, as for a parameter longer than it takes: grep's status
+ # must not end the script here, before the GPU bridge is stopped)
+ { sudo dmesg | grep -a "fki: xnu: " | tail -3 | sed 's/^\[[^]]*\] */ /' >&2; } || true
+ if [ $WAIT = 0 ]; then
+ sudo systemctl stop xnudrmd 2>/dev/null || true
+ exit 1
+ fi
+ # --wait has said why as well, and goes on to keep the run's log and to end with 3, as for any run that ended
+else
+ echo "booting: console scripts/xnu-console.sh, screen tools/hosted/fb2png.py $FB_DUMP"
+ [ $WAIT = 1 ] || exit 0
+fi
# --wait: until the run ends (insmod returns), then keep its kernel log and say how it ended: 0 a halt (from inside, or
# a stop asked for), 2 an XNU panic, 4 a restart the hosted system asked for, 3 the run ended otherwise
@@ -170,21 +205,27 @@ collect() { # the run's kernel log, kept; the status says how it ended
local LOGDIR=/var/log/xnulinux LOG
# insmod has returned but xnu.ko stays loaded after a run that ended by itself (a panic, a halt): unload it, or the
# next start (systemd's restart after a panic) finds it and refuses
- if [ -d /sys/module/xnu ]; then sudo rmmod xnu || echo "xnu.ko did not unload" >&2; fi
+ # (a stop that was asked for unloads it as well: whichever of the two gets there second finds it gone)
+ if [ -d /sys/module/xnu ]; then sudo rmmod xnu 2>/dev/null || [ ! -d /sys/module/xnu ] || echo "xnu.ko did not unload" >&2; fi
sudo systemctl stop xnudrmd 2>/dev/null || true
# XNU's CPUs are Linux's again, as after a stop: a run that ended by itself otherwise left them out of the deep idle states
for f in /sys/devices/system/cpu/cpu*/cpuidle/state[1-9]*/disable; do [ -e "$f" ] && echo 0 | sudo tee "$f" >/dev/null 2>&1 || true; done
+ irqs_back
sudo mkdir -p "$LOGDIR"
LOG=$LOGDIR/run-$(date -d @"$START" +%Y%m%d-%H%M%S).log
- { cat /var/tmp/xnu-insmod.log; sudo journalctl -k -q -o short-monotonic --no-pager --since @"$START" | grep -a "fki:"; } |
+ # (no line of fki's at all when xnu.ko did not load: set -e must not end the script here, before it says how the run ended)
+ { cat /var/tmp/xnu-insmod.log; sudo journalctl -k -q -o short-monotonic --no-pager --since @"$START" | grep -a "fki:" || true; } |
sudo tee "$LOG" >/dev/null
ls -1t "$LOGDIR"/run-*.log | tail -n +21 | xargs -r sudo rm -f # the last 20 runs
- if grep -aq "XNU panic" "$LOG"; then echo "the hosted system panicked: $LOG" >&2; return 2; fi
+ # how it ended is in xnu.ko's own lines, not in what the hosted console printed (the log has those too: a console that
+ # showed the words "XNU panic" turned a clean shutdown into a panic, and systemd started the system again)
+ said() { grep -av "fki: darwin console: " "$LOG" | grep -aq "$1"; }
+ if said "XNU panic"; then echo "the hosted system panicked: $LOG" >&2; return 2; fi
# shut down from inside (shutdown -h, the Apple menu): a halt is a clean end; a restart ends with 4 for systemd to start it again
# (checked before the stop: the other CPUs log "run stopped by the host" as they leave after it)
- if grep -aq "xnu: the hosted system halted" "$LOG"; then echo "the hosted system shut down: $LOG"; return 0; fi
- if grep -aq "xnu: the hosted system asked for a restart" "$LOG"; then echo "the hosted system restarts: $LOG"; return 4; fi
- if [ "${1:-}" = stopped ] || grep -aq "run stopped by the host" "$LOG"; then echo "the hosted system stopped: $LOG"; return 0; fi
+ if said "xnu: the hosted system halted"; then echo "the hosted system shut down: $LOG"; return 0; fi
+ if said "xnu: the hosted system asked for a restart"; then echo "the hosted system restarts: $LOG"; return 4; fi
+ if [ "${1:-}" = stopped ] || said "run stopped by the host"; then echo "the hosted system stopped: $LOG"; return 0; fi
echo "the run ended: $LOG" >&2; return 3
}
# systemctl stop: ExecStop (xnulinux-boot.sh stop) ends the run, then systemd sends this script SIGTERM
diff --git a/tests/scripts/host-services-remove.test.sh b/tests/scripts/host-services-remove.test.sh
new file mode 100755
index 0000000..9b8b738
--- /dev/null
+++ b/tests/scripts/host-services-remove.test.sh
@@ -0,0 +1,70 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# `scripts/install-service.sh remove` and `scripts/vm-install-fki-service.sh remove` on a stand-in host. The scripts are
+# the repository's, with one change made here: /etc and /sys/module start under a temporary directory. sudo runs its
+# command; systemctl, update-grub and rmmod are stand-ins that write down how they were called (rmmod also "unloads").
+. "$(dirname "$0")/lib.sh"
+sandbox_repo
+P=$T/repo; R=$T/root; export R
+for s in install-service.sh vm-install-fki-service.sh; do
+ sed -e "s|/sys/module|$R/sys/module|g" -e "s|/etc/|$R/etc/|g" "$REPO/scripts/$s" > "$P/scripts/$s"
+done
+cat > "$P/scripts/xnulinux-boot.sh" <<'EOF'
+#!/bin/bash
+echo "xnulinux-boot.sh $*" >> "$T/calls"; [ "$1" != stop ] || rm -rf "$R/sys/module/xnu"
+EOF
+chmod +x "$P/scripts/xnulinux-boot.sh"; export T
+stub sudo <<'EOF'
+while [ $# -gt 0 ]; do case $1 in -n|-E|-k) shift;; *=*) export "$1"; shift;; *) break;; esac; done
+exec "$@"
+EOF
+stub systemctl <<'EOF'
+case "$1 $2" in "disable --now") [ "$3" != xnulinux.service ] || rm -rf "$R/sys/module/xnu";; esac # its ExecStop ends the system
+EOF
+stub update-grub < /dev/null
+stub rmmod <<'EOF'
+[ -d "$R/sys/module/$1" ] || { echo "rmmod: ERROR: Module $1 is not currently loaded" >&2; exit 1; }
+rm -rf "$R/sys/module/$1"
+EOF
+U=$R/etc/systemd/system; G=$R/etc/default/grub.d/99-xnulinux.cfg
+host() { # a host with both installed and a hosted system running ($1 = idle: none running)
+ rm -rf "$R"; mkdir -p "$U" "$R/etc/default/grub.d" "$R/sys/module/fki"; : > "$T/calls"
+ echo unit > "$U/xnulinux.service"; echo unit > "$U/xnulinux-fki.service"; echo 'GRUB_CMDLINE_LINUX="mem=7G"' > "$G"; echo conf > "$R/etc/xnulinux.conf"
+ [ "${1:-}" = idle ] || mkdir -p "$R/sys/module/xnu"
+}
+run() { /bin/bash "$P/scripts/$1" remove > "$T/out" 2>&1; }
+
+host; run vm-install-fki-service.sh; s=$?
+check 'vm-install-fki-service.sh remove with a hosted system running: refused, nothing touched' \
+ [ $s = 1 -a -e "$U/xnulinux-fki.service" -a -e "$G" -a -d "$R/sys/module/fki" ]
+check '... and it names what to run first' grep -q 'install-service.sh remove' "$T/out"
+
+run install-service.sh; s=$?
+check 'install-service.sh remove: status 0, the unit gone' [ $s = 0 -a ! -e "$U/xnulinux.service" ]
+check '... stopped through the unit (disable --now), which ends the hosted system' called '^systemctl disable --now xnulinux.service'
+check '... systemd told (daemon-reload)' called '^systemctl daemon-reload'
+check "... the settings and fki's unit left alone" [ -e "$R/etc/xnulinux.conf" -a -e "$U/xnulinux-fki.service" -a -e "$G" ]
+check '... and it says what it kept and names the other remove' grep -q 'kept: .*vm-install-fki-service.sh remove' "$T/out"
+
+run vm-install-fki-service.sh; s=$?
+check 'vm-install-fki-service.sh remove: status 0, the unit and the mem= command line gone' [ $s = 0 -a ! -e "$U/xnulinux-fki.service" -a ! -e "$G" ]
+check '... the boot loader told (update-grub)' called '^update-grub'
+check '... fki.ko unloaded' [ ! -d "$R/sys/module/fki" ]
+check '... and it says a reboot gives the memory back' grep -q 'after a reboot' "$T/out"
+
+: > "$T/calls"; run install-service.sh; a=$?; run vm-install-fki-service.sh; b=$?
+check 'both again on the host that has nothing of theirs left: status 0' [ $a = 0 -a $b = 0 ]
+check '... without stopping or unloading anything' not called '^systemctl disable|^rmmod'
+
+# a hosted system started by hand, with no unit: install-service.sh remove still ends it
+host; rm "$U/xnulinux.service"; run install-service.sh; s=$?
+check 'install-service.sh remove, a system running without the unit: ended through xnulinux-boot.sh stop' \
+ [ $s = 0 -a ! -d "$R/sys/module/xnu" ]
+check '... (the boot script was asked)' called '^xnulinux-boot.sh stop'
+
+# the install paths are as they were: the fki installer still writes its unit and the command line
+host idle; rm "$U/xnulinux-fki.service" "$G"
+LINUX_MEM=3G CARVE_BASE=0x100000000 CARVE_MB=512 /bin/bash "$P/scripts/vm-install-fki-service.sh" > "$T/out" 2>&1; s=$?
+check 'vm-install-fki-service.sh (no argument) installs as before' \
+ [ $s = 0 -a "$(grep -c 'carve_base=0x100000000 carve_mb=512' "$U/xnulinux-fki.service")$(grep -c 'mem=3G' "$G")" = 11 ]
+finish
diff --git a/tests/scripts/relative-paths.test.sh b/tests/scripts/relative-paths.test.sh
new file mode 100755
index 0000000..a4f1a59
--- /dev/null
+++ b/tests/scripts/relative-paths.test.sh
@@ -0,0 +1,101 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# Scripts that are given a path relative to where the caller stands, and work somewhere else: console-send-file.sh
+# (LOCAL), xnulinux-boot.sh (MAC_CONF, DISK), free-kc/build.sh (FREE_KC_WORK, DVM) and build-host.sh (W). Each runs as
+# it is from $T/there, a directory that is not the repository's, on stand-ins for what it calls.
+. "$(dirname "$0")/lib.sh"
+sandbox_repo kexts
+R=$T/repo; mkdir -p "$T/there"; cd "$T/there" || exit 1
+
+# console-send-file.sh: the hosted console gets the caller's file, whatever the repository has under that name
+echo 127.0.0.1 > "$T/vm.ip"; : > "$T/vmkey"; stub_ssh # scripts/vm.sh's, next to the repository; the VM's console-in
+echo "the caller's notes" > notes.txt; echo "the repository's notes" > "$R/notes.txt"; echo 'only here' > here.txt
+typed() { sed -n 's/^echo \(.*\) >> .*/\1/p' "$VM/var/tmp/console-in" | python3 -c 'import base64, sys; sys.stdout.write(base64.b64decode(sys.stdin.read()).decode())'; }
+/bin/bash "$R/scripts/console-send-file.sh" here.txt /tmp/h > "$T/out" 2>&1; s=$?
+check 'console-send-file.sh FILE (a file where the caller is): it is what gets typed' [ "$s $(typed)" = '0 only here' ]
+: > "$VM/var/tmp/console-in"; /bin/bash "$R/scripts/console-send-file.sh" notes.txt /tmp/n >> "$T/out" 2>&1
+check "... also when the repository has a file of that name" [ "$(typed)" = "the caller's notes" ]
+: > "$VM/var/tmp/console-in"; /bin/bash "$R/scripts/console-send-file.sh" nothing.txt /tmp/precious >> "$T/out" 2>&1; s=$?
+check '... and a file that is not there is an error, with nothing typed (the first line typed removes REMOTE)' [ $s != 0 -a ! -s "$VM/var/tmp/console-in" ]
+[ $FAILED = 0 ] || sed 's/^/ | /' "$T/out"
+
+# xnulinux-boot.sh: stopped at its first build step by a make that fails, after it has read its configuration and before
+# it does anything as root (sudo fails too). The stand-in make writes down the DISK the script would boot from (the
+# caller exported it, so make inherits it).
+f=$FAILED
+stub sudo <<'EOF'
+exit 1
+EOF
+stub make <<'EOF'
+echo "$PWD" > "$T/make.cwd"; echo "${DISK:-}" > "$T/make.disk"; echo "make (stand-in): stops the boot here" >&2; exit 2
+EOF
+printf 'ROOT_UUID=1111\nBOOT_UUID=2222\n' > pd.conf; : > pd.img
+if [ -e /etc/xnulinux.conf ] || [ -d /sys/module/xnu ]; then
+ echo 'skip xnulinux-boot.sh: this host has a hosted system of its own (/etc/xnulinux.conf would be read)'
+else
+ MAC_CONF=pd.conf DISK=pd.img /bin/bash "$R/scripts/xnulinux-boot.sh" > "$T/out" 2>&1
+ check 'xnulinux-boot.sh with MAC_CONF=pd.conf (docs/free-kc.md): the UUIDs are read from the file where the caller is' called '^make '
+ check '... and DISK=pd.img is that directory'"'"'s pd.img, from where xnu.ko is loaded' \
+ eval '[ -s "$T/make.cwd" ] && cd "$(cat "$T/make.cwd")" && [ "$(cat "$T/make.disk")" -ef "$T/there/pd.img" ]'
+ cd "$T/there" || exit 1
+ [ $FAILED = $f ] || sed 's/^/ | /' "$T/out"
+fi
+
+# free-kc/build.sh: kcc.py and genspec.py are the repository's; the compiler (the k27 recipes' "cc"), mk-template.py and
+# kclink.py are stand-ins that write their output, PureDarwin and Mbed TLS are a few empty files "fetched already"
+f=$FAILED
+stub sudo <<'EOF'
+exec "$@"
+EOF
+stub cc <<'EOF'
+while [ $# -gt 1 ]; do [ "$1" != -o ] || : > "$2"; shift; done
+EOF
+stub git <<'EOF'
+[ "$1 $3 $4" != '-C rev-parse HEAD' ] || cat "$2/.rev"
+EOF
+echo 'import sys; open(sys.argv[4], "w").write("template\n")' > "$R/scripts/free-kc/mk-template.py"
+rm -rf "$R/scripts/kclink"; mkdir -p "$R/scripts/kclink"
+cat > "$R/scripts/kclink/kclink.py" <<'EOF'
+import json, sys
+natives = sys.argv[sys.argv.index('--native') + 1:]
+for n in natives: json.load(open(json.load(open(n))['objects'])) # as kclink reads a kext's description and its object list
+open(sys.argv[3], 'w').write('collection\n'); print('wrote', sys.argv[3], 'with', len(natives), 'kexts')
+EOF
+E=free-kc/src/pd/src/Kernel/Extensions; O=dvm/out/x12377; X=dvm/out/k27
+mkdir -p $E/amfi $E/pthread $E/IOStorageFamily $E/HFSEncodings $E/hfs/core free-kc/src/mbedtls $O/native-kexts \
+ $O/build/xnu/k27-obj/DEVELOPMENT_ARM64_BCM2837/iokit/DEVELOPMENT $O/build/xnu/k27-obj/DEVELOPMENT_ARM64_BCM2837/bsd/DEVELOPMENT \
+ $O/build/xnu/k27h-dst/System/Library/Frameworks/Kernel.framework/Versions/A/PrivateHeaders $X/xnu "$T/out.d"
+sed -n 's/.* PD_REV=\([0-9a-f]*\).*/\1/p' "$R/scripts/free-kc/build.sh" > free-kc/src/pd/.rev
+sed -n 's/^MBEDTLS_REV=//p' "$R/kexts/free/corecrypto/mbedtls.rev" > free-kc/src/mbedtls/.rev
+for k in amfi/Info pthread/pthread-Info IOStorageFamily/Info HFSEncodings/Info hfs/Info; do
+ printf '<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>org.test.%s</string></dict></plist>\n' "${k%%/*}" > "$E/$k.plist"
+done
+: > $E/IOStorageFamily/a.cpp; : > $E/HFSEncodings/a.c; : > $E/HFSEncodings/b.cpp; : > $E/hfs/core/a.c; : > $E/hfs/core/b.cpp; : > $E/hfs/core/kext-config.h
+for r in iokit/DEVELOPMENT/IOPlatformExpert.cpo.json bsd/DEVELOPMENT/bsd_init.o.json; do
+ echo '{"directory": "/", "file": "x.c", "arguments": ["cc", "-c", "x.c", "-o", "x.o"]}' > "$O/build/xnu/k27-obj/DEVELOPMENT_ARM64_BCM2837/$r"
+done
+for k in XnuCPU XnuDisk XnuDrm; do mkdir -p $O/native-kexts/$k; echo '[]' > $O/native-kexts/$k/objects.json; done # vm-xnu-rebuild.sh's
+echo 'Darwin Kernel Version 27.2.0: a stand-in' > $X/kernel-k27.macho
+DVM=dvm FREE_KC_WORK=free-kc OUT=$T/out.d/kc-free.bin /bin/bash "$R/scripts/free-kc/build.sh" > "$T/out" 2>&1; s=$?
+check 'free-kc/build.sh with DVM=dvm FREE_KC_WORK=free-kc: the collection is built' [ $s = 0 -a -s "$T/out.d/kc-free.bin" ]
+check '... its objects in FREE_KC_WORK, none beside the sources they were compiled from' \
+ eval '[ -s free-kc/obj/corecrypto/objects.json ] && [ -z "$(find "$R/kexts" free-kc/src -name objects.json)" ]'
+[ $FAILED = $f ] || tail -8 "$T/out" | sed 's/^/ | /'
+
+# build-host.sh: make gets the output directory the header promises ($W/out/linux), whatever directory it runs in
+f=$FAILED
+mkdir -p w/src/linux/drivers w/src/linux/scripts
+echo 'source "drivers/fki/Kconfig"' > w/src/linux/drivers/Kconfig; echo 'obj-$(CONFIG_FKI) += fki/' > w/src/linux/drivers/Makefile
+printf '#!/bin/sh\n' > w/src/linux/scripts/config; chmod +x w/src/linux/scripts/config
+for c in rsync nproc; do stub $c <<'EOF'
+echo 4
+EOF
+done
+stub make <<'EOF'
+for a in "$@"; do case $a in O=*) o=${a#O=};; Image) mkdir -p "$o/arch/arm64/boot" && : > "$o/arch/arm64/boot/Image";; esac; done
+EOF
+W=w /bin/bash "$R/scripts/build-host.sh" > "$T/out" 2>&1; s=$?
+check 'build-host.sh with W=w: the kernel is built into w/out/linux, not into the Linux tree' \
+ [ $s = 0 -a -e w/out/linux/arch/arm64/boot/Image -a ! -e w/src/linux/w ]
+[ $FAILED = $f ] || sed 's/^/ | /' "$T/out"
+finish
diff --git a/tests/scripts/vm-net-up.test.sh b/tests/scripts/vm-net-up.test.sh
new file mode 100755
index 0000000..bfe202a
--- /dev/null
+++ b/tests/scripts/vm-net-up.test.sh
@@ -0,0 +1,57 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# scripts/vm-net-up.sh run again and again on one host, as scripts/xnulinux-boot.sh runs it at every start of the hosted
+# system: after each run a dnsmasq has to be serving xnu0. The stand-in dnsmasq holds 192.168.77.1's ports from its start
+# until a moment after it is told to end, and one started while they are held fails as dnsmasq does. While it is ending
+# it is no longer to be found by its command line, as a real process is not once it has given up its memory and not yet
+# its sockets. ip, iptables, sysctl and ethtool are stand-ins that only write down how they were called.
+. "$(dirname "$0")/lib.sh"
+sandbox_repo
+stub sudo <<'EOF'
+while [ $# -gt 0 ]; do case $1 in *=*) export "$1"; shift;; *) break;; esac; done
+exec "$@"
+EOF
+stub ip <<'EOF'
+case "$*" in "route show default") cat "$T/default-route";; esac
+exit 0
+EOF
+stub iptables <<'EOF'
+case " $* " in *" -C "*) exit 1;; esac # no rule is there yet: the script adds it
+EOF
+stub sysctl < /dev/null
+stub ethtool < /dev/null
+stub dnsmasq <<'EOF'
+mkdir "$T/port" 2>/dev/null ||
+ { echo "dnsmasq: failed to create listening socket for 192.168.77.1: Address already in use" >&2; exit 2; }
+( trap 'exec /bin/bash -c "sleep 0.3; rmdir \"\$0\"" "$T/port"' TERM; while :; do sleep 0.1; done ) > /dev/null 2>&1 &
+echo $! > "$T/dnsmasq.pid"
+EOF
+echo "default via 10.0.2.2 dev eth0 proto dhcp src 10.0.2.15 metric 100" > "$T/default-route"
+run() { /bin/bash "$T/repo/scripts/vm-net-up.sh" > "$T/out" 2>&1; sleep 0.8; } # (and what was ended has had time to go)
+serving() { [ -d "$T/port" ] && kill -0 "$(cat "$T/dnsmasq.pid")" 2>/dev/null; }
+
+run; first=$(cat "$T/dnsmasq.pid")
+check 'the first run starts dnsmasq on xnu0' serving
+check '... and says so, and where the NAT goes' grep -q 'NAT via eth0, dnsmasq: yes$' "$T/out"
+check '... with the NAT rule on the default route'"'"'s interface' called '^iptables -t nat -A POSTROUTING .* -o eth0 -j MASQUERADE'
+
+run
+check 'after a second run (the next start of the hosted system) a dnsmasq is serving' serving
+check '... a new one, the first having been ended' [ "$(cat "$T/dnsmasq.pid")" != "$first" ]
+check '... and none was started while the old one still held the address' not grep -q 'Address already in use' "$T/out"
+run
+check 'after a third run too' serving
+
+# a dnsmasq that cannot start (something else has the address): the script must not report it as there
+pkill -f "$T/bin/dnsmasq"; wait_for 3 not test -d "$T/port"; mkdir "$T/port"
+run
+check 'a dnsmasq that did not start is reported, not "dnsmasq: yes"' grep -q 'dnsmasq: DID NOT START' "$T/out"
+rmdir "$T/port"
+
+# a host without a default route has nothing to NAT to
+: > "$T/default-route"; : > "$T/calls"
+run
+check 'without a default route no NAT rule is asked for (iptables takes no empty interface)' not called '^iptables -t nat'
+check '... and the script says there is none' grep -q 'NAT none (this host has no default route)' "$T/out"
+check '... while dnsmasq is still started' serving
+finish
diff --git a/tests/scripts/vm-xnu-rebuild.test.sh b/tests/scripts/vm-xnu-rebuild.test.sh
new file mode 100755
index 0000000..6bbee80
--- /dev/null
+++ b/tests/scripts/vm-xnu-rebuild.test.sh
@@ -0,0 +1,78 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# scripts/vm-xnu-rebuild.sh on a new host: nothing has made /lib/firmware/xnu yet, and there is no Apple kernelcache
+# (out/kc/kc27.bin), which is all the PureDarwin collection (scripts/free-kc/build.sh) is documented to need. The script
+# runs as it is on stand-ins: ~/w/dvm is a made-up macOS-DroidVM tree (a git tree for XNU, a build-kernel27.sh that
+# writes a "kernel", a build-native-kext.py that writes a kext's objects.json), xnu-patches holds one small patch, and
+# sudo runs its command with /lib/firmware inside the sandbox.
+. "$(dirname "$0")/lib.sh"
+sandbox_repo kexts
+P=$T/repo; D=$HOME/w/dvm; X=$D/out/k27/xnu
+rm -rf "$P/scripts/kclink"; mkdir -p "$P/scripts/kclink" # the linker and the AMFI patch: stand-ins that write the collection
+cat > "$P/scripts/kclink/kclink.py" <<'EOF'
+import sys
+open(sys.argv[3], 'w').write('collection: ' + ' '.join(sys.argv[sys.argv.index('--native') + 1:sys.argv.index('--rebind')]) + '\n')
+print('wrote', sys.argv[3])
+EOF
+echo 'pass' > "$P/scripts/kc-amfi-platform.py"
+# the kernel's slots from layout numbers (scripts/free-kc/kernel-slots.py, which the tree may or may not have yet): a stand-in
+SLOTS=$P/scripts/free-kc/kernel-slots.py; mkdir -p "$P/scripts/free-kc"
+cat > "$SLOTS" <<'EOF'
+import sys
+assert sys.argv[1].endswith('scripts/free-kc/layout.json') and sys.argv[2] == 'out/k27/kernel-k27.macho', sys.argv
+open(sys.argv[sys.argv.index('--write') + 1], 'w').write('slots from the layout numbers\n'); print('kernel slots: written')
+EOF
+mkdir -p "$P/xnu-patches/include" "$P/xnu-patches/corecrypto/include/corecrypto" "$P/xnu-patches/corecrypto/kernel" \
+ "$P/build/IONetworkingFamily-188" "$X/bsd" "$D/k27" "$D/scripts" "$D/out/kc" "$VM/lib/firmware"
+: > "$P/build/IONetworkingFamily-188/IOEthernetController.h" # as fetched already: the test clones nothing
+echo '#define LINUX64 1' > "$P/xnu-patches/include/linux64.h"
+echo '/* cc */' > "$P/xnu-patches/corecrypto/include/corecrypto/cc.h"; echo '/* glue */' > "$P/xnu-patches/corecrypto/kernel/glue.c"
+printf 'int a;\n' > "$X/bsd/a.c"
+git -C "$X" init -q && git -C "$X" add . && git -C "$X" -c user.name=t -c user.email=t@t commit -qm xnu
+cat > "$P/xnu-patches/0001-a.patch" <<'EOF'
+--- a/bsd/a.c
++++ b/bsd/a.c
+@@ -1 +1 @@
+-int a;
++int a = 1;
+EOF
+echo 'mkdir -p out/k27; echo kernel > out/k27/kernel-k27.macho; echo built >> k27/builds; echo "kernel built"' > "$D/k27/build-kernel27.sh"
+: > "$D/k27/segaddrs.sh"; echo 'pass' > "$D/k27/kc27-layout.py"
+cat > "$D/scripts/build-native-kext.py" <<'EOF'
+import os, sys
+d = 'out/x12377/native-kexts/' + sys.argv[1]; os.makedirs(d, exist_ok=True)
+open(d + '/objects.json', 'w').write('[]\n'); print('kext', sys.argv[1])
+EOF
+stub sudo <<'EOF'
+a=(); for x in "$@"; do case $x in /lib/firmware/*) x=$VM$x;; esac; a[${#a[@]}]=$x; done
+exec "${a[@]}"
+EOF
+kexts=$(cd "$P/kexts" && ls */*.json | sed 's|/.*||' | sort | tr '\n' ' ')
+built() { (cd "$D/out/x12377/native-kexts" 2>/dev/null && ls */objects.json | sed 's|/.*||' | sort | tr '\n' ' '); }
+F=$VM/lib/firmware/xnu
+
+/bin/bash "$P/scripts/vm-xnu-rebuild.sh" > "$T/out" 2>&1; s=$?
+check 'a host without /lib/firmware/xnu: the script ends well' [ $s = 0 ]
+check '... with the kernel installed as /lib/firmware/xnu/kernel.macho' cmp -s "$D/out/k27/kernel-k27.macho" "$F/kernel.macho"
+check "without Apple's kernelcache: xnulinux's kexts are built all the same ($kexts)" [ "$(built)" = "$kexts" ]
+check '... against build/netinc, which is set up' [ -L "$P/build/netinc/IOKit/network" ]
+check '... and no collection of Apple kexts is linked or installed' not test -e "$F/kc.bin" -o -e "$D/out/k27/natives.txt"
+check '... the kernel gets its slots from the layout numbers, there being no kernelcache to take them from' \
+ grep -qx 'slots from the layout numbers' "$D/k27/segaddrs.sh"
+check '... and is linked again for them, once' [ "$(grep -c built "$D/k27/builds")" = 2 ]
+[ $FAILED = 0 ] || sed 's/^/ | /' "$T/out"
+
+# a tree that has no kernel-slots.py: the slots are left as they are and the script ends as well
+rm -rf "$D/out/x12377" "$VM/lib/firmware/xnu" "$SLOTS" "$D/k27/builds"; : > "$D/k27/segaddrs.sh"
+/bin/bash "$P/scripts/vm-xnu-rebuild.sh" > "$T/out" 2>&1; s=$?
+check 'without kernel-slots.py in the tree: the script ends well, the slots untouched, the kernel linked once' \
+ [ $s = 0 -a ! -s "$D/k27/segaddrs.sh" -a "$(grep -c built "$D/k27/builds")" = 1 ]
+[ $FAILED = 0 ] || sed 's/^/ | /' "$T/out"
+
+rm -rf "$D/out/x12377" "$VM/lib/firmware/xnu"; echo kernelcache > "$D/out/kc/kc27.bin"
+/bin/bash "$P/scripts/vm-xnu-rebuild.sh" > "$T/out" 2>&1; s=$?
+check "with the kernelcache: the script ends well, the kexts are built" [ $s = 0 -a "$(built)" = "$kexts" ]
+check '... natives.txt lists them for scripts/apple-kc/package.sh' [ "$(sed 's|.*/||; s|\.json$||' "$D/out/k27/natives.txt" 2>/dev/null | sort | tr '\n' ' ')" = "$kexts" ]
+check '... and the collection linked with them is installed as kc.bin' grep -qs "^collection: .*XnuDisk.json" "$F/kc.bin"
+[ $FAILED = 0 ] || sed 's/^/ | /' "$T/out"
+finish
diff --git a/tests/scripts/xnulinux-boot.test.sh b/tests/scripts/xnulinux-boot.test.sh
new file mode 100755
index 0000000..3a979a6
--- /dev/null
+++ b/tests/scripts/xnulinux-boot.test.sh
@@ -0,0 +1,179 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# scripts/xnulinux-boot.sh (start, --wait, stop) and scripts/install-service.sh on a stand-in host. The scripts are the
+# repository's, with one change made here: the system paths they name (/sys/module, /proc/irq, /run, /etc, /var/tmp,
+# /var/log, /dev/dri, /sys/devices/system/cpu) start under a temporary directory. sudo runs its command; make, insmod,
+# rmmod, dmesg, journalctl, systemctl are stand-ins. The stand-in insmod of xnu.ko "runs" as the real one does (it
+# returns when the run ends) and ends as its scenario says: by a halt, a panic, a stop, or by not loading at all.
+. "$(dirname "$0")/lib.sh"
+[ "$(uname -s)" = Linux ] || { echo "skipped: xnulinux-boot.sh is for the Linux host (bash 4, GNU date, /proc)"; exit 0; }
+! pgrep -f "insmod xnu-ko/xnu.ko" > /dev/null || { echo "skipped: a hosted system is being started on this machine"; exit 0; }
+sandbox_repo
+P=$T/repo; R=$T/root; export R
+mkdir -p "$P/fki-ko" "$P/xnu-ko" "$P/gpu/xnu-drm"
+echo 'echo "vm-net-up: stand-in"' > "$P/scripts/vm-net-up.sh"
+for s in xnulinux-boot.sh install-service.sh; do # the system paths, under $R
+ sed -e "s|/sys/module|$R/sys/module|g" -e "s|/sys/devices/system/cpu|$R/sys/devices/system/cpu|g" -e "s|/proc/irq|$R/proc/irq|g" \
+ -e "s|/proc/sys/vm|$R/proc/sys/vm|g" -e "s|/run/xnu-irq-affinity|$R/run/xnu-irq-affinity|g" -e "s|/etc/|$R/etc/|g" \
+ -e "s|/var/tmp|$R/var/tmp|g" -e "s|/var/log/xnulinux|$R/var/log/xnulinux|g" -e "s|/dev/dri|$R/dev/dri|g" \
+ "$REPO/scripts/$s" > "$P/scripts/$s"
+done
+
+stub sudo <<'EOF'
+[ "${1:-}" != -k ] || { [ ! -e "$T/sudo-asks" ] || exit 1; shift; } # -k: not on a password typed a moment ago
+while [ $# -gt 0 ]; do case $1 in -n|-E) shift;; *=*) export "$1"; shift;; *) break;; esac; done
+exec "$@"
+EOF
+stub make <<'EOF'
+[ ! -e "$T/make-fails" ] || { echo "fki.c:1:1: error: the stand-in make was told to fail"; exit 2; }
+for a in "$@"; do case $a in M=*) d=${a#M=}; n=$(basename "$d"); : > "$d/${n%-ko}.ko";; esac; done
+EOF
+stub modinfo <<'EOF'
+echo SRC1
+EOF
+stub nproc <<'EOF'
+echo 4
+EOF
+stub lscpu < /dev/null
+stub sync < /dev/null
+stub systemctl < /dev/null
+stub systemd-run < /dev/null
+stub sleep <<'EOF'
+case $1 in 20) set -- 0.3;; 5) set -- 0.6;; 3|2|1) set -- 0.2;; esac # the script's waits, shortened
+PATH=${PATH#*:} exec sleep "$@"
+EOF
+stub dmesg <<'EOF'
+case ${1:-} in -n) echo "$2" > "$T/conlevel";; -C) : > "$T/ring";; *) cat "$T/ring";; esac
+EOF
+stub journalctl <<'EOF'
+case " $* " in *" -k "*) cat "$T/klog";; esac
+EOF
+cat > "$T/bin/klog" <<'EOF' # one kernel log record, as the ring buffer and journald show it
+#!/bin/bash
+t=$(awk '{printf "%12.6f", $1}' /proc/uptime)
+echo "[$t] $*" >> "$T/ring"; echo "[$t] host kernel: $*" >> "$T/klog"
+EOF
+chmod +x "$T/bin/klog"; export T
+stub rmmod <<'EOF'
+case ${RMMOD:-} in
+lost) rm -rf "$R/sys/module/$1"; echo "rmmod: ERROR: Module $1 is not currently loaded" >&2; exit 1;; # another rmmod got there first
+busy) echo "rmmod: ERROR: Module $1 is in use" >&2; exit 1;;
+esac
+[ -d "$R/sys/module/$1" ] || { echo "rmmod: ERROR: Module $1 is not currently loaded" >&2; exit 1; }
+rm -rf "$R/sys/module/$1"
+EOF
+stub insmod <<'EOF'
+case $1 in
+*fki.ko)
+ mkdir -p "$R/sys/module/fki/parameters"; echo SRC1 > "$R/sys/module/fki/srcversion"; : > "$R/sys/module/fki/parameters/cpu_list"
+ for a in "$@"; do case $a in carve_base=*|carve_mb=*) echo "${a#*=}" > "$R/sys/module/fki/parameters/${a%%=*}";; esac; done
+ exit 0;;
+esac
+read -r how after < "$T/scenario"
+case $how in
+noload) echo "insmod: ERROR: could not insert module $1: Unknown symbol in module" >&2; exit 1;; # before the module's init
+refused) klog "fki: xnu: FKI caps 0x000000000000000c"; klog "fki: xnu: cannot read the trust cache, err 0xfffffffffffffffe"
+ echo "insmod: ERROR: could not insert module $1: Unknown symbol in module" >&2; exit 1;; # xnu.ko's init returned -2
+esac
+mkdir -p "$R/sys/module/xnu/parameters"; echo 0 > "$R/sys/module/xnu/parameters/stop_run"
+klog "fki: xnu: mode=3: the kernel collection"; klog "fki: darwin console: xnulinux# "
+s=$SECONDS
+while :; do
+ if [ "$(cat "$R/sys/module/xnu/parameters/stop_run" 2>/dev/null)" = 1 ]; then klog "fki: xnu: run stopped by the host (stop_run)"; exit 0; fi
+ if [ -n "${after:-}" ] && [ $((SECONDS - s)) -ge "$after" ]; then
+ case $how in
+ halt) klog "fki: xnu: the hosted system halted: run ended";;
+ panic) klog "fki: xnu: XNU panic:"; klog "fki: panic(cpu 0 caller 0xfffffe0000000000): stand-in";;
+ esac
+ exit 0 # the module stays loaded after a run that ended by itself
+ fi
+ sleep 0.1
+done
+EOF
+
+host() { # a host after its boot: fki.ko loaded by its unit (unless FKI=no), nothing running; $1: how xnu.ko's run will go
+ pkill -f "$T/bin/insmod" 2>/dev/null; rm -rf "$R"
+ mkdir -p "$R/sys/module" "$R/proc/irq/1" "$R/proc/irq/2" "$R/proc/sys/vm" "$R/run" "$R/etc/systemd/system" "$R/var/tmp" "$R/dev"
+ for c in 0 1 2 3; do mkdir -p "$R/sys/devices/system/cpu/cpu$c/cpuidle/state1"; echo 0 > "$R/sys/devices/system/cpu/cpu$c/cpuidle/state1/disable"; done
+ echo f > "$R/proc/irq/default_smp_affinity"; echo f > "$R/proc/irq/1/smp_affinity"; echo 3 > "$R/proc/irq/2/smp_affinity"
+ printf 'ROOT_UUID=11111111-2222-3333-4444-555555555555\nBOOT_UUID=66666666-7777-8888-9999-000000000000\n' > "$R/var/tmp/mac.conf"
+ : > "$T/ring"; : > "$T/klog"; : > "$T/calls"; rm -f "$T/conlevel"; echo "${1:-run}" > "$T/scenario"
+ [ "${FKI:-}" = no ] || insmod fki-ko/fki.ko carve_base=0x200000000 carve_mb=8156
+}
+boot() { /bin/bash "$P/scripts/xnulinux-boot.sh" "$@" > "$T/out" 2>&1; }
+is() { [ "$(cat "$1" 2>/dev/null)" = "$2" ]; } # is FILE TEXT
+log() { ls "$R"/var/log/xnulinux/run-*.log 2>/dev/null | head -1; }
+
+# ---- a start, and a stop
+host; boot; s=$?
+check 'a start returns 0 once the hosted system runs, and says where its console is' [ $s = 0 -a "$(grep -c '^booting: ' "$T/out")" = 1 ]
+check '... the console level lets an alert (an XNU panic) through to the VM console: 2' is "$T/conlevel" 2
+check "... Linux's device interrupts are off XNU's CPU (CPUS=1 of 4: mask e)" is "$R/proc/irq/default_smp_affinity" e
+check "... XNU's CPU is out of the deep idle states, the others are not" [ "$(cat "$R"/sys/devices/system/cpu/cpu[01]/cpuidle/state1/disable | tr -d '\n')" = 10 ]
+boot stop; s=$?
+check 'stop ends it: status 0, xnu.ko unloaded' [ $s = 0 -a ! -d "$R/sys/module/xnu" -a "$(grep -c '^hosted system stopped' "$T/out")" != 0 ]
+check '... and gives the interrupts their CPUs back, each its own (f, f, 3)' \
+ [ "$(cat "$R/proc/irq/default_smp_affinity" "$R/proc/irq/1/smp_affinity" "$R/proc/irq/2/smp_affinity" | tr '\n' ' ')" = "f f 3 " ]
+check '... and the idle states' is "$R/sys/devices/system/cpu/cpu0/cpuidle/state1/disable" 0
+check '... with nothing left in /run' [ ! -e "$R/run/xnu-irq-affinity" ]
+
+# ---- a start whose xnu.ko does not load
+host refused; boot; s=$?
+check 'a start whose xnu.ko did not load fails' [ $s = 1 ]
+check '... does not say "booting"' not grep -q '^booting' "$T/out"
+check "... and says why in xnu.ko's own words, under insmod's" \
+ [ "$(grep -A2 '^xnu.ko did not load: insmod: ERROR' "$T/out" | tail -1)" = " fki: xnu: cannot read the trust cache, err 0xfffffffffffffffe" ]
+host noload; boot; s=$?
+check 'a start whose load Linux itself refused (nothing of xnu.ko in the kernel log): status 1, with insmod'"'"'s words' \
+ [ $s = 1 -a "$(grep -c '^xnu.ko did not load: insmod: ERROR' "$T/out")" = 1 ]
+check '... and the last thing it does is stop the GPU bridge (it did not end at the empty search of the kernel log)' \
+ [ "$(tail -1 "$T/calls")" = "systemctl stop xnudrmd" ]
+host noload; boot --wait; s=$?
+check '--wait, the kernel having logged nothing of fki: status 3 and a message with the log' [ $s = 3 -a "$(grep -c "^the run ended: $R/var/log/xnulinux/run-" "$T/out")" != 0 ]
+check '... and it says that xnu.ko did not load, as the plain start does, and not "booting"' \
+ [ "$(grep -c '^xnu.ko did not load: insmod: ERROR' "$T/out")$(grep -c '^booting' "$T/out")" = 10 ]
+
+# ---- --wait: how the run ended
+host 'panic 1'; boot --wait; s=$?
+check '--wait, an XNU panic: status 2, "panicked"' [ $s = 2 -a "$(grep -c '^the hosted system panicked: ' "$T/out")" != 0 ]
+check "... the run's log is kept, with the panic" grep -q 'fki: xnu: XNU panic:' "$(log)"
+check '... xnu.ko is unloaded and the interrupts are back (a run that ended by itself)' [ ! -d "$R/sys/module/xnu" -a "$(cat "$R/proc/irq/default_smp_affinity")" = f ]
+host 'halt 2'; /bin/bash "$P/scripts/xnulinux-boot.sh" --wait > "$T/out" 2>&1 & w=$!
+wait_for 10 grep -q '^booting' "$T/out"
+klog "fki: darwin console: # grep -c 'XNU panic' /var/log/notes"; klog "fki: darwin console: XNU panic: 3 lines"
+wait $w; s=$?
+check '--wait, a clean halt of a system whose console showed the words "XNU panic": status 0, "shut down"' \
+ [ $s = 0 -a "$(grep -c '^the hosted system shut down: ' "$T/out")" != 0 ]
+
+# ---- stop and the --wait process both unload xnu.ko (as under systemd: ExecStop, then SIGTERM to --wait)
+host; boot
+RMMOD=lost boot stop; s=$?
+check "stop, xnu.ko unloaded by the other one between its test and its rmmod: not a failed stop" [ $s = 0 -a "$(grep -c '^hosted system stopped' "$T/out")" != 0 ]
+host; boot
+RMMOD=busy boot stop; s=$?
+check "stop, xnu.ko really not unloading: status 1 with rmmod's message" [ $s = 1 -a "$(grep -c 'Module xnu is in use' "$T/out")" != 0 ]
+host; /bin/bash "$P/scripts/xnulinux-boot.sh" --wait > "$T/out" 2>&1 & w=$!
+wait_for 10 grep -q '^booting' "$T/out"
+/bin/bash "$P/scripts/xnulinux-boot.sh" stop > "$T/out.stop" 2>&1; kill -TERM $w 2>/dev/null; wait $w; s=$?
+check 'a stop of the service: --wait ends with status 0 and "stopped"' [ $s = 0 -a "$(grep -c '^the hosted system stopped: ' "$T/out")" != 0 ]
+
+# ---- fki.ko not loaded at the start (its load at boot failed: after a kernel update it was the old kernel's)
+FKI=no host; echo "ExecStart=/usr/sbin/insmod /opt/xnulinux/fki-ko/fki.ko carve_base=0x400000000 carve_mb=4060" > "$R/etc/systemd/system/xnulinux-fki.service"
+boot; boot stop
+check "fki.ko not loaded at the start: loaded with its boot unit's carve-out, not the default one" \
+ called '^insmod fki-ko/fki.ko carve_base=0x400000000 carve_mb=4060'
+FKI=no host; boot; boot stop
+check '... and with the default one where there is no such unit (and the start goes on)' \
+ [ "$(grep -c '^insmod fki-ko/fki.ko carve_base=0x200000000 carve_mb=8156' "$T/calls")$(grep -c '^insmod xnu-ko/xnu.ko ' "$T/calls")" = 11 ]
+
+# ---- the installer
+host; : > "$T/sudo-asks"
+/bin/bash "$P/scripts/install-service.sh" > "$T/out" 2>&1; s=$?
+check "install-service.sh, a user whose sudo asks for a password: refused, with the rule to add" [ $s = 1 -a "$(grep -c 'NOPASSWD' "$T/out")" != 0 ]
+check '... and no unit written' [ ! -e "$R/etc/systemd/system/xnulinux.service" ]
+rm "$T/sudo-asks"; /bin/bash "$P/scripts/install-service.sh" > "$T/out" 2>&1; s=$?
+check 'install-service.sh with sudo that does not ask: the unit is written' [ $s = 0 -a -s "$R/etc/systemd/system/xnulinux.service" ]
+check "... and it wants fki's boot unit, it does not require it (a failed load there must not keep the service down)" \
+ [ "$(grep -c '^Wants=.*xnulinux-fki.service' "$R/etc/systemd/system/xnulinux.service")$(grep -c '^Requires=' "$R/etc/systemd/system/xnulinux.service")" = 10 ]
+pkill -f "$T/bin/insmod" 2>/dev/null
+finish
diff --git a/tools/dgx-spark/guest/hcmd.sh b/tools/dgx-spark/guest/hcmd.sh
index 846564b..4d0a73c 100755
--- a/tools/dgx-spark/guest/hcmd.sh
+++ b/tools/dgx-spark/guest/hcmd.sh
@@ -1,9 +1,12 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-only
# hcmd.sh [TIMEOUT] < commands : run commands in the hosted macOS's console shell, output returned over the xnu0 link (not dmesg)
-T=${1:-60}; cat > /var/tmp/www/cmd.sh
+T=${1:-60}; mkdir -p /var/tmp/www; cat > /var/tmp/www/cmd.sh
+# the hosted shell fetches the commands from 192.168.77.1:8099: served here for this run (a server already there keeps the port)
+(timeout $T python3 -m http.server 8099 --bind 192.168.77.1 --directory /var/tmp/www >/dev/null 2>&1 &)
rm -f /var/tmp/hout; (timeout $T nc -l 192.168.77.1 8100 > /var/tmp/hout 2>/dev/null &)
sleep 0.5
-printf '\ncurl -s -o /tmp/cmd.sh http://192.168.77.1:8099/cmd.sh; bash /tmp/cmd.sh 2>&1 | nc 192.168.77.1 8100\n' >> /var/tmp/console-in
+# (-f and &&: commands that could not be fetched are not replaced by the ones an earlier run left in /tmp/cmd.sh)
+printf '\n{ curl -sf -o /tmp/cmd.sh http://192.168.77.1:8099/cmd.sh && bash /tmp/cmd.sh || echo "hcmd: the commands could not be fetched or failed"; } 2>&1 | nc 192.168.77.1 8100\n' >> /var/tmp/console-in
while pgrep -f "nc -l 192.168.77.1 8100" >/dev/null; do sleep 1; done
cat /var/tmp/hout