Skip to content

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

C

Boot macOS 27.2.1 from a disk installed by Apple's own installer: launchd, all volumes, the keystore

Heyang Zhou0812f3222785
diff --git a/kexts/XnuEAN/XnuEAN.cpp b/kexts/XnuEAN/XnuEAN.cpp
index c5260b0..01feea0 100644
--- a/kexts/XnuEAN/XnuEAN.cpp
+++ b/kexts/XnuEAN/XnuEAN.cpp
@@ -15,6 +15,7 @@
#include <IOKit/IOLib.h>
#include <IOKit/IOLocks.h>
#include <IOKit/IOService.h>
+#include <kern/thread.h>
#include <libkern/OSByteOrder.h>
#include <ptrauth.h>
@@ -29,6 +30,8 @@ extern "C" void appleEanGetSize(void) __asm("__ZN12AppleNVMeEAN10eanGetSizeEj");
extern "C" void appleEanRead(void) __asm("__ZN12AppleNVMeEAN7eanReadEjPvj");
extern "C" void appleEanWrite(void) __asm("__ZN12AppleNVMeEAN8eanWriteEjPvj");
extern "C" void appleEanSwap(void) __asm("__ZN12AppleNVMeEAN7eanSwapEjj");
+// AppleVirtualPlatform's sealed registers (non-virtual; AppleVPKeyStore calls it on the instance it waits for at late init)
+extern "C" void appleSealedRegisterUpdate(void) __asm("__ZN35AppleVirtualPlatformSealedRegisters20sealedRegisterUpdateEPKhyS1_m");
namespace {
constexpr uint32_t kMagic = 'XEAN', kMaxEntries = 16, kMaxBlob = 64 * 1024, kStoreMax = 1024 * 1024;
@@ -162,10 +165,19 @@ extern "C" IOReturn xnu_ean_swap(void *, uint32_t a, uint32_t b)
return kIOReturnSuccess;
}
+// AppleVirtualPlatformSealedRegisters::sealedRegisterUpdate(const uint8_t *uuid, uint64_t, const uint8_t *bytes, size_t):
+// on a VirtualMac it passes the value to the host (Virtualization.framework) to fold into a register the VM cannot read
+// back; the hosted system has no such host side and nothing reads the registers, so an update is accepted as made.
+extern "C" uint32_t xnu_sealed_register_update(void *, const uint8_t *, uint64_t, const uint8_t *, size_t length)
+{
+ return length <= 512;
+}
+
class XnuEAN : public IOService {
OSDeclareDefaultStructors(XnuEAN)
- IOService *fEan = nullptr;
+ IOService *fEan = nullptr, *fSealed = nullptr;
static bool redirect(void (*from)(void), const void *to, const char *what);
+ static void publishSealedRegisters(void *self, wait_result_t);
public:
bool start(IOService *provider) override;
@@ -215,11 +227,43 @@ bool XnuEAN::start(IOService *provider)
return false;
}
fEan->registerService();
+ // the virtual platform's sealed registers, which AppleVPKeyStore's late init waits for forever (holding the keystore's
+ // gate, so every AppleKeyStore open blocks behind it). Published only once AppleKeyStore itself is: present while the
+ // keystore starts, the instance (never started) sends its start down another path that never publishes the service.
+ if (redirect(appleSealedRegisterUpdate, (const void *)&xnu_sealed_register_update, "sealedRegisterUpdate")) {
+ thread_t thread;
+ retain();
+ if (kernel_thread_start(&XnuEAN::publishSealedRegisters, this, &thread) == KERN_SUCCESS)
+ thread_deallocate(thread);
+ else
+ release();
+ }
registerService();
IOLog("XnuEAN: AppleNVMeEAN registered; its EAN calls go to the hosted store\n");
return true;
}
+void XnuEAN::publishSealedRegisters(void *arg, wait_result_t)
+{
+ XnuEAN *self = (XnuEAN *)arg;
+ OSDictionary *match = IOService::serviceMatching("AppleKeyStore");
+ IOService *aks = match ? IOService::waitForMatchingService(match) : nullptr;
+ OSSafeReleaseNULL(match);
+ OSSafeReleaseNULL(aks);
+ OSObject *sealed = OSMetaClass::allocClassWithName("AppleVirtualPlatformSealedRegisters");
+ self->fSealed = OSDynamicCast(IOService, sealed);
+ if (self->fSealed && self->fSealed->init(nullptr) && self->fSealed->attach(self)) {
+ self->fSealed->registerService();
+ IOLog("XnuEAN: AppleVirtualPlatformSealedRegisters registered (after AppleKeyStore)\n");
+ } else {
+ IOLog("XnuEAN: cannot make an AppleVirtualPlatformSealedRegisters (%p)\n", sealed);
+ OSSafeReleaseNULL(sealed);
+ self->fSealed = nullptr;
+ }
+ self->release();
+ thread_terminate(current_thread());
+}
+
// Module start/stop for the collection's kext entry; the driver starts through IOKit matching.
#include <mach/kmod.h>
extern "C" {
diff --git a/kexts/XnuEAN/XnuEAN.json b/kexts/XnuEAN/XnuEAN.json
index 1322aac..43de259 100644
--- a/kexts/XnuEAN/XnuEAN.json
+++ b/kexts/XnuEAN/XnuEAN.json
@@ -7,6 +7,7 @@
"stop": "_native_kext_stop",
"libraries": {
"com.apple.iokit.AppleVirtIOStorage": "1.0.0",
+ "com.apple.driver.AppleVirtualPlatform": "1.0.0",
"com.apple.kpi.bsd": "18.0.0",
"com.apple.kpi.iokit": "18.0.0",
"com.apple.kpi.libkern": "18.0.0",
diff --git a/scripts/extract-trustcache.py b/scripts/extract-trustcache.py
index e8c7629..d8a40fb 100755
--- a/scripts/extract-trustcache.py
+++ b/scripts/extract-trustcache.py
@@ -1,14 +1,16 @@
#!/usr/bin/env python3
"""Write the raw static trust cache module of this Mac's OS (the payload of StaticTrustCache.img4) to OUT.
- extract-trustcache.py OUT
+ extract-trustcache.py OUT [PREBOOT]
-Run on the Mac whose OS the hosted system disk was made from. The output is Apple data: it stays local (the VM's
+Run on the Mac whose OS the hosted system disk was made from, or give the mounted Preboot volume of that disk (an
+installed macOS VM disk, scripts/mk-macvm-disk.sh). The output is Apple data: it stays local (the VM's
/lib/firmware/xnu/trustcache.bin, passed to xnu.ko as trustcache=), never in the repository.
"""
import glob, struct, sys
-paths = glob.glob('/System/Volumes/Preboot/*/boot/*/usr/standalone/firmware/FUD/StaticTrustCache.img4')
+preboot = sys.argv[2] if len(sys.argv) > 2 else '/System/Volumes/Preboot'
+paths = glob.glob(preboot + '/*/boot/*/usr/standalone/firmware/FUD/StaticTrustCache.img4')
if len(paths) != 1:
sys.exit(f'expected one StaticTrustCache.img4, found {paths}')
d = open(paths[0], 'rb').read()
diff --git a/scripts/mk-macvm-disk.sh b/scripts/mk-macvm-disk.sh
new file mode 100755
index 0000000..c579f00
--- /dev/null
+++ b/scripts/mk-macvm-disk.sh
@@ -0,0 +1,88 @@
+#!/bin/bash
+# On the macOS host (tokyo): the hosted system's disk from a macOS VM disk installed by Apple's own installer, then sent to
+# the xnupoc VM as /var/tmp/mac.img (xnu.ko disk=, kexts/XnuDisk; boot-arg rd=<its system volume>).
+#
+# `tart create NAME --from-ipsw latest` installs macOS with Virtualization.framework, as Apple's own VMs are installed: the
+# whole Apple Silicon layout (iBootSystemContainer with xART and Hardware, the main container with the System and Data
+# volume group and Preboot with the cryptexes, the Recovery container). The sealed System volume stays as installed; what the
+# hosted system needs is added to the Data volume only:
+# - the local user, automatic login, Setup Assistant done (tools/hosted/gui-user.py)
+# - the CPU Metal plugin in /Library/GPUBundles (the GPU line's dist/XnuCpuMetal.bundle)
+# - a root shell on /dev/console (xnulinux.shell), the hosted system's console
+# - launchd's disabled list for daemons of hardware the hosted system has not (watchdog, audio, ...) and Rosetta's
+# and the static trust cache of that macOS build, for xnu.ko trustcache=. Apple's files stay on this host and in the VM.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+V="bash scripts/vm.sh"
+SRC=${SRC:-$HOME/.tart/vms/xnumac/disk.img}; W=${W:-$PWD/../macvm}; IMG=$W/mac.img
+GPU=${GPU:-/Users/admin/.stillfail/sessions/chat/c-73ef26e7b6/workspace/src/xnulinux/gpu/xnu-cpu-metal/dist/XnuCpuMetal.bundle}
+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 ${DISABLE:-}"
+# images of ours left attached by an earlier run
+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
+ 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
+DEV=$(hdiutil attach -imagekey diskimage-class=CRawDiskImage -nomount "$IMG" 2>/dev/null | awk '/GUID_partition_scheme/{print $1}')
+sleep 3 # the containers' synthesized disks appear after the attach returns
+cleanup() { for m in "$W/data" "$W/sys" "$W/preboot"; do diskutil unmount force "$m" >/dev/null 2>&1 || true; done; hdiutil detach "$DEV" -force >/dev/null 2>&1 || true; }
+trap cleanup EXIT
+vol() { # the APFS volume named $1 in the main container of this image (the names the installer gives)
+ for v in $(diskutil list | awk '/APFS Volume/ {print $NF}'); do
+ diskutil info "$v" | grep -q "APFS Physical Store: *$(basename "$DEV")s2$" || continue
+ diskutil info "$v" | grep -q "Volume Name: *$1$" && { echo "$v"; return; }
+ done
+}
+DATA=$(vol Data); SYS=$(vol "Macintosh HD"); PRE=$(vol Preboot)
+echo "image on $DEV: system $SYS, data $DATA, preboot $PRE"
+mkdir -p "$W/data" "$W/sys" "$W/preboot"
+diskutil mount -mountPoint "$W/data" "$DATA" >/dev/null; sudo -n diskutil enableOwnership "$W/data" >/dev/null
+diskutil mount readOnly -mountPoint "$W/sys" "$SYS" >/dev/null
+diskutil mount -mountPoint "$W/preboot" "$PRE" >/dev/null; sudo -n diskutil enableOwnership "$W/preboot" >/dev/null
+D=$W/data
+# The system keybag the installer and the first boot made is sealed to the keys of the VM it ran in (Apple's virtual
+# platform keystore, xART in that VM's auxiliary storage); the hosted keystore (kexts/XnuEAN) has its own, so
+# applekeystored would wait on a bag it cannot open. Without one it makes a new bag on first boot, as after a restore.
+echo "keybags: $(sudo -n ls "$D/private/var/keybags" 2>/dev/null | tr '\n' ' ')"
+sudo -n rm -f "$D"/private/var/keybags/*
+sudo -n python3 tools/hosted/gui-user.py "$D" "$W/sys/System/Library/User Template"
+sudo -n mkdir -p "$D/Library/GPUBundles" "$D/Library/LaunchDaemons" "$D/private/var/db/com.apple.xpc.launchd"
+sudo -n rm -rf "$D/Library/GPUBundles/XnuCpuMetal.bundle"; sudo -n ditto "$GPU" "$D/Library/GPUBundles/XnuCpuMetal.bundle"
+sudo -n chown -R root:wheel "$D/Library/GPUBundles"
+sudo -n D="$D" DISABLE="$DISABLE" python3 - <<'PY'
+import os, plistlib
+D = os.environ["D"]
+shell = {"Label": "xnulinux.shell", "ProgramArguments": ["/bin/bash", "-i"], "RunAtLoad": True,
+ "StandardInPath": "/dev/console", "StandardOutPath": "/dev/console", "StandardErrorPath": "/dev/console",
+ "EnvironmentVariables": {"HOME": "/var/root", "LOGNAME": "root", "USER": "root", "SHELL": "/bin/bash", "TERM": "dumb",
+ "PATH": "/bin:/usr/bin:/sbin:/usr/sbin", "PS1": "xnulinux# "}}
+p = D + "/Library/LaunchDaemons/xnulinux.shell.plist"
+plistlib.dump(shell, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)
+p = D + "/private/var/db/com.apple.xpc.launchd/disabled.plist"
+disabled = plistlib.load(open(p, "rb")) if os.path.exists(p) else {}
+disabled.update({label: True for label in os.environ["DISABLE"].split()})
+plistlib.dump(disabled, open(p, "wb")); os.chown(p, 0, 0); os.chmod(p, 0o644)
+print("console shell job, %d daemons disabled" % len(disabled))
+PY
+# The boot cryptexes' contents where dyld finds them without a graft: on a Mac, dyld in launchd grafts the OS and App
+# cryptexes (Preboot/<group>/cryptex1/current/{os,app}.dmg) onto Preboot/Cryptexes/{OS,App} from the ignition blob
+# AppleImage4 makes out of iBoot's boot object manifests; a hosted boot has neither, so the images' trees are copied in.
+CX=$(ls -d "$W"/preboot/*/cryptex1/current | head -1)
+for c in OS:os App:app; do
+ mkdir -p "$W/cx"; hdiutil attach -readonly -nobrowse -mountpoint "$W/cx" "$CX/${c#*:}.dmg" >/dev/null
+ sudo -n rm -rf "$W/preboot/Cryptexes/${c%%:*}"; sudo -n mkdir -p "$W/preboot/Cryptexes/${c%%:*}"
+ sudo -n ditto "$W/cx" "$W/preboot/Cryptexes/${c%%:*}"
+ hdiutil detach "$W/cx" >/dev/null
+ echo "cryptex ${c%%:*}: $(sudo -n du -sh "$W/preboot/Cryptexes/${c%%:*}" | cut -f1)"
+done
+sudo -n python3 scripts/extract-trustcache.py "$W/trustcache.bin" "$W/preboot"
+grep -h -A1 ProductVersion "$W/sys/System/Library/CoreServices/SystemVersion.plist" | tr -d '\t\n'; echo
+cleanup; trap - EXIT
+t0=$(date +%s)
+$V "rm -f /var/tmp/apfs.img /var/tmp/apfs.cow"
+tar -C "$W" -cSf - mac.img | $V "rm -f /var/tmp/mac.img; tar -C /var/tmp -xSf -; ls -ls /var/tmp/mac.img; df -h /var/tmp | tail -1"
+$V -put "$W/trustcache.bin" /var/tmp/trustcache-mac.bin; $V "sudo mv /var/tmp/trustcache-mac.bin /lib/firmware/xnu/trustcache-mac.bin; ls -la /lib/firmware/xnu/trustcache-mac.bin"
+echo "sent in $(( $(date +%s) - t0 ))s"
diff --git a/scripts/vm-gui-prep.sh b/scripts/vm-gui-prep.sh
index 5e336c8..441325f 100644
--- a/scripts/vm-gui-prep.sh
+++ b/scripts/vm-gui-prep.sh
@@ -8,6 +8,7 @@
# - automatic login as that user (loginwindow's autoLoginUser plus /etc/kcpassword), and Setup Assistant marked done
# for the system (.AppleSetupDone) and for the user, so the session goes straight to the desktop
set -e -o pipefail
+cd "$(dirname "$0")/.."
IMG=${IMG:-/var/tmp/full.img}
USERNAME=${GUI_USER:-xnu}; PASSWORD=${GUI_PASSWORD:-xnulinux}; UID_=${GUI_UID:-501}
sudo dmsetup remove xnusys 2>/dev/null || true; for l in $(losetup -j $IMG -O NAME -n); do sudo losetup -d $l; done
@@ -15,64 +16,7 @@ sudo fsck.hfsplus -fy $IMG 2>&1 | tail -1
sudo mkdir -p /mnt/sys; sudo mount -o loop,rw,force -t hfsplus $IMG /mnt/sys
M=/mnt/sys
[ -e $M/private/var/xnulinux-parked/com.apple.loginwindow.plist ] && sudo mv $M/private/var/xnulinux-parked/com.apple.loginwindow.plist $M/System/Library/LaunchDaemons/
-sudo M=$M USERNAME="$USERNAME" PASSWORD="$PASSWORD" UID_="$UID_" python3 - <<'PY'
-import hashlib, os, plistlib, uuid
-M, name, pw, uid = os.environ["M"], os.environ["USERNAME"], os.environ["PASSWORD"], int(os.environ["UID_"])
-D = M + "/private/var/db/dslocal/nodes/Default"
-# the password as opendirectoryd keeps it: SALTED-SHA512-PBKDF2 inside a binary plist in ShadowHashData
-salt, iters = os.urandom(32), 45000
-shadow = plistlib.dumps({"SALTED-SHA512-PBKDF2": {"entropy": hashlib.pbkdf2_hmac("sha512", pw.encode(), salt, iters, 128),
- "iterations": iters, "salt": salt}}, fmt=plistlib.FMT_BINARY)
-guid = str(uuid.uuid5(uuid.NAMESPACE_DNS, "xnulinux.user." + name)).upper()
-user = {"name": [name], "uid": [str(uid)], "gid": ["20"], "home": ["/Users/" + name], "shell": ["/bin/zsh"],
- "realname": [name], "generateduid": [guid], "passwd": ["********"],
- "authentication_authority": [";ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2>"], "ShadowHashData": [shadow]}
-with open(D + "/users/%s.plist" % name, "wb") as f:
- plistlib.dump(user, f, fmt=plistlib.FMT_BINARY)
-os.chmod(D + "/users/%s.plist" % name, 0o600)
-def member(group, gid, gguid):
- p = D + "/groups/%s.plist" % group
- g = plistlib.load(open(p, "rb")) if os.path.exists(p) else {"name": [group], "gid": [str(gid)], "generateduid": [gguid]}
- g["users"] = sorted(set(g.get("users", [])) | {name})
- g["groupmembers"] = sorted(set(g.get("groupmembers", [])) | {guid})
- with open(p, "wb") as f:
- plistlib.dump(g, f, fmt=plistlib.FMT_BINARY)
- os.chmod(p, 0o600)
-member("admin", 80, "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050")
-member("staff", 20, "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000014")
-# automatic login: loginwindow reads the user from its preferences and the password from /etc/kcpassword (the password
-# XORed with loginwindow's fixed key, padded with NULs to a multiple of 12 bytes)
-key = bytes([0x7D, 0x89, 0x52, 0x23, 0xD2, 0xBC, 0xDD, 0xEA, 0xA3, 0xB9, 0x1F])
-b = pw.encode() + b"\0"; b += b"\0" * (-len(b) % 12)
-with open(M + "/private/etc/kcpassword", "wb") as f:
- f.write(bytes(c ^ key[i % len(key)] for i, c in enumerate(b)))
-os.chmod(M + "/private/etc/kcpassword", 0o600)
-lp = M + "/Library/Preferences/com.apple.loginwindow.plist"
-lw = plistlib.load(open(lp, "rb")) if os.path.exists(lp) else {}
-lw.update({"autoLoginUser": name, "autoLoginUserUID": uid, "GuestEnabled": False})
-with open(lp, "wb") as f:
- plistlib.dump(lw, f, fmt=plistlib.FMT_BINARY)
-open(M + "/private/var/db/.AppleSetupDone", "w").close()
-PY
-# the home directory from the system's user template, and the user's own Setup Assistant panes marked seen
+sudo python3 tools/hosted/gui-user.py $M "$M/System/Library/User Template" "$USERNAME" "$PASSWORD" "$UID_"
H=$M/Users/$USERNAME
-if [ ! -d $H ]; then
- sudo mkdir -p $H
- sudo cp -a "$M/System/Library/User Template/Non_localized/." $H/ 2>/dev/null || true
- sudo cp -a "$M/System/Library/User Template/English.lproj/." $H/ 2>/dev/null || true
-fi
-sudo mkdir -p $H/Library/Preferences
-sudo H=$H python3 - <<'PY'
-import os, plistlib
-p = {k: True for k in ["DidSeeCloudSetup", "DidSeePrivacy", "DidSeeSiriSetup", "DidSeeTouchIDSetup", "DidSeeScreenTime",
- "DidSeeAppearanceSetup", "DidSeeAccessibility", "DidSeeActivationLock", "DidSeeTermsOfAddress", "DidSeeIntelligence",
- "DidSeeApplePaySetup", "DidSeeAvatarSetup", "DidSeeiCloudLoginForStorageServices", "DidSeeSyncSetup", "DidSeeSyncSetup2",
- "DidSeeTrueTonePrivacy", "DidSeeWalletSetup", "SkipFirstLoginOptimization"]}
-p.update({"LastSeenCloudProductVersion": "99.0", "LastSeenBuddyBuildVersion": "99Z999", "LastPreLoginTasksPerformedVersion": "99.0",
- "LastPreLoginTasksPerformedBuild": "99Z999"})
-with open(os.environ["H"] + "/Library/Preferences/com.apple.SetupAssistant.plist", "wb") as f:
- plistlib.dump(p, f, fmt=plistlib.FMT_BINARY)
-PY
-sudo chown -R $UID_:20 $H; sudo chmod 755 $H
echo "gui-prep: loginwindow $(ls $M/System/Library/LaunchDaemons/com.apple.loginwindow.plist 2>/dev/null | wc -l), user $USERNAME ($UID_), home $(sudo du -sh $H | cut -f1), autologin set"
sudo umount /mnt/sys; sudo fsck.hfsplus -fy $IMG 2>&1 | tail -1; sync
diff --git a/scripts/vm-m2-kbisect.sh b/scripts/vm-m2-kbisect.sh
index b51b97f..828b4af 100755
--- a/scripts/vm-m2-kbisect.sh
+++ b/scripts/vm-m2-kbisect.sh
@@ -18,7 +18,7 @@ sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /
for K in "$@"; do
sudo dmesg -C
echo ">>> kmax=$K"; sync
- sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${TRUSTCACHE:+trustcache=$TRUSTCACHE} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${FB_DUMP:+fb_dump=$FB_DUMP} ${INPUT_IN:+input_in=$INPUT_IN} ${KEYSTORE:+keystore=$KEYSTORE} ${DISK:+disk=$DISK} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}
+ sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${TRUSTCACHE:+trustcache=$TRUSTCACHE} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${FB_DUMP:+fb_dump=$FB_DUMP} ${INPUT_IN:+input_in=$INPUT_IN} ${KEYSTORE:+keystore=$KEYSTORE} ${DISK:+disk=$DISK} ${BOOT_UUID:+boot_uuid=$BOOT_UUID} ${PREBOOT_UUID:+preboot_uuid=$PREBOOT_UUID} ${ROOT_UUID:+root_uuid=$ROOT_UUID} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}
echo "lines: $(sudo dmesg | grep -ac 'xnu\]')"
sudo dmesg | grep -a "xnu\]\|XNU stage 4\|budget\|panic\|run ended" | tail -${SHOW:-4}
sudo rmmod xnu
diff --git a/tools/hosted/gui-user.py b/tools/hosted/gui-user.py
new file mode 100644
index 0000000..c07b7e2
--- /dev/null
+++ b/tools/hosted/gui-user.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+"""Make the hosted macOS's local user and automatic login, in a mounted system tree (run as root).
+
+ gui-user.py ROOT TEMPLATE [NAME PASSWORD UID]
+
+ROOT is where the user data lives: the whole system disk (HFS+) or a Mac's Data volume (APFS). TEMPLATE is the system's
+"System/Library/User Template" (on APFS, from the System volume). Nothing comes from the host: one local administrator
+(default xnu / xnulinux, uid 501) with the password as opendirectoryd keeps it (SALTED-SHA512-PBKDF2), member of admin and
+staff, a home from the system's own template, automatic login (loginwindow's autoLoginUser plus /etc/kcpassword), and
+Setup Assistant marked done for the system and the user.
+"""
+import hashlib, os, plistlib, subprocess, sys, uuid
+
+root, template = sys.argv[1], sys.argv[2]
+name = sys.argv[3] if len(sys.argv) > 3 else 'xnu'
+pw = sys.argv[4] if len(sys.argv) > 4 else 'xnulinux'
+uid = int(sys.argv[5]) if len(sys.argv) > 5 else 501
+D = root + '/private/var/db/dslocal/nodes/Default'
+
+
+def dump(path, value, mode=0o600):
+ with open(path, 'wb') as f:
+ plistlib.dump(value, f, fmt=plistlib.FMT_BINARY)
+ os.chmod(path, mode)
+
+
+salt, iters = os.urandom(32), 45000
+shadow = plistlib.dumps({'SALTED-SHA512-PBKDF2': {'entropy': hashlib.pbkdf2_hmac('sha512', pw.encode(), salt, iters, 128),
+ 'iterations': iters, 'salt': salt}}, fmt=plistlib.FMT_BINARY)
+guid = str(uuid.uuid5(uuid.NAMESPACE_DNS, 'xnulinux.user.' + name)).upper()
+dump(D + '/users/%s.plist' % name, {
+ 'name': [name], 'uid': [str(uid)], 'gid': ['20'], 'home': ['/Users/' + name], 'shell': ['/bin/zsh'], 'realname': [name],
+ 'generateduid': [guid], 'passwd': ['********'], 'authentication_authority': [';ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2>'],
+ 'ShadowHashData': [shadow]})
+
+
+def member(group, gid, gguid):
+ p = D + '/groups/%s.plist' % group
+ g = plistlib.load(open(p, 'rb')) if os.path.exists(p) else {'name': [group], 'gid': [str(gid)], 'generateduid': [gguid]}
+ g['users'] = sorted(set(g.get('users', [])) | {name})
+ g['groupmembers'] = sorted(set(g.get('groupmembers', [])) | {guid})
+ dump(p, g)
+
+
+member('admin', 80, 'ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050')
+member('staff', 20, 'ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000014')
+# automatic login: the user from loginwindow's preferences, the password from /etc/kcpassword (XORed with loginwindow's
+# fixed key, padded with NULs to a multiple of 12 bytes)
+key = bytes([0x7D, 0x89, 0x52, 0x23, 0xD2, 0xBC, 0xDD, 0xEA, 0xA3, 0xB9, 0x1F])
+b = pw.encode() + b'\0'
+b += b'\0' * (-len(b) % 12)
+os.makedirs(root + '/private/etc', exist_ok=True)
+with open(root + '/private/etc/kcpassword', 'wb') as f:
+ f.write(bytes(c ^ key[i % len(key)] for i, c in enumerate(b)))
+os.chmod(root + '/private/etc/kcpassword', 0o600)
+lp = root + '/Library/Preferences/com.apple.loginwindow.plist'
+lw = plistlib.load(open(lp, 'rb')) if os.path.exists(lp) else {}
+lw.update({'autoLoginUser': name, 'autoLoginUserUID': uid, 'GuestEnabled': False})
+dump(lp, lw, 0o644)
+open(root + '/private/var/db/.AppleSetupDone', 'w').close()
+# the home from the system's user template, the user's own Setup Assistant panes marked seen
+home = root + '/Users/' + name
+if not os.path.isdir(home):
+ os.makedirs(home)
+ for sub in ('Non_localized', 'English.lproj'):
+ if os.path.isdir(os.path.join(template, sub)):
+ subprocess.run(['cp', '-a', os.path.join(template, sub) + '/.', home + '/'], check=False)
+os.makedirs(home + '/Library/Preferences', exist_ok=True)
+seen = {k: True for k in ['DidSeeCloudSetup', 'DidSeePrivacy', 'DidSeeSiriSetup', 'DidSeeTouchIDSetup', 'DidSeeScreenTime',
+ 'DidSeeAppearanceSetup', 'DidSeeAccessibility', 'DidSeeActivationLock', 'DidSeeTermsOfAddress', 'DidSeeIntelligence',
+ 'DidSeeApplePaySetup', 'DidSeeAvatarSetup', 'DidSeeiCloudLoginForStorageServices', 'DidSeeSyncSetup',
+ 'DidSeeSyncSetup2', 'DidSeeTrueTonePrivacy', 'DidSeeWalletSetup', 'SkipFirstLoginOptimization']}
+seen.update({'LastSeenCloudProductVersion': '99.0', 'LastSeenBuddyBuildVersion': '99Z999',
+ 'LastPreLoginTasksPerformedVersion': '99.0', 'LastPreLoginTasksPerformedBuild': '99Z999'})
+dump(home + '/Library/Preferences/com.apple.SetupAssistant.plist', seen, 0o644)
+subprocess.run(['chown', '-R', '%d:20' % uid, home], check=True)
+os.chmod(home, 0o755)
+print('gui-user: %s (%d), admin, automatic login, home from the template' % (name, uid))
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 10718cd..95e7556 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -105,6 +105,22 @@ static void *ks_file;
static char *disk;
module_param(disk, charp, 0444);
static void *dk_file; static fki_u64 dk_size;
+/*
+ * What iBoot tells an APFS boot in /chosen: the system volume's UUID (boot-uuid; boot-arg rd=uuid finds the root by it) and
+ * the volume group's folder in Preboot (apfs-preboot-uuid: kern.apfsprebootuuid, from which dyld's libignition grafts the
+ * boot cryptexes, the OS cryptex with the dyld shared cache, before launchd runs).
+ */
+static char *boot_uuid, *preboot_uuid;
+module_param(boot_uuid, charp, 0444);
+module_param(preboot_uuid, charp, 0444);
+/*
+ * root_uuid: the root volume itself, by its APFS volume UUID, as /chosen root-matching (IOFindBSDRoot takes it before
+ * boot-uuid): BSD disk numbers follow probe order and change from boot to boot, and the boot-uuid route waits on APFS to
+ * publish boot-uuid-media from its volume group tree, which a disk that never booted on a Mac does not have yet.
+ */
+static char *root_uuid;
+module_param(root_uuid, charp, 0444);
+static char root_matching[256];
static void *in_file; static fki_u64 in_off;
/* hook returns must be 0 (nonzero ends the run): results come back through the request */
struct xnu_hostdisk_req { u64_t write, off, len; void *buf; long result; };
@@ -563,7 +579,17 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t
adt_prop_str(&a, "name", "device-tree");
adt_prop_str(&a, "compatible", "xnulinux,linux64");
adt_prop_str(&a, "model", "xnulinux");
- adt_node(&a, 22, 3); /* /chosen */
+ if (root_uuid && x_strlen(root_uuid) == 36) {
+ static const char pre[] = "<dict><key>IOProviderClass</key><string>IOMedia</string><key>IOPropertyMatch</key>"
+ "<dict><key>UUID</key><string>", post[] = "</string></dict></dict>";
+ x_memcpy(root_matching, pre, sizeof(pre) - 1);
+ x_memcpy(root_matching + sizeof(pre) - 1, root_uuid, 36);
+ x_memcpy(root_matching + sizeof(pre) - 1 + 36, post, sizeof(post));
+ }
+ adt_node(&a, 22 + (boot_uuid ? 1 : 0) + (preboot_uuid ? 1 : 0) + (root_matching[0] ? 1 : 0), 3); /* /chosen */
+ if (root_matching[0]) adt_prop_str(&a, "root-matching", root_matching);
+ if (boot_uuid) adt_prop_str(&a, "boot-uuid", boot_uuid);
+ if (preboot_uuid) adt_prop_str(&a, "apfs-preboot-uuid", preboot_uuid);
adt_prop_str(&a, "name", "chosen");
adt_prop_u64(&a, "dram-base", phys);
adt_prop_u64(&a, "dram-size", size);
diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patch
index 7aeb430..55268f9 100644
--- a/xnu-patches/0001-linux64-stage-hook.patch
+++ b/xnu-patches/0001-linux64-stage-hook.patch
@@ -267,7 +267,7 @@ index ec19ee7..6baf626 100644
}
}
diff --git a/bsd/kern/bsd_init.c b/bsd/kern/bsd_init.c
-index 5362b32..6f378e2 100644
+index 5362b32..6d03460 100644
--- a/bsd/kern/bsd_init.c
+++ b/bsd/kern/bsd_init.c
@@ -585,7 +585,7 @@ bsd_init(void)
@@ -309,6 +309,32 @@ index 5362b32..6f378e2 100644
if (require_rootauth) {
/* enforce sealedness */
int autherr = VNOP_IOCTL(rootvnode, FSIOC_KERNEL_ROOTAUTH, NULL, 0, vfs_context_kernel());
+@@ -1177,6 +1193,25 @@ bsd_init(void)
+ }
+ #endif /* DEVFS */
+
++#if CONFIG_MOUNT_PREBOOTRECOVERY
++ {
++ /*
++ * LINUX64 (xnulinux): a hosted APFS root from a Mac's own disk. On a Mac, dyld in launchd grafts the boot
++ * cryptexes (the OS cryptex holds the dyld shared cache) from the ignition blob AppleImage4 builds out of iBoot's
++ * boot object manifests; a hosted boot has no iBoot. The OS and App cryptexes' contents sit in the Preboot
++ * volume's Cryptexes/OS and Cryptexes/App (scripts/mk-macvm-disk.sh), where dyld also looks: mount the Preboot
++ * volume of the root's container at its usual place before launchd runs, as the Recovery volume is mounted.
++ */
++ extern uintptr_t linux64_hook;
++ if (linux64_hook && rootvnode && strcmp(rootvnode->v_mount->mnt_vfsstat.f_fstypename, "apfs") == 0) {
++ char prebootpath[] = "/System/Volumes/Preboot"; /* !const because of internal casting */
++ int perr = kernel_mount("apfs", NULLVP, NULLVP, prebootpath, rootvnode->v_mount, 0, 0,
++ KERNEL_MOUNT_PREBOOTVOL, vfs_context_kernel());
++ printf("LINUX64: Preboot volume at %s: %d\n", prebootpath, perr);
++ }
++ }
++#endif
++
+ #if CONFIG_BASESYSTEMROOT
+ #if CONFIG_IMAGEBOOT
+ if (bsdmgroot_bootable()) {
diff --git a/bsd/kern/kern_csr.c b/bsd/kern/kern_csr.c
index 604f16a..7cffe13 100644
--- a/bsd/kern/kern_csr.c
@@ -1233,6 +1259,19 @@ index d8fd4af..815051f 100644
/* convert kern_return_t to errno */
switch (kr) {
case KERN_SUCCESS:
+diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837
+index 0c52cc6..87d19c7 100644
+--- a/config/MASTER.arm64.bcm2837
++++ b/config/MASTER.arm64.bcm2837
+@@ -33,7 +33,7 @@
+ # BSD_RELEASE = [ BSD_BASE no_printf_str no_kprintf_str secure_kernel config_imgsrc_access ]
+ # BSD_DEV = [ BSD_BASE config_netboot config_imgsrc_access pgo config_vnguard rosetta BSD_EXTRAS_DEV ]
+ # BSD_DEBUG = [ BSD_BASE config_netboot config_imgsrc_access pgo config_vnguard rosetta BSD_EXTRAS_DEBUG ]
+-# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_triggers config_fse routefs namedstreams config_dataless_files bindfs config_ext_resolver config_firmlinks config_searchfs config_file_leases ]
++# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_triggers config_fse routefs namedstreams config_dataless_files bindfs config_ext_resolver config_firmlinks config_searchfs config_file_leases config_mount_prebootrecovery ]
+ # FILESYS_RELEASE= [ FILESYS_BASE ]
+ # FILESYS_DEV = [ FILESYS_BASE fdesc config_union_mounts ]
+ # FILESYS_DEBUG = [ FILESYS_BASE fdesc config_union_mounts ]
diff --git a/iokit/Kernel/IONVRAMCHRPHandler.cpp b/iokit/Kernel/IONVRAMCHRPHandler.cpp
index 0cc7f6e..c07d35c 100644
--- a/iokit/Kernel/IONVRAMCHRPHandler.cpp
@@ -2474,7 +2513,7 @@ index 84deb3f..767b8f8 100644
.macro BRANCH_EXTERN
diff --git a/osfmk/arm64/cpu.c b/osfmk/arm64/cpu.c
-index d10d7a1..7f195a2 100644
+index d10d7a1..3ba7323 100644
--- a/osfmk/arm64/cpu.c
+++ b/osfmk/arm64/cpu.c
@@ -100,6 +100,7 @@ extern void __attribute__((noreturn)) arm64_prepare_for_sleep(boolean_t deep_sle
@@ -2519,7 +2558,7 @@ index d10d7a1..7f195a2 100644
+ {
+ extern unsigned long linux64_dbg[16];
+ extern void linux64_dump_threads(void);
-+ if (++linux64_dbg[3] == 20000) {
++ if (++linux64_dbg[3] % 150000 == 0) { /* about every two to three minutes of idle */
+ linux64_dump_threads(); /* LINUX64 debug: who is blocked, and where */
+ }
+ }
@@ -3914,7 +3953,7 @@ index 2fc6931..dd59ae6 100644
struct console_printbuf_state info_data;
diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c
-index b2aae03..3b2058f 100644
+index b2aae03..e7bd92d 100644
--- a/osfmk/kern/sched_prim.c
+++ b/osfmk/kern/sched_prim.c
@@ -3010,6 +3010,7 @@ thread_invoke(
@@ -3933,7 +3972,7 @@ index b2aae03..3b2058f 100644
/*
* Ensure that updates to my processor and pset state,
* made by the IPI source processor before sending the IPI,
-@@ -9984,3 +9986,34 @@ sysctl_clutch_thread_group_cpu_time_for_thread(__unused thread_t thread,
+@@ -9984,3 +9986,45 @@ sysctl_clutch_thread_group_cpu_time_for_thread(__unused thread_t thread,
#endif /* !SCHED_TEST_HARNESS */
#endif /* DEVELOPMENT || DEBUG */
@@ -3948,10 +3987,21 @@ index b2aae03..3b2058f 100644
+{
+ thread_t t;
+ int n = 0;
++ extern int proc_pid(struct proc *);
+ queue_iterate(&threads, t, thread_t, threads) {
-+ if (++n > 120) {
++ if (++n > 400) {
+ break;
+ }
++ void *bp = get_bsdthreadtask_info(t);
++ if (bp == NULL || proc_pid((struct proc *)bp) == 0) {
++ /* the kernel's own threads: only those blocked with a saved stack (not parked on a continuation) */
++ if (t->continuation != NULL || t->kernel_stack == 0) {
++ continue;
++ }
++ kprintf("linux64 proc 0 kernel_task\n");
++ } else {
++ kprintf("linux64 proc %d %s\n", proc_pid((struct proc *)bp), proc_name_address((struct proc *)bp));
++ }
+ struct arm_kernel_saved_state *ss = (struct arm_kernel_saved_state *)(void *)t->machine.kstackptr;
+ uint64_t lr = 0, fp = 0;
+ if (ss != NULL && t->kernel_stack != 0) {
@@ -3960,7 +4010,7 @@ index b2aae03..3b2058f 100644
+ }
+ kprintf("linux64 thread %p tid %llu state 0x%x pri %d wait %p cont %p lr 0x%llx\n",
+ t, t->thread_id, t->state, t->sched_pri, (void *)t->wait_event, (void *)t->continuation, lr);
-+ for (int f = 0; f < 8 && fp != 0 && t->kernel_stack != 0 &&
++ for (int f = 0; f < 14 && fp != 0 && t->kernel_stack != 0 &&
+ fp >= t->kernel_stack && fp < t->kernel_stack + kernel_stack_size; f++) {
+ uint64_t *frame = (uint64_t *)fp;
+ kprintf("linux64 frame 0x%llx\n", frame[1] | 0xffffff8000000000ULL);