XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
apple-kc and the PureDarwin disk: kit, link and im4p refuse what is broken; the PureDarwin disk is made on Linux too; tests and CI
Fred Nix3b42d306ba46
diff --git a/.github/workflows/im4p.yml b/.github/workflows/im4p.ymlnew file mode 100644index 0000000..1a5a9ed--- /dev/null+++ b/.github/workflows/im4p.yml@@ -0,0 +1,34 @@+# SPDX-License-Identifier: GPL-2.0-only+# scripts/apple-kc/im4p.py (the kernelcache unpacker of scripts/apple-kc/link.sh) on kernelcaches the test makes itself:+# tests/apple-kc/test_im4p.py, with the lzfse tool for the LZFSE round trip. Nothing of Apple's is read.+name: im4p+on:+ push:+ paths:+ - .github/workflows/im4p.yml+ - scripts/apple-kc/im4p.py+ - tests/apple-kc/test_im4p.py+ pull_request:+ paths:+ - .github/workflows/im4p.yml+ - scripts/apple-kc/im4p.py+ - tests/apple-kc/test_im4p.py+jobs:+ test:+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-24.04, macos-latest]+ runs-on: ${{ matrix.os }}+ steps:+ - uses: actions/checkout@v4+ - name: lzfse+ run: |+ if [ "$RUNNER_OS" = Linux ]; then+ sudo apt-get update -qq+ sudo apt-get install -y -qq lzfse >/dev/null+ else+ HOMEBREW_NO_AUTO_UPDATE=1 brew install lzfse+ fi+ - name: Tests+ run: IM4P_TEST_NEED_LZFSE=1 python3 tests/apple-kc/test_im4p.py -vdiff --git a/.github/workflows/modules.yml b/.github/workflows/modules.ymlindex 226986b..1b9e369 100644--- a/.github/workflows/modules.yml+++ b/.github/workflows/modules.yml@@ -25,6 +25,12 @@ jobs:run: |test "$(modinfo -F license fki-ko/fki.ko)" = GPLtest "$(modinfo -F license xnu-ko/xnu.ko)" = Proprietary+ apple-kc:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - name: scripts/apple-kc (package.sh, link.sh) on stand-ins for what they read+ run: tests/apple-kc/run.shspdx:runs-on: ubuntu-24.04steps:diff --git a/.github/workflows/puredarwin-disk.yml b/.github/workflows/puredarwin-disk.ymlnew file mode 100644index 0000000..6ab57be--- /dev/null+++ b/.github/workflows/puredarwin-disk.yml@@ -0,0 +1,35 @@+# SPDX-License-Identifier: GPL-2.0-only+# scripts/mk-puredarwin-disk.sh on both hosts it runs on: the disk it makes from a small root file system, checked from+# outside (tests/puredarwin-disk). On Linux the HFS+ tools and the kernel's hfsplus module are installed first, and the+# job fails if the module cannot be loaded: it never passes without having made a disk.+name: puredarwin-disk+on:+ push:+ paths:+ - .github/workflows/puredarwin-disk.yml+ - scripts/mk-puredarwin-disk.sh+ - tests/puredarwin-disk/**+ pull_request:+ paths:+ - .github/workflows/puredarwin-disk.yml+ - scripts/mk-puredarwin-disk.sh+ - tests/puredarwin-disk/**+jobs:+ disk:+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-24.04, ubuntu-24.04-arm, macos-latest]+ runs-on: ${{ matrix.os }}+ steps:+ - uses: actions/checkout@v4+ - name: HFS+ tools and the hfsplus module (Linux)+ if: runner.os == 'Linux'+ run: |+ sudo apt-get update -q+ sudo apt-get install -y -q hfsprogs gdisk uuid-runtime+ # the module comes with the kernel's own modules on newer kernels and in linux-modules-extra on older ones+ sudo modprobe hfsplus || { sudo apt-get install -y -q "linux-modules-extra-$(uname -r)" && sudo modprobe hfsplus; }+ grep -w hfsplus /proc/filesystems+ - name: The disk, made and checked+ run: tests/puredarwin-disk/run.shdiff --git a/docs/free-kc.md b/docs/free-kc.mdindex 4c2a4df..a1f284c 100644--- a/docs/free-kc.md+++ b/docs/free-kc.md@@ -43,7 +43,8 @@ kernel has; and a kext's load tag.`nix build 'git+https://github.com/AFK-surf/PureDarwin?submodules=1&rev=b3b4b2812fdd1c5c251dc3089b5a1a9e00d29970#image-arm64-virt-minimal'` (PureDarwin'sbinary cache, https://hydra.lab004.dev, has its toolchain and what the fork did not change; the images there areupstream's).-2. `scripts/mk-puredarwin-disk.sh root.tar.gz pd.img > pd.conf` (Mac) makes the HFS+ disk and prints its UUIDs.+2. `scripts/mk-puredarwin-disk.sh root.tar.gz pd.img > pd.conf` (Linux, with `hfsprogs`, `gdisk` and the kernel's+ `hfsplus` module, or a Mac) makes the HFS+ disk and prints its UUIDs.3. In the VM, after `scripts/vm-xnu-rebuild.sh`: `scripts/free-kc/build.sh`, which writes `/lib/firmware/xnu/kc-free.bin`.4. Boot it: `MAC_CONF=pd.conf DISK=pd.img IMAGE=xnu/kc-free.bin TRUSTCACHE= GPU=off scripts/xnulinux-boot.sh`. The console(`CONSOLE_IN`) is PureDarwin's zsh. Its `halt` and `reboot` end the run.@@ -62,7 +63,8 @@ Apple's kexts from their own copy of macOS into a collection of their own, and c`scripts/apple-kc/link.sh KIT`. It reads macOS 27.2's `kernelcache.release.vma2` straight from Apple's IPSW (its URLis in `kit.json`; only that member is downloaded, with HTTP range requests), links the collection with`scripts/kclink` and installs it as `/lib/firmware/xnu/kc-apple.bin`. A second argument gives the- kernelcache instead: an IPSW or its URL, the IM4P, or that unpacked (`scripts/apple-kc/im4p.py`). The collection is+ kernelcache instead: an IPSW or its URL, the IM4P, the kernelcache file of an installed macOS (an IMG4), or that+ unpacked (`scripts/apple-kc/im4p.py`; a file that is cut short or damaged is refused). The collection isthe one `vm-xnu-rebuild.sh` links from the same kernelcache, byte for byte. Another kernelcache is refused: thekernel's segment slots were laid out for that one.3. `IMAGE=xnu/kc-apple.bin scripts/xnulinux-boot.sh` boots macOS on it; `IMAGE=xnu/kc-free.bin` boots PureDarwin.diff --git a/docs/hosted-service.md b/docs/hosted-service.mdindex e385773..6585718 100644--- a/docs/hosted-service.md+++ b/docs/hosted-service.md@@ -142,7 +142,7 @@ Apple's installer (`tart` or another Virtualization.framework installer).| Gap | Effect on the service ||---|---|| PureDarwin's userland `libcorecrypto` is PureDarwin's unaudited interim fork (§2.3) | replace it on the PureDarwin disk before offering it for anything that keeps secrets |-| Making the macOS disk needs a Mac with Xcode and `tart` (`mk-macvm-disk.sh`), and the PureDarwin disk needs `hdiutil` (`mk-puredarwin-disk.sh`) | users need a Mac to make their macOS disk; a Linux disk maker (from the IPSW's APFS images) would remove that. Check `tart`'s own license for commercial use, or use another Virtualization.framework installer. The PureDarwin disk should move to a Linux build (`mkfs.hfsplus`) so the pipeline runs without a Mac |+| Making the macOS disk needs a Mac with Xcode and `tart` (`mk-macvm-disk.sh`) | users need a Mac to make their macOS disk; a Linux disk maker (from the IPSW's APFS images) would remove that. Check `tart`'s own license for commercial use, or use another Virtualization.framework installer. The PureDarwin disk needs none: `mk-puredarwin-disk.sh` makes it on the Linux host (`mkfs.hfsplus`) as well || One kit per macOS build, fixed segment slots | each macOS release needs a new kit before users can update || AMFI relaxed (`amfi_get_out_of_my_way=1`) and SIP partly off (`lp-sip0`); the OS cryptex merged into the system volume | the hosted macOS is less locked down than a real Mac. State this in the service's documentation (`docs/production.md` §3) || The keystore is fresh at every boot | FileVault-style data protection does not persist across reboots |diff --git a/scripts/apple-kc/im4p.py b/scripts/apple-kc/im4p.pyindex 6f630ac..1cb3ac6 100755--- a/scripts/apple-kc/im4p.py+++ b/scripts/apple-kc/im4p.py@@ -5,10 +5,17 @@im4p.py INPUT OUTPUT [MEMBER]INPUT is an IPSW (a zip: MEMBER, default kernelcache.release.vma2, is read from it), an IPSW's URL (Apple's own:-only the member is downloaded, with HTTP range requests), an IM4P, or an unpacked Mach-O (copied). An IM4P is DER: SEQUENCE { "IM4P", type, description, OCTET STRING payload, ... }; the payload is LZFSE-("bvx2...", decoded by the lzfse tool: apt install lzfse), LZSS ("complzss" with Apple's 0x180-byte header), or plain.+only the member is downloaded, with HTTP range requests), an IM4P, an IMG4 with the IM4P in it (the kernelcache file of+an installed macOS, on its Preboot volume), or an unpacked Mach-O (copied). An IM4P is DER: SEQUENCE { "IM4P", type,+description, OCTET STRING payload, ... }; the payload is LZFSE ("bvx2...", decoded by the lzfse tool: apt install+lzfse), LZSS ("complzss" with Apple's 0x180-byte header), or plain.++A file that is cut short or does not unpack to what it says is refused, and OUTPUT is not written: the DER lengths+must fit the file, the unpacked size must be the one the IM4P (LZFSE) or the LZSS header states, and the result must+be a Mach-O."""import http.client+import osimport shutilimport structimport subprocess@@ -19,6 +26,9 @@ import urllib.requestimport zipfile+MACHO = b'\xcf\xfa\xed\xfe'++class Remote:"""A read-only, seekable file over HTTP range requests (what zipfile needs to read one member of a remote zip).Small reads (zip records) go through a cache of 256 KiB blocks; large ones (the member) are fetched as they are, in@@ -81,28 +91,49 @@ class Remote:def der(data, at):- """(tag, start of contents, end of contents) of the DER element at `at`."""+ """(tag, start of contents, end of contents) of the DER element at `at`. Its contents must be there: a file+ that was cut short (a download that stopped) ends before one of its elements does."""+ if at + 2 > len(data):+ raise SystemExit(f'cut short: {len(data)} bytes, and a DER element starts at {at}')tag, n = data[at], data[at + 1]at += 2if n & 0x80:k = n & 0x7fn = int.from_bytes(data[at:at + k], 'big')at += k+ if at + n > len(data):+ raise SystemExit(f'cut short: {len(data)} bytes, and a DER element of it ends at {at + n}')return tag, at, at + n-def payload(data):- tag, at, end = der(data, 0)- if tag != 0x30:- raise SystemExit('not an IM4P (no DER SEQUENCE)')+def elements(data, at, end):+ """The DER elements in data[at:end], as der() gives them."""items = []while at < end:t, s, e = der(data, at)items.append((t, s, e))at = e+ return items+++def payload(data):+ """(payload, its unpacked size or None) of an IM4P, or of the IM4P in an IMG4 (SEQUENCE { "IMG4", IM4P, manifest }).+ The size is the IM4P's compression record, SEQUENCE { INTEGER algorithm, INTEGER unpacked size }, where it has one+ (Apple's LZFSE kernelcaches do)."""+ tag, at, end = der(data, 0)+ if tag != 0x30:+ raise SystemExit('not an IM4P (no DER SEQUENCE)')+ items = elements(data, at, end)+ if len(items) > 1 and data[items[0][1]:items[0][2]] == b'IMG4' and items[1][0] == 0x30:+ items = elements(data, items[1][1], items[1][2])if len(items) < 4 or data[items[0][1]:items[0][2]] != b'IM4P' or items[3][0] != 0x04:raise SystemExit('not an IM4P')- return data[items[3][1]:items[3][2]]+ size = None+ for t, s, e in items[4:]:+ sub = elements(data, s, e) if t == 0x30 else []+ if len(sub) == 2 and sub[0][0] == sub[1][0] == 0x02:+ size = int.from_bytes(data[sub[1][1]:sub[1][2]], 'big')+ return data[items[3][1]:items[3][2]], sizedef lzss(src, size):@@ -151,25 +182,39 @@ def main():data = z.read(member)else:data = open(src, 'rb').read()- if data[:4] == b'\xcf\xfa\xed\xfe':+ if data[:4] == MACHO:open(dst, 'wb').write(data)return- body = payload(data)+ body, size = payload(data)if body[:4] == b'bvx2':lz = shutil.which('lzfse')if not lz:raise SystemExit('the kernelcache is LZFSE-compressed: install lzfse (apt install lzfse)')- with tempfile.NamedTemporaryFile() as f:+ # beside OUTPUT, moved there once it is known to be whole+ with tempfile.NamedTemporaryFile() as f, tempfile.TemporaryDirectory(dir=os.path.dirname(os.path.abspath(dst))) as d:f.write(body)f.flush()- subprocess.run([lz, '-decode', '-i', f.name, '-o', dst], check=True)- elif body[:8] == b'complzss':+ out = os.path.join(d, 'kernelcache')+ if subprocess.run([lz, '-decode', '-i', f.name, '-o', out]).returncode != 0 or not os.path.exists(out):+ raise SystemExit(f'{src}: lzfse could not decode the payload (damaged?)')+ have = os.path.getsize(out)+ if size is not None and have != size:+ raise SystemExit(f'{src}: the payload unpacks to {have} bytes, the IM4P says {size} (damaged?)')+ if open(out, 'rb').read(4) != MACHO:+ raise SystemExit(f'{src}: the payload does not unpack to a Mach-O (damaged?)')+ os.replace(out, dst)+ return+ if body[:8] == b'complzss':+ if len(body) < 0x180:+ raise SystemExit(f'{src}: cut short (an LZSS payload of {len(body)} bytes, less than its header)')size, = struct.unpack('>I', body[12:16])- open(dst, 'wb').write(lzss(body[0x180:], size))- elif body[:4] == b'\xcf\xfa\xed\xfe':- open(dst, 'wb').write(body)- else:- raise SystemExit(f'unknown IM4P payload ({body[:8]!r})')+ body = lzss(body[0x180:], size)+ if len(body) != size:+ raise SystemExit(f'{src}: the payload unpacks to {len(body)} bytes, its LZSS header says {size} (cut short?)')+ if body[:4] != MACHO:+ raise SystemExit(f'{src}: the IM4P payload is not a kernelcache ({body[:8]!r})')+ open(dst, 'wb').write(body)-main()+if __name__ == '__main__':+ main()diff --git a/scripts/apple-kc/link.sh b/scripts/apple-kc/link.shindex 6e9e1f4..960db7d 100755--- a/scripts/apple-kc/link.sh+++ b/scripts/apple-kc/link.sh@@ -17,7 +17,7 @@ POC=$(cd "$(dirname "$0")/../.." && pwd)abs() { python3 -c 'import os,sys; print(os.path.abspath(sys.argv[1]))' "$1"; }KIT=$(abs "$1"); OUT=$(abs "${3:-$KIT/kc-apple.bin}")INSTALL=; [ $# -lt 3 ] && [ -d /lib/firmware/xnu ] && INSTALL=/lib/firmware/xnu/kc-apple.bin-W=${APPLE_KC_WORK:-$KIT/.work}; mkdir -p "$W"+W=$(abs "${APPLE_KC_WORK:-$KIT/.work}"); mkdir -p "$W" # absolute: kclink runs in the kitkit() { python3 -c 'import json,sys; v=json.load(open(sys.argv[1]))for k in sys.argv[2].split("."): v=v[k]print(" ".join(v) if isinstance(v, list) else v)' "$KIT/kit.json" "$1"; }@@ -43,6 +43,6 @@ grep -E "^wrote" "$W/kclink.log" || true# AMFI of 27.2 expects platform version 27; the system disks the kit was made for carry 26 (scripts/kc-amfi-platform.py)python3 "$POC/scripts/kc-amfi-platform.py" "$OUT" "${AMFI_PLATFORM:-$(kit amfi_platform)}"if [ -n "$INSTALL" ]; then- sudo install -m 644 "$OUT" "$INSTALL" && OUT=$INSTALL+ sudo install -m 644 "$OUT" "$INSTALL"; OUT=$INSTALL # (not &&: a failed install must stop here, not go on to "boot it")fiecho "kernel collection with Apple's kexts: $OUT (boot it: IMAGE=xnu/$(basename "$OUT") scripts/xnulinux-boot.sh)"diff --git a/scripts/apple-kc/package.sh b/scripts/apple-kc/package.shindex 0488216..995018d 100755--- a/scripts/apple-kc/package.sh+++ b/scripts/apple-kc/package.sh@@ -13,8 +13,12 @@ set -euo pipefailPOC=$(cd "$(dirname "$0")/../.." && pwd)DVM=${DVM:-$HOME/w/dvm}; KIT=${1:-$HOME/w/apple-kc-kit}[ -s "$DVM/out/k27/natives.txt" ] || { echo "$DVM/out/k27/natives.txt: run scripts/vm-xnu-rebuild.sh (with out/kc/kc27.bin) first" >&2; exit 1; }+[ -s "$DVM/out/kc/kc27.bin" ] || { echo "$DVM/out/kc/kc27.bin: the kernelcache the kit is for is not there (kit.json names its sha256)" >&2; exit 1; }mapfile -t lines < "$DVM/out/k27/natives.txt" # one kext description a line, paths whole (a file not read stops here)natives=(); for l in "${lines[@]}"; do [ -n "$l" ] && natives+=("$l"); done+# KIT is replaced whole: only a kit (or nothing) may be there, not a directory that holds something else+[ ! -e "$KIT" ] || [ -e "$KIT/kit.json" ] || { [ -d "$KIT" ] && [ -z "$(ls -A "$KIT")" ]; } ||+ { echo "$KIT: exists and is not a kit (no kit.json): not replacing it" >&2; exit 1; }rm -rf "$KIT"; mkdir -p "$KIT/kexts"cp "$DVM/out/k27/kernel-k27.macho" "$KIT/kernel.macho"[ -e /lib/firmware/xnu/kc-free.bin ] && cp /lib/firmware/xnu/kc-free.bin "$KIT/kc-free.bin"diff --git a/scripts/mk-puredarwin-disk.sh b/scripts/mk-puredarwin-disk.shindex 67d03ef..cd0a554 100755--- a/scripts/mk-puredarwin-disk.sh+++ b/scripts/mk-puredarwin-disk.sh@@ -1,7 +1,11 @@#!/bin/bash# SPDX-License-Identifier: GPL-2.0-only-# On the Mac: PureDarwin's root file system (scripts/puredarwin-root.sh) as the hosted system's disk, a GUID partition table+# On the Mac or on Linux: PureDarwin's root file system (scripts/puredarwin-root.sh) as the hosted system's disk, a GUID partition table# with one journaled HFS+ volume (hfs.kext, Apple's or the free collection's, mounts it), and the ROOT_UUID xnu.ko boots it by.+# On Linux (the machine that runs xnu.ko: no Mac is needed) the volume is mkfs.hfsplus's (hfsprogs; sgdisk from gdisk; the+# kernel's hfsplus module), with a journal as hdiutil's has: without one XNU refuses the root after the first run that+# ended without an unmount ("cannot mount dirty non-journaled volumes"), and a hosted system is stopped, never unmounted.+# Linux writes to a journaled volume only with -o force, which is safe on a new one: its journal is empty and stays so.# The kernel mounts the root read-only; PureDarwin's own images use ext4, whose kext clears that, and its mount(8) has no# -uw for launchctl's remount, so /sbin/fsck (which launchctl runs first, on a read-only root) remounts it read-write as# PureDarwin's HFS images do. The disk is checked on the Linux side before each boot (fsck.hfsplus), not here.@@ -11,10 +15,29 @@ set -euo pipefailROOT=$1 OUT=$2 SIZE=${3:-1g}M=$(mktemp -d); D="$OUT.dmg"rm -f "$D"-hdiutil create -quiet -size "$SIZE" -fs "Journaled HFS+" -volname PureDarwin -layout GPTSPUD "$D"-hdiutil attach -quiet -owners on -nobrowse -mountpoint "$M" "$D"-trap 'hdiutil detach -quiet "$M" 2>/dev/null || true' EXIT+if [ "$(uname -s)" = Linux ]; then+ uuid=$(tr a-z A-Z < /proc/sys/kernel/random/uuid)+ truncate -s "$(echo "$SIZE" | tr a-z A-Z)" "$D"+ sgdisk -o -n 1:2048:0 -t 1:af00 -c 1:PureDarwin -u 1:"$uuid" "$D" >/dev/null+ sudo modprobe hfsplus+ L=$(sudo losetup --show -fP "$D")+ trap 'sudo umount "$M" 2>/dev/null || true; sudo losetup -d "$L" 2>/dev/null || true' EXIT+ sudo mkfs.hfsplus -J -v PureDarwin "${L}p1" >/dev/null+ sudo mount -t hfsplus -o rw,force "${L}p1" "$M"+else+ hdiutil create -quiet -size "$SIZE" -fs "Journaled HFS+" -volname PureDarwin -layout GPTSPUD "$D"+ hdiutil attach -quiet -owners on -nobrowse -mountpoint "$M" "$D"+ trap 'hdiutil detach -quiet "$M" 2>/dev/null || true' EXIT+fisudo tar -xzf "$ROOT" -C "$M"+if [ "$(uname -s)" = Linux ]; then+ # Linux's hfsplus writes a hard link the old way, without the link chain macOS has kept since 10.5. XNU's hfs marks+ # such a file as having a chain when it first touches it, and from then on fsck finds the volume corrupt ("Incorrect+ # number of file hard links"). The root's few hard links (zsh and zsh-5.9.1) become files of their own here.+ sudo find "$M" -xdev -type f -links +1 -print0 | while IFS= read -r -d '' f; do+ sudo cp -p "$f" "$f.mkpd" && sudo mv -f "$f.mkpd" "$f"+ done+fisudo rm -rf "$M/.fseventsd" "$M/.Spotlight-V100"F=$(mktemp)cat > "$F" <<'FSCK'@@ -25,7 +48,11 @@ dev=$(/bin/df / | /bin/awk 'NR==2 {print $1}')exit 0FSCKsudo install -m 755 -o 0 -g 0 "$F" "$M/sbin/fsck"; rm -f "$F"-P=$(mktemp); diskutil info -plist "$M" > "$P"; uuid=$(plutil -extract DiskUUID raw "$P"); rm -f "$P"-sync; hdiutil detach -quiet "$M"; trap - EXIT; rmdir "$M"+if [ "$(uname -s)" = Linux ]; then+ sync; sudo umount "$M"; sudo losetup -d "$L"; trap - EXIT; rmdir "$M"+else+ P=$(mktemp); diskutil info -plist "$M" > "$P"; uuid=$(plutil -extract DiskUUID raw "$P"); rm -f "$P"+ sync; hdiutil detach -quiet "$M"; trap - EXIT; rmdir "$M"+fimv "$D" "$OUT"printf 'ROOT_UUID=%s\nBOOT_UUID=%s\n' "$uuid" "$uuid"diff --git a/tests/apple-kc/run.sh b/tests/apple-kc/run.shnew file mode 100755index 0000000..53f62d2--- /dev/null+++ b/tests/apple-kc/run.sh@@ -0,0 +1,58 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# scripts/apple-kc/package.sh and link.sh on stand-ins for what they read (macOS-DroidVM's tree, a kit, a kernelcache),+# with the linker replaced by one that only writes its output: what the two scripts do around the link. Run it on+# Linux, where package.sh is run (bash 4, sha256sum): tests/apple-kc/run.sh+set -u+command -v sha256sum >/dev/null && [ "${BASH_VERSINFO[0]}" -ge 4 ] || { echo "skipped: needs bash 4 and sha256sum (Linux)"; exit 0; }+POC=$(cd "$(dirname "$0")/../.." && pwd); T=$(mktemp -d); trap 'rm -rf "$T"' EXIT; fails=0+check() { local name=$1; shift; if "$@"; then echo "ok $name"; else echo "FAIL $name"; sed 's/^/ /' "$T/out"; fails=$((fails + 1)); fi; }++dvm() { # what package.sh reads of macOS-DroidVM's tree, in $T/w/dvm+ rm -rf "$T/w"; mkdir -p "$T/w/dvm/out/k27" "$T/w/dvm/out/kc" "$T/w/dvm/configs" "$T/w/dvm/obj" "$T/w/notes"+ echo kernel > "$T/w/dvm/out/k27/kernel-k27.macho"; echo kc > "$T/w/dvm/out/kc/kc27.bin"; echo obj > "$T/w/dvm/obj/K.o"+ echo '{"ipsw":{"url":"https://example.invalid/x.ipsw"}}' > "$T/w/dvm/configs/macos-27.2-26B123.json"+ echo "[\"$T/w/dvm/obj/K.o\"]" > "$T/w/dvm/obj/objects.json"; echo notes > "$T/w/notes/todo.txt"+ echo '{"name":"K","objects":"obj/objects.json"}' > "$T/w/dvm/K.json"; echo "$T/w/dvm/K.json" > "$T/w/dvm/out/k27/natives.txt"+}+package() { DVM=$T/w/dvm bash "$POC/scripts/apple-kc/package.sh" "$@" > "$T/out" 2>&1; }+sha_in() { python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["kernelcache_sha256"])' "$1/kit.json"; }++dvm+check "package.sh: a kit where there was nothing" package "$T/kit"+check "package.sh: kit.json names the kernelcache's sha256" [ "$(sha_in "$T/kit")" = "$(sha256sum "$T/w/dvm/out/kc/kc27.bin" | cut -d' ' -f1)" ]+touch "$T/kit/stale"+check "package.sh: a kit is replaced whole" eval 'package "$T/kit" && [ ! -e "$T/kit/stale" ] && [ -s "$T/kit/kernel.macho" ]'+mkdir "$T/empty"+check "package.sh: an empty directory becomes the kit" eval 'package "$T/empty" && [ -s "$T/empty/kit.json" ]'+check "package.sh: a directory that is not a kit is refused" eval '! package "$T/w"'+check "package.sh: ...and nothing in it is removed" eval '[ -s "$T/w/notes/todo.txt" ] && [ -s "$T/w/dvm/out/k27/kernel-k27.macho" ]'+dvm; echo precious > "$T/afile"+check "package.sh: a file is refused and kept" eval '! package "$T/afile" && [ "$(cat "$T/afile")" = precious ]'+dvm; rm "$T/w/dvm/out/kc/kc27.bin"+check "package.sh: no kernelcache, no kit" eval '! package "$T/kit2" && [ ! -e "$T/kit2" ]'+: > "$T/w/dvm/out/kc/kc27.bin"+check "package.sh: an empty kernelcache, no kit" eval '! package "$T/kit2" && [ ! -e "$T/kit2" ]'++# link.sh in a copy of the tree whose kclink.py writes its OUTPUT argument and whose kc-amfi-platform.py does nothing+mkdir -p "$T/poc/scripts/apple-kc" "$T/poc/scripts/kclink" "$T/lk/kit" "$T/bin"; cp "$POC/scripts/apple-kc/link.sh" "$T/poc/scripts/apple-kc/"+printf 'import sys\nopen(sys.argv[3], "w").write("NEW\\n"); print("wrote", sys.argv[3])\n' > "$T/poc/scripts/kclink/kclink.py"+: > "$T/poc/scripts/kc-amfi-platform.py"; : > "$T/lk/kit/kernel.macho"; printf '\xcf\xfa\xed\xfe a stand-in kernelcache\n' > "$T/lk/kc.macho"+printf '{"kernelcache_sha256":"%s","kernelcache":"a stand-in","ipsw":"https://example.invalid/x.ipsw","amfi_platform":26,"keep":["com.apple.a"],"rebind":["0x1=_x"],"native":["kexts/K/K.json"]}\n' \+ "$(sha256sum "$T/lk/kc.macho" | cut -d' ' -f1)" > "$T/lk/kit/kit.json"+link() { ( cd "$T/lk" && "$@" bash "$T/poc/scripts/apple-kc/link.sh" kit kc.macho out.bin ) > "$T/out" 2>&1; }+check "link.sh: links with its work directory in the kit" eval 'link env && [ -s "$T/lk/out.bin" ] && [ -s "$T/lk/kit/.work/kclink.log" ]'+rm -f "$T/lk/out.bin"+check "link.sh: a relative APPLE_KC_WORK" eval 'link env APPLE_KC_WORK=work && [ -s "$T/lk/out.bin" ] && [ -s "$T/lk/work/kclink.log" ]'++# the install into /lib/firmware/xnu, in a mount namespace of our own where that can be made (not everywhere: skipped then)+printf '#!/bin/sh\necho "sudo: a terminal is required to read the password" >&2; exit 1\n' > "$T/bin/sudo"; chmod +x "$T/bin/sudo"+inns() { unshare -rm sh -c 'mount -t tmpfs none /lib/firmware 2>/dev/null && mkdir /lib/firmware/xnu && echo OLD > /lib/firmware/xnu/kc-apple.bin && '"$1" 2>/dev/null; }+if inns true; then+ export T+ check "link.sh: a failed install is a failed link.sh" eval '! inns "cd $T/lk && PATH=$T/bin:\$PATH bash $T/poc/scripts/apple-kc/link.sh kit kc.macho > $T/out 2>&1"'+ check "link.sh: ...and it does not say 'boot it'" eval '! grep -q "boot it" "$T/out"'+else+ echo "skip link.sh: a failed install (no unprivileged mount namespace here to stand in for /lib/firmware/xnu)"+fi+[ $fails = 0 ] && echo "apple-kc tests: pass" || { echo "apple-kc tests: $fails failed"; exit 1; }diff --git a/tests/apple-kc/test_im4p.py b/tests/apple-kc/test_im4p.pynew file mode 100644index 0000000..92a8a16--- /dev/null+++ b/tests/apple-kc/test_im4p.py@@ -0,0 +1,256 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""scripts/apple-kc/im4p.py on kernelcaches made here (nothing of Apple's): every input it takes unpacks to the kernel+that went in (a Mach-O, an IM4P that is plain, LZSS or LZFSE, the IMG4 around one, an IPSW, an IPSW's URL read with range+requests), and a file that is cut short or does not unpack to what it says is refused with OUTPUT not written.++ python3 tests/apple-kc/test_im4p.py [-v]++The LZFSE round trip needs the lzfse tool (it packs the test's kernel too) and is skipped without it, unless+IM4P_TEST_NEED_LZFSE is set (CI), where a missing tool fails the test.+"""+import http.server+import os+import shutil+import struct+import subprocess+import sys+import tempfile+import threading+import unittest+import zipfile+import zlib+from pathlib import Path++IM4P = Path(__file__).resolve().parents[2] / 'scripts/apple-kc/im4p.py'+MACHO = b'\xcf\xfa\xed\xfe'+SMALL = MACHO + bytes(range(256)) * 60 + b'xnulinux ' * 3000 + bytes(4000) # 46 KB: literals, matches, a long run+BIG = MACHO + bytes((i * 7 + (i >> 8)) & 0xff for i in range(400000)) # more than one of Remote's cache blocks+++def tlv(tag, body):+ n = len(body)+ if n < 0x80:+ return bytes([tag, n]) + body+ b = n.to_bytes((n.bit_length() + 7) // 8, 'big')+ return bytes([tag, 0x80 | len(b)]) + b + body+++def integer(v):+ return tlv(0x02, v.to_bytes(v.bit_length() // 8 + 1, 'big'))+++def im4p(payload, size=None):+ """SEQUENCE { "IM4P", type, description, OCTET STRING payload [, SEQUENCE { INTEGER 1, INTEGER unpacked size }] }"""+ record = tlv(0x30, integer(1) + integer(size)) if size is not None else b''+ return tlv(0x30, tlv(0x16, b'IM4P') + tlv(0x16, b'krnl') + tlv(0x16, b'a test kernelcache') + tlv(0x04, payload) + record)+++def img4(inner):+ """SEQUENCE { "IMG4", IM4P, [0] manifest }: the kernelcache file of an installed macOS"""+ return tlv(0x30, tlv(0x16, b'IMG4') + inner + tlv(0xa0, tlv(0x30, tlv(0x16, b'IM4M') + bytes(300))))+++def lzss_pack(data):+ """Apple's kernelcache LZSS (4096-byte ring written from 4078 on, matches of 3 to 18 bytes), with its header."""+ out, i, last = bytearray(), 0, {}+ while i < len(data):+ flags, group = 0, bytearray()+ for bit in range(8):+ if i >= len(data):+ break+ j, n = last.get(data[i:i + 3], -1), 0+ if j >= 0 and i - j <= 4000:+ while n < 18 and i + n < len(data) and data[j + n] == data[i + n]:+ n += 1+ if n >= 3:+ at = (4078 + j) & 4095+ group += bytes([at & 0xff, ((at >> 4) & 0xf0) | (n - 3)])+ else:+ n = 1+ flags |= 1 << bit+ group.append(data[i])+ for k in range(i, i + n):+ last[data[k:k + 3]] = k+ i += n+ out.append(flags)+ out += group+ return b'complzss' + struct.pack('>III', zlib.adler32(data), len(data), len(out)) + bytes(0x180 - 20) + bytes(out)+++class Ranges(http.server.BaseHTTPRequestHandler):+ """One file, with byte ranges. server.mode: 'cut' breaks the first transfer of more than 64 KiB off halfway,+ 'whole' ignores Range (200 and the whole file)."""++ def log_message(self, *args):+ pass++ def do_HEAD(self):+ self.send_response(200)+ self.send_header('Content-Length', str(len(self.server.blob)))+ self.end_headers()++ def do_GET(self):+ try:+ self.answer()+ except (BrokenPipeError, ConnectionResetError): # the client had enough (a 200 where it asked for a range)+ pass++ def answer(self):+ blob, rng = self.server.blob, self.headers.get('Range')+ if rng is None or self.server.mode == 'whole':+ self.send_response(200)+ self.send_header('Content-Length', str(len(blob)))+ self.end_headers()+ self.wfile.write(blob)+ return+ a, b = (int(x) for x in rng.split('=')[1].split('-'))+ piece = blob[a:b + 1]+ self.send_response(206)+ self.send_header('Content-Range', f'bytes {a}-{b}/{len(blob)}')+ self.send_header('Content-Length', str(len(piece)))+ self.end_headers()+ if self.server.mode == 'cut' and len(piece) > 1 << 16:+ self.server.mode = None+ piece = piece[:len(piece) // 2]+ self.server.served += len(piece)+ self.wfile.write(piece)+++class Im4p(unittest.TestCase):+ def setUp(self):+ self.dir = tempfile.TemporaryDirectory()+ self.d = Path(self.dir.name)+ self.out = self.d / 'out' / 'kernelcache'+ self.out.parent.mkdir()+ self.env = {k: v for k, v in os.environ.items() if not k.lower().endswith('_proxy')}++ def tearDown(self):+ self.dir.cleanup()++ def run_im4p(self, src, *more, path=None):+ env = dict(self.env, PATH=f'{path}{os.pathsep}{self.env["PATH"]}') if path else self.env+ return subprocess.run([sys.executable, str(IM4P), str(src), str(self.out), *more], capture_output=True, text=True, env=env)++ def file(self, name, blob):+ (self.d / name).write_bytes(blob)+ return self.d / name++ def unpacks(self, src, kernel, *more, path=None):+ p = self.run_im4p(src, *more, path=path)+ self.assertEqual(p.returncode, 0, p.stderr)+ self.assertEqual(self.out.read_bytes(), kernel)++ def refused(self, src, why, *more, path=None):+ self.out.unlink(missing_ok=True)+ p = self.run_im4p(src, *more, path=path)+ self.assertNotEqual(p.returncode, 0)+ self.assertIn(why, p.stderr)+ self.assertNotIn('Traceback', p.stderr)+ self.assertEqual(os.listdir(self.out.parent), [], 'nothing is written (and nothing left) beside OUTPUT')++ def test_what_it_takes(self):+ for name, blob in (('macho', SMALL), ('plain.im4p', im4p(SMALL)), ('lzss.im4p', im4p(lzss_pack(SMALL))),+ ('plain.img4', img4(im4p(SMALL))), ('lzss.img4', img4(im4p(lzss_pack(SMALL))))):+ with self.subTest(name):+ self.unpacks(self.file(name, blob), SMALL)++ def test_lzss_has_matches(self):+ self.assertLess(len(lzss_pack(SMALL)), len(SMALL) // 2) # the round trip above went through the match path++ def test_ipsw(self):+ ipsw = self.d / 'test.ipsw'+ with zipfile.ZipFile(ipsw, 'w') as z:+ z.writestr('kernelcache.release.vma2', im4p(lzss_pack(SMALL)))+ z.writestr('other/kernelcache', im4p(SMALL[:5000]))+ self.unpacks(ipsw, SMALL)+ self.unpacks(ipsw, SMALL[:5000], 'other/kernelcache')++ def test_cut_short(self):+ for name, blob in (('plain', im4p(SMALL)), ('lzss', im4p(lzss_pack(SMALL))), ('img4', img4(im4p(SMALL)))):+ for keep in (1, 3, 40, len(blob) // 2, len(blob) - 1):+ with self.subTest(name, keep=keep):+ self.refused(self.file('cut.im4p', blob[:keep]), 'cut short')++ def test_lzss_stream_ends_early(self):+ packed = lzss_pack(SMALL)+ self.refused(self.file('early.im4p', im4p(packed[:len(packed) // 2])), 'its LZSS header says')+ self.refused(self.file('header.im4p', im4p(packed[:0x100])), 'cut short')++ def test_not_a_kernelcache(self):+ self.refused(self.file('empty', b''), 'cut short')+ self.refused(self.file('text', b'<html>503 Service Unavailable</html>\n' * 4), 'not an IM4P')+ self.refused(self.file('other.im4p', im4p(b'not a Mach-O at all, whatever it is')), 'not a kernelcache')+ self.refused(self.file('lzss-other.im4p', im4p(lzss_pack(b'packed, and still not a Mach-O' * 9))), 'not a kernelcache')++ def fake_lzfse(self, script):+ """A directory with an `lzfse` that does what the script says with its -i and -o arguments."""+ tool = self.d / 'bin' / 'lzfse'+ tool.parent.mkdir(exist_ok=True)+ tool.write_text(f'#!{sys.executable}\nimport sys\na = sys.argv\nsrc, dst = a[a.index("-i") + 1], a[a.index("-o") + 1]\n{script}\n')+ tool.chmod(0o755)+ return tool.parent++ def test_lzfse_result_is_checked(self):+ body = b'bvx2' + SMALL # what the stand-in tools "decode": everything after the magic+ whole = self.fake_lzfse('open(dst, "wb").write(open(src, "rb").read()[4:])')+ self.unpacks(self.file('ok.im4p', im4p(body, len(SMALL))), SMALL, path=whole)+ self.unpacks(self.file('nosize.im4p', im4p(body)), SMALL, path=whole)+ self.unpacks(self.file('ok.img4', img4(im4p(body, len(SMALL)))), SMALL, path=whole)+ self.refused(self.file('size.im4p', im4p(body, len(SMALL) + 512)), 'the IM4P says', path=whole)+ self.refused(self.file('other.im4p', im4p(b'bvx2' + b'no Mach-O in here' * 40)), 'does not unpack to a Mach-O', path=whole)+ short = self.fake_lzfse('open(dst, "wb").write(open(src, "rb").read()[4:1000])')+ self.refused(self.file('short.im4p', im4p(body, len(SMALL))), 'the IM4P says', path=short)+ failing = self.fake_lzfse('open(dst, "wb").write(b"half"); sys.exit(1)')+ self.refused(self.file('fail.im4p', im4p(body, len(SMALL))), 'could not decode', path=failing)++ def test_lzfse(self):+ lz = shutil.which('lzfse')+ if not lz:+ if os.environ.get('IM4P_TEST_NEED_LZFSE'):+ self.fail('no lzfse tool')+ self.skipTest('no lzfse tool')+ plain, packed = self.file('kernel', BIG), self.d / 'kernel.lzfse'+ subprocess.run([lz, '-encode', '-i', str(plain), '-o', str(packed)], check=True)+ body = packed.read_bytes()+ self.assertEqual(body[:4], b'bvx2')+ self.unpacks(self.file('lzfse.im4p', im4p(body, len(BIG))), BIG)+ self.unpacks(self.file('lzfse.img4', img4(im4p(body, len(BIG)))), BIG)+ self.refused(self.file('cut.im4p', im4p(body, len(BIG))[:len(body) // 2]), 'cut short')+ self.refused(self.file('early.im4p', im4p(body[:len(body) // 2], len(BIG))), 'damaged?') # DER whole, stream not++ def serve(self, blob, mode=None):+ server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Ranges)+ server.blob, server.mode, server.served = blob, mode, 0+ threading.Thread(target=server.serve_forever, daemon=True).start()+ self.addCleanup(server.server_close)+ self.addCleanup(server.shutdown)+ return server, f'http://127.0.0.1:{server.server_address[1]}/test.ipsw'++ def ipsw(self):+ path = self.d / 'big.ipsw'+ with zipfile.ZipFile(path, 'w', zipfile.ZIP_STORED) as z:+ z.writestr('BuildManifest.plist', b'<plist/>')+ z.writestr('disk.dmg', bytes(3 << 20))+ z.writestr('kernelcache.release.vma2', im4p(BIG))+ z.writestr('more.dmg', bytes(1 << 20))+ return path.read_bytes()++ def test_url_reads_only_the_member(self):+ blob = self.ipsw()+ server, url = self.serve(blob)+ self.unpacks(url, BIG)+ self.assertLess(server.served, len(BIG) + (1 << 20), f'{server.served} of {len(blob)} bytes were downloaded')++ def test_url_transfer_that_breaks_off_is_asked_again(self):+ server, url = self.serve(self.ipsw(), 'cut')+ self.unpacks(url, BIG)+ self.assertIsNone(server.mode, 'a transfer was cut')++ def test_url_without_ranges(self):+ _, url = self.serve(self.ipsw(), 'whole')+ self.refused(url, 'byte ranges')+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/puredarwin-disk/check.py b/tests/puredarwin-disk/check.pynew file mode 100755index 0000000..aa5419a--- /dev/null+++ b/tests/puredarwin-disk/check.py@@ -0,0 +1,197 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""The disk scripts/mk-puredarwin-disk.sh makes, looked at from outside (tests/puredarwin-disk/run.sh).++ check.py --make-root ROOT.tar.gz a small root file system as a tarball (no root needed: the members' owners+ and modes are written into the archive)+ check.py IMG CONF ROOT.tar.gz MOUNT IMG is the disk, CONF what the script printed, MOUNT the volume mounted+ read-only with owners (run as root)++The second form checks what the hosted kernel depends on: the GUID partition table has one Apple HFS+ partition whose+unique GUID is CONF's ROOT_UUID and BOOT_UUID (xnu.ko finds the root by it); the volume is HFS+ with a journal that has+nothing to replay, and was unmounted cleanly (XNU refuses a dirty volume without a journal for good, and would replay+a journal that still holds transactions over what the host wrote); every member of the tarball is on the volume+with its type, mode, owner, group, size, content and link target, a hard link as one file with its target on a Mac+and as a file of its own on Linux; /sbin/fsck is the script's own.+"""+import hashlib+import io+import os+import stat+import struct+import sys+import tarfile+import uuid++HFS_PLUS = uuid.UUID('48465300-0000-11AA-AA11-00306543ECAC')+OWN = {'.journal', '.journal_info_block'} # the journal's two files (Linux shows them, a Mac hides them)+# Linux's hfsplus writes a hard link without the link chain macOS has kept since 10.5; XNU's hfs then marks the file as+# having one, and fsck finds the volume corrupt after the first boot. The script stores such files as copies there.+LINUX = sys.platform == 'linux'+++def make_root(out):+ blob = bytes((i * 7 + (i >> 8)) & 0xff for i in range(1 << 20))+ members = [ # name, type, mode, uid, gid, content or link target+ ('.', 'd', 0o755, 0, 0, None),+ ('./sbin', 'd', 0o755, 0, 0, None),+ ('./bin', 'd', 0o755, 0, 0, None),+ ('./bin/tool', 'f', 0o755, 0, 0, b'#!/bin/sh\necho tool\n'),+ ('./bin/also-tool', 'h', 0o755, 0, 0, './bin/tool'),+ ('./bin/sh', 'l', 0o755, 0, 0, 'tool'),+ ('./usr', 'd', 0o755, 0, 0, None),+ ('./usr/bin', 'd', 0o755, 0, 0, None),+ ('./usr/bin/su', 'f', 0o4755, 0, 0, b'setuid\n'),+ ('./etc', 'd', 0o755, 0, 0, None),+ ('./etc/master.passwd', 'f', 0o600, 0, 0, b'root:*:0:0::0:0:System Administrator:/var/root:/bin/sh\n'),+ ('./private', 'd', 0o755, 0, 0, None),+ ('./private/tmp', 'd', 0o1777, 0, 0, None),+ ('./tmp', 'l', 0o755, 0, 0, 'private/tmp'),+ ('./Users', 'd', 0o755, 0, 80, None),+ ('./Users/someone', 'd', 0o700, 501, 20, None),+ ('./Users/someone/notes.txt', 'f', 0o644, 501, 20, b'owned by 501:20\n'),+ ('./Users/someone/megabyte.bin', 'f', 0o640, 501, 20, blob),+ ('./Users/someone/empty', 'f', 0o644, 501, 20, b''),+ ('./var', 'd', 0o755, 0, 0, None),+ ('./var/empty', 'd', 0o555, 0, 3, None),+ ('./var/daemon-owned', 'f', 0o644, 1, 1, b'uid 1, gid 1\n'),+ ]+ with tarfile.open(out, 'w:gz', format=tarfile.GNU_FORMAT) as tar:+ for name, kind, mode, uid, gid, data in members:+ m = tarfile.TarInfo(name)+ m.mode, m.uid, m.gid, m.mtime = mode, uid, gid, 1700000000+ m.type = {'d': tarfile.DIRTYPE, 'f': tarfile.REGTYPE, 'l': tarfile.SYMTYPE, 'h': tarfile.LNKTYPE}[kind]+ if kind in 'lh':+ m.linkname = data+ if kind == 'f':+ m.size = len(data)+ tar.addfile(m, io.BytesIO(data) if kind == 'f' else None)+ print(f'{out}: {len(members)} members')+++def partition(img, conf):+ """The one Apple HFS+ partition of the GUID partition table: its first byte. Its GUID must be CONF's."""+ with open(img, 'rb') as f:+ f.seek(512)+ head = f.read(92)+ if head[:8] != b'EFI PART':+ sys.exit(f'{img}: no GUID partition table')+ lba, count, size = struct.unpack('<QII', head[72:88])+ f.seek(lba * 512)+ entries = [f.read(size) for _ in range(count)]+ hfs = [e for e in entries if uuid.UUID(bytes_le=e[:16]) == HFS_PLUS]+ if len(hfs) != 1:+ sys.exit(f'{img}: {len(hfs)} Apple HFS+ partitions, expected 1')+ guid = str(uuid.UUID(bytes_le=hfs[0][16:32])).upper()+ want = dict(line.split('=', 1) for line in open(conf).read().split())+ if set(want) != {'ROOT_UUID', 'BOOT_UUID'} or want['ROOT_UUID'] != guid or want['BOOT_UUID'] != guid:+ sys.exit(f"the partition's GUID is {guid}, the script printed {want}")+ print(f'partition: Apple HFS+, GUID {guid} = ROOT_UUID = BOOT_UUID')+ return struct.unpack('<Q', hfs[0][32:40])[0] * 512+++def volume(img, start):+ with open(img, 'rb') as f:+ f.seek(start + 1024)+ head = f.read(512)+ sig, _, attr = struct.unpack('>2sHI', head[:8])+ info_block, = struct.unpack('>I', head[12:16])+ block_size, = struct.unpack('>I', head[40:44])+ if sig != b'H+':+ sys.exit(f'the volume is not HFS+ (signature {sig!r})')+ if not attr & 0x2000 or not info_block:+ sys.exit(f'the volume has no journal (attributes {attr:#x}): XNU refuses it for good after the first '+ 'run that ends without an unmount')+ if not attr & 0x100 or attr & 0x800:+ sys.exit(f'the volume was not unmounted cleanly, or is marked inconsistent (attributes {attr:#x})')+ f.seek(start + info_block * block_size)+ flags, = struct.unpack('>I', f.read(4))+ f.seek(start + info_block * block_size + 36)+ offset, jsize = struct.unpack('>QQ', f.read(16))+ if flags & 4: # kJIJournalNeedInitMask: the first mount writes the journal's header+ state = 'to be initialised by the first mount'+ else:+ f.seek(start + offset)+ j = f.read(32)+ order = '<' if j[:4] == b'xLNJ' else '>'+ if j[:4] not in (b'xLNJ', b'JNLx'):+ sys.exit(f'the journal has no header (magic {j[:4]!r}) and is not marked for initialisation')+ first, last = struct.unpack(order + 'QQ', j[8:24])+ if first != last:+ sys.exit(f'the journal still holds transactions ({first:#x} to {last:#x}): XNU would replay them '+ 'over the files written since')+ state = 'empty'+ print(f'volume: HFS+, journal of {jsize >> 10} kB {state}, unmounted cleanly (attributes {attr:#x})')+++def tree(root_tar, mount):+ tar = tarfile.open(root_tar)+ names, inode, bad, n = set(), {}, 0, 0+ for m in tar:+ name = m.name[2:] if m.name.startswith('./') else m.name+ if name in ('', '.'):+ continue+ names.add(name)+ if name == 'sbin/fsck':+ continue+ n += 1+ p = os.path.join(mount, name)+ try:+ st = os.lstat(p)+ except OSError as e:+ bad += 1+ print('missing:', name, e.strerror)+ continue+ want = [stat.S_IMODE(m.mode), m.uid, m.gid]+ have = [stat.S_IMODE(st.st_mode), st.st_uid, st.st_gid]+ if m.issym(): # a link's own mode is the file system's business+ kind = stat.S_ISLNK(st.st_mode)+ want, have = want[1:] + [m.linkname], have[1:] + [os.readlink(p) if kind else None]+ elif m.isdir():+ kind = stat.S_ISDIR(st.st_mode)+ elif m.islnk(): # a hard link: one file with its target on a Mac, a file of its own on Linux (LINKED)+ kind = stat.S_ISREG(st.st_mode)+ target = m.linkname[2:] if m.linkname.startswith('./') else m.linkname+ data = tar.extractfile(tar.getmember(m.linkname)).read()+ want += [len(data), hashlib.sha256(data).hexdigest(), None if LINUX else inode.get(target)]+ have += [st.st_size, hashlib.sha256(open(p, 'rb').read()).hexdigest() if kind else None, None if LINUX else st.st_ino]+ else:+ kind = stat.S_ISREG(st.st_mode)+ inode[name] = st.st_ino+ want += [m.size, hashlib.sha256(tar.extractfile(m).read()).hexdigest()]+ have += [st.st_size, hashlib.sha256(open(p, 'rb').read()).hexdigest() if kind else None]+ if not kind or want != have:+ bad += 1+ print('differs:', name, 'want', want, 'have', have)+ extra, linked = [], []+ for d, dirs, files in os.walk(mount):+ for f in dirs + files:+ rel = os.path.relpath(os.path.join(d, f), mount)+ if rel not in names and rel not in OWN and rel != 'sbin/fsck':+ extra.append(rel)+ st = os.lstat(os.path.join(d, f))+ if LINUX and stat.S_ISREG(st.st_mode) and st.st_nlink > 1:+ linked.append(rel)+ if linked:+ bad += 1+ print('hard links written by Linux (no link chain: fsck fails after the first boot):', sorted(linked))+ if extra:+ bad += 1+ print('on the disk and not in the tarball:', sorted(extra))+ fsck = os.path.join(mount, 'sbin/fsck')+ st = os.lstat(fsck) if os.path.lexists(fsck) else None+ if not st or not stat.S_ISREG(st.st_mode) or [stat.S_IMODE(st.st_mode), st.st_uid, st.st_gid] != [0o755, 0, 0] \+ or '-o update,rw' not in open(fsck).read():+ bad += 1+ print('/sbin/fsck is not the remount script, 0755 and root:wheel:',+ [oct(st.st_mode), st.st_uid, st.st_gid] if st else 'it is not there')+ print(f'tree: {n} members compared, {bad} wrong')+ return bad+++if sys.argv[1] == '--make-root':+ make_root(sys.argv[2])+else:+ img, conf, root_tar, mount = sys.argv[1:5]+ volume(img, partition(img, conf))+ sys.exit(1 if tree(root_tar, mount) else 0)diff --git a/tests/puredarwin-disk/run.sh b/tests/puredarwin-disk/run.shnew file mode 100755index 0000000..4608399--- /dev/null+++ b/tests/puredarwin-disk/run.sh@@ -0,0 +1,27 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# scripts/mk-puredarwin-disk.sh on this host, Linux or a Mac: a disk from a small root file system made here, then the+# disk looked at from outside (check.py: the partition and its GUID against what the script printed, the HFS+ volume+# and its journal, every file with its owner, mode and content). Like the script it needs sudo; on Linux hfsprogs,+# gdisk and the kernel's hfsplus module, which it must be able to load: a host without them fails, it does not skip.+# tests/puredarwin-disk/run.sh [SCRIPT] (SCRIPT: another copy of mk-puredarwin-disk.sh to try)+set -euo pipefail+HERE=$(cd "$(dirname "$0")" && pwd)+SCRIPT=${1:-$HERE/../../scripts/mk-puredarwin-disk.sh}+W=$(mktemp -d); M="$W/mnt"; mkdir "$M"+trap 'rm -rf "$W"' EXIT+python3 "$HERE/check.py" --make-root "$W/root.tar.gz"+bash "$SCRIPT" "$W/root.tar.gz" "$W/pd.img" 64m > "$W/pd.conf"+cat "$W/pd.conf"+[ ! -e "$W/pd.img.dmg" ] || { echo "the script left its work file $W/pd.img.dmg"; exit 1; }+if [ "$(uname -s)" = Linux ]; then+ L=$(sudo losetup --show -fP -r "$W/pd.img")+ trap 'sudo umount "$M" 2>/dev/null || true; sudo losetup -d "$L" 2>/dev/null || true; rm -rf "$W"' EXIT+ sudo fsck.hfsplus -fn "${L}p1"+ sudo mount -t hfsplus -o ro "${L}p1" "$M"+else+ trap 'sudo hdiutil detach -quiet "$M" 2>/dev/null || true; rm -rf "$W"' EXIT+ sudo hdiutil attach -quiet -readonly -owners on -nobrowse -imagekey diskimage-class=CRawDiskImage -mountpoint "$M" "$W/pd.img"+fi+sudo python3 "$HERE/check.py" "$W/pd.img" "$W/pd.conf" "$W/root.tar.gz" "$M"+echo "mk-puredarwin-disk.sh on $(uname -s): ok"