Skip to content

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

C

Graphical session: loginwindow and SecurityAgent run, WindowServer composites

Heyang Zhou680016f9b9cf
diff --git a/kexts/XnuDisplay/XnuDisplay.cpp b/kexts/XnuDisplay/XnuDisplay.cpp
index 97300a2..7f87bf4 100644
--- a/kexts/XnuDisplay/XnuDisplay.cpp
+++ b/kexts/XnuDisplay/XnuDisplay.cpp
@@ -812,7 +812,7 @@ void XnuDisplay::program_hardware_gated()
// 8-bit BGRA, 16-bit half-float RGBA, and 'b3a8': two planes, 10-bit extended-range BGR in 32 bits and 8-bit alpha (QuartzCore's
// four_cc_to_mtl_format: Metal's format 550), what WindowServer draws with a deep framebuffer (CADeviceUseCIF10).
-static constexpr uint32_t kFormatBGRA = 'BGRA', kFormatRGhA = 'RGhA', kFormatB3A8 = 'b3a8';
+static constexpr uint32_t kFormatBGRA = 'BGRA', kFormatRGhA = 'RGhA', kFormatB3A8 = 'b3a8', kFormatLosslessBGRA = '&BGA';
// A half float's value in [0, 1] as a byte, in integer arithmetic (no floating point in the kernel).
static uint8_t halfToByte(uint16_t half)
@@ -1093,6 +1093,15 @@ void XnuDisplay::copySurface(IOSurface *surface, bool refresh)
ioSurfacePlaneBytesPerElement(surface, plane));
fSurfaceFormat = format;
}
+ // xnulinux: WindowServer's framebuffers are '&BGA' (Apple's lossless-compressed 32-bit BGRA). The CPU Metal device never
+ // compresses: plane 0 holds plain BGRA rows (the surface's own row bytes are those of the compressed layout).
+ if (format == kFormatLosslessBGRA) {
+ if (ioSurfacePlaneCount(surface) < 1 || ioSurfacePlaneBytesPerElement(surface, 0) != 4)
+ return;
+ base = ioSurfacePlaneOffset(surface, 0);
+ rowBytes = ioSurfacePlaneBytesPerRow(surface, 0);
+ format = kFormatBGRA;
+ }
if (format == kFormatB3A8) { // the colour plane; alpha is not shown
if (ioSurfacePlaneCount(surface) < 1 || ioSurfacePlaneBytesPerElement(surface, 0) != 4)
return;
diff --git a/kexts/XnuInput/XnuInput.cpp b/kexts/XnuInput/XnuInput.cpp
new file mode 100644
index 0000000..f0efaf7
--- /dev/null
+++ b/kexts/XnuInput/XnuInput.cpp
@@ -0,0 +1,248 @@
+// SPDX-License-Identifier: BSD-2-Clause-Patent
+// XnuInput: a keyboard and an absolute pointer (a tablet) for the hosted macOS, as IOHIDDevices whose reports IOHIDFamily's
+// event drivers turn into keyboard and pointer events. It follows DroidVMInput of Droid-VM/macOS-DroidVM
+// (overlay/kext/DroidVMInput/DroidVMInput.cpp, BSD-2-Clause-Patent): the same report descriptors (QEMU's USB keyboard and tablet),
+// the same evdev-to-report translation. Its events come from the host instead of virtio-input: Linux evdev records
+// {u16 type, u16 code, s32 value} that tools/hosted/xnu-input.py appends to xnu.ko's input_in file, read through the hosted
+// kernel's upcall (linux64_input_read, bsd/net/if_linux64.c). Keys (EV_KEY codes below 0x100) go to the keyboard; buttons,
+// absolute X/Y (0..32767 across the screen) and the wheel to the tablet; SYN_REPORT ends a frame.
+#include <IOKit/IOBufferMemoryDescriptor.h>
+#include <IOKit/IOLib.h>
+#include <IOKit/IOService.h>
+#include <IOKit/hid/IOHIDDevice.h>
+#include <kern/thread.h>
+
+extern "C" long linux64_input_read(void *buffer, unsigned long size);
+
+namespace {
+
+enum : uint16_t { evSyn = 0, evKey = 1, evRel = 2, evAbs = 3, synReport = 0 };
+enum : uint16_t { absX = 0x00, absY = 0x01, relWheel = 0x08, btnLeft = 0x110, btnRight = 0x111, btnMiddle = 0x112 };
+enum class Kind : uint8_t { keyboard, tablet };
+constexpr unsigned pollMs = 4;
+
+// usb_kbd_keycode of Linux (drivers/hid/usbhid/usbkbd.c): HID usage -> Linux key code; inverted at start (DroidVMInput's table).
+const uint8_t hidToLinux[256] = {
+ 0, 0, 0, 0, 30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38,
+ 50, 49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 21, 44, 2, 3,
+ 4, 5, 6, 7, 8, 9, 10, 11, 28, 1, 14, 15, 57, 12, 13, 26,
+ 27, 43, 43, 39, 40, 41, 51, 52, 53, 58, 59, 60, 61, 62, 63, 64,
+ 65, 66, 67, 68, 87, 88, 99, 70,119,110,102,104,111,107,109,106,
+ 105,108,103, 69, 98, 55, 74, 78, 96, 79, 80, 81, 75, 76, 77, 71,
+ 72, 73, 82, 83, 86,127,116,117,183,184,185,186,187,188,189,190,
+ 191,192,193,194,134,138,130,132,128,129,131,137,133,135,136,113,
+ 115,114, 0, 0, 0,121, 0, 89, 93,124, 92, 94, 95, 0, 0, 0,
+ 122,123, 90, 91, 85, 0, 0, 0, 0, 0, 0, 0,111, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 29, 42, 56,125, 97, 54,100,126,164,166,165,163,161,115,114,113,
+ 150,158,159,128,136,177,178,176,142,152,173,140,
+};
+uint8_t linuxToHid[256];
+
+// QEMU hw/input/hid.c / dev-hid.c report descriptors (as DroidVMInput).
+const uint8_t keyboardDescriptor[] = {
+ 0x05, 0x01, 0x09, 0x06, 0xa1, 0x01,
+ 0x75, 0x01, 0x95, 0x08, 0x05, 0x07, 0x19, 0xe0, 0x29, 0xe7, 0x15, 0x00, 0x25, 0x01, 0x81, 0x02,
+ 0x95, 0x01, 0x75, 0x08, 0x81, 0x01,
+ 0x95, 0x05, 0x75, 0x01, 0x05, 0x08, 0x19, 0x01, 0x29, 0x05, 0x91, 0x02,
+ 0x95, 0x01, 0x75, 0x03, 0x91, 0x01,
+ 0x95, 0x06, 0x75, 0x08, 0x15, 0x00, 0x26, 0xff, 0x00, 0x05, 0x07, 0x19, 0x00, 0x2a, 0xff, 0x00, 0x81, 0x00,
+ 0xc0,
+};
+const uint8_t tabletDescriptor[] = {
+ 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00,
+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02,
+ 0x95, 0x01, 0x75, 0x05, 0x81, 0x01,
+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x26, 0xff, 0x7f, 0x35, 0x00, 0x46, 0xff, 0x7f, 0x75, 0x10, 0x95, 0x02,
+ 0x81, 0x02,
+ 0x05, 0x01, 0x09, 0x38, 0x15, 0x81, 0x25, 0x7f, 0x35, 0x00, 0x45, 0x00, 0x75, 0x08, 0x95, 0x01, 0x81, 0x06,
+ 0xc0, 0xc0,
+};
+
+struct Event { uint16_t type, code; int32_t value; };
+static_assert(sizeof(Event) == 8, "evdev record");
+
+int8_t clamp8(int32_t v) { return static_cast<int8_t>(v < -127 ? -127 : v > 127 ? 127 : v); }
+uint16_t clamp15(int32_t v) { return static_cast<uint16_t>(v < 0 ? 0 : v > 0x7fff ? 0x7fff : v); }
+
+} // namespace
+
+class XnuHIDDevice : public IOHIDDevice {
+ OSDeclareDefaultStructors(XnuHIDDevice)
+
+public:
+ Kind fKind = Kind::keyboard;
+
+ IOReturn newReportDescriptor(IOMemoryDescriptor **descriptor) const override;
+ OSString *newTransportString() const override { return OSString::withCString("Virtual"); }
+ OSString *newManufacturerString() const override { return OSString::withCString("xnulinux"); }
+ OSString *newProductString() const override
+ {
+ return OSString::withCString(fKind == Kind::keyboard ? "xnulinux Keyboard" : "xnulinux Tablet");
+ }
+ OSNumber *newVendorIDNumber() const override { return OSNumber::withNumber(0x1209, 32); } // pid.codes' open-source vendor ID
+ OSNumber *newProductIDNumber() const override { return OSNumber::withNumber(fKind == Kind::keyboard ? 0x5801 : 0x5802, 32); }
+ OSNumber *newLocationIDNumber() const override { return OSNumber::withNumber(fKind == Kind::keyboard ? 0x58550001 : 0x58550002, 32); }
+ OSNumber *newPrimaryUsagePageNumber() const override { return OSNumber::withNumber(kHIDPage_GenericDesktop, 32); }
+ OSNumber *newPrimaryUsageNumber() const override
+ {
+ return OSNumber::withNumber(fKind == Kind::keyboard ? kHIDUsage_GD_Keyboard : kHIDUsage_GD_Mouse, 32);
+ }
+};
+
+OSDefineMetaClassAndStructors(XnuHIDDevice, IOHIDDevice)
+
+IOReturn XnuHIDDevice::newReportDescriptor(IOMemoryDescriptor **descriptor) const
+{
+ const uint8_t *bytes = fKind == Kind::keyboard ? keyboardDescriptor : tabletDescriptor;
+ size_t length = fKind == Kind::keyboard ? sizeof(keyboardDescriptor) : sizeof(tabletDescriptor);
+ *descriptor = IOBufferMemoryDescriptor::withBytes(bytes, length, kIODirectionNone);
+ return *descriptor ? kIOReturnSuccess : kIOReturnNoMemory;
+}
+
+class XnuInput : public IOService {
+ OSDeclareDefaultStructors(XnuInput)
+
+ XnuHIDDevice *fKeyboard = nullptr, *fTablet = nullptr;
+ uint8_t fModifiers = 0, fKeys[6] = {}, fLastKeyboard[8] = {};
+ int32_t fX = 0, fY = 0, fWheel = 0;
+ uint8_t fButtons = 0, fLastTablet[6] = {};
+ bool fFirstTablet = true;
+ Event fEvents[64];
+
+ XnuHIDDevice *makeDevice(Kind kind);
+ void event(const Event &e);
+ void report();
+ static void pollThread(void *self, wait_result_t);
+
+public:
+ bool start(IOService *provider) override;
+};
+
+OSDefineMetaClassAndStructors(XnuInput, IOService)
+
+XnuHIDDevice *XnuInput::makeDevice(Kind kind)
+{
+ XnuHIDDevice *device = OSTypeAlloc(XnuHIDDevice);
+ if (!device)
+ return nullptr;
+ device->fKind = kind;
+ if (!device->init(nullptr) || !device->attach(this)) {
+ device->release();
+ return nullptr;
+ }
+ if (!device->start(this)) {
+ device->detach(this);
+ device->release();
+ return nullptr;
+ }
+ return device;
+}
+
+bool XnuInput::start(IOService *provider)
+{
+ if (!IOService::start(provider))
+ return false;
+ for (unsigned usage = 0; usage < 256; usage++)
+ if (hidToLinux[usage] && !linuxToHid[hidToLinux[usage]])
+ linuxToHid[hidToLinux[usage]] = static_cast<uint8_t>(usage);
+ fKeyboard = makeDevice(Kind::keyboard);
+ fTablet = makeDevice(Kind::tablet);
+ if (!fKeyboard || !fTablet) {
+ IOLog("XnuInput: cannot start the HID devices (keyboard %p, tablet %p)\n", fKeyboard, fTablet);
+ return false;
+ }
+ registerService();
+ thread_t thread;
+ if (kernel_thread_start(pollThread, this, &thread) != KERN_SUCCESS)
+ return false;
+ thread_deallocate(thread);
+ IOLog("XnuInput: keyboard and tablet, events from the host's input_in\n");
+ return true;
+}
+
+void XnuInput::event(const Event &e)
+{
+ if (e.type == evSyn) {
+ if (e.code == synReport)
+ report();
+ return;
+ }
+ if (e.type == evKey && e.code < 0x100) {
+ if (e.value == 2) // autorepeat: the event system repeats on its own
+ return;
+ uint8_t usage = linuxToHid[e.code];
+ if (usage >= 0xe0) {
+ uint8_t mask = static_cast<uint8_t>(1 << (usage - 0xe0));
+ fModifiers = e.value ? fModifiers | mask : fModifiers & ~mask;
+ } else if (usage) {
+ for (auto &key : fKeys)
+ if (key == usage)
+ key = 0;
+ for (auto &key : fKeys)
+ if (e.value && !key) {
+ key = usage;
+ break;
+ }
+ }
+ } else if (e.type == evKey) {
+ uint8_t mask = e.code == btnLeft ? 1 : e.code == btnRight ? 2 : e.code == btnMiddle ? 4 : 0;
+ fButtons = e.value ? fButtons | mask : fButtons & ~mask;
+ } else if (e.type == evAbs) {
+ if (e.code == absX)
+ fX = e.value;
+ else if (e.code == absY)
+ fY = e.value;
+ } else if (e.type == evRel && e.code == relWheel) {
+ fWheel += e.value;
+ }
+}
+
+// At the end of a frame: a report from each device whose state changed.
+void XnuInput::report()
+{
+ uint8_t keyboard[8] = {fModifiers, 0};
+ memcpy(keyboard + 2, fKeys, sizeof(fKeys));
+ if (memcmp(keyboard, fLastKeyboard, sizeof(keyboard))) {
+ memcpy(fLastKeyboard, keyboard, sizeof(keyboard));
+ if (IOBufferMemoryDescriptor *r = IOBufferMemoryDescriptor::withBytes(keyboard, sizeof(keyboard), kIODirectionNone)) {
+ fKeyboard->handleReport(r);
+ r->release();
+ }
+ }
+ uint16_t x = clamp15(fX), y = clamp15(fY);
+ int8_t wheel = clamp8(fWheel);
+ fWheel = 0;
+ uint8_t tablet[6] = {fButtons, static_cast<uint8_t>(x), static_cast<uint8_t>(x >> 8), static_cast<uint8_t>(y),
+ static_cast<uint8_t>(y >> 8), static_cast<uint8_t>(wheel)};
+ if (fFirstTablet || wheel || memcmp(tablet, fLastTablet, sizeof(tablet))) {
+ fFirstTablet = false;
+ memcpy(fLastTablet, tablet, sizeof(tablet));
+ if (IOBufferMemoryDescriptor *r = IOBufferMemoryDescriptor::withBytes(tablet, sizeof(tablet), kIODirectionNone)) {
+ fTablet->handleReport(r);
+ r->release();
+ }
+ }
+}
+
+void XnuInput::pollThread(void *self, wait_result_t)
+{
+ XnuInput *input = static_cast<XnuInput *>(self);
+ for (;;) {
+ long bytes = linux64_input_read(input->fEvents, sizeof(input->fEvents));
+ for (long i = 0; i + 8 <= bytes; i += 8)
+ input->event(input->fEvents[i / 8]);
+ if (bytes < static_cast<long>(sizeof(input->fEvents)))
+ IOSleep(pollMs);
+ }
+}
+
+// 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/XnuInput/XnuInput.json b/kexts/XnuInput/XnuInput.json
new file mode 100644
index 0000000..9c70bde
--- /dev/null
+++ b/kexts/XnuInput/XnuInput.json
@@ -0,0 +1,41 @@
+{
+ "name": "XnuInput",
+ "bundle": "org.xnulinux.driver.XnuInput",
+ "version": "1.0.0",
+ "objects": "out/x12377/native-kexts/XnuInput/objects.json",
+ "start": "_native_kext_start",
+ "stop": "_native_kext_stop",
+ "libraries": {
+ "com.apple.iokit.IOHIDFamily": "2.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.unsupported": "18.0.0"
+ },
+ "personalities": {
+ "XnuInput": {
+ "CFBundleIdentifier": "org.xnulinux.driver.XnuInput",
+ "IOClass": "XnuInput",
+ "IOProviderClass": "IOResources",
+ "IOResourceMatch": "IOKit",
+ "IOMatchCategory": "XnuInput"
+ },
+ "XnuHIDEventDriver": {
+ "CFBundleIdentifier": "com.apple.iokit.IOHIDFamily",
+ "IOClass": "IOHIDEventDriver",
+ "IOProviderClass": "IOHIDInterface",
+ "VendorID": 4617,
+ "IOProbeScore": 3000
+ }
+ },
+ "vtable": {
+ "class": "XnuHIDDevice",
+ "base": "IOHIDDevice",
+ "base_kext": "com.apple.iokit.IOHIDFamily",
+ "slots": 334,
+ "ignore_slots": [
+ 16
+ ]
+ }
+}
diff --git a/scripts/kc-amfi-platform.py b/scripts/kc-amfi-platform.py
index 46a65af..1945df7 100644
--- a/scripts/kc-amfi-platform.py
+++ b/scripts/kc-amfi-platform.py
@@ -10,12 +10,22 @@ AMFI keeps the expected version in a 32-bit global, read by a small accessor tha
logs that message. This finds the message, the accessor called just before its use, the global the accessor loads, and
writes the given version there. It changes nothing when the value is already the requested one.
+It also turns off AMFI's version restriction, which the same mismatch trips: 27.2's AMFI refuses to run some Apple
+programs unless they carry a com.apple.private.amfi.version-restriction entitlement of at least a given version (a table
+of signing identifiers and versions, e.g. com.apple.SecurityAgent). Programs of an older macOS do not carry it, and AMFI
+kills them at exec ("com.apple.SecurityAgent disallowed without correct ... entitlement version"); SecurityAgent runs
+loginwindow's login mechanisms, so no graphical session starts. The check function starts with a fast path that allows
+every process without one flag (`bti c; tbnz w1, #N, slow; mov w0, #1; ret`); the tbnz becomes a nop, so the check
+always allows.
+
kc-amfi-platform.py KC VERSION
"""
import struct
import sys
MESSAGE = b'%s: platformVersion %u is lower than expected version %u.'
+VR_MESSAGE = b'%s: %s disallowed without correct com.apple.private.amfi.version-restriction entitlement version'
+NOP = 0xd503201f
def segments(d):
@@ -91,6 +101,29 @@ def accessor_global(d, segs, fva):
return adrp_page(w1, fva + 4) + ((w2 >> 10) & 0xfff) * 4
+def version_restriction_check(d, segs):
+ """File offset of the version-restriction check's fast-path tbnz (or of the nop already there), or None."""
+ at = d.find(VR_MESSAGE + b'\0')
+ if at < 0:
+ return None
+ found = set()
+ for pc, fo in string_xrefs(d, segs, file_to_va(segs, at)):
+ for back in range(1, 8): # bl check; tbnz w0, #0, allowed; ... adrp x3, message
+ w = word(d, fo - 4 * back)
+ if (w & 0xfc000000) != 0x94000000:
+ continue
+ imm = w & 0x3ffffff
+ if imm & 0x2000000:
+ imm -= 1 << 26
+ ffo = va_to_file(segs, pc - 4 * back + imm * 4)
+ if ffo is None or word(d, ffo) != 0xd503245f: # bti c
+ continue
+ t, m, r = word(d, ffo + 4), word(d, ffo + 8), word(d, ffo + 12)
+ if m == 0x52800020 and r == 0xd65f03c0 and ((t & 0x7f00001f) == 0x37000001 or t == NOP): # tbnz w1 / nop; mov w0, #1; ret
+ found.add(ffo + 4)
+ return found.pop() if len(found) == 1 else None
+
+
def main():
path, version = sys.argv[1], int(sys.argv[2])
d = bytearray(open(path, 'rb').read())
@@ -117,10 +150,20 @@ def main():
old = struct.unpack_from('<I', d, gfo)[0]
if not 10 <= old <= 60:
sys.exit('kc-amfi-platform: implausible expected platform version %d at %#x' % (old, g))
- if old != version:
+ changed = old != version
+ if changed:
struct.pack_into('<I', d, gfo, version)
- open(path, 'wb').write(d)
print('kc-amfi-platform: AMFI expected platform version at %#x: %d -> %d' % (g, old, version))
+ vr = version_restriction_check(d, segs)
+ if vr is None:
+ print('kc-amfi-platform: AMFI version-restriction check not found: left as it is')
+ else:
+ if word(d, vr) != NOP:
+ struct.pack_into('<I', d, vr, NOP)
+ changed = True
+ print('kc-amfi-platform: AMFI version-restriction check at %#x: always allows' % file_to_va(segs, vr))
+ if changed:
+ open(path, 'wb').write(d)
if __name__ == '__main__':
diff --git a/scripts/mk-gui-extras.sh b/scripts/mk-gui-extras.sh
new file mode 100755
index 0000000..ca33ccf
--- /dev/null
+++ b/scripts/mk-gui-extras.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# On the macOS host (tokyo), with no hosted XNU running from the disk: add what a graphical session needs to the golden
+# full disk (/var/tmp/full.img in the xnupoc VM) that scripts/mk-fulldisk.sh leaves out. Apple's files stream from this
+# host into the VM's image and stay there (never in the repo).
+# - the App cryptex (Safari and its helpers: /System/Volumes/Preboot/Cryptexes/App)
+# - /System/Applications (Finder's and the Dock's apps: System Settings, Terminal, Preview, ...)
+# - /System/Cryptexes/{OS,App}: the links a real Mac has to the cryptexes in Preboot. dyld finds the OS cryptex's own
+# dylibs (/System/Cryptexes/OS/usr/lib, e.g. libLaunchServicesSupport.dylib, which loginwindow and the Dock link)
+# only through this graft point; without it loginwindow stops at launch ("Library not loaded").
+# - /Applications/Safari.app, the link into the App cryptex
+set -euo pipefail
+cd "$(dirname "$0")/.."
+V="bash scripts/vm.sh"
+IMG=/var/tmp/full.img
+$V "set -e; sudo dmsetup remove xnusys 2>/dev/null || true; for l in \$(losetup -j $IMG -O NAME -n); do sudo losetup -d \$l; done
+ sudo fsck.hfsplus -fy $IMG 2>&1 | tail -1; sudo mkdir -p /mnt/full; sudo mount -o loop,rw,force -t hfsplus $IMG /mnt/full"
+t0=$(date +%s)
+cd /
+sudo -n tar -c -f - --no-mac-metadata --no-xattrs --no-acls System/Volumes/Preboot/Cryptexes/App System/Applications 2> /tmp/mk-gui-extras.err \
+ | bash ~-/scripts/vm.sh "sudo tar -x -p -f - -C /mnt/full --warning=no-unknown-keyword 2>&1 | tail -5" \
+ || echo "host tar ended nonzero (see /tmp/mk-gui-extras.err)"
+cd ~-
+echo "streamed in $(( $(date +%s) - t0 ))s; host tar warnings: $(wc -l < /tmp/mk-gui-extras.err)"
+LINKS="OS App" # not Rosetta: the hosted system has no x86_64 support and presents itself as a Mac without Rosetta
+$V "set -e; sudo mkdir -p /mnt/full/System/Cryptexes /mnt/full/Applications
+ for c in $LINKS; do [ -e /mnt/full/System/Cryptexes/\$c ] || sudo ln -s ../../System/Volumes/Preboot/Cryptexes/\$c /mnt/full/System/Cryptexes/\$c; done
+ [ -e /mnt/full/Applications/Safari.app ] || sudo ln -s ../System/Cryptexes/App/System/Applications/Safari.app /mnt/full/Applications/Safari.app
+ ls -la /mnt/full/System/Cryptexes | tail -n +2; ls /mnt/full/System/Cryptexes/OS/usr/lib | head -3; ls -d /mnt/full/Applications/Safari.app/Contents/MacOS/Safari
+ echo \"\$(ls /mnt/full/System/Applications | wc -l) apps in /System/Applications\"; df -h /mnt/full | tail -1
+ sudo umount /mnt/full; sudo fsck.hfsplus -fy $IMG 2>&1 | tail -1; sync"
diff --git a/scripts/vm-gpu-prep.sh b/scripts/vm-gpu-prep.sh
index 0c658dc..1ed45ce 100644
--- a/scripts/vm-gpu-prep.sh
+++ b/scripts/vm-gpu-prep.sh
@@ -9,6 +9,11 @@ sudo mkdir -p /mnt/sys/Library/GPUBundles
sudo rm -rf /mnt/sys/Library/GPUBundles/XnuCpuMetal.bundle
sudo tar -C /mnt/sys/Library/GPUBundles --no-same-owner -xzf /var/tmp/XnuCpuMetal.bundle.tgz
sudo chown -R 0:0 /mnt/sys/Library/GPUBundles
+# lavapipe's ICD manifest where the Vulkan loader looks in every process: it ignores VK_ICD_FILENAMES (the plugin's own
+# pointer to the bundle's manifest) in processes like WindowServer ("Found no drivers!"), and searches only system
+# directories such as /usr/local/share/vulkan/icd.d
+sudo mkdir -p /mnt/sys/usr/local/share/vulkan/icd.d
+printf '{"file_format_version":"1.0.1","ICD":{"library_path":"/Library/GPUBundles/XnuCpuMetal.bundle/Contents/Frameworks/libvulkan_lvp.dylib","api_version":"1.4.363"}}\n' | sudo tee /mnt/sys/usr/local/share/vulkan/icd.d/xnu_lvp_icd.aarch64.json >/dev/null
sudo du -sh /mnt/sys/Library/GPUBundles/XnuCpuMetal.bundle
df -h /mnt/sys | tail -1
sudo umount /mnt/sys; sudo fsck.hfsplus -fy $IMG | tail -1
diff --git a/scripts/vm-gui-prep.sh b/scripts/vm-gui-prep.sh
new file mode 100644
index 0000000..5e336c8
--- /dev/null
+++ b/scripts/vm-gui-prep.sh
@@ -0,0 +1,78 @@
+#!/bin/bash
+# In the VM: make the golden full disk boot into a graphical session.
+# - loginwindow back in /System/Library/LaunchDaemons (earlier disks parked it). logind starts it when it opens the console
+# session at boot; with loginwindow absent then, logind's SOStartSessionWithOptions dies (_xpc_api_misuse) and no
+# later restart of logind or WindowServer opens the session again.
+# - one local administrator made here (never copied from the host): name GUI_USER (xnu), password GUI_PASSWORD (xnulinux),
+# uid 501, home from the system's own user template, member of admin and staff
+# - 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
+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
+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
+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 c310e5d..4acc0ed 100755
--- a/scripts/vm-m2-kbisect.sh
+++ b/scripts/vm-m2-kbisect.sh
@@ -14,10 +14,11 @@ fi
# XNU's DRAM is one physically contiguous block (GBs): free the page cache and compact first, or the allocation fails
sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/null
[ -n "${FB_DUMP:-}" ] && { : > "$FB_DUMP"; } # xnu.ko writes the framebuffer into this existing file
+[ -n "${INPUT_IN:-}" ] && { touch "$INPUT_IN"; } # input events for XnuInput (tools/hosted/xnu-input.py appends)
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} ${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} ${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-sysdisk-launchd.sh b/scripts/vm-sysdisk-launchd.sh
index 0590d60..e486e25 100755
--- a/scripts/vm-sysdisk-launchd.sh
+++ b/scripts/vm-sysdisk-launchd.sh
@@ -20,12 +20,13 @@ if [ "${MODE:-launchd}" = launchd ]; then
[ -e /mnt/sys/private/var/select/sh ] || sudo ln -s /bin/bash /mnt/sys/private/var/select/sh
[ -e /mnt/sys/private/var/select/developer_dir ] || sudo ln -s /Applications/Xcode.app/Contents/Developer /mnt/sys/private/var/select/developer_dir
# no third-party software of the host (its own /Library/LaunchDaemons, /usr/local); GUI and hardware-only
- # daemons (no watchdog hardware; loginwindow until the graphical session works) are parked in /private/var/xnulinux-parked
- # (DISABLE adds more). WindowServer stays: it drives XnuDisplay (kexts/XnuDisplay).
+ # daemons (no watchdog hardware) are parked in /private/var/xnulinux-parked
+ # (DISABLE adds more). WindowServer and loginwindow stay: they drive XnuDisplay (kexts/XnuDisplay); the user and
+ # automatic login come from scripts/vm-gui-prep.sh.
sudo rm -rf /mnt/sys/usr/local
sudo find /mnt/sys/Library/LaunchDaemons /mnt/sys/Library/LaunchAgents -name '*.plist' ! -name 'com.apple.*' -delete 2>/dev/null || true
sudo mkdir -p /mnt/sys/private/var/xnulinux-parked
- for d in com.apple.loginwindow com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServices com.apple.PerfPowerServicesExtended ${DISABLE:-}; do
+ for d in com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServices com.apple.PerfPowerServicesExtended ${DISABLE:-}; do
[ -e /mnt/sys/System/Library/LaunchDaemons/$d.plist ] && sudo mv /mnt/sys/System/Library/LaunchDaemons/$d.plist /mnt/sys/private/var/xnulinux-parked/
done
else
diff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.sh
index d4b38d7..7ccb710 100755
--- a/scripts/vm-xnu-rebuild.sh
+++ b/scripts/vm-xnu-rebuild.sh
@@ -28,10 +28,16 @@ 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
+ for h in toolchains/sdks/*.sdk/System/Library/Frameworks/Kernel.framework/Headers/IOKit/hid; do
+ [ -e $h/IOHIDDevice.h ] && { ln -sfn $PWD/$h $NETINC/IOKit/hid; ln -sfn $PWD/$h/../hidsystem $NETINC/IOKit/hidsystem; ln -sfn $PWD/$h/../graphics $NETINC/IOKit/graphics
+ ln -sfn $PWD/${h%%/System/*}/usr/include/TargetConditionals.h $NETINC/TargetConditionals.h; break; }
+ done
for j in ~/w/poc/kexts/*/*.json; do
[ -e "$j" ] || continue
n=$(basename $j .json)
- python3 scripts/build-native-kext.py $n $(dirname $j)/$n.cpp -I $NETINC --obj ${KEXT_OBJ:-k27-obj}
+ # a kext that does not build is left out of the collection (reported), not the whole rebuild
+ python3 scripts/build-native-kext.py $n $(dirname $j)/$n.cpp -I $NETINC --obj ${KEXT_OBJ:-k27-obj} || { echo "kext $n failed to build: left out"; continue; }
NATIVE="$NATIVE $j"
done
K27_NO_BOOT=1 NATIVE="$NATIVE" bash k27/try.sh 0 2>&1 | tail -3
diff --git a/tools/hosted/xnu-input.py b/tools/hosted/xnu-input.py
new file mode 100644
index 0000000..e64cc0c
--- /dev/null
+++ b/tools/hosted/xnu-input.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+"""Send keyboard and pointer input to the hosted macOS (XnuInput): Linux evdev records appended to xnu.ko's input_in.
+
+ xnu-input.py [--file /var/tmp/xnu-input] [--screen 1280x800] COMMAND ...
+ move X Y pointer to pixel X,Y
+ click [X Y] left click (at X,Y)
+ rclick [X Y] right click
+ drag X1 Y1 X2 Y2 left-button drag
+ scroll N wheel N notches (negative: down)
+ type TEXT type TEXT (US layout)
+ key NAME... press and release keys together (e.g. key cmd space, key return)
+ sleep SECONDS
+Several commands can follow one another: xnu-input.py click 640 400 type hello key return
+"""
+import struct, sys, time
+
+EV_SYN, EV_KEY, EV_REL, EV_ABS = 0, 1, 2, 3
+BTN = {'left': 0x110, 'right': 0x111, 'middle': 0x112}
+KEYS = { # Linux key codes (input-event-codes.h)
+ 'esc': 1, 'escape': 1, 'backspace': 14, 'delete': 14, 'tab': 15, 'return': 28, 'enter': 28, 'ctrl': 29, 'control': 29,
+ 'shift': 42, 'rshift': 54, 'alt': 56, 'option': 56, 'space': 57, 'capslock': 58, 'cmd': 125, 'command': 125,
+ 'rcmd': 126, 'up': 103, 'left': 105, 'right': 106, 'down': 108, 'home': 102, 'end': 107, 'pageup': 104,
+ 'pagedown': 109, 'forwarddelete': 111,
+ **{f'f{i}': c for i, c in zip(range(1, 11), range(59, 69))}, 'f11': 87, 'f12': 88,
+}
+for i, ch in enumerate('1234567890'):
+ KEYS[ch] = 2 + i
+for row, start in (('qwertyuiop', 16), ('asdfghjkl', 30), ('zxcvbnm', 44)):
+ for i, ch in enumerate(row):
+ KEYS[ch] = start + i
+PLAIN = {'-': 12, '=': 13, '[': 26, ']': 27, ';': 39, "'": 40, '`': 41, '\\': 43, ',': 51, '.': 52, '/': 53, ' ': 57,
+ '\n': 28, '\t': 15}
+SHIFTED = {'!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-',
+ '+': '=', '{': '[', '}': ']', ':': ';', '"': "'", '~': '`', '|': '\\', '<': ',', '>': '.', '?': '/'}
+
+
+class Input:
+ def __init__(self, path, width, height):
+ self.out, self.w, self.h = open(path, 'ab', buffering=0), width, height
+
+ def ev(self, t, c, v):
+ self.out.write(struct.pack('<HHi', t, c, v))
+
+ def syn(self):
+ self.ev(EV_SYN, 0, 0)
+ time.sleep(0.02)
+
+ def move(self, x, y):
+ self.ev(EV_ABS, 0, int(x * 32767 / (self.w - 1)))
+ self.ev(EV_ABS, 1, int(y * 32767 / (self.h - 1)))
+ self.syn()
+
+ def button(self, name, down):
+ self.ev(EV_KEY, BTN[name], 1 if down else 0)
+ self.syn()
+
+ def keys(self, codes):
+ for c in codes:
+ self.ev(EV_KEY, c, 1)
+ self.syn()
+ for c in reversed(codes):
+ self.ev(EV_KEY, c, 0)
+ self.syn()
+
+ def type(self, text):
+ for ch in text:
+ if ch in SHIFTED:
+ self.keys([KEYS['shift'], KEYS.get(SHIFTED[ch]) or PLAIN[SHIFTED[ch]]])
+ elif ch.isupper():
+ self.keys([KEYS['shift'], KEYS[ch.lower()]])
+ elif ch in KEYS:
+ self.keys([KEYS[ch]])
+ elif ch in PLAIN:
+ self.keys([PLAIN[ch]])
+
+
+def main(argv):
+ path, screen = '/var/tmp/xnu-input', '1280x800'
+ while argv and argv[0].startswith('--'):
+ opt, value = argv[0], argv[1]
+ argv = argv[2:]
+ if opt == '--file':
+ path = value
+ elif opt == '--screen':
+ screen = value
+ w, h = (int(v) for v in screen.split('x'))
+ d = Input(path, w, h)
+ i = 0
+ while i < len(argv):
+ cmd = argv[i]; i += 1
+ if cmd == 'move':
+ d.move(float(argv[i]), float(argv[i + 1])); i += 2
+ elif cmd in ('click', 'rclick'):
+ if i + 1 < len(argv) and argv[i].replace('.', '').isdigit():
+ d.move(float(argv[i]), float(argv[i + 1])); i += 2
+ b = 'left' if cmd == 'click' else 'right'
+ d.button(b, True); d.button(b, False)
+ elif cmd == 'drag':
+ x1, y1, x2, y2 = (float(v) for v in argv[i:i + 4]); i += 4
+ d.move(x1, y1); d.button('left', True)
+ for s in range(1, 11):
+ d.move(x1 + (x2 - x1) * s / 10, y1 + (y2 - y1) * s / 10)
+ d.button('left', False)
+ elif cmd == 'scroll':
+ d.ev(EV_REL, 8, int(argv[i])); d.syn(); i += 1
+ elif cmd == 'type':
+ d.type(argv[i]); i += 1
+ elif cmd == 'key':
+ names = []
+ while i < len(argv) and argv[i] in KEYS:
+ names.append(KEYS[argv[i]]); i += 1
+ d.keys(names)
+ elif cmd == 'sleep':
+ time.sleep(float(argv[i])); i += 1
+ else:
+ sys.exit(f'unknown command {cmd}')
+
+
+if __name__ == '__main__':
+ main(sys.argv[1:])
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index f24febb..37373f2 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -92,6 +92,13 @@ static char *console_in;
module_param(console_in, charp, 0444);
static void *ci_file; static fki_u64 ci_off;
struct xnu_cons_req { void *buf; u64_t len; long result; };
+/*
+ * Input events for XnuInput (kexts/XnuInput): a host file of 8-byte records {u16 type, u16 code, s32 value} as Linux's evdev
+ * (tools/hosted/xnu-input.py appends them); upcall 818 reads the whole records written since the load.
+ */
+static char *input_in;
+module_param(input_in, charp, 0444);
+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; };
struct xnu_net_req { void *buf; u64_t len; long result; };
@@ -329,6 +336,16 @@ static long xnu_hook_body(unsigned long stage, unsigned long a1, unsigned long a
}
return 0;
}
+ if (stage == 818) { /* input events: whole 8-byte records of input_in, into q->buf */
+ struct xnu_cons_req *q = (struct xnu_cons_req *)a1;
+ if (!q) return 0;
+ q->result = 0;
+ if (in_file && q->len >= 8) {
+ long n = fki_file_rw(in_file, 0, q->buf, (unsigned long)(q->len & ~7ULL), in_off);
+ if (n > 0) { n &= ~7L; in_off += n; q->result = n; }
+ }
+ return 0;
+ }
if (stage == 815) { /* frames Linux sent on xnu0 waiting for XNU, into *a1 */
if (a1) *(u64_t *)a1 = (u64_t)fki_net_pending();
return 0;
@@ -888,6 +905,12 @@ 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 (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 (hostdisk) {
hd_file = fki_file_open(hostdisk, hostdisk_rw, &hd_size);
if (!hd_file) { logs("xnu: cannot open the host disk"); return -2; }
@@ -926,6 +949,7 @@ static void __exit xnu_exit(void)
if (tc_blob) fki_blob_put(tc_blob);
if (hd_file) fki_file_close(hd_file);
if (ci_file) fki_file_close(ci_file);
+ if (in_file) fki_file_close(in_file);
}
module_init(xnu_init);
diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patch
index ee41ac8..a48d46e 100644
--- a/xnu-patches/0001-linux64-stage-hook.patch
+++ b/xnu-patches/0001-linux64-stage-hook.patch
@@ -506,10 +506,25 @@ index 6e740c2..bfbdd29 100644
/* consumes reason */
return exit_with_reason(p, W_EXITCODE(0, SIGKILL), NULL,
diff --git a/bsd/kern/kern_mman.c b/bsd/kern/kern_mman.c
-index 32d27c9..8f9bc0c 100644
+index 32d27c9..20aa26b 100644
--- a/bsd/kern/kern_mman.c
+++ b/bsd/kern/kern_mman.c
-@@ -669,7 +669,9 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)
+@@ -487,7 +487,13 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)
+ /*
+ * Entitlement check.
+ */
+- error = mac_proc_check_map_anon(p, current_cached_proc_cred(p),
++ /*
++ * LINUX64 (xnulinux): under amfi_get_out_of_my_way a JIT mapping is let through without the JIT entitlement, as
++ * AMFI's other verdicts on code are (F_CHECK_LV, executable mmap): the CPU Metal device (Mesa's llvmpipe) compiles
++ * shaders to machine code in every Metal client, WindowServer included, which is hardened and not JIT-entitled.
++ */
++ extern int linux64_amfi_off(void);
++ error = ((flags & MAP_JIT) && linux64_amfi_off()) ? 0 : mac_proc_check_map_anon(p, current_cached_proc_cred(p),
+ user_addr, user_size, prot, flags, &maxprot);
+ if (error) {
+ return EINVAL;
+@@ -669,7 +675,9 @@ mmap(proc_t p, struct mmap_args *uap, user_addr_t *retval)
handle = (void *)vp;
#if CONFIG_MACF
@@ -732,10 +747,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..55fe82d
+index 0000000..461d993
--- /dev/null
+++ b/bsd/net/if_linux64.c
-@@ -0,0 +1,239 @@
+@@ -0,0 +1,256 @@
+/*
+ * LINUX64 (xnulinux): the hosted kernel's Ethernet interface en0.
+ *
@@ -901,6 +916,23 @@ index 0000000..55fe82d
+ return q.result > 0 ? q.result : 0;
+}
+
++/*
++ * The host's input events for the IOKit HID driver (kexts/XnuInput), through the same kind of upcall: whole 8-byte evdev
++ * records {u16 type, u16 code, s32 value} into buffer, their bytes (0 when none wait).
++ */
++long linux64_input_read(void *buffer, unsigned long size);
++long
++linux64_input_read(void *buffer, unsigned long size)
++{
++ struct linux64_net_req q = { .buf = buffer, .len = size, .result = 0 };
++
++ if (linux64_hook == 0) {
++ return 0;
++ }
++ linux64_stage_arg(818, (unsigned long)&q);
++ return q.result > 0 ? q.result : 0;
++}
++
+/* 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