Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Emulate scalar CSSC in the kernel and abort failed X1 boot patches

Phineas Guoab4c7c81dd68
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index a131457b..00b78fe8 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1,5 +1,17 @@
# Patch Comparison: Regular / Development / Jailbreak / Experimental
+> **CSSC kernel compatibility experiment (2026-10-25).**
+> `kernel-boot-cssc_emulation` targets iOS 27 with cloudOS 26.4. It reuses the
+> kernel's undefined-instruction copyin, PAC-safe interrupt helpers and
+> signed-state check/sign ABI. Only known EL0 scalar CSSC words are evaluated;
+> unknown faults retain native triage. The single baseline-A64 payload occupies
+> persistent kernel text; no userland/cache CSSC trampolines or writable code
+> pages are introduced. Existing X1 PAuth/CPA lowering remains unchanged.
+> Selected X1 boot patch failures abort installation, and an unresolved CSSC
+> kernel handler aborts kernel preparation. TV and HomePod presets exclude
+> this operation. See `Research/Guest/iphone_duo_bringup.md` for the reveal
+> procedure and signed-state handling.
+
> **HomePod local app installation (2026-10-23).**
> `system-installd-exp-homepod_adhoc` is selected only by `homepod-mini` on
> HomePod 27. It loads a dedicated TVOS arm64e build of the existing MIS
diff --git a/Research/Guest/iphone_duo_bringup.md b/Research/Guest/iphone_duo_bringup.md
index 9f29eae7..752b576e 100644
--- a/Research/Guest/iphone_duo_bringup.md
+++ b/Research/Guest/iphone_duo_bringup.md
@@ -1,5 +1,47 @@
# iPhone Duo single-display bring-up
+## Kernel CSSC fallback (2026-10-25)
+
+This branch starts from upstream main, without the static CSSC trampoline
+experiment. On an independent Banana clone, the installed experimental image
+panicked with PID 1 SIGILL at user PC 0x2bd6380e8, ESR 0x02000000. The kernel's
+exception codes contained the copied instruction 0xdac1a7fe (PACIBSPPC), matching
+/usr/lib/libSystem.B.dylib at image offset 0x10e8. CSSC allocation had aborted
+the entire X1 cache operation, leaving PAuth/CPA conversion unapplied; the
+installer nevertheless continued. The new route retains upstream PAuth/CPA
+conversion and handles CSSC independently in the kernel.
+
+Reveal procedure for `kernelcache.research.vphone600`, UUID
+784F88D3-2AF5-3D4A-AB00-365607646E44:
+
+1. Find the unique function referencing `Undefined kernel instruction: pc=%p
+ instr=%x`. Identify it as XNU handle_uncategorized by decoded control flow,
+ not a recovered symbol (the indexed research symbol JSON is absent).
+2. Validate its copyin of four bytes from the saved PC and its EL0/EL1 gate.
+ Hook only the user path before undefined-instruction triage. The observed
+ handler file offset is 0x1e626ec; the hook is 0x1e62918.
+3. Follow the handler's existing signed-state manipulation sequence to recover
+ ml_check_signed_state (0x1caa37c), ml_sign_thread_state (0x1caa32c) and its
+ interrupt disable/restore helpers. Validate register and saved-state ABI,
+ PACGA bodies, and the original stack-canary checked epilogue. These names
+ are source correlations; offsets are observations, never runtime constants.
+4. Plan the complete fixed-size payload and one entry branch before writing.
+ Restrict it to persistent __TEXT_EXEC; do not use boot-only reclaimed text.
+ Unknown or ambiguous layouts abort the selected operation.
+
+The fallback accepts only 64-bit user saved states with an uncategorized
+exception and successful instruction copyin. It evaluates scalar ABS/CNT/CTZ
+and signed/unsigned MIN/MAX register and immediate forms, preserving the
+saved NZCV and all unrelated registers. W results zero-extend and register 31
+is ZR. A successful operation verifies the old signed state, updates the
+destination and PC, and re-signs with the new LR/X16/X17 when applicable.
+There are no stack accesses while SPSel selects the interrupt stack. The
+original canary check and epilogue remain in use. Unknown words preserve the
+original instruction, registers, kernel flags and exception path.
+
+Kernel emulation has per-execution exception overhead. Native CSSC execution
+does not enter this fallback; PAuth/CPA retain the existing X1 conversion path.
+
## Scope and inputs (2026-10-23)
This experiment attempts to boot the iPhone Duo userland on the existing
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchCSSC.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchCSSC.swift
new file mode 100644
index 00000000..b8b87bc0
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchCSSC.swift
@@ -0,0 +1,240 @@
+import Foundation
+import VPhonePatchKit
+
+extension KernelCustomFirmwarePatcher {
+ struct CSSCHandler {
+ let hook: Int
+ let epilogue: Int
+ let context: UInt32
+ let word: UInt32
+ let displacedRegister: UInt32
+ let displacedImmediate: UInt16
+ let pc: UInt32
+ let check: Int
+ let sign: Int
+ let disableInterrupts: Int
+ let restoreInterrupts: Int
+ }
+
+ /// Reveal from the actual kernel's undefined-instruction handler. The
+ /// copyin and signed-state helpers must all resolve before any write.
+ func revealCSSCHandler() -> CSSCHandler? {
+ guard let range = kernTextRange,
+ let anchor = buffer.findString("Undefined kernel instruction: pc=%p instr=%x") else { return nil }
+ let refs = findStringRefs(anchor, in: (range.0, range.1))
+ var starts = Set<Int>()
+ for ref in refs {
+ let low = max(range.0, ref.adrpOff - 0x800)
+ let prefix = disasm.disassemble(in: buffer.original, at: low, count: (ref.adrpOff - low) / 4)
+ if let start = prefix.last(where: { $0.mnemonic == "pacibsp" }) { starts.insert(Int(start.address)) }
+ }
+ guard starts.count == 1, let start = starts.first else { return nil }
+ var i = disasm.disassemble(in: buffer.original, at: start, count: min(0x800, range.1 - start) / 4)
+ if let next = i.dropFirst().firstIndex(where: { $0.mnemonic == "pacibsp" }) { i = Array(i[..<next]) }
+ guard i.count > 30 else { return nil }
+
+ func reg(_ op: ARM64Operand?) -> UInt32? {
+ guard let op, op.type == .register else { return nil }
+ return (0..<31).first(where: { op.reg == .x($0) || op.reg == .w($0) }).map(UInt32.init)
+ }
+ func load(_ item: ARM64Instruction, rt: ARM64Register, base: ARM64Register, offset: Int64) -> Bool {
+ guard item.mnemonic == "ldr", let o = item.detail?.operands, o.count == 2 else { return false }
+ return o[0].reg == rt && o[1].type == .memory && o[1].mem.base == base && o[1].mem.disp == offset
+ }
+ func target(_ item: ARM64Instruction, _ name: String) -> Int? {
+ guard item.mnemonic == name, let o = item.detail?.operands.last, o.type == .immediate else { return nil }
+ return Int(exactly: o.imm)
+ }
+ // System-register names are not exposed by ARM64Operand; use its
+ // printed system operand only here, never for GPRs or memory operands.
+ func stackSelect(_ item: ARM64Instruction, _ value: Int64) -> Bool {
+ item.mnemonic == "msr" && item.operandString.split(separator: ",").first?.lowercased() == "spsel"
+ && item.detail?.operands.last?.imm == value
+ }
+
+ // COPYIN(user PC, &instruction, 4), followed by the user/kernel gate.
+ var copies: [(Int, UInt32, UInt32, UInt32)] = []
+ for n in 3..<i.count - 4 where i[n].mnemonic == "bl" {
+ guard let source = i[n - 3].detail?.operands, source.count == 2,
+ i[n - 3].mnemonic == "ldr", source[0].reg == .x(0), source[1].type == .memory,
+ let context = (0..<29).first(where: { source[1].mem.base == .x($0) }),
+ source[1].mem.disp >= 256, source[1].mem.disp % 8 == 0,
+ let count = i[n - 1].detail?.operands, i[n - 1].mnemonic == "mov", count.count == 2,
+ count[0].reg == .w(2), count[1].imm == 4,
+ let destination = i[n - 2].detail?.operands, i[n - 2].mnemonic == "add", destination.count == 3,
+ destination[0].reg == .x(1), destination[1].reg == .sp, destination[2].type == .immediate,
+ let loaded = i[n + 2].detail?.operands, loaded.count == 2,
+ let word = reg(loaded[0]), loaded[0].reg == .w(Int(word)),
+ load(i[n + 2], rt: .w(Int(word)), base: .sp, offset: destination[2].imm),
+ i[n + 1].mnemonic == "ldr", i[n + 1].detail?.operands.last?.mem.base == .x(context)
+ else { continue }
+ copies.append((n, UInt32(context), word, UInt32(source[1].mem.disp)))
+ }
+ guard copies.count == 1 else { return nil }
+ let (copy, context, word, pc) = copies[0]
+ // Restrict the ABI to the verified arm_saved_state64 layout. These are
+ // structure fields, not a kernel file offset or runtime address.
+ guard pc == 8 + 32 * 8 else { return nil }
+
+ var gates: [(Int, UInt32, UInt16)] = []
+ for n in copy + 3..<min(copy + 16, i.count - 1) {
+ guard let o = i[n].detail?.operands, i[n].mnemonic == "tst", o.count == 2, o[1].imm == 0xc,
+ let destination = target(i[n + 1], "b.eq"),
+ let entry = i.firstIndex(where: { $0.address == UInt64(destination) }), entry + 2 < i.count,
+ i[entry].mnemonic == "mov", let move = i[entry].detail?.operands, move.count == 2,
+ let scratch = reg(move[0]), move[1].type == .immediate, move[1].imm == 0xdefe,
+ i[entry + 1].mnemonic == "movk", i[entry + 2].mnemonic == "cmp",
+ !i[(copy + 1)...n].contains(where: { $0.isCall || $0.detail?.operands.first?.reg == .x(0) || $0.detail?.operands.first?.reg == .w(0) })
+ else { continue }
+ gates.append((destination, scratch, UInt16(move[1].imm)))
+ }
+ guard gates.count == 1 else { return nil }
+
+ // Reuse the same kernel's signed-state ABI, including its PAC-safe
+ // interrupt helpers. handle_uncategorized already advances a PC for
+ // recoverable debugger traps; this is the source-backed reveal anchor.
+ var support: [(Int, Int, Int, Int)] = []
+ for n in 4..<i.count - 12 where stackSelect(i[n], 1) {
+ guard i[n + 1].mnemonic == "ldp", let pair = i[n + 1].detail?.operands, pair.count == 3,
+ pair[0].reg == .x(4), pair[1].reg == .x(5), pair[2].mem.base == .x(0), pair[2].mem.disp == Int64(pc - 16 * 8),
+ load(i[n + 2], rt: .x(7), base: .x(0), offset: Int64(pc)),
+ load(i[n + 3], rt: .w(8), base: .x(0), offset: Int64(pc + 8)),
+ load(i[n + 4], rt: .x(3), base: .x(0), offset: Int64(pc - 16)),
+ let check = target(i[n + 7], "bl"), let disable = target(i[n - 4], "bl"),
+ let exit = (n + 8..<i.count - 3).first(where: { stackSelect(i[$0], 0) }),
+ let sign = target(i[exit - 1], "bl"), let restore = target(i[exit + 3], "bl")
+ else { continue }
+ let checkCode = disasm.disassemble(in: buffer.original, at: check, count: 40)
+ let signCode = disasm.disassemble(in: buffer.original, at: sign, count: 20)
+ let restoreCode = disasm.disassemble(in: buffer.original, at: restore, count: 3)
+ guard checkCode.contains(where: { $0.mnemonic == "pacga" }),
+ signCode.contains(where: { $0.mnemonic == "pacga" }),
+ restoreCode.contains(where: { $0.mnemonic == "msr" && $0.operandString.lowercased().hasPrefix("daif,") })
+ else { continue }
+ support.append((check, sign, disable, restore))
+ }
+ guard support.count == 1 else { return nil }
+ let returns = i.indices.filter { n in
+ guard n >= 10, i[n].mnemonic == "retab", i[n - 4].mnemonic == "ldp",
+ i[n - 4].detail?.operands.first?.reg == .x(29),
+ i[n - 3].mnemonic == "ldp", i[n - 2].mnemonic == "ldp", i[n - 1].mnemonic == "add",
+ i[n - 10].mnemonic == "ldur", i[n - 10].detail?.operands.last?.mem.base == .x(29),
+ i[n - 5].mnemonic == "b.ne", i[n - 6].mnemonic == "cmp"
+ else { return false }
+ return true
+ }
+ guard returns.count == 1 else { return nil }
+ let s = support[0], g = gates[0]
+ return CSSCHandler(hook: g.0, epilogue: Int(i[returns[0] - 10].address), context: context, word: word,
+ displacedRegister: g.1, displacedImmediate: g.2, pc: pc,
+ check: s.0, sign: s.1, disableInterrupts: s.2, restoreInterrupts: s.3)
+ }
+
+ func patchCSSC() throws {
+ let identifier = FirmwareKernelCustomFirmwarePatchSet.cssc
+ guard gate.isEnabled(identifier) else { return }
+ guard let handler = revealCSSCHandler() else {
+ throw PatcherError.invalidFormat("cannot validate kernel CSSC exception and signed-state paths")
+ }
+ // One fixed payload in persistent __TEXT_EXEC, never boot-only code.
+ let sample = try csscPayload(handler, at: handler.hook)
+ guard let cave = findCodeCave(size: sample.count),
+ segments.contains(where: { $0.name == "__TEXT_EXEC" && UInt64(cave) >= $0.fileOffset && UInt64(cave + sample.count) <= $0.fileOffset + $0.fileSize }),
+ let entry = ARM64Encoder.encodeB(from: handler.hook, to: cave)
+ else { throw PatcherError.invalidFormat("no persistent executable space for kernel CSSC handler") }
+ let payload = try csscPayload(handler, at: cave)
+ guard payload.count == sample.count else { throw PatcherError.invalidFormat("kernel CSSC payload size changed") }
+ emit(cave, payload, patchID: identifier + ".handler", virtualAddress: fileOffsetToVA(cave), description: "EL0 scalar CSSC emulator with signed-state recovery")
+ emit(handler.hook, entry, patchID: identifier + ".entry", virtualAddress: fileOffsetToVA(handler.hook), description: "try CSSC before undefined-instruction triage")
+ }
+
+ func csscPayload(_ h: CSSCHandler, at base: Int) throws -> Data {
+ var c = VPhoneCSSCCode.Builder()
+ let frame: UInt32 = 192
+ func registerOffset(_ r: UInt32) -> UInt32 { r == 30 ? 152 : r * 8 }
+ func loadContext(_ c: inout VPhoneCSSCCode.Builder) {
+ if h.context < 19 { c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 31, offset: registerOffset(h.context))) }
+ else { c.emit(ARM64Encoder.encodeMovX(rd: 0, rm: h.context)) }
+ }
+ func call(_ c: inout VPhoneCSSCCode.Builder, _ target: Int) {
+ c.emit(ARM64Encoder.encodeBL(from: base + c.data.count, to: target))
+ }
+ c.emit(ARM64Encoder.encodeSubImm12(rd: 31, rn: 31, imm12: frame))
+ for r: UInt32 in 0..<19 { c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: r, rn: 31, offset: r * 8)) }
+ c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: 30, rn: 31, offset: 152))
+ c.emit(ARM64Encoder.encodeReadStatus(rt: 16))
+ c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: 16, rn: 31, offset: 160))
+ // copyin return value remains in x0 on this validated user path.
+ c.branch("unknown", register: 0, nonzero: true)
+ loadContext(&c)
+ c.emit(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 3, rn: 0, offset: 0))
+ c.emit(ARM64Encoder.encodeCmpWImmediate(rn: 3, imm12: 21)) // ARM_SAVED_STATE64
+ c.emit(ARM64Encoder.encodeCsetW(rd: 3, condition: .ne))
+ c.branch("unknown", register: 3, nonzero: true)
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 3, rn: 0, offset: h.pc + 24))
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 3, rn: 3, lsb: 26, width: 6))
+ c.branch("unknown", register: 3, nonzero: true) // EC_UNCATEGORIZED only
+ c.emit(ARM64Encoder.encodeAddImm12(rd: 1, rn: 0, imm12: h.pc - 32 * 8))
+ c.emit(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 31, offset: registerOffset(h.word)))
+ c.emit(ARM64Encoder.encodeAddImm12(rd: 2, rn: 31, imm12: 168))
+ let emulatorCall = c.data.count
+ c.emit(ARM64.nop)
+ c.branch("unknown", register: 0)
+
+ call(&c, h.disableInterrupts)
+ c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 31, offset: 176))
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 10, rn: 31, offset: 168))
+ c.emit(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 11, rn: 31, offset: registerOffset(h.word)))
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 11, rn: 11, lsb: 0, width: 5))
+ loadContext(&c)
+ c.emit(ARM64Encoder.encodeAddImm12(rd: 12, rn: 0, imm12: h.pc - 32 * 8))
+ c.emit(ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 12, rn: 12, rm: 11, shift: 3))
+ // Same protected sequence as MANIPULATE_SIGNED_THREAD_STATE: no stack
+ // accesses between SPSel=1 and SPSel=0; verify before any state write.
+ c.emit(ARM64Encoder.encodeSelectStackPointer(interruptStack: true))
+ for (r, offset): (UInt32, UInt32) in [(4, h.pc - 128), (5, h.pc - 120), (7, h.pc), (3, h.pc - 16)] {
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: r, rn: 0, offset: offset))
+ }
+ c.emit(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 8, rn: 0, offset: h.pc + 8))
+ c.emit(ARM64Encoder.encodeMovX(rd: 1, rm: 7))
+ c.emit(ARM64Encoder.encodeMovX(rd: 2, rm: 8))
+ call(&c, h.check)
+ c.emit(ARM64Encoder.encodeAddImm12(rd: 1, rn: 7, imm12: 4))
+ c.emit(ARM64Encoder.encodeMovX(rd: 2, rm: 8))
+ for (destination, signatureRegister): (UInt32, UInt32) in [(30, 3), (16, 4), (17, 5)] {
+ c.emit(ARM64Encoder.encodeCmpWImmediate(rn: 11, imm12: destination))
+ c.emit(ARM64Encoder.encodeConditionalSelect(rd: signatureRegister, rn: 10, rm: signatureRegister, condition: .eq))
+ }
+ c.emit(ARM64Encoder.encodeCmpWImmediate(rn: 11, imm12: 31))
+ c.equal("zeroDestination")
+ c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: 10, rn: 12, offset: 0))
+ c.label("zeroDestination")
+ c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: 1, rn: 0, offset: h.pc))
+ call(&c, h.sign)
+ c.emit(ARM64Encoder.encodeSelectStackPointer(interruptStack: false))
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 31, offset: 176))
+ call(&c, h.restoreInterrupts)
+ restore(&c, frame: frame)
+ c.labels["return"] = h.epilogue - base
+ c.branch("return")
+ c.label("unknown")
+ restore(&c, frame: frame)
+ c.emit(ARM64Encoder.encodeMovzW(rd: h.displacedRegister, imm16: h.displacedImmediate))
+ c.labels["original"] = h.hook + 4 - base
+ c.branch("original")
+ var code = try c.finish()
+ guard let call = ARM64Encoder.encodeBL(from: emulatorCall, to: code.count) else { throw PatcherError.invalidFormat("CSSC emulator call out of range") }
+ code.replaceSubrange(emulatorCall..<emulatorCall + 4, with: call)
+ code += try VPhoneCSSCCode.emulator()
+ return code
+ }
+
+ private func restore(_ c: inout VPhoneCSSCCode.Builder, frame: UInt32) {
+ for r: UInt32 in 0..<19 where r != 16 { c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: r, rn: 31, offset: r * 8)) }
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 30, rn: 31, offset: 152))
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 16, rn: 31, offset: 160))
+ c.emit(ARM64Encoder.encodeWriteStatus(rt: 16))
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 16, rn: 31, offset: 128))
+ c.emit(ARM64Encoder.encodeAddImm12(rd: 31, rn: 31, imm12: frame))
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index 02351df9..3514570a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -86,7 +86,10 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
patchIoucFailedSandbox()
patchDiskImages2ClientAbi()
patchSharedRegionSize()
- patchArm64eX1Admission()
+ if gate.isEnabled("kernel-boot-arm64e_x1"), !patchArm64eX1Admission() {
+ throw PatcherError.invalidFormat("cannot validate required ARM64E_X1 kernel admission")
+ }
+ try patchCSSC()
} else if applyParavirtUserClients {
patchParavirtUserClientsNarrow()
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/VPhoneCSSCCode.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/VPhoneCSSCCode.swift
new file mode 100644
index 00000000..2676ed44
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/VPhoneCSSCCode.swift
@@ -0,0 +1,176 @@
+import Foundation
+import VPhonePatchKit
+
+/// One shared baseline-A64 emulator, not a per-instruction trampoline pool.
+enum VPhoneCSSCCode {
+ struct Builder {
+ var data = Data()
+ var labels: [String: Int] = [:]
+ var fixups: [(Int, String, UInt32?, UInt32?, Bool)] = []
+ var valid = true
+
+ mutating func emit(_ bytes: Data?) {
+ guard let bytes else { valid = false; return }
+ data += bytes
+ }
+
+ mutating func label(_ name: String) { labels[name] = data.count }
+ mutating func branch(_ name: String, register: UInt32? = nil, bit: UInt32? = nil, nonzero: Bool = false) {
+ fixups.append((data.count, name, register, bit, nonzero))
+ emit(ARM64.nop)
+ }
+
+ mutating func equal(_ name: String) {
+ emit(ARM64Encoder.encodeCsetW(rd: 13, condition: .eq))
+ branch(name, register: 13, nonzero: true)
+ }
+
+ mutating func constant(_ register: UInt32, _ value: UInt32) {
+ emit(ARM64Encoder.encodeMovzX(rd: register, imm16: UInt16(truncatingIfNeeded: value)))
+ if value >> 16 != 0 {
+ emit(ARM64Encoder.encodeMovkX(rd: register, imm16: UInt16(value >> 16), shift: 16))
+ }
+ }
+
+ func finish() throws -> Data {
+ guard valid else { throw PatcherError.invalidFormat("unencodable CSSC fallback") }
+ var result = data
+ for (offset, label, register, bit, nonzero) in fixups {
+ guard let target = labels[label] else { throw PatcherError.invalidFormat("missing CSSC label \(label)") }
+ let bytes: Data?
+ if let register, let bit {
+ bytes = ARM64Encoder.encodeTestBitBranch(nonzero: nonzero, register: register, bit: bit, from: offset, to: target)
+ } else if let register {
+ bytes = ARM64Encoder.encodeCompareBranch(nonzero: nonzero, register: register, from: offset, to: target, width64: true)
+ } else {
+ bytes = ARM64Encoder.encodeB(from: offset, to: target)
+ }
+ guard let bytes else { throw PatcherError.invalidFormat("CSSC branch out of range") }
+ result.replaceSubrange(offset..<offset + 4, with: bytes)
+ }
+ return result
+ }
+ }
+
+ /// C ABI: bool emulate(uint32_t word, const uint64_t regs[31], uint64_t *result).
+ /// Unknown words leave result untouched. Only caller-saved GPRs are used;
+ /// no FP/SIMD, allocation, memory patching or privileged instructions.
+ static func emulator() throws -> Data {
+ var c = Builder()
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 14, rn: 0, lsb: 31, width: 1))
+ // Rn; encoded register 31 is ZR, never SP or an out-of-bounds load.
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 3, rn: 0, lsb: 5, width: 5))
+ loadRegister(&c, destination: 4, index: 3, name: "a")
+ c.branch("a64", register: 14, nonzero: true)
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 4, rn: 4, lsb: 0, width: 32))
+ c.label("a64")
+ c.constant(12, 0x7FFF_FC00)
+ c.emit(ARM64Encoder.encodeAndRegister(rd: 3, rn: 0, rm: 12, width64: false))
+ for (word, label) in [(UInt32(0x5AC0_2000), "abs"), (0x5AC0_1C00, "cnt"), (0x5AC0_1800, "ctz")] {
+ c.constant(12, word)
+ c.emit(ARM64Encoder.encodeCompareRegister(rn: 3, rm: 12))
+ c.equal(label)
+ }
+ c.constant(12, 0x7FE0_FC00)
+ c.emit(ARM64Encoder.encodeAndRegister(rd: 3, rn: 0, rm: 12, width64: false))
+ for kind in 0..<4 {
+ c.constant(12, 0x1AC0_6000 + UInt32(kind) * 0x400)
+ c.emit(ARM64Encoder.encodeCompareRegister(rn: 3, rm: 12))
+ c.equal("reg\(kind)")
+ }
+ c.constant(12, 0x7FFC_0000)
+ c.emit(ARM64Encoder.encodeAndRegister(rd: 3, rn: 0, rm: 12, width64: false))
+ for kind in 0..<4 {
+ c.constant(12, 0x11C0_0000 + UInt32(kind) * 0x40000)
+ c.emit(ARM64Encoder.encodeCompareRegister(rn: 3, rm: 12))
+ c.equal("imm\(kind)")
+ }
+ c.constant(0, 0)
+ c.emit(ARM64.ret)
+
+ for kind in 0..<4 {
+ c.label("reg\(kind)")
+ c.constant(15, UInt32(kind))
+ c.branch("register")
+ c.label("imm\(kind)")
+ c.constant(15, UInt32(kind))
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 5, rn: 0, lsb: 10, width: 8, signed: kind & 1 == 0))
+ c.branch("minmax")
+ }
+ c.label("register")
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 3, rn: 0, lsb: 16, width: 5))
+ loadRegister(&c, destination: 5, index: 3, name: "b")
+ c.label("minmax")
+ c.branch("wide", register: 14, nonzero: true)
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 4, rn: 4, lsb: 0, width: 32))
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 5, rn: 5, lsb: 0, width: 32))
+ c.branch("wide", register: 15, bit: 0, nonzero: true)
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 4, rn: 4, lsb: 0, width: 32, signed: true))
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 5, rn: 5, lsb: 0, width: 32, signed: true))
+ c.label("wide")
+ c.emit(ARM64Encoder.encodeCompareRegister(rn: 4, rm: 5))
+ c.branch("unsigned", register: 15, bit: 0, nonzero: true)
+ c.branch("signedMin", register: 15, bit: 1, nonzero: true)
+ c.emit(ARM64Encoder.encodeConditionalSelect(rd: 4, rn: 4, rm: 5, condition: .ge))
+ c.branch("done")
+ c.label("signedMin")
+ c.emit(ARM64Encoder.encodeConditionalSelect(rd: 4, rn: 4, rm: 5, condition: .lt))
+ c.branch("done")
+ c.label("unsigned")
+ c.branch("unsignedMin", register: 15, bit: 1, nonzero: true)
+ c.emit(ARM64Encoder.encodeConditionalSelect(rd: 4, rn: 4, rm: 5, condition: .hs))
+ c.branch("done")
+ c.label("unsignedMin")
+ c.emit(ARM64Encoder.encodeConditionalSelect(rd: 4, rn: 4, rm: 5, condition: .lo))
+ c.branch("done")
+
+ c.label("abs")
+ c.branch("abs64", register: 14, nonzero: true)
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 4, rn: 4, lsb: 0, width: 32, signed: true))
+ c.label("abs64")
+ c.emit(ARM64Encoder.encodeAddSubXShifted(subtract: true, rd: 5, rn: 31, rm: 4))
+ c.emit(ARM64Encoder.encodeCompareRegister(rn: 4, rm: 31))
+ c.emit(ARM64Encoder.encodeConditionalSelect(rd: 4, rn: 4, rm: 5, condition: .ge))
+ c.branch("done")
+
+ c.label("ctz")
+ c.branch("ctz64", register: 14, nonzero: true)
+ c.emit(ARM64Encoder.encodeReverseBits(rd: 4, rn: 4, width64: false))
+ c.emit(ARM64Encoder.encodeCountLeadingZeros(rd: 4, rn: 4, width64: false))
+ c.branch("done")
+ c.label("ctz64")
+ c.emit(ARM64Encoder.encodeReverseBits(rd: 4, rn: 4, width64: true))
+ c.emit(ARM64Encoder.encodeCountLeadingZeros(rd: 4, rn: 4, width64: true))
+ c.branch("done")
+
+ c.label("cnt")
+ c.constant(5, 0)
+ c.label("bits")
+ c.branch("counted", register: 4)
+ c.emit(ARM64Encoder.encodeSubImm12(rd: 6, rn: 4, imm12: 1))
+ c.emit(ARM64Encoder.encodeAndRegister(rd: 4, rn: 4, rm: 6))
+ c.emit(ARM64Encoder.encodeAddImm12(rd: 5, rn: 5, imm12: 1))
+ c.branch("bits")
+ c.label("counted")
+ c.emit(ARM64Encoder.encodeMovX(rd: 4, rm: 5))
+ c.label("done")
+ c.branch("result64", register: 14, nonzero: true)
+ c.emit(ARM64Encoder.encodeBitfieldExtract(rd: 4, rn: 4, lsb: 0, width: 32))
+ c.label("result64")
+ c.emit(ARM64Encoder.encodeStrXUnsignedOffset(rt: 4, rn: 2, offset: 0))
+ c.constant(0, 1)
+ c.emit(ARM64.ret)
+ return try c.finish()
+ }
+
+ private static func loadRegister(_ c: inout Builder, destination: UInt32, index: UInt32, name: String) {
+ c.emit(ARM64Encoder.encodeCmpWImmediate(rn: index, imm12: 31))
+ c.equal("zero\(name)")
+ c.emit(ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 6, rn: 1, rm: index, shift: 3))
+ c.emit(ARM64Encoder.encodeLdrXUnsignedOffset(rt: destination, rn: 6, offset: 0))
+ c.branch("loaded\(name)")
+ c.label("zero\(name)")
+ c.constant(destination, 0)
+ c.label("loaded\(name)")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index 94c82c84..b1e2ca44 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -16,6 +16,7 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
public static let identifier = "com.vphone.patchset.kernel.cfw"
public static let tvTPROPagers = "kernel-exp-tv_tpro_pagers"
+ public static let cssc = "kernel-boot-cssc_emulation"
/// Only applies to an iOS 27 userland.
private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))
@@ -240,6 +241,15 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
// MARK: iOS 27 Userland
+ VPhonePatchDeclaration(
+ identifier: cssc,
+ title: "CSSC instruction compatibility",
+ summary: "Emulates scalar CSSC instructions in user-mode exception handling, including before launchd starts, on hosts without native CSSC.",
+ target: .firmware(.kernelcache),
+ applicability: VPhonePatchApplicability(iOSBase: .major(27), cloudOS: .release(major: 26, minor: 4)),
+ bootEssential: true,
+ ),
+
VPhonePatchDeclaration(
identifier: "kernel-boot-arm64e_x1",
title: "ARM64E_X1 admission",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 4aee5869..5a9aa405 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -245,6 +245,7 @@ public enum FirmwarePatchSetCatalog {
"dyld-boot-xpc_lwcr",
"dyld-cfw-camera",
"kernel-boot-arm64e_x1",
+ FirmwareKernelCustomFirmwarePatchSet.cssc,
"preboot-cfw-devicetree_board_audio",
"preboot-cfw-devicetree_haptics",
"preboot-cfw-devicetree_iphone_product",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCSSCTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCSSCTests.swift
new file mode 100644
index 00000000..fd81b7f6
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCSSCTests.swift
@@ -0,0 +1,155 @@
+@testable import FirmwarePatcher
+import Darwin
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@_silgen_name("sys_icache_invalidate")
+private func invalidateKernelCSSCTestCode(_ memory: UnsafeMutableRawPointer, _ count: Int)
+
+@Suite("Kernel CSSC compatibility")
+struct KernelCSSCTests {
+ @Test func `new encoders match Keystone 0_9_2`() throws {
+ let cases: [(Data?, UInt32)] = [
+ (ARM64Encoder.encodeBitfieldExtract(rd: 3, rn: 4, lsb: 5, width: 6), 0xD3452883),
+ (ARM64Encoder.encodeBitfieldExtract(rd: 3, rn: 4, lsb: 0, width: 32, signed: true), 0x93407C83),
+ (ARM64Encoder.encodeAndRegister(rd: 3, rn: 0, rm: 12, width64: false), 0x0A0C0003),
+ (ARM64Encoder.encodeAndRegister(rd: 3, rn: 4, rm: 5), 0x8A050083),
+ (ARM64Encoder.encodeCompareRegister(rn: 3, rm: 4), 0xEB04007F),
+ (ARM64Encoder.encodeConditionalSelect(rd: 3, rn: 4, rm: 5, condition: .ge), 0x9A85A083),
+ (ARM64Encoder.encodeReverseBits(rd: 3, rn: 4, width64: false), 0x5AC00083),
+ (ARM64Encoder.encodeReverseBits(rd: 3, rn: 4, width64: true), 0xDAC00083),
+ (ARM64Encoder.encodeCountLeadingZeros(rd: 3, rn: 4, width64: false), 0x5AC01083),
+ (ARM64Encoder.encodeCountLeadingZeros(rd: 3, rn: 4, width64: true), 0xDAC01083),
+ (ARM64Encoder.encodeReadStatus(rt: 16), 0xD53B4210),
+ (ARM64Encoder.encodeWriteStatus(rt: 16), 0xD51B4210),
+ (ARM64Encoder.encodeSelectStackPointer(interruptStack: true), 0xD50041BF),
+ (ARM64Encoder.encodeSelectStackPointer(interruptStack: false), 0xD50040BF),
+ ]
+ for (data, expected) in cases {
+ let bytes = try #require(data)
+ #expect(bytes.loadLE(UInt32.self, at: 0) == expected)
+ }
+ #expect(ARM64Encoder.encodeBitfieldExtract(rd: 0, rn: 0, lsb: 63, width: 2) == nil)
+ #expect(ARM64Encoder.encodeBitfieldExtract(rd: 0, rn: 0, lsb: 0, width: 0) == nil)
+ #expect(ARM64Encoder.encodeReverseBits(rd: 32, rn: 0, width64: true) == nil)
+ }
+
+ #if arch(arm64)
+ @Test func `baseline emulator executes all scalar forms without modifying input registers`() throws {
+ let code = try VPhoneCSSCCode.emulator()
+ #expect(code.count < 4096)
+ let decoded = ARM64Disassembler().disassemble(code)
+ #expect(decoded.allSatisfy { $0.isDecoded })
+ #expect(!decoded.contains(where: { ["abs", "ctz", "cnt", "smax", "smin", "umax", "umin", "mrs", "msr"].contains($0.mnemonic) }))
+ let memory = try #require(mmap(nil, 0x4000, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0))
+ try #require(memory != MAP_FAILED)
+ defer { munmap(memory, 0x4000) }
+ code.copyBytes(to: memory.assumingMemoryBound(to: UInt8.self), count: code.count)
+ try #require(mprotect(memory, 0x4000, PROT_READ | PROT_EXEC) == 0)
+ invalidateKernelCSSCTestCode(memory, code.count)
+ typealias Function = @convention(c) (UInt32, UnsafePointer<UInt64>, UnsafeMutablePointer<UInt64>) -> UInt64
+ let function = unsafeBitCast(memory, to: Function.self)
+ var registers = (0..<31).map { UInt64($0) &* 0xFEDC_BA98_7654_3211 }
+ let values: [UInt64] = [0, 1, 7, 0x8000_0000, 0xFFFF_FFFF, 1 << 63, .max, .max - 6]
+ for wide in [false, true] {
+ let sf: UInt32 = wide ? 0x8000_0000 : 0
+ let mask: UInt64 = wide ? .max : UInt64(UInt32.max)
+ let sign: UInt64 = wide ? 1 << 63 : 1 << 31
+ for rn: UInt32 in [0, 16, 17, 29, 30, 31] {
+ for value in values {
+ if rn < 31 { registers[Int(rn)] = value }
+ let a = rn == 31 ? 0 : value & mask
+ let unary: [(UInt32, UInt64)] = [
+ (0x5AC02000, a & sign == 0 ? a : (0 &- a) & mask),
+ (0x5AC01C00, UInt64(a.nonzeroBitCount)),
+ (0x5AC01800, a == 0 ? (wide ? 64 : 32) : UInt64(a.trailingZeroBitCount)),
+ ]
+ for (opcode, expected) in unary {
+ for rd: UInt32 in [0, 16, 17, 29, 30, 31, rn] {
+ var result = UInt64.max
+ let before = registers
+ #expect(registers.withUnsafeBufferPointer { function(sf | opcode | rn << 5 | rd, $0.baseAddress!, &result) } == 1)
+ #expect(result == expected)
+ #expect(registers == before)
+ }
+ }
+ for kind: UInt32 in 0..<4 {
+ for immediate in [false, true] {
+ for operand in [UInt64(0), 1, 127, 128, 255, .max] {
+ let rm: UInt32 = 18
+ registers[Int(rm)] = operand
+ let opcode: UInt32 = immediate ? 0x11C00000 + kind * 0x40000 : 0x1AC06000 + kind * 0x400
+ let encoded = immediate ? UInt32(operand & 255) << 10 : rm << 16
+ var b = immediate ? operand & 255 : operand & mask
+ let signed = kind & 1 == 0
+ if immediate && signed && b & 128 != 0 { b |= .max << 8 }
+ b &= mask
+ let flip = signed ? sign : 0
+ let expected = ((a ^ flip) < (b ^ flip)) == (kind & 2 != 0) ? a : b
+ var result: UInt64 = 0
+ #expect(registers.withUnsafeBufferPointer { function(sf | opcode | encoded | rn << 5 | rn, $0.baseAddress!, &result) } == 1)
+ #expect(result == expected)
+ }
+ }
+ }
+ }
+ }
+ }
+ for word: UInt32 in [0, 0xD503201F, 0xDAC1A7FE, 0x4E205800, .max] {
+ var result: UInt64 = 0xAABBCCDD
+ let before = registers
+ #expect(registers.withUnsafeBufferPointer { function(word, $0.baseAddress!, &result) } == 0)
+ #expect(result == 0xAABBCCDD)
+ #expect(registers == before)
+ }
+ }
+ #endif
+
+ @Test func `gate is narrow and presets retain their exclusions`() throws {
+ for (base, cloud, expected) in [("27.1", "26.4", true), ("26.7", "26.4", false), ("27.1", "26.5", false)] {
+ let plan = try VPhonePatchPlan.resolve(preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled, iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion(cloud))
+ #expect(plan.isEnabled(FirmwareKernelCustomFirmwarePatchSet.cssc) == expected)
+ }
+ let patcher = KernelCustomFirmwarePatcher(data: Data(repeating: 0, count: 256), verbose: false)
+ #expect(throws: (any Error).self) { try patcher.patchCSSC() }
+ #expect(patcher.patches.isEmpty)
+ #expect(patcher.patchedData == patcher.buffer.original)
+ }
+
+ @Test(.enabled(if: ProcessInfo.processInfo.environment["VPHONE_CSSC_KERNEL"] != nil))
+ func `real research kernel reveals the complete handler before writing`() throws {
+ let path = try #require(ProcessInfo.processInfo.environment["VPHONE_CSSC_KERNEL"])
+ let data = try Data(contentsOf: URL(fileURLWithPath: path))
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: true)
+ patcher.parseMachO()
+ patcher.buildADRPIndex()
+ let h = try #require(patcher.revealCSSCHandler())
+ print("CSSC reveal hook=\(String(h.hook, radix: 16)) check=\(String(h.check, radix: 16)) sign=\(String(h.sign, radix: 16))")
+ try patcher.patchCSSC()
+ #expect(patcher.patches.count == 2)
+ let payload = try #require(patcher.patches.first)
+ #expect(payload.patchedBytes.count < 4096)
+ let code = ARM64Disassembler().disassemble(payload.patchedBytes, at: UInt64(payload.fileOffset))
+ var protected = false
+ for instruction in code {
+ if instruction.mnemonic == "msr", instruction.operandString.lowercased().hasPrefix("spsel,") {
+ protected = instruction.detail?.operands.last?.imm == 1
+ }
+ if protected {
+ #expect(!(instruction.detail?.operands.contains(where: { $0.type == .memory && $0.mem.base == .sp }) ?? false))
+ }
+ }
+ #expect(!protected)
+ // Unrecognized layouts fail before any mutation, rather than guessing.
+ var changed = data
+ changed.replaceSubrange(h.check..<h.check + 160, with: Data(repeating: 0, count: 160))
+ let invalid = KernelCustomFirmwarePatcher(data: changed, verbose: false)
+ invalid.parseMachO()
+ invalid.buildADRPIndex()
+ #expect(throws: (any Error).self) { try invalid.patchCSSC() }
+ #expect(invalid.patchedData == changed)
+ #expect(invalid.patches.isEmpty)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index ff2474c6..1a08736d 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -1235,7 +1235,9 @@ struct VPhoneCustomFirmwareInstaller {
/// no restore-tree step runs.
///
/// Paired TV dyld updates abort on failure and discard the private disk
- /// clone, preserving the original disk and receipt. Other patches run in isolation: one patch failing — a verb rejecting an
+ /// clone, preserving the original disk and receipt. Selected X1 bootstrap
+ /// patches also abort on failure: continuing would boot an incompatible
+ /// cache or executable. Other patches run in isolation: one patch failing — a verb rejecting an
/// unexpected prologue on an older VM, say — is reported and the patch is
/// left in its prior state, but the run continues and the vphoned redeploy,
/// done first, is never blocked. Non-patch failures (a volume that will not
@@ -1367,17 +1369,36 @@ struct VPhoneCustomFirmwareInstaller {
}
let version = try productVersion(system: system)
+ func requireX1Bootstrap() throws {
+ let required: Set<String> = [
+ FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,
+ ]
+ let failed = Set(failures).intersection(required).filter {
+ plan?.isEnabled($0) ?? version.hasPrefix("27.")
+ }.sorted()
+ guard failed.isEmpty else {
+ throw ValidationError("Required X1 boot patches failed; installation stopped before setup boot: \(failed.joined(separator: ", ")). See the patch error above.")
+ }
+ }
+
if version.hasPrefix("27.") || priorGuest.contains(FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap) {
machO(FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap, path: "usr/lib/dyld",
verbs: ["patch-arm64e-x1"], preserveEntitlements: true)
+ try requireX1Bootstrap()
}
if version.hasPrefix("27.") || priorGuest.contains(FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap) {
machO(FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap, path: "sbin/fsck",
verbs: ["patch-arm64e-x1"], preserveEntitlements: true)
+ try requireX1Bootstrap()
}
if version.hasPrefix("27.") || priorGuest.contains(FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap) {
machO(FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap, path: "sbin/mount",
verbs: ["patch-arm64e-x1"], preserveEntitlements: true)
+ try requireX1Bootstrap()
}
// 0. A cache whose span alone overruns the guest kernel's shared region
@@ -1594,10 +1615,11 @@ struct VPhoneCustomFirmwareInstaller {
("dyld-exp-hv_vmm", "patch-hv-vmm-dsc", [dsc]),
("dyld-cfw-camera", "patch-camera-dsc", [dsc, DyldSharedCacheChunkSet.mainCacheURL(in: URL(fileURLWithPath: dsc)).path]),
]
- applyDyldPatches(
+ try applyDyldPatches(
dyld, dsc: dsc, cacheRelative: cacheRelative, system: system, plan: plan, priorGuest: priorGuest,
live: &live, failures: &failures,
)
+ try requireX1Bootstrap()
// The feature plist exists from iOS 26. Turning the patch off restores
// the original.
@@ -1930,6 +1952,7 @@ struct VPhoneCustomFirmwareInstaller {
}
}
+ try requireX1Bootstrap()
if !isHomePod {
isolate([]) { try restoreMISFixTargets(system: system) }
}
@@ -2078,7 +2101,8 @@ struct VPhoneCustomFirmwareInstaller {
/// multi-gigabyte scan when nothing changed. A disabled patch with no undo
/// record was either never applied (nothing to do) or applied before the
/// undo log existed; the latter is told apart by the prior-live set and
- /// reported as not revertible, staying live. Each verb runs in isolation.
+ /// reported as not revertible, staying live. The selected X1 bootstrap
+ /// patch must succeed; optional cache patches still run in isolation.
private func applyDyldPatches(
_ dyld: [(id: String, verb: String, args: [String])],
dsc: String,
@@ -2088,10 +2112,15 @@ struct VPhoneCustomFirmwareInstaller {
priorGuest: Set<String>,
live: inout Set<String>,
failures: inout [String],
- ) {
+ ) throws {
func enabled(_ id: String) -> Bool {
plan?.isEnabled(id) ?? !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(id)
}
+ func requireBootstrap(_ id: String, error: any Error) throws {
+ if id == FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap {
+ throw ValidationError("Required X1 boot patch \(id) failed; installation stopped before setup boot: \(error)")
+ }
+ }
let undoAbsolute = (dsc as NSString).appendingPathComponent(Self.dscUndoLogLeaf)
let undoRelative = "\(cacheRelative)/\(Self.dscUndoLogLeaf)"
let undoLog = (try? system.readData(undoRelative)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }
@@ -2112,6 +2141,7 @@ struct VPhoneCustomFirmwareInstaller {
} catch {
failures.append(entry.id)
print(" [!] \(entry.id): re-running the applied patch failed, left as it was: \(error)")
+ try requireBootstrap(entry.id, error: error)
}
} else if let undoLog, undoLog.hasOutdatedImplementation(of: entry.id) {
print(" [*] \(entry.id): an earlier implementation is applied; reverting it and applying the current one")
@@ -2121,6 +2151,7 @@ struct VPhoneCustomFirmwareInstaller {
failures.append(entry.id)
live.insert(entry.id)
print(" [!] \(entry.id): reverting the earlier implementation failed, left as it was: \(error)")
+ try requireBootstrap(entry.id, error: error)
continue
}
do {
@@ -2128,6 +2159,7 @@ struct VPhoneCustomFirmwareInstaller {
} catch {
failures.append(entry.id)
print(" [!] \(entry.id): the earlier implementation was reverted but the current one failed; the cache is unpatched for it: \(error)")
+ try requireBootstrap(entry.id, error: error)
continue
}
}
@@ -2139,6 +2171,7 @@ struct VPhoneCustomFirmwareInstaller {
} catch {
failures.append(entry.id)
print(" [!] \(entry.id): dyld patch failed, left in its prior state: \(error)")
+ try requireBootstrap(entry.id, error: error)
}
case (false, true):
if recorded.contains(entry.id) {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64EncoderCSSC.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64EncoderCSSC.swift
new file mode 100644
index 00000000..ab679e81
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64EncoderCSSC.swift
@@ -0,0 +1,50 @@
+import Foundation
+
+// Baseline A64 instructions used by the kernel CSSC fallback. Expected words
+// are checked against Keystone 0.9.2 in KernelCSSCTests; no CSSC is emitted.
+public extension ARM64Encoder {
+ static func encodeBitfieldExtract(rd: UInt32, rn: UInt32, lsb: UInt32, width: UInt32, signed: Bool = false) -> Data? {
+ guard rd < 32, rn < 32, width > 0, lsb < 64, width <= 64 - lsb else { return nil }
+ return ARM64.encodeU32((signed ? 0x9340_0000 : 0xD340_0000)
+ | (lsb << 16) | ((lsb + width - 1) << 10) | (rn << 5) | rd)
+ }
+
+ static func encodeAndRegister(rd: UInt32, rn: UInt32, rm: UInt32, width64: Bool = true) -> Data? {
+ guard rd < 32, rn < 32, rm < 32 else { return nil }
+ return ARM64.encodeU32((width64 ? 0x8A00_0000 : 0x0A00_0000) | (rm << 16) | (rn << 5) | rd)
+ }
+
+ static func encodeCompareRegister(rn: UInt32, rm: UInt32, width64: Bool = true) -> Data? {
+ guard rn < 32, rm < 32 else { return nil }
+ return ARM64.encodeU32((width64 ? 0xEB00_001F : 0x6B00_001F) | (rm << 16) | (rn << 5))
+ }
+
+ static func encodeConditionalSelect(rd: UInt32, rn: UInt32, rm: UInt32, condition: ARM64Condition) -> Data? {
+ guard rd < 32, rn < 32, rm < 32 else { return nil }
+ return ARM64.encodeU32(0x9A80_0000 | (rm << 16) | (condition.rawValue << 12) | (rn << 5) | rd)
+ }
+
+ static func encodeReverseBits(rd: UInt32, rn: UInt32, width64: Bool) -> Data? {
+ guard rd < 32, rn < 32 else { return nil }
+ return ARM64.encodeU32((width64 ? 0xDAC0_0000 : 0x5AC0_0000) | (rn << 5) | rd)
+ }
+
+ static func encodeCountLeadingZeros(rd: UInt32, rn: UInt32, width64: Bool) -> Data? {
+ guard rd < 32, rn < 32 else { return nil }
+ return ARM64.encodeU32((width64 ? 0xDAC0_1000 : 0x5AC0_1000) | (rn << 5) | rd)
+ }
+
+ static func encodeReadStatus(rt: UInt32) -> Data? {
+ guard rt < 31 else { return nil }
+ return ARM64.encodeU32(0xD53B_4200 | rt)
+ }
+
+ static func encodeWriteStatus(rt: UInt32) -> Data? {
+ guard rt < 31 else { return nil }
+ return ARM64.encodeU32(0xD51B_4200 | rt)
+ }
+
+ static func encodeSelectStackPointer(interruptStack: Bool) -> Data {
+ ARM64.encodeU32(interruptStack ? 0xD500_41BF : 0xD500_40BF)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index ef66455f..b8be2b4f 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -98,6 +98,7 @@
<string>dyld-boot-iomfb_swapend</string>
<string>dyld-cfw-camera</string>
<string>kernel-boot-arm64e_x1</string>
+ <string>kernel-boot-cssc_emulation</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index cec02f3e..943cc5eb 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -109,6 +109,7 @@
<string>dyld-boot-iomfb_swapend</string>
<string>dyld-cfw-camera</string>
<string>kernel-boot-arm64e_x1</string>
+ <string>kernel-boot-cssc_emulation</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 47dbcb70..a6d234f5 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -112,6 +112,7 @@
<string>dyld-boot-xpc_lwcr</string>
<string>dyld-cfw-camera</string>
<string>kernel-boot-arm64e_x1</string>
+ <string>kernel-boot-cssc_emulation</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>