Skip to content

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

C

Emulated SEP keystore and an APFS system disk: XnuEAN, XnuDisk, APFS root

Heyang Zhou0dbcef0378b3
diff --git a/kexts/XnuDisk/XnuDisk.cpp b/kexts/XnuDisk/XnuDisk.cpp
new file mode 100644
index 0000000..6906239
--- /dev/null
+++ b/kexts/XnuDisk/XnuDisk.cpp
@@ -0,0 +1,159 @@
+// XnuDisk: the hosted macOS's internal disk, a block storage device whose blocks are a file on the Linux side.
+//
+// The file is a whole disk as macOS makes one: a GUID partition table and an APFS container (System and Data volumes),
+// built on a macOS host with Apple's own tools (scripts/mk-apfs-disk.sh). IOStorageFamily's IOBlockStorageDriver takes
+// this device, publishes its media, the GUID partition scheme finds the container partition and APFS mounts its volumes,
+// as on a Mac's internal SSD. I/O goes through the host: xnu.ko disk=, upcalls 820 (I/O) and 821 (size) in
+// bsd/net/if_linux64.c, done synchronously through a bounce buffer (the host reads and writes the file in Linux context).
+// IOBlockStorageDevice.h declares some of its virtual methods (doLockUnlockMedia, reportLockability,
+// reportPollRequirements, doDiscard) only under TARGET_OS_OSX; the collection's IOStorageFamily is the macOS one, so
+// without it this class's vtable is three slots short of the family's and the family's calls land on the wrong methods
+// (a PAC failure at the first, reportRemovability, from IOBlockStorageDriver::handleStart).
+#include <TargetConditionals.h>
+#undef TARGET_OS_OSX
+#define TARGET_OS_OSX 1
+#include <IOKit/IOLib.h>
+#include <IOKit/IOLocks.h>
+#include <IOKit/IOMemoryDescriptor.h>
+#include <IOKit/storage/IOBlockStorageDevice.h>
+#include <IOKit/storage/IOStorageProtocolCharacteristics.h>
+#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
+
+extern "C" uint64_t linux64_disk_size(void);
+extern "C" long linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset);
+
+namespace {
+constexpr UInt64 kBlockSize = 512; // the partition table's LBA size as the host tools wrote it
+constexpr IOByteCount kBounce = 1024 * 1024; // the largest piece one upcall moves
+}
+
+class XnuDisk : public IOBlockStorageDevice {
+ OSDeclareDefaultStructors(XnuDisk)
+ UInt64 fBlocks = 0;
+ IOLock *fLock = nullptr;
+ uint8_t *fBounce = nullptr;
+ char fVendor[8] = "Apple", fProduct[24] = "xnulinux Disk", fRevision[8] = "1.0", fInfo[4] = "";
+
+public:
+ bool start(IOService *provider) override;
+ void free() override;
+ IOReturn doEjectMedia() override { return kIOReturnUnsupported; }
+ IOReturn doFormatMedia(UInt64) override { return kIOReturnUnsupported; }
+ UInt32 doGetFormatCapacities(UInt64 *capacities, UInt32 max) const override
+ {
+ if (capacities && max)
+ capacities[0] = fBlocks * kBlockSize;
+ return 1;
+ }
+ char *getVendorString() override { return fVendor; }
+ char *getProductString() override { return fProduct; }
+ char *getRevisionString() override { return fRevision; }
+ char *getAdditionalDeviceInfoString() override { return fInfo; }
+ IOReturn reportBlockSize(UInt64 *size) override { *size = kBlockSize; return kIOReturnSuccess; }
+ IOReturn reportEjectability(bool *ejectable) override { *ejectable = false; return kIOReturnSuccess; }
+ IOReturn reportMaxValidBlock(UInt64 *block) override { *block = fBlocks - 1; return kIOReturnSuccess; }
+ IOReturn reportMediaState(bool *present, bool *changed) override
+ {
+ *present = true;
+ if (changed)
+ *changed = false;
+ return kIOReturnSuccess;
+ }
+ IOReturn reportRemovability(bool *removable) override { *removable = false; return kIOReturnSuccess; }
+ IOReturn reportWriteProtection(bool *protect) override { *protect = false; return kIOReturnSuccess; }
+ IOReturn getWriteCacheState(bool *enabled) override { *enabled = false; return kIOReturnSuccess; }
+ IOReturn setWriteCacheState(bool) override { return kIOReturnSuccess; }
+ IOReturn doSynchronize(UInt64, UInt64, IOStorageSynchronizeOptions) override { return kIOReturnSuccess; }
+ IOReturn doAsyncReadWrite(IOMemoryDescriptor *buffer, UInt64 block, UInt64 nblks, IOStorageAttributes *attributes,
+ IOStorageCompletion *completion) override;
+};
+
+OSDefineMetaClassAndStructors(XnuDisk, IOBlockStorageDevice)
+
+bool XnuDisk::start(IOService *provider)
+{
+ UInt64 bytes = linux64_disk_size();
+ if (bytes < kBlockSize || !IOBlockStorageDevice::start(provider))
+ return false;
+ fBlocks = bytes / kBlockSize;
+ fLock = IOLockAlloc();
+ fBounce = (uint8_t *)IOMallocData(kBounce);
+ if (!fLock || !fBounce)
+ return false;
+ // an internal disk, as the Mac's own: APFS and the system treat the container on it as the boot disk's
+ OSDictionary *protocol = OSDictionary::withCapacity(2);
+ OSDictionary *device = OSDictionary::withCapacity(2);
+ if (protocol && device) {
+ OSString *virt = OSString::withCString(kIOPropertyPhysicalInterconnectTypeVirtual);
+ OSString *internal = OSString::withCString(kIOPropertyInternalKey);
+ OSString *product = OSString::withCString(fProduct);
+ OSString *vendor = OSString::withCString(fVendor);
+ protocol->setObject(kIOPropertyPhysicalInterconnectTypeKey, virt);
+ protocol->setObject(kIOPropertyPhysicalInterconnectLocationKey, internal);
+ device->setObject(kIOPropertyProductNameKey, product);
+ device->setObject(kIOPropertyVendorNameKey, vendor);
+ setProperty(kIOPropertyProtocolCharacteristicsKey, protocol);
+ setProperty(kIOPropertyDeviceCharacteristicsKey, device);
+ OSSafeReleaseNULL(virt);
+ OSSafeReleaseNULL(internal);
+ OSSafeReleaseNULL(product);
+ OSSafeReleaseNULL(vendor);
+ }
+ OSSafeReleaseNULL(protocol);
+ OSSafeReleaseNULL(device);
+ registerService();
+ IOLog("XnuDisk: %llu blocks of %llu bytes (%llu MB)\n", fBlocks, kBlockSize, bytes >> 20);
+ return true;
+}
+
+void XnuDisk::free()
+{
+ if (fBounce)
+ IOFreeData(fBounce, kBounce);
+ if (fLock)
+ IOLockFree(fLock);
+ IOBlockStorageDevice::free();
+}
+
+IOReturn XnuDisk::doAsyncReadWrite(IOMemoryDescriptor *buffer, UInt64 block, UInt64 nblks, IOStorageAttributes *,
+ IOStorageCompletion *completion)
+{
+ if (!buffer || block + nblks > fBlocks)
+ return kIOReturnBadArgument;
+ bool write = buffer->getDirection() == kIODirectionOut;
+ IOByteCount total = nblks * kBlockSize, done = 0;
+ IOReturn status = buffer->prepare();
+ if (status == kIOReturnSuccess) {
+ IOLockLock(fLock);
+ while (done < total) {
+ IOByteCount piece = total - done < kBounce ? total - done : kBounce;
+ if (write && buffer->readBytes(done, fBounce, piece) != piece) {
+ status = kIOReturnIOError;
+ break;
+ }
+ long moved = linux64_disk_rw(write, fBounce, piece, block * kBlockSize + done);
+ if (moved != (long)piece) {
+ IOLog("XnuDisk: %s of %llu bytes at block %llu failed (%ld)\n", write ? "write" : "read", (UInt64)piece,
+ block + done / kBlockSize, moved);
+ status = kIOReturnIOError;
+ break;
+ }
+ if (!write && buffer->writeBytes(done, fBounce, piece) != piece) {
+ status = kIOReturnIOError;
+ break;
+ }
+ done += piece;
+ }
+ IOLockUnlock(fLock);
+ buffer->complete();
+ }
+ IOStorage::complete(completion, status, status == kIOReturnSuccess ? total : done);
+ return kIOReturnSuccess;
+}
+
+// Module start/stop for the collection's kext entry; the driver starts through IOKit matching.
+#include <mach/kmod.h>
+extern "C" {
+kern_return_t native_kext_start(kmod_info_t *, void *) { return KERN_SUCCESS; }
+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }
+}
diff --git a/kexts/XnuDisk/XnuDisk.json b/kexts/XnuDisk/XnuDisk.json
new file mode 100644
index 0000000..84a7908
--- /dev/null
+++ b/kexts/XnuDisk/XnuDisk.json
@@ -0,0 +1,26 @@
+{
+ "name": "XnuDisk",
+ "bundle": "org.xnulinux.driver.XnuDisk",
+ "version": "1.0.0",
+ "objects": "out/x12377/native-kexts/XnuDisk/objects.json",
+ "start": "_native_kext_start",
+ "stop": "_native_kext_stop",
+ "libraries": {
+ "com.apple.iokit.IOStorageFamily": "1.0.0",
+ "com.apple.kpi.bsd": "18.0.0",
+ "com.apple.kpi.iokit": "18.0.0",
+ "com.apple.kpi.libkern": "18.0.0",
+ "com.apple.kpi.mach": "18.0.0",
+ "com.apple.kpi.private": "18.0.0",
+ "com.apple.kpi.unsupported": "18.0.0"
+ },
+ "personalities": {
+ "XnuDisk": {
+ "CFBundleIdentifier": "org.xnulinux.driver.XnuDisk",
+ "IOClass": "XnuDisk",
+ "IOProviderClass": "IOResources",
+ "IOResourceMatch": "IOKit",
+ "IOMatchCategory": "XnuDisk"
+ }
+ }
+}
diff --git a/kexts/XnuEAN/XnuEAN.cpp b/kexts/XnuEAN/XnuEAN.cpp
new file mode 100644
index 0000000..c5260b0
--- /dev/null
+++ b/kexts/XnuEAN/XnuEAN.cpp
@@ -0,0 +1,228 @@
+// XnuEAN: the EAN of the hosted macOS, the small keyed store the Secure Enclave's replacement on Apple's virtual platform keeps
+// its xART in.
+//
+// The collection is VirtualMac's: AppleVPKeyStore and AppleVPCredentialManager are the keystore in software, and
+// AppleVirtualPlatformXART (AppleVirtualPlatform) derives, seals and loads the xART seeds (the SEP's anti-replay storage).
+// It reads and writes them as two blobs, keys 'xrtC' and 'xrtP', of an EAN: it waits forever for an IOService named
+// "AppleNVMeEAN", casts it to that class (AppleVirtIOStorage's), and calls AppleNVMeEAN::eanGetSize / eanRead / eanWrite /
+// eanSwap on it directly. On a VirtualMac that object sits on the auxiliary disk of AppleVirtIOStorageDevice; the hosted
+// system has no such device, and without an EAN the keystore's first open (applekeystored, powerd at boot) blocks forever.
+//
+// Here: an AppleNVMeEAN instance (never started: it has no device) is registered so the cast succeeds, and the four entry
+// points of the class are redirected to the functions below (a branch written over each one's first instruction). The blobs
+// live in memory and are written through to a file on the Linux side (xnu.ko keystore=, upcall 819 in bsd/net/if_linux64.c),
+// so they last as long as that file does. Nothing else on this system uses AppleNVMeEAN.
+#include <IOKit/IOLib.h>
+#include <IOKit/IOLocks.h>
+#include <IOKit/IOService.h>
+#include <libkern/OSByteOrder.h>
+#include <ptrauth.h>
+
+extern "C" long linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset);
+// the kernel's own (osfmk), under names of ours: the kernel headers some of them come from disagree on their types
+extern "C" uint64_t xnuKvtophys(vm_offset_t va) __asm("_kvtophys");
+extern "C" void xnuPhysWriteWord(uint64_t paddr, unsigned int data) __asm("_ml_phys_write_word_64");
+extern "C" void xnuInvalidateIcache(vm_offset_t va, size_t length) __asm("_InvalidatePoU_IcacheRegion");
+
+// AppleVirtIOStorage's AppleNVMeEAN (non-virtual members; AppleVirtualPlatform calls them with bl)
+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");
+
+namespace {
+constexpr uint32_t kMagic = 'XEAN', kMaxEntries = 16, kMaxBlob = 64 * 1024, kStoreMax = 1024 * 1024;
+struct Entry { uint32_t key, length; uint8_t *data; };
+Entry gEntries[kMaxEntries];
+IOLock *gLock;
+uint8_t *gImage; // the store file's contents: magic, count, then {key, length, bytes} per entry
+
+Entry *find(uint32_t key)
+{
+ for (auto &e : gEntries)
+ if (e.data && e.key == key)
+ return &e;
+ return nullptr;
+}
+
+void persist()
+{
+ uint32_t at = 8, count = 0;
+ for (auto &e : gEntries) {
+ if (!e.data || at + 8 + e.length > kStoreMax)
+ continue;
+ memcpy(gImage + at, &e.key, 4);
+ memcpy(gImage + at + 4, &e.length, 4);
+ memcpy(gImage + at + 8, e.data, e.length);
+ at += 8 + e.length;
+ count++;
+ }
+ memcpy(gImage, &kMagic, 4);
+ memcpy(gImage + 4, &count, 4);
+ long done = linux64_store_rw(1, gImage, (at + 4095) & ~4095u, 0);
+ if (done < (long)at)
+ IOLog("XnuEAN: writing the store failed (%ld)\n", done);
+}
+
+void load()
+{
+ long got = linux64_store_rw(0, gImage, kStoreMax, 0);
+ uint32_t magic = 0, count = 0;
+ if (got >= 8) {
+ memcpy(&magic, gImage, 4);
+ memcpy(&count, gImage + 4, 4);
+ }
+ if (magic != kMagic) {
+ IOLog("XnuEAN: empty store (%ld bytes read)\n", got);
+ return;
+ }
+ uint32_t at = 8;
+ for (uint32_t i = 0; i < count && i < kMaxEntries && at + 8 <= (uint64_t)got; i++) {
+ Entry &e = gEntries[i];
+ memcpy(&e.key, gImage + at, 4);
+ memcpy(&e.length, gImage + at + 4, 4);
+ if (e.length > kMaxBlob || at + 8 + e.length > (uint64_t)got)
+ break;
+ e.data = (uint8_t *)IOMallocData(e.length ? e.length : 1);
+ memcpy(e.data, gImage + at + 8, e.length);
+ at += 8 + e.length;
+ }
+ IOLog("XnuEAN: %u blobs loaded from the store\n", count);
+}
+}
+
+// The replacements, with AppleNVMeEAN's signatures (this first). Return values as AppleVirtualPlatformXART reads them: the
+// blob's size, 0 when there is none; kIOReturnSuccess or an error.
+extern "C" uint32_t xnu_ean_get_size(void *, uint32_t key)
+{
+ IOLockLock(gLock);
+ Entry *e = find(key);
+ uint32_t size = e ? e->length : 0;
+ IOLockUnlock(gLock);
+ return size;
+}
+
+extern "C" IOReturn xnu_ean_read(void *, uint32_t key, void *buffer, uint32_t length)
+{
+ IOLockLock(gLock);
+ Entry *e = find(key);
+ IOReturn result = kIOReturnNotFound;
+ if (e && buffer) {
+ memcpy(buffer, e->data, length < e->length ? length : e->length);
+ result = kIOReturnSuccess;
+ }
+ IOLockUnlock(gLock);
+ return result;
+}
+
+extern "C" IOReturn xnu_ean_write(void *, uint32_t key, void *buffer, uint32_t length)
+{
+ if (length > kMaxBlob || (length && !buffer))
+ return kIOReturnBadArgument;
+ uint8_t *copy = (uint8_t *)IOMallocData(length ? length : 1);
+ if (!copy)
+ return kIOReturnNoMemory;
+ memcpy(copy, buffer, length);
+ IOLockLock(gLock);
+ Entry *e = find(key);
+ if (!e)
+ for (auto &slot : gEntries)
+ if (!slot.data) {
+ e = &slot;
+ break;
+ }
+ IOReturn result = kIOReturnNoSpace;
+ if (e) {
+ if (e->data)
+ IOFreeData(e->data, e->length ? e->length : 1);
+ e->key = key;
+ e->length = length;
+ e->data = copy;
+ copy = nullptr;
+ persist();
+ result = kIOReturnSuccess;
+ }
+ IOLockUnlock(gLock);
+ if (copy)
+ IOFreeData(copy, length ? length : 1);
+ return result;
+}
+
+extern "C" IOReturn xnu_ean_swap(void *, uint32_t a, uint32_t b)
+{
+ IOLockLock(gLock);
+ Entry *ea = find(a), *eb = find(b);
+ if (ea)
+ ea->key = b;
+ if (eb)
+ eb->key = a;
+ if (ea || eb)
+ persist();
+ IOLockUnlock(gLock);
+ return kIOReturnSuccess;
+}
+
+class XnuEAN : public IOService {
+ OSDeclareDefaultStructors(XnuEAN)
+ IOService *fEan = nullptr;
+ static bool redirect(void (*from)(void), const void *to, const char *what);
+
+public:
+ bool start(IOService *provider) override;
+};
+
+OSDefineMetaClassAndStructors(XnuEAN, IOService)
+
+// A branch to `to` over the first instruction of `from` (its callers enter with bl, which a BTI landing pad does not need).
+bool XnuEAN::redirect(void (*from)(void), const void *to, const char *what)
+{
+ uintptr_t src = (uintptr_t)ptrauth_strip((void *)from, ptrauth_key_function_pointer);
+ uintptr_t dst = (uintptr_t)ptrauth_strip((void *)to, ptrauth_key_function_pointer);
+ intptr_t delta = (intptr_t)(dst - src);
+ if (delta & 3 || delta >= (1 << 27) || delta < -(1 << 27)) {
+ IOLog("XnuEAN: %s is out of branch range (%p -> %p)\n", what, (void *)src, (void *)dst);
+ return false;
+ }
+ uint64_t pa = xnuKvtophys(src);
+ if (!pa)
+ return false;
+ xnuPhysWriteWord(pa, 0x14000000u | (((uint32_t)(delta >> 2)) & 0x03ffffffu));
+ xnuInvalidateIcache(src, 4);
+ return true;
+}
+
+bool XnuEAN::start(IOService *provider)
+{
+ if (!IOService::start(provider))
+ return false;
+ gLock = IOLockAlloc();
+ gImage = (uint8_t *)IOMallocData(kStoreMax);
+ if (!gLock || !gImage)
+ return false;
+ load();
+ if (!redirect(appleEanGetSize, (const void *)&xnu_ean_get_size, "eanGetSize") ||
+ !redirect(appleEanRead, (const void *)&xnu_ean_read, "eanRead") ||
+ !redirect(appleEanWrite, (const void *)&xnu_ean_write, "eanWrite") ||
+ !redirect(appleEanSwap, (const void *)&xnu_ean_swap, "eanSwap"))
+ return false;
+ // an instance of the class AppleVirtualPlatformXART casts to, registered under its class name (its IOName)
+ OSObject *object = OSMetaClass::allocClassWithName("AppleNVMeEAN");
+ fEan = OSDynamicCast(IOService, object);
+ if (!fEan || !fEan->init(nullptr) || !fEan->attach(this)) {
+ IOLog("XnuEAN: cannot make an AppleNVMeEAN (%p)\n", object);
+ OSSafeReleaseNULL(object);
+ fEan = nullptr;
+ return false;
+ }
+ fEan->registerService();
+ registerService();
+ IOLog("XnuEAN: AppleNVMeEAN registered; its EAN calls go to the hosted store\n");
+ return true;
+}
+
+// Module start/stop for the collection's kext entry; the driver starts through IOKit matching.
+#include <mach/kmod.h>
+extern "C" {
+kern_return_t native_kext_start(kmod_info_t *, void *) { return KERN_SUCCESS; }
+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }
+}
diff --git a/kexts/XnuEAN/XnuEAN.json b/kexts/XnuEAN/XnuEAN.json
new file mode 100644
index 0000000..1322aac
--- /dev/null
+++ b/kexts/XnuEAN/XnuEAN.json
@@ -0,0 +1,26 @@
+{
+ "name": "XnuEAN",
+ "bundle": "org.xnulinux.driver.XnuEAN",
+ "version": "1.0.0",
+ "objects": "out/x12377/native-kexts/XnuEAN/objects.json",
+ "start": "_native_kext_start",
+ "stop": "_native_kext_stop",
+ "libraries": {
+ "com.apple.iokit.AppleVirtIOStorage": "1.0.0",
+ "com.apple.kpi.bsd": "18.0.0",
+ "com.apple.kpi.iokit": "18.0.0",
+ "com.apple.kpi.libkern": "18.0.0",
+ "com.apple.kpi.mach": "18.0.0",
+ "com.apple.kpi.private": "18.0.0",
+ "com.apple.kpi.unsupported": "18.0.0"
+ },
+ "personalities": {
+ "XnuEAN": {
+ "CFBundleIdentifier": "org.xnulinux.driver.XnuEAN",
+ "IOClass": "XnuEAN",
+ "IOProviderClass": "IOResources",
+ "IOResourceMatch": "IOKit",
+ "IOMatchCategory": "XnuEAN"
+ }
+ }
+}
diff --git a/scripts/mk-apfs-disk.sh b/scripts/mk-apfs-disk.sh
new file mode 100755
index 0000000..88257c7
--- /dev/null
+++ b/scripts/mk-apfs-disk.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# On the macOS host (tokyo): the hosted system's APFS disk, /var/tmp/apfs.img in the xnupoc VM (xnu.ko disk=, kexts/XnuDisk).
+# A whole disk as macOS makes one, made with Apple's own tools on this host: a GUID partition table and an APFS container
+# with the system volume, filled with the golden full disk's tree (/var/tmp/full.img in the VM, HFS+, made by
+# mk-fulldisk.sh, vm-gui-prep.sh and friends). Linux has no APFS writer; the hosted XNU's own apfs.kext mounts it.
+# The image is sparse: built in a host file, then sent to the VM keeping its holes. Apple's files stay on this host and in
+# that VM (never in the repo).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+V="bash scripts/vm.sh"
+SIZE=${SIZE:-96g}; W=${W:-$PWD/../apfs-build}; IMG=$W/apfs.img; NAME=${VOLNAME:-xnulinux}
+mkdir -p "$W"; rm -f "$IMG"; mkfile -n "$SIZE" "$IMG"
+DEV=$(hdiutil attach -imagekey diskimage-class=CRawDiskImage -nomount "$IMG" | awk 'NR==1{print $1}')
+cleanup() { sudo -n umount "$W/mnt" 2>/dev/null || true; hdiutil detach "$DEV" -force >/dev/null 2>&1 || true; }
+trap cleanup EXIT
+echo "image on $DEV"
+diskutil partitionDisk "$DEV" GPT APFS "$NAME" 100% >/dev/null
+diskutil list "$DEV"
+VOL=$(diskutil list | awk -v n="$NAME" '$0 ~ "APFS Volume" && $0 ~ n {print $NF}' | tail -1)
+CONTAINER=$(diskutil info "$VOL" | awk -F': *' '/APFS Container:/{print $2}')
+echo "volume $VOL in container $CONTAINER"
+diskutil unmount "$VOL" >/dev/null
+mkdir -p "$W/mnt"; diskutil mount -mountPoint "$W/mnt" "$VOL" >/dev/null
+sudo -n diskutil enableOwnership "$W/mnt" >/dev/null
+t0=$(date +%s)
+# the golden tree as the VM's Linux sees it (owners, modes, links; mk-fulldisk.sh wrote it without Mac metadata)
+$V "set -e; sudo dmsetup remove xnusys 2>/dev/null || true; for l in \$(losetup -j /var/tmp/full.img -O NAME -n); do sudo losetup -d \$l; done
+ sudo mkdir -p /mnt/fullro; sudo mount -o loop,ro -t hfsplus /var/tmp/full.img /mnt/fullro
+ sudo tar -C /mnt/fullro --numeric-owner -cf - . ; sudo umount /mnt/fullro" \
+ | sudo -n tar -C "$W/mnt" --numeric-owner -xpf - 2> "$W/tar.err" || echo "tar ended nonzero ($(wc -l < "$W/tar.err") lines in $W/tar.err)"
+echo "copied in $(( $(date +%s) - t0 ))s"; tail -3 "$W/tar.err" || true
+df -h "$W/mnt" | tail -1; ls "$W/mnt" | tr '\n' ' '; echo
+sudo -n umount "$W/mnt"; hdiutil detach "$DEV" >/dev/null; trap - EXIT
+t0=$(date +%s)
+tar -C "$W" -cSf - apfs.img | $V "rm -f /var/tmp/apfs.img; tar -C /var/tmp -xSf -; ls -ls /var/tmp/apfs.img"
+echo "sent in $(( $(date +%s) - t0 ))s"
diff --git a/scripts/vm-m2-kbisect.sh b/scripts/vm-m2-kbisect.sh
index 4acc0ed..b51b97f 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} ${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} ${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/scripts/vm-snap.sh b/scripts/vm-snap.sh
index 5845367..d6f620b 100755
--- a/scripts/vm-snap.sh
+++ b/scripts/vm-snap.sh
@@ -1,12 +1,13 @@
#!/bin/bash
# In the VM: a fresh copy-on-write view of the golden system disk for one hosted run, /dev/mapper/xnusys.
# A hosted XNU that dies mid-write (or takes the host with it) leaves HFS+ corrupt; the golden image stays clean.
+# NAME=xnuapfs IMG=/var/tmp/apfs.img COW=/var/tmp/apfs.cow: the same for the APFS disk (scripts/mk-apfs-disk.sh).
set -e
-IMG=${IMG:-/var/tmp/full.img}; COW=${COW:-/var/tmp/full.cow}
-sudo dmsetup remove xnusys 2>/dev/null || true
+IMG=${IMG:-/var/tmp/full.img}; COW=${COW:-/var/tmp/full.cow}; NAME=${NAME:-xnusys}
+sudo dmsetup remove $NAME 2>/dev/null || true
for l in $(losetup -j "$IMG" -O NAME -n) $(losetup -j "$COW" -O NAME -n 2>/dev/null); do sudo losetup -d "$l"; done
rm -f "$COW"; truncate -s ${COW_SIZE:-40G} "$COW"
B=$(sudo losetup -f -r --show "$IMG"); C=$(sudo losetup -f --show "$COW")
-sudo dmsetup create xnusys --table "0 $(sudo blockdev --getsz "$B") snapshot $B $C N 16"
-sudo chmod 666 /dev/mapper/xnusys 2>/dev/null || true
-echo "xnusys over $B (cow $C): $(sudo blockdev --getsize64 /dev/mapper/xnusys) bytes"
+sudo dmsetup create $NAME --table "0 $(sudo blockdev --getsz "$B") snapshot $B $C N 16"
+sudo chmod 666 /dev/mapper/$NAME 2>/dev/null || true
+echo "$NAME over $B (cow $C): $(sudo blockdev --getsize64 /dev/mapper/$NAME) bytes"
diff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.sh
index f67953a..eed9124 100755
--- a/scripts/vm-xnu-rebuild.sh
+++ b/scripts/vm-xnu-rebuild.sh
@@ -28,9 +28,10 @@ if [ -e out/kc/kc27.bin ]; then
NETINC=~/w/poc/build/netinc; NETSRC=~/w/poc/build/IONetworkingFamily-188; mkdir -p $NETINC/IOKit
[ -e $NETSRC/IOEthernetController.h ] || git clone -q --depth 1 --branch IONetworkingFamily-188 https://github.com/apple-oss-distributions/IONetworkingFamily.git $NETSRC
ln -sfn $NETSRC $NETINC/IOKit/network
- # IOHIDFamily's kernel headers (IOKit/hid/*.h) for XnuInput: the SDK's Kernel.framework has them
+ # IOHIDFamily's kernel headers (IOKit/hid/*.h) for XnuInput and IOStorageFamily's (IOKit/storage/*.h) for XnuDisk: the SDK's
+ # Kernel.framework has them
for h in toolchains/sdks/*.sdk/System/Library/Frameworks/Kernel.framework/Headers/IOKit/hid; do
- [ -e $h/IOHIDDevice.h ] && { ln -sfn $PWD/$h $NETINC/IOKit/hid; ln -sfn $PWD/$h/../hidsystem $NETINC/IOKit/hidsystem; ln -sfn $PWD/$h/../graphics $NETINC/IOKit/graphics
+ [ -e $h/IOHIDDevice.h ] && { ln -sfn $PWD/$h $NETINC/IOKit/hid; ln -sfn $PWD/$h/../hidsystem $NETINC/IOKit/hidsystem; ln -sfn $PWD/$h/../graphics $NETINC/IOKit/graphics; ln -sfn $PWD/$h/../storage $NETINC/IOKit/storage
ln -sfn $PWD/${h%%/System/*}/usr/include/TargetConditionals.h $NETINC/TargetConditionals.h
ln -sfn $PWD/$h/../../HIDDriverKit $NETINC/HIDDriverKit; break; } # IOHIDDevice.h includes HIDDriverKit/IOHIDDevice.h
done
diff --git a/tools/hosted/probe-window.m b/tools/hosted/probe-window.m
new file mode 100644
index 0000000..c19fd0f
--- /dev/null
+++ b/tools/hosted/probe-window.m
@@ -0,0 +1,62 @@
+// A rendering probe for the hosted macOS: one borderless window above everything (screen-saver level), for SECONDS seconds.
+// MODE picks who renders its content, to tell the client's rendering from WindowServer's compositing apart:
+// draw AppKit drawRect: four colour quadrants and a label (the client renders its layer tree)
+// image a layer whose contents is a CGImage of the same quadrants (WindowServer gets the pixels as shared memory)
+// color a layer with only a red background colour (WindowServer fills it itself; no client pixels at all)
+// clang -fobjc-arc -framework AppKit -framework QuartzCore probe-window.m -o probe-window && ./probe-window [SECONDS] [MODE]
+#import <AppKit/AppKit.h>
+#import <QuartzCore/QuartzCore.h>
+
+@interface ProbeView : NSView
+@end
+@implementation ProbeView
+- (void)drawRect:(NSRect)dirty {
+ NSRect b = self.bounds;
+ CGFloat w = b.size.width / 2, h = b.size.height / 2;
+ NSColor *colors[4] = {NSColor.systemRedColor, NSColor.systemGreenColor, NSColor.systemBlueColor, NSColor.systemYellowColor};
+ for (int i = 0; i < 4; i++) {
+ [colors[i] setFill];
+ NSRectFill(NSMakeRect((i % 2) * w, (i / 2) * h, w, h));
+ }
+ NSDictionary *attrs = @{NSFontAttributeName: [NSFont boldSystemFontOfSize:36], NSForegroundColorAttributeName: NSColor.whiteColor};
+ [@"xnulinux" drawAtPoint:NSMakePoint(w - 80, h - 20) withAttributes:attrs];
+}
+@end
+
+int main(int argc, char **argv) {
+ @autoreleasepool {
+ double seconds = argc > 1 ? atof(argv[1]) : 30;
+ [NSApplication sharedApplication];
+ [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
+ NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(340, 200, 600, 400) styleMask:NSWindowStyleMaskBorderless
+ backing:NSBackingStoreBuffered defer:NO];
+ window.level = NSScreenSaverWindowLevel;
+ const char *mode = argc > 2 ? argv[2] : "draw";
+ if (!strcmp(mode, "draw")) {
+ window.contentView = [[ProbeView alloc] initWithFrame:NSMakeRect(0, 0, 600, 400)];
+ } else {
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 600, 400)];
+ view.wantsLayer = YES;
+ if (!strcmp(mode, "color")) {
+ view.layer.backgroundColor = CGColorCreateSRGB(1, 0, 0, 1);
+ } else {
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ CGContextRef cg = CGBitmapContextCreate(NULL, 600, 400, 8, 0, space, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
+ CGFloat rgb[4][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}};
+ for (int i = 0; i < 4; i++) {
+ CGContextSetRGBFillColor(cg, rgb[i][0], rgb[i][1], rgb[i][2], 1);
+ CGContextFillRect(cg, CGRectMake((i % 2) * 300, (i / 2) * 200, 300, 200));
+ }
+ CGImageRef image = CGBitmapContextCreateImage(cg);
+ view.layer.contents = (__bridge id)image;
+ CGImageRelease(image); CGContextRelease(cg); CGColorSpaceRelease(space);
+ }
+ window.contentView = view;
+ }
+ [window orderFrontRegardless];
+ fprintf(stderr, "probe-window: %s window %ld on screen %s\n", mode, (long)window.windowNumber, window.screen ? "yes" : "no");
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [NSApp terminate:nil]; });
+ [NSApp run];
+ }
+ return 0;
+}
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 37373f2..10718cd 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -98,6 +98,13 @@ struct xnu_cons_req { void *buf; u64_t len; long result; };
*/
static char *input_in;
module_param(input_in, charp, 0444);
+static char *keystore; /* the hosted keystore's file (XnuEAN's EAN blobs): read and written through upcall 819 */
+module_param(keystore, charp, 0444);
+static void *ks_file;
+/* The hosted system's block disk (kexts/XnuDisk: IOKit media, e.g. an APFS container), read-write: upcalls 821 (size), 820 (I/O) */
+static char *disk;
+module_param(disk, charp, 0444);
+static void *dk_file; static fki_u64 dk_size;
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; };
@@ -360,6 +367,21 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a
if (a1) fki_realtime(&((fki_u64 *)a1)[0], &((fki_u64 *)a1)[1]);
return 0;
}
+ if (stage == 821) { /* the block disk's size in bytes into *a1, 0 when there is none */
+ if (a1) *(u64_t *)a1 = dk_file ? dk_size : 0;
+ return 0;
+ }
+ if (stage == 820) { /* block disk I/O: q->result = bytes moved or -errno */
+ struct xnu_hostdisk_req *q = (struct xnu_hostdisk_req *)a1;
+ if (q) q->result = dk_file ? fki_file_rw(dk_file, (int)q->write, q->buf, (unsigned long)q->len, q->off) : -6;
+ return 0;
+ }
+ if (stage == 819) { /* the keystore file: q->result = bytes moved or -errno */
+ struct xnu_hostdisk_req *q = (struct xnu_hostdisk_req *)a1;
+ if (!q) return 0;
+ q->result = ks_file ? fki_file_rw(ks_file, (int)q->write, q->buf, (unsigned long)q->len, q->off) : -6;
+ return 0;
+ }
if (stage == 995) { /* host disk size in bytes into *a1, 0 when there is none */
if (a1) *(u64_t *)a1 = hd_file ? hd_size : 0;
return 0;
@@ -469,6 +491,16 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a
logs("xnu: XNU panic:");
logs(m);
logkv("xnu: panic caller", a2);
+ { /* the frame-pointer chain from here through XNU's frames (the hook runs on XNU's stack); return addresses
+ * with their pointer-authentication bits replaced by the kernel's all-ones top */
+ unsigned long *fp = __builtin_frame_address(0);
+ for (i = 0; i < 24 && fp && !((unsigned long)fp & 15) && (unsigned long)fp >> 48 == 0xffff; i++) {
+ unsigned long lr = fp[1] | 0xffffff8000000000ul;
+ logkv("xnu: frame", lr);
+ if ((unsigned long *)fp[0] <= fp) break;
+ fp = (unsigned long *)fp[0];
+ }
+ }
return 1;
}
static const struct { unsigned long s; const char *what; } names[] = {
@@ -905,12 +937,22 @@ static int __init xnu_init(void)
ci_off = sz; /* only what is written after the load */
if (!ci_file) logs("xnu: cannot open console_in");
}
+ if (keystore) {
+ fki_u64 sz;
+ ks_file = fki_file_open(keystore, 1, &sz);
+ if (!ks_file) logs("xnu: cannot open the keystore file");
+ }
if (input_in) {
fki_u64 sz = 0;
in_file = fki_file_open(input_in, 0, &sz);
in_off = sz & ~7ULL; /* only what is written after the load */
if (!in_file) logs("xnu: cannot open input_in");
}
+ if (disk) {
+ dk_file = fki_file_open(disk, 1, &dk_size);
+ if (!dk_file) { logs("xnu: cannot open the block disk"); return -2; }
+ logkv("xnu: block disk bytes", dk_size);
+ }
if (hostdisk) {
hd_file = fki_file_open(hostdisk, hostdisk_rw, &hd_size);
if (!hd_file) { logs("xnu: cannot open the host disk"); return -2; }
@@ -948,6 +990,8 @@ static void __exit xnu_exit(void)
if (rd_blob) fki_blob_put(rd_blob);
if (tc_blob) fki_blob_put(tc_blob);
if (hd_file) fki_file_close(hd_file);
+ if (ks_file) fki_file_close(ks_file);
+ if (dk_file) fki_file_close(dk_file);
if (ci_file) fki_file_close(ci_file);
if (in_file) fki_file_close(in_file);
}
diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patch
index a48d46e..7aeb430 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..8028c48 100644
+index 5362b32..6f378e2 100644
--- a/bsd/kern/bsd_init.c
+++ b/bsd/kern/bsd_init.c
@@ -585,7 +585,7 @@ bsd_init(void)
@@ -291,6 +291,24 @@ index 5362b32..8028c48 100644
#endif /* ETHER */
#if NETWORKING
+@@ -1083,6 +1088,17 @@ bsd_init(void)
+ }
+ }
+ #endif
++ {
++ /*
++ * LINUX64 (xnulinux): a hosted APFS root is the host's own image, unsealed, with no boot manifest to
++ * authenticate it against. With SIP's unauthenticated-root allowance (boot-arg lp-sip0 with 0x800, what
++ * "csrutil authenticated-root disable" sets on a Mac) it mounts as it is.
++ */
++ extern uintptr_t linux64_hook;
++ if (linux64_hook && csr_check(CSR_ALLOW_UNAUTHENTICATED_ROOT) == 0) {
++ require_rootauth = FALSE;
++ }
++ }
+ if (require_rootauth) {
+ /* enforce sealedness */
+ int autherr = VNOP_IOCTL(rootvnode, FSIOC_KERNEL_ROOTAUTH, NULL, 0, vfs_context_kernel());
diff --git a/bsd/kern/kern_csr.c b/bsd/kern/kern_csr.c
index 604f16a..7cffe13 100644
--- a/bsd/kern/kern_csr.c
@@ -747,10 +765,10 @@ index c08a74c..1e26f75 100644
355 AUE_NULL ALL { int nosys(void); } { old getaudit }
diff --git a/bsd/net/if_linux64.c b/bsd/net/if_linux64.c
new file mode 100644
-index 0000000..461d993
+index 0000000..29cf3df
--- /dev/null
+++ b/bsd/net/if_linux64.c
-@@ -0,0 +1,256 @@
+@@ -0,0 +1,307 @@
+/*
+ * LINUX64 (xnulinux): the hosted kernel's Ethernet interface en0.
+ *
@@ -933,6 +951,57 @@ index 0000000..461d993
+ return q.result > 0 ? q.result : 0;
+}
+
++/*
++ * The hosted keystore's backing file (xnu.ko keystore=): XnuEAN keeps the EAN blobs of the virtual platform's xART there.
++ * Reads or writes `length` bytes at `offset`; bytes moved, or a negative error.
++ */
++struct linux64_store_req {
++ uint64_t write, off, len;
++ void *buf;
++ long result;
++};
++long linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset);
++long
++linux64_store_rw(int write, void *buffer, unsigned long length, unsigned long offset)
++{
++ struct linux64_store_req q = { .write = (uint64_t)write, .off = offset, .len = length, .buf = buffer, .result = -6 };
++
++ if (linux64_hook == 0) {
++ return -6;
++ }
++ linux64_stage_arg(819, (unsigned long)&q);
++ return q.result;
++}
++
++/*
++ * The hosted system's block disk (XnuDisk, kexts/XnuDisk): a second host file, an APFS container, served to IOKit as media.
++ * Upcall 821 returns its size in bytes (0: none), 820 reads or writes `length` bytes at `offset` (bytes moved or -errno).
++ */
++uint64_t linux64_disk_size(void);
++uint64_t
++linux64_disk_size(void)
++{
++ uint64_t size = 0;
++
++ if (linux64_hook != 0) {
++ linux64_stage_arg(821, (unsigned long)&size);
++ }
++ return size;
++}
++
++long linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset);
++long
++linux64_disk_rw(int write, void *buffer, unsigned long length, unsigned long offset)
++{
++ struct linux64_store_req q = { .write = (uint64_t)write, .off = offset, .len = length, .buf = buffer, .result = -6 };
++
++ if (linux64_hook == 0) {
++ return -6;
++ }
++ linux64_stage_arg(820, (unsigned long)&q);
++ return q.result;
++}
++
+/* From the hosted idle loop, after the host let it sleep: wake the receive thread when Linux queued frames. */
+void linux64_net_idle_poll(void);
+void
@@ -1061,21 +1130,22 @@ index cb27db6..2a73564 100644
wq_init_constrained_limit = 0;
}
diff --git a/bsd/vfs/vfs_subr.c b/bsd/vfs/vfs_subr.c
-index 229d6a1..e610b22 100644
+index 229d6a1..cb42a6f 100644
--- a/bsd/vfs/vfs_subr.c
+++ b/bsd/vfs/vfs_subr.c
-@@ -1144,7 +1144,14 @@ vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)
+@@ -1144,7 +1144,15 @@ vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)
mp->mnt_vtable = vfsp;
mp->mnt_op = vfsp->vfc_vfsops;
- mp->mnt_flag = MNT_RDONLY | MNT_ROOTFS;
+ {
+ /*
-+ * LINUX64 (xnulinux): a hosted root (the host-file disk) mounts read-write; nothing here runs the boot tasks
-+ * that would remount it (logd traps on EROFS writing /private/var/db/diagnostics).
++ * LINUX64 (xnulinux): a hosted HFS+ root (the host-file disk) mounts read-write; nothing here runs the boot
++ * tasks that would remount it (logd traps on EROFS writing /private/var/db/diagnostics). APFS refuses a
++ * writable root at mountroot ("can't mount root filesystem writeable"): an APFS root mounts read-only, as on a Mac.
+ */
+ extern uintptr_t linux64_hook;
-+ mp->mnt_flag = (linux64_hook ? 0 : MNT_RDONLY) | MNT_ROOTFS;
++ mp->mnt_flag = (linux64_hook && strcmp(vfsp->vfc_name, "hfs") == 0 ? 0 : MNT_RDONLY) | MNT_ROOTFS;
+ }
mp->mnt_vnodecovered = NULLVP;
//mp->mnt_stat.f_type = vfsp->vfc_typenum;
@@ -1179,7 +1249,7 @@ index 0cc7f6e..c07d35c 100644
DEBUG_INFO("region = %d\n", currentRegion->type);
cnt = 0;
diff --git a/iokit/Kernel/IOPlatformExpert.cpp b/iokit/Kernel/IOPlatformExpert.cpp
-index 76555f6..280d150 100644
+index 76555f6..42b940f 100644
--- a/iokit/Kernel/IOPlatformExpert.cpp
+++ b/iokit/Kernel/IOPlatformExpert.cpp
@@ -1403,15 +1403,18 @@ PESetGMTTimeOfDay(long secs)
@@ -1205,11 +1275,12 @@ index 76555f6..280d150 100644
assert(nsecs < NSEC_PER_SEC);
*usecs = nsecs / NSEC_PER_USEC;
-@@ -1540,6 +1543,100 @@ IOPlatformExpert::registerNVRAMController(IONVRAMController * caller)
+@@ -1540,6 +1543,114 @@ IOPlatformExpert::registerNVRAMController(IONVRAMController * caller)
publishResource("IONVRAM");
}
+extern "C" uintptr_t linux64_hook; /* LINUX64 (xnulinux) */
++#include <libkern/c++/OSKext.h>
+
+/*
+ * LINUX64 (xnulinux): a stand-in for AppleKeyStore's "AKSKernelServices" table, which AMFI requires (AKS_services()
@@ -1250,8 +1321,21 @@ index 76555f6..280d150 100644
+ if (!buf) {
+ return kIOReturnNoMemory;
+ }
-+ IOByteCount got = src->readBytes(0, buf, (IOByteCount)len);
-+ IOByteCount put = dst->writeBytes(0, buf, got);
++ /* the descriptors come unprepared (a real engine prepares them for its DMA): wire them for the copy, each in its
++ * own direction (AppleVirtualPlatformXART encrypts in place: one in-out descriptor as both, which a read-only
++ * preparation would keep writeBytes from) */
++ IOReturn rs = src->prepare(), rd = (src == dst) ? kIOReturnSuccess : dst->prepare();
++ IOByteCount got = 0, put = 0;
++ if (rs == kIOReturnSuccess && rd == kIOReturnSuccess) {
++ got = src->readBytes(0, buf, (IOByteCount)len);
++ put = dst->writeBytes(0, buf, got);
++ }
++ if (rs == kIOReturnSuccess) {
++ src->complete();
++ }
++ if (rd == kIOReturnSuccess && src != dst) {
++ dst->complete();
++ }
+ IOFreeData(buf, (vm_size_t)len);
+ return (got == len && put == len) ? kIOReturnSuccess : kIOReturnIOError;
+}
@@ -1306,14 +1390,25 @@ index 76555f6..280d150 100644
IOReturn
IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,
bool waitForFunction,
-@@ -1564,7 +1661,48 @@ IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,
+@@ -1564,7 +1675,63 @@ IOPlatformExpert::callPlatformFunction(const OSSymbol *functionName,
}
if (waitForFunction) {
- _resources = waitForService(resourceMatching(functionName));
++ /*
++ * LINUX64 (xnulinux): with the virtual platform's software keystore in the collection (AppleVPKeyStore, as in
++ * Apple's VirtualMac), AppleKeyStore provides AKSKernelServices itself: the stand-ins below for the SEP's
++ * endpoint and the AES engine are still needed, the stand-in table is not.
++ */
++ static int linux64_real_aks = -1;
++ if (linux64_hook && linux64_real_aks < 0) {
++ OSKext *vpks = OSKext::lookupKextWithIdentifier("com.apple.driver.AppleVPKeyStore");
++ linux64_real_aks = vpks != NULL;
++ OSSafeReleaseNULL(vpks);
++ }
+ if (linux64_hook && functionName->isEqualTo("AKSKernelServices")) {
+ static bool scrd_done;
-+ if (param1) {
++ if (param1 && !linux64_real_aks) {
+ *(void **)param1 = linux64_aks_services();
+ }
+ if (!scrd_done) {
@@ -1337,10 +1432,14 @@ index 76555f6..280d150 100644
+ OSSafeReleaseNULL(aes);
+ }
+ }
-+ IOLog("LINUX64: AKSKernelServices from the hosted stand-in\n");
-+ return kIOReturnSuccess;
++ if (!linux64_real_aks) {
++ IOLog("LINUX64: AKSKernelServices from the hosted stand-in\n");
++ return kIOReturnSuccess;
++ }
+ }
-+ if (linux64_hook) {
++ if (linux64_hook && linux64_real_aks && functionName->isEqualTo("AKSKernelServices")) {
++ _resources = waitForService(resourceMatching(functionName)); /* AppleVPKeyStore publishes it */
++ } else if (linux64_hook) {
+ /*
+ * LINUX64 (xnulinux): a hosted XNU has no providers for some platform functions (AppleKeyStore's, which AMFI
+ * waits for): wait a while, then report the function unsupported instead of blocking its caller forever.
@@ -1356,7 +1455,7 @@ index 76555f6..280d150 100644
} else {
_resources = getResourceService();
}
-@@ -2341,6 +2479,8 @@ IOPlatformDevice::getResources( void )
+@@ -2341,6 +2508,8 @@ IOPlatformDevice::getResources( void )
* the kernel with a suitable message.
*********************************************************************/
@@ -1365,7 +1464,7 @@ index 76555f6..280d150 100644
class IOPanicPlatform : IOPlatformExpert {
OSDeclareDefaultStructors(IOPanicPlatform);
-@@ -2361,6 +2501,19 @@ IOPanicPlatform::start(IOService * provider)
+@@ -2361,6 +2530,19 @@ IOPanicPlatform::start(IOService * provider)
platform_name = provider->getName();
}
diff --git a/xnu-patches/kc-keep-extra.txt b/xnu-patches/kc-keep-extra.txt
index 5e85c11..2ec3e7f 100644
--- a/xnu-patches/kc-keep-extra.txt
+++ b/xnu-patches/kc-keep-extra.txt
@@ -4,3 +4,8 @@ com.apple.iokit.IOGraphicsFamily
com.apple.filesystems.lifs
com.apple.iokit.IOMobileGraphicsFamily
com.apple.iokit.IOAVFamily
+# the keystore of Apple's virtual platform (VirtualMac): AppleKeyStore and AppleCredentialManager in software, no SEP
+# hardware; AppleVirtualPlatform is their library
+com.apple.driver.AppleVirtualPlatform
+com.apple.driver.AppleVPCredentialManager
+com.apple.driver.AppleVPKeyStore