Skip to content

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

C

Mac host scripts: only our images detached, the console from the kernel log, the krunkit agent stops its VM cleanly, vm.sh and serial-pty.py

Fred Nixc78c44371689
diff --git a/scripts/install-krun-agent.sh b/scripts/install-krun-agent.sh
index 04bd7af..80a3fc4 100755
--- a/scripts/install-krun-agent.sh
+++ b/scripts/install-krun-agent.sh
@@ -3,7 +3,7 @@
# On the Mac host: keep the Linux VM running under krunkit as a launchd agent of this user. krunkit exits when the guest
# reboots or powers off; launchd starts it again (KeepAlive), and at login (RunAtLoad). With the hosted macOS as a service
# in the VM (scripts/install-service.sh) a reboot of either comes back by itself.
-# scripts/install-krun-agent.sh install and start
+# scripts/install-krun-agent.sh install and start (again, for new settings: the VM is stopped as remove stops it)
# scripts/install-krun-agent.sh remove stop the VM (the guest shut down first) and remove the agent
# Settings: the environment of scripts/krun-vm.sh (CPUS, MEM, DISK, SSH_PORT), written into the agent at install.
set -euo pipefail
@@ -12,17 +12,25 @@ L=org.xnulinux.krun-vm
domain() { launchctl print "gui/$(id -u)" >/dev/null 2>&1 && echo "gui/$(id -u)" || echo "user/$(id -u)"; } # no login session: the user domain
PL=$HOME/Library/LaunchAgents/$L.plist
S=${S:-$HOME/.local/state/xnupoc-krun}
-if [ "${1:-}" = remove ]; then
- # the VM as the agent runs it: the SSH_PORT and KRUN written into the agent at install, unless the environment says
- setting() { local v; v=$([ -f "$PL" ] && /usr/libexec/PlistBuddy -c "Print :EnvironmentVariables:$1" "$PL" 2>/dev/null) && echo "$v" || true; }
- SSH_PORT=${SSH_PORT:-$(setting SSH_PORT)}; KRUN=${KRUN:-$(setting KRUN)}
- # a clean guest shutdown first (the hosted macOS's disk synced by xnulinux.service), then the agent
- ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -p "${SSH_PORT:-2223}" \
- ${VMKEY:+-i "$VMKEY"} [email protected] 'sudo systemctl poweroff' 2>/dev/null || true
- for _ in $(seq 1 120); do pgrep -f "${KRUN:-$HOME/.local/krunkit}/bin/krunkit" >/dev/null || break; sleep 1; done
+# the VM as the agent runs it: the SSH_PORT and KRUN written into the agent at install
+setting() { local v; v=$([ -f "$PL" ] && /usr/libexec/PlistBuddy -c "Print :EnvironmentVariables:$1" "$PL" 2>/dev/null) && echo "$v" || true; }
+stop_vm() { # stop_vm SSH_PORT KRUN: a clean guest shutdown first (the hosted macOS's disk synced by xnulinux.service), then the agent
+ local k p key=${VMKEY:-$P/../vmkey}; [ -f "$key" ] || key= # the key scripts/vm.sh uses, unless VMKEY names another
+ # The wait is for one of the krunkits that run now to end: the VM that is told to power off. The moment it has, launchd
+ # starts the VM again (KeepAlive): a wait for no krunkit at all met that one, sat out its two minutes, and the agent's
+ # removal then killed a guest that had just booted.
+ k=$(pgrep -f "${2:-$HOME/.local/krunkit}/bin/krunkit" || true)
+ ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -p "${1:-2223}" \
+ ${key:+-i "$key"} [email protected] 'sudo systemctl poweroff' 2>/dev/null || true
+ for _ in $(seq 1 600); do [ -n "$k" ] || break; for p in $k; do kill -0 "$p" 2>/dev/null || break 2; done; sleep 0.2; done
launchctl bootout "$(domain)/$L" 2>/dev/null || true
+}
+if [ "${1:-}" = remove ]; then
+ stop_vm "${SSH_PORT:-$(setting SSH_PORT)}" "${KRUN:-$(setting KRUN)}" # unless the environment says
rm -f "$PL"; echo "removed"; exit 0
fi
+# installed already (new settings): the VM the agent runs is stopped the same way first, with the settings it runs with
+if launchctl print "$(domain)/$L" >/dev/null 2>&1; then stop_vm "$(setting SSH_PORT)" "$(setting KRUN)"; fi
mkdir -p "$(dirname "$PL")" "$S"
env_xml() { for v in CPUS MEM DISK SSH_PORT KRUN; do [ -n "${!v:-}" ] && printf ' <key>%s</key><string>%s</string>\n' "$v" "${!v}"; done; true; }
cat > "$PL" <<PLIST
diff --git a/scripts/krun-vm.sh b/scripts/krun-vm.sh
index c909796..402c255 100644
--- a/scripts/krun-vm.sh
+++ b/scripts/krun-vm.sh
@@ -47,13 +47,15 @@ locked "$KRUN"/bin/krunkit --cpus "$CPUS" --memory "$MEM" \
--restful-uri "unix://$S/rest.sock" --pidfile "$S/krunkit.pid" --log-file "$S/krunkit.log" &
KR=$!
trap 'kill $KR $GV 2>/dev/null' EXIT
-api() { curl -sf --unix-socket "$S/gvapi.sock" "http://gv$1" "${@:2}"; }
+api() { curl -s --fail-with-body --unix-socket "$S/gvapi.sock" "http://gv$1" "${@:2}"; } # an HTTP error: status 22 and gvproxy's reason
for _ in $(seq 1 120); do
ip=$(api /services/dhcp/leases | python3 -c 'import json,sys; m=sys.argv[1].lower(); print(next((k for k,v in json.load(sys.stdin).items() if v.lower()==m), ""))' "$MAC" 2>/dev/null || true)
[ -n "$ip" ] && break; sleep 1
done
if [ -n "$ip" ]; then
- api /services/forwarder/expose -X POST -d "{\"local\":\"127.0.0.1:$SSH_PORT\",\"remote\":\"$ip:22\"}" && echo "ssh: 127.0.0.1:$SSH_PORT -> $ip:22"
+ # gvproxy says why not (SSH_PORT taken: "listen tcp ...: bind: address already in use"); the VM runs on, without ssh
+ why=$(api /services/forwarder/expose -X POST -d "{\"local\":\"127.0.0.1:$SSH_PORT\",\"remote\":\"$ip:22\"}") &&
+ echo "ssh: 127.0.0.1:$SSH_PORT -> $ip:22" || echo "no ssh: gvproxy did not forward 127.0.0.1:$SSH_PORT to the guest: ${why:-no answer}" >&2
else
echo "the guest never took a DHCP lease" >&2
fi
diff --git a/scripts/mk-macvm-disk.sh b/scripts/mk-macvm-disk.sh
index 6602cba..9e4fe88 100755
--- a/scripts/mk-macvm-disk.sh
+++ b/scripts/mk-macvm-disk.sh
@@ -20,11 +20,13 @@ GPU=${GPU:-$PWD/gpu/xnu-cpu-metal/dist/XnuCpuMetal.bundle}
# bluetoothd: no Bluetooth controller; it fails to boot the chip and exits, and launchd starts it again every few seconds
DISABLE="com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServices
com.apple.PerfPowerServicesExtended com.apple.oahd com.apple.oahd-root-helper com.apple.bluetoothd ${DISABLE:-}"
-# images of ours left attached by an earlier run
+# images of ours left attached by an earlier run: a clone (mac.img), and the installed disk, which is $SRC and not
+# whatever is called disk.img (every tart VM's disk is: one attached for something else is not ours to detach)
for d in $(hdiutil info -plist | python3 -c 'import plistlib,sys,os
for i in plistlib.loads(sys.stdin.buffer.read()).get("images", []):
- if os.path.basename(i.get("image-path", "")) in ("disk.img", "mac.img"):
- print(*[e["dev-entry"] for e in i.get("system-entities", []) if "content-hint" in e and e["content-hint"] == "GUID_partition_scheme"])'); do
+ p = i.get("image-path", "")
+ if os.path.basename(p) == "mac.img" or os.path.realpath(p) == os.path.realpath(sys.argv[1]):
+ print(*[e["dev-entry"] for e in i.get("system-entities", []) if "content-hint" in e and e["content-hint"] == "GUID_partition_scheme"])' "$SRC"); do
hdiutil detach "$d" -force >/dev/null 2>&1 || true
done
mkdir -p "$W"; rm -f "$IMG"; cp -c "$SRC" "$IMG" # an APFS clone of the installed disk: the installed one stays pristine
diff --git a/scripts/serial-pty.py b/scripts/serial-pty.py
index 7919a22..86a7f7c 100644
--- a/scripts/serial-pty.py
+++ b/scripts/serial-pty.py
@@ -1,7 +1,9 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# On the Mac host: create a pty for `tart run --serial-path`, write its name to argv[1] and append
-# everything the guest writes to its console to argv[2]. Output survives a guest hang.
+# everything the guest writes to its console to argv[2]. Output survives a guest hang. It ends when the VM has: this
+# end of the pty is kept open only until the console's first output (the VM has it open by then), so the read ends
+# when the VM closes it. Held for good, it never did, and every run left one of these behind.
import os, sys, tty
m, s = os.openpty()
tty.setraw(s)
@@ -15,4 +17,7 @@ while True:
break
if not d:
break
+ if s is not None:
+ os.close(s)
+ s = None
out.write(d)
diff --git a/scripts/vm.sh b/scripts/vm.sh
index c4b9df9..19ec0cb 100755
--- a/scripts/vm.sh
+++ b/scripts/vm.sh
@@ -2,9 +2,11 @@
# SPDX-License-Identifier: GPL-2.0-only
# On the macOS host: run a command (or a script with -s FILE) in the xnupoc VM.
W="$(cd "$(dirname "$0")/../.." && pwd)" # the session work dir (vmkey, vm.ip)
-ip=$(cat $W/vm.ip); port=$(cat $W/vm.port 2>/dev/null || echo 22) # vm.port: 2223 when the VM runs under krunkit (gvproxy)
-O="-o Port=$port -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o ServerAliveInterval=30 -o LogLevel=ERROR -i $W/vmkey"
-if [ "$1" = -s ]; then exec ssh $O admin@$ip bash -s < "$2"; fi
-if [ "$1" = -put ]; then exec scp -O $O -r "$2" admin@$ip:"$3"; fi
-if [ "$1" = -get ]; then exec scp -O $O -r admin@$ip:"$2" "$3"; fi
-exec ssh $O admin@$ip "$@"
+# nothing in the repository makes these two: say so here, not as "cat: .../vm.ip: No such file or directory"
+[ -s "$W/vm.ip" ] && [ -e "$W/vmkey" ] || { echo "scripts/vm.sh: needs $W/vm.ip (the Linux VM's address: \`tart ip xnupoc\`; under scripts/krun-vm.sh 127.0.0.1, with its SSH_PORT, 2223, in $W/vm.port) and $W/vmkey (an ssh key the VM's admin user accepts)" >&2; exit 1; }
+ip=$(cat "$W/vm.ip"); port=$(cat "$W/vm.port" 2>/dev/null || echo 22) # vm.port: 2223 when the VM runs under krunkit (gvproxy)
+O=(-o Port=$port -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o ServerAliveInterval=30 -o LogLevel=ERROR -i "$W/vmkey")
+if [ "$1" = -s ]; then exec ssh "${O[@]}" admin@$ip bash -s < "$2"; fi
+if [ "$1" = -put ]; then exec scp -O "${O[@]}" -r "$2" admin@$ip:"$3"; fi
+if [ "$1" = -get ]; then exec scp -O "${O[@]}" -r admin@$ip:"$2" "$3"; fi
+exec ssh "${O[@]}" admin@$ip "$@"
diff --git a/scripts/xnu-console.sh b/scripts/xnu-console.sh
index 1977798..135b96e 100755
--- a/scripts/xnu-console.sh
+++ b/scripts/xnu-console.sh
@@ -1,11 +1,13 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-only
# On the Mac host, with the VM running and XNU loaded with CONSOLE_IN=/var/tmp/console-in: an interactive terminal on
-# XNU's /dev/console. Output: the "darwin console:" lines of the captured serial log; input: each line typed here is
-# appended to the console input file in the VM.
-P=$(cd "$(dirname "$0")/.." && pwd); LOG=${LOG:-$P/../serial-cap.log}
-tail -n 0 -F "$LOG" | tr -d '\r' | sed -un 's/^\[ *[0-9.]*\] fki: darwin console: //p' &
-TP=$!; trap 'kill $TP 2>/dev/null' EXIT
+# XNU's /dev/console. Output: the "darwin console:" lines of the VM's kernel log, followed through journald as
+# scripts/vm-dmesg-shell.sh reads it (scripts/xnulinux-boot.sh keeps XNU's lines off the VM console, so a captured serial
+# log has none of them); input: each line typed here is appended to the console input file in the VM.
+P=$(cd "$(dirname "$0")/.." && pwd)
+# (the reader's ssh gets no input of its own: the first command of a background pipeline has the script's, the lines typed)
+bash "$P/scripts/vm.sh" 'sudo journalctl -k -f -n 0 -q -o cat' < /dev/null | sed -un 's/^fki: darwin console: //p' &
+trap 'pkill -P $$' EXIT # the reader: its ssh as well as its sed ($! is only the sed)
while IFS= read -r line; do
printf '%s\n' "$line" | bash "$P/scripts/vm.sh" 'cat >> /var/tmp/console-in'
done
diff --git a/tests/scripts/krun-agent.test.sh b/tests/scripts/krun-agent.test.sh
new file mode 100755
index 0000000..2a3f362
--- /dev/null
+++ b/tests/scripts/krun-agent.test.sh
@@ -0,0 +1,121 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# scripts/install-krun-agent.sh and scripts/krun-vm.sh, as they are, without launchd, krunkit, gvproxy or a guest:
+# - launchctl is a small model of launchd for one agent (bootstrap, bootout, print): it runs the agent's program with
+# the plist's environment, starts it again at once when it exits (KeepAlive, for a job that has run longer than its
+# ThrottleInterval, as a VM that is being stopped has), and on bootout sends it SIGTERM and ends what is left of it
+# - krunkit is a "VM" that writes what happens to it to $T/vm.log: "N start", "N up" once its guest has run for 2 s,
+# "N off" when the guest powered off (ssh ... 'sudo systemctl poweroff', 0.3 s later), "N killed [with its guest up]"
+# - gvproxy makes its socket; curl answers for its API as a real gvproxy does (leases as {ip: mac}; a forward of a
+# taken port: HTTP 500 with the reason, which is curl's status 22)
+. "$(dirname "$0")/lib.sh"
+sandbox_repo
+K=$HOME/.local/krunkit; S=$HOME/.local/state/xnupoc-krun; D=$HOME/.tart/vms/xnupoc
+PL=$HOME/Library/LaunchAgents/org.xnulinux.krun-vm.plist
+mkdir -p "$K/bin" "$D" "$T/launchd"; : > "$D/disk.img"; echo '{"macAddress": "52:54:00:12:34:56"}' > "$D/config.json"
+: > "$T/vm.log"; : > "$T/vmkey" # the key of the Mac-side scripts (scripts/vm.sh), next to the repository
+cat > "$T/launchd.py" <<'EOF'
+import os, plistlib, signal, subprocess, sys, threading, time
+T = os.environ['T']; cmd, arg = sys.argv[1], sys.argv[2]
+pidfile = lambda label: f'{T}/launchd/{label}.pid'
+def loaded(label):
+ try: pid = int(open(pidfile(label)).read()); os.kill(pid, 0); return pid
+ except (OSError, ValueError): return 0
+if cmd == 'print': # a domain (gui/UID), or a service in it (gui/UID/LABEL)
+ sys.exit(0 if arg.count('/') == 1 or loaded(arg.split('/')[2]) else 113)
+if cmd == 'bootout':
+ pid = loaded(arg.split('/')[2])
+ if not pid: sys.exit('Boot-out failed: 3: No such process')
+ os.kill(pid, signal.SIGTERM)
+ while loaded(arg.split('/')[2]): time.sleep(0.05)
+ sys.exit(0)
+assert cmd == 'bootstrap'
+pl = plistlib.load(open(sys.argv[3], 'rb'))
+if loaded(pl['Label']): sys.exit('Bootstrap failed: 5: Input/output error')
+if os.fork(): sys.exit(0)
+os.setsid(); open(pidfile(pl['Label']), 'w').write(str(os.getpid()))
+env = dict(pl.get('EnvironmentVariables', {}), HOME=os.environ['HOME'])
+env['PATH'] = f'{T}/bin:' + env.get('PATH', '/usr/bin:/bin') # the stand-ins (curl) before the agent's PATH
+log = open(pl['StandardOutPath'], 'ab'); job = None; stopping = False
+def kill_group(pg):
+ try: os.killpg(pg, signal.SIGKILL)
+ except OSError: pass
+def term(*_):
+ global stopping; stopping = True
+ if job and job.poll() is None: job.terminate()
+signal.signal(signal.SIGTERM, term)
+while not stopping:
+ job = subprocess.Popen(pl['ProgramArguments'], env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
+ if stopping: job.terminate()
+ job.wait()
+ threading.Timer(0.5, kill_group, [job.pid]).start() # what the job left running goes with it
+ if not pl.get('KeepAlive'): break
+os.unlink(pidfile(pl['Label']))
+EOF
+stub launchctl <<'EOF'
+exec python3 "$T/launchd.py" "$@"
+EOF
+cat > "$T/krunkit.py" <<'EOF'
+import os, signal, sys, time
+T, VM = os.environ['T'], os.environ['VM']; t0 = time.time(); said = False
+n = sum(l.endswith(' start\n') for l in open(f'{T}/vm.log')) + 1
+def log(what): open(f'{T}/vm.log', 'a').write(f'{n} {what}\n')
+def up(): return time.time() - t0 >= 2
+def term(*_): log('killed with its guest up' if up() else 'killed'); os._exit(143)
+signal.signal(signal.SIGTERM, term); log('start')
+while not os.path.exists(f'{VM}/poweroff'):
+ if up() and not said: said = True; log('up')
+ time.sleep(0.05)
+time.sleep(0.3); os.unlink(f'{VM}/poweroff'); log('off')
+EOF
+stub krunkit "$K/bin" <<'EOF'
+exec python3 "$T/krunkit.py" "$0" "$@" # one process, with krunkit's path and arguments in its command line
+EOF
+stub gvproxy "$K/bin" <<'EOF'
+while [ $# -gt 0 ]; do [ "$1" != -listen-vfkit ] || s=${2#unixgram://}; shift; done
+cd "$(dirname "$s")" && exec python3 -c 'import socket, sys, time; socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM).bind(sys.argv[1]); time.sleep(1000000)' "$(basename "$s")" "$s"
+EOF
+stub curl <<'EOF'
+case "$*" in
+ */services/dhcp/leases*) echo '{"192.168.127.1":"5a:94:ef:e4:0c:dd","192.168.127.2":"52:54:00:12:34:56"}';;
+ */services/forwarder/expose*) [ ! -e "$T/port-taken" ] || { case "$*" in *--fail-with-body*) echo 'listen tcp 127.0.0.1:2223: bind: address already in use';; esac; exit 22; };;
+esac
+EOF
+stub_ssh
+vmstub sudo <<'EOF'
+exec "$@"
+EOF
+vmstub systemctl <<'EOF'
+[ "$1" != poweroff ] || : > "$VM/poweroff"
+EOF
+A=$T/repo/scripts/install-krun-agent.sh
+vm() { grep -qx "$1" "$T/vm.log"; }
+krunkits() { pgrep -f "$K/bin/krunkit" >/dev/null; }
+
+/bin/bash "$A" > "$T/out" 2>&1
+check 'install: launchd runs krun-vm.sh, the VM starts and its ssh is forwarded' wait_for 10 grep -qx 'ssh: 127.0.0.1:2223 -> 192.168.127.2:22' "$S/agent.log"
+wait_for 10 vm '1 up'
+within 20 /bin/bash "$A" remove >> "$T/out" 2>&1; s=$?
+check 'remove: the guest is asked to power off (ssh to the SSH_PORT of the agent) and its VM ends by that' eval 'called "^ssh .* -p 2223 .*systemctl poweroff" && vm "1 off"'
+check "... with the key of the Mac-side scripts (../vmkey, as scripts/vm.sh)" called "^ssh .* -i $T/repo/\.\./vmkey .*systemctl poweroff"
+check '... remove returns when that VM is down, not after waiting out the one launchd started in its place' [ $s = 0 ]
+check '... leaving no VM running, and none killed with its guest up' not eval 'krunkits || grep -q "guest up" "$T/vm.log"'
+check '... and no agent' not eval '[ -e "$PL" ] || launchctl print gui/$(id -u)/org.xnulinux.krun-vm'
+[ $FAILED = 0 ] || { sed 's/^/ | /' "$T/out" "$T/vm.log"; }
+pkill -f "$T/launchd.py" 2>/dev/null; pkill -f "$K/bin/" 2>/dev/null; sleep 0.3 # (what a failed remove left)
+
+: > "$T/vm.log"; : > "$T/calls"; : > "$S/agent.log"; f=$FAILED
+/bin/bash "$A" >> "$T/out" 2>&1; wait_for 10 vm '1 up'
+CPUS=4 within 20 /bin/bash "$A" >> "$T/out" 2>&1; s=$?
+check 'install over a running agent (new settings): its guest is powered off first, not killed' eval '[ $s = 0 ] && vm "1 off" && ! grep -q "guest up" "$T/vm.log"'
+check '... and the VM comes back with the new settings' wait_for 10 eval 'grep -q "^krunkit --cpus 4 " "$T/calls" && pgrep -f "$K/bin/krunkit --cpus 4 " >/dev/null'
+[ $FAILED = $f ] || { sed 's/^/ | /' "$T/out" "$T/vm.log"; }
+launchctl bootout "gui/$(id -u)/org.xnulinux.krun-vm" 2>/dev/null; pkill -f "$K/bin/" 2>/dev/null; sleep 0.3
+
+: > "$T/port-taken"; : > "$T/calls"; f=$FAILED
+/bin/bash "$T/repo/scripts/krun-vm.sh" > "$T/vm.out" 2>&1 & pid=$!
+check 'krun-vm.sh, SSH_PORT taken: it says that the VM has no ssh, and why' wait_for 10 grep -q 'no ssh.*127.0.0.1:2223.*address already in use' "$T/vm.out"
+check '... and runs the VM all the same' wait_for 5 called '^krunkit '
+kill $pid 2>/dev/null; wait $pid 2>/dev/null
+[ $FAILED = $f ] || sed 's/^/ | /' "$T/vm.out"
+finish
diff --git a/tests/scripts/mk-macvm-disk.test.sh b/tests/scripts/mk-macvm-disk.test.sh
new file mode 100755
index 0000000..ddfe58f
--- /dev/null
+++ b/tests/scripts/mk-macvm-disk.test.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# scripts/mk-macvm-disk.sh, its first step only: which attached disk images it force-detaches before it makes its clone.
+# hdiutil is a stand-in: `info -plist` lists four attached images, `detach` is only written down, and `attach` fails,
+# which ends the script there (on Linux its `cp -c` does, one line earlier). No image is touched; diskutil and sudo
+# are stand-ins that fail, should the script ever get to them.
+. "$(dirname "$0")/lib.sh"
+sandbox_repo
+V=$HOME/.tart/vms; mkdir -p "$V/xnumac" "$V/xnupoc"; : > "$V/xnumac/disk.img"; : > "$V/xnupoc/disk.img"; : > "$HOME/installed.img"
+# attached: disk21 an earlier run's clone, disk22 the installed disk (the default SRC), disk23 another VM's disk, which
+# is called disk.img as every tart VM's is, disk24 an image under another name
+python3 - "$T/macvm/mac.img" "$V/xnumac/disk.img" "$V/xnupoc/disk.img" "$HOME/installed.img" > "$T/info.plist" <<'EOF'
+import plistlib, sys
+image = lambda path, n: {'image-path': path, 'system-entities': [
+ {'dev-entry': f'/dev/disk{n}', 'content-hint': 'GUID_partition_scheme'}, {'dev-entry': f'/dev/disk{n}s2', 'content-hint': 'Apple_APFS'}]}
+sys.stdout.buffer.write(plistlib.dumps({'images': [image(p, 21 + i) for i, p in enumerate(sys.argv[1:])]}))
+EOF
+stub hdiutil <<'EOF'
+case $1 in info) cat "$T/info.plist";; attach) exit 1;; esac
+EOF
+for c in diskutil sudo; do stub $c <<'EOF'
+exit 1
+EOF
+done
+detached() { grep '^hdiutil detach ' "$T/calls" | sed 's|.*/dev/||; s| .*||' | sort | tr '\n' ' '; }
+
+/bin/bash "$T/repo/scripts/mk-macvm-disk.sh" > "$T/out" 2>&1
+check "detached first: the clone an earlier run left (mac.img) and the installed disk, not another VM's disk.img" [ "$(detached)" = 'disk21 disk22 ' ]
+: > "$T/calls"; SRC=$HOME/installed.img /bin/bash "$T/repo/scripts/mk-macvm-disk.sh" >> "$T/out" 2>&1
+check 'with SRC=<an image of another name>: the clone and that image, and no disk.img' [ "$(detached)" = 'disk21 disk24 ' ]
+[ $FAILED = 0 ] || sed 's/^/ | /' "$T/out" "$T/calls"
+finish
diff --git a/tests/scripts/vm-host-helpers.test.sh b/tests/scripts/vm-host-helpers.test.sh
new file mode 100755
index 0000000..edd1657
--- /dev/null
+++ b/tests/scripts/vm-host-helpers.test.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# The Mac-side helpers of the Linux VM. scripts/vm.sh: without the session files it says which ones it needs and runs
+# nothing; with them it reaches the VM also from a directory whose path has a space. scripts/serial-pty.py: the console
+# logger of vm-run-serial.sh ends when the VM has closed the console.
+. "$(dirname "$0")/lib.sh"
+sandbox_repo
+for c in ssh scp; do stub $c <<EOF # the stand-in's arguments, one a line
+printf '%s\n' "\$@" > "\$T/$c.args"
+EOF
+done
+has() { grep -qxF -- "$2" "$T/$1.args"; } # has ssh|scp ARGUMENT: the stand-in was given exactly that argument
+
+# vm.sh with nothing beside the repository
+out=$(bash "$T/repo/scripts/vm.sh" uname -a 2>&1); st=$?
+check 'vm.sh without ../vm.ip and ../vmkey: fails' [ $st != 0 ]
+check '... names both files and where they are' sh -c 'echo "$1" | grep -q "$2/vm.ip" && echo "$1" | grep -q "$2/vmkey"' - "$out" "$T"
+check '... says how to get the address' sh -c 'echo "$1" | grep -q "tart ip"' - "$out"
+check '... and has not called ssh' not called '^ssh'
+
+# with them, in a directory whose path has a space
+D="$T/my work"; mkdir -p "$D"; cp -Rp "$T/repo" "$D/repo"; echo 192.168.64.7 > "$D/vm.ip"; : > "$D/vmkey"
+bash "$D/repo/scripts/vm.sh" uname -a >/dev/null 2>&1
+check 'vm.sh from a path with a space: ssh is called' called '^ssh'
+check '... with the key as one argument' has ssh "$D/vmkey"
+check '... on port 22 without ../vm.port' has ssh Port=22
+check '... to the address in ../vm.ip' has ssh [email protected]
+check '... with the command' has ssh uname
+echo 2223 > "$D/vm.port"; echo 127.0.0.1 > "$D/vm.ip"
+bash "$D/repo/scripts/vm.sh" -put "$D/a file" /var/tmp/there >/dev/null 2>&1
+check 'vm.sh -put under krunkit: scp on the port in ../vm.port' has scp Port=2223
+check '... with the key as one argument' has scp "$D/vmkey"
+check '... the file to copy as one argument' has scp "$D/a file"
+check '... to the VM' has scp [email protected]:/var/tmp/there
+
+# serial-pty.py: a stand-in VM opens the pty, writes its console output and ends
+python3 "$T/repo/scripts/serial-pty.py" "$T/serial-name" "$T/serial-cap.log" & logger=$!
+check 'serial-pty.py: writes the name of its pty' wait_for 5 test -s "$T/serial-name"
+python3 -c 'import os, sys, time
+fd = os.open(sys.argv[1], os.O_RDWR | os.O_NOCTTY)
+for i in range(3):
+ os.write(fd, b"console line %d\n" % i); time.sleep(0.1)
+os.close(fd)' "$(cat "$T/serial-name")"
+check '... the console output is in the log' wait_for 5 grep -q 'console line 2' "$T/serial-cap.log"
+check '... and it ends when the VM has closed the console' wait_for 5 not kill -0 $logger
+finish
diff --git a/tests/scripts/xnu-console.test.sh b/tests/scripts/xnu-console.test.sh
new file mode 100755
index 0000000..4d58c7d
--- /dev/null
+++ b/tests/scripts/xnu-console.test.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0-only
+# scripts/xnu-console.sh against a stand-in VM booted the way scripts/xnulinux-boot.sh boots it: the hosted console's
+# lines are in the kernel log (pr_info, read through journald) and not on the VM console (`dmesg -n`), so the captured
+# serial log has none of them. The script and scripts/vm.sh run as they are; ssh runs its command in the stand-in VM,
+# whose journalctl follows a file and whose "hosted console shell" answers each line that arrives in console-in.
+. "$(dirname "$0")/lib.sh"
+sandbox_repo
+echo 127.0.0.1 > "$T/vm.ip"; : > "$T/vmkey" # what scripts/vm.sh reads next to the repository
+echo '[ 1.000000] systemd[1]: Reached target multi-user.target' > "$T/serial-cap.log" # scripts/vm-run-serial.sh's capture
+: > "$VM/journal"; : > "$VM/var/tmp/console-in"
+stub_ssh
+vmstub sudo <<'EOF'
+exec "$@"
+EOF
+vmstub journalctl <<'EOF'
+# (ssh passes its own input on: started with the script's, here a FIFO, it would take what is typed)
+[ ! -p /dev/stdin ] || { echo "the log's reader was started with the script's own input" >&2; exit 1; }
+case " $* " in *" -k "*) ;; *) echo "journalctl (stand-in): not the kernel log: $*" >&2; exit 1;; esac
+case " $* " in *" -f "*" -o cat "*|*" -o cat "*" -f "*) exec tail -n 0 -F "$VM/journal";; esac # -o cat: the message alone
+echo "journalctl (stand-in): only -f with -o cat: $*" >&2; exit 1
+EOF
+tail -n 0 -F "$VM/var/tmp/console-in" 2>/dev/null | while IFS= read -r l; do # the hosted system
+ printf '%s\n' 'fki: xnu: a kernel line that is not the console' "fki: darwin console: xnulinux# $l" \
+ "fki: darwin console: reply to $l" >> "$VM/journal"
+done &
+
+mkfifo "$T/in"
+/bin/bash "$T/repo/scripts/xnu-console.sh" < "$T/in" > "$T/out" 2>&1 & pid=$!
+exec 3> "$T/in"
+wait_for 3 called '^journalctl '; sleep 0.5 # the reader has had time to start, as a person types later than that
+echo 'uname -a' >&3
+check 'a line typed arrives in the console input of the hosted system' wait_for 5 grep -qx 'uname -a' "$VM/var/tmp/console-in"
+check 'what the console prints back is shown, while the console is otherwise quiet' wait_for 5 grep -qx 'reply to uname -a' "$T/out"
+echo 'second' >&3
+check '... for the next line too' wait_for 5 grep -qx 'reply to second' "$T/out"
+check '... and nothing but the console lines' not grep -q 'not the console' "$T/out"
+kids=$(pgrep -P $pid | tr '\n' ' ')
+exec 3>&- # end of input (^D)
+check 'the script ends with its input' wait_for 5 not kill -0 $pid
+sleep 0.3; left=
+for k in $kids; do kill -0 "$k" 2>/dev/null && left="$left [$(ps -o command= -p "$k" | sed "s|$T|\$T|g")]"; done
+check "... and leaves none of its processes running${left:+: left$left}" [ -z "$left" ]
+[ $FAILED = 0 ] || sed 's/^/ | /' "$T/out"
+finish