Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

cfw: jb: Accept the 5-scalar aks_unlock_bag on the 26.4 kernel (iOS 26.6+)

zqxwceac83d371f880
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 971d2535..cb2b15dd 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1289,6 +1289,7 @@ Apple's ROM and this patch. See `Firmware/openavb_boot_rom.md`.
| JB-32 | B/C | `patchParavirtTask3Version` (`kernel-cfw-paravirt_gpu_task3.request`, `.features`, `.features_code`, `.identity_hook`, `.identity_code`) | `setupVersion`; task initializer's `Failed to create Page Table Lock`; superclass task retain/store; XNU flow-divert CDHASH log and proc/task inverse getter | **Persistent per-executable host shader caches through Task3, enabled in Standard.** Phase 1 (2026-10-19) requests binary version 252 while computing guest features from the lower of the granted version and the original 245 (`.features` branches to `.features_code`, a five-instruction clamp after the identity trampoline in the same cave; a refusal passes through). Phase 2 (2026-10-20) writes the owning executable's 20-byte code-signing cdhash at TaskRoot+0x28 before descriptor preparation and task registration. The host uses `task-<40 hex>` and retains that directory. A missing proc/hash leaves twenty zero bytes and preserves the ephemeral fallback. The owning task field is recovered from the superclass initializer, not guessed or taken from current_proc. Kernel helpers are found through source-backed semantic call flow (`cs_get_cdhash`) and the dynamically recovered proc_struct_size global (`get_bsdtask_info`); no task/proc layout offsets or kernel VAs are hardcoded. The trampoline preserves x0–x18, LR and SP, copies exactly 20 bytes and replays the displaced descriptor load. All four sites must resolve before any is emitted; failure aborts a selected install. Replacements use ARM64Encoder; new encoders have Keystone 0.9.2 parity tests. Gated by applyParavirtTask3 and declared for cloudOS 26.4 only; Standard enables it there and tvOS presets block it. Static fixture, missing-anchor and register-clobber execution tests pass. Lychee on macOS 27.0.1 / cloudOS 26.4 / iOS 27.0.1 negotiated 252 across three full boots, retained the same nine executable keys, and passed Camera with zero GPU resets. Host GPU compilation events fell 631 → 17 → 12; the Settings windows fell 121 → 5 → 0. Frame-counter gaps do not establish visible animation stutter; the user reports smooth warmed animations. Measurements, cdhash checks and crash analysis are in `Research/Guest/gpu_acceleration.md`. Older hosts remain untested. | Y |
| JB-33 | B | `patchTproOff` (record `kernel-exp-frida_tpro_off`) | `_xprr_tpro_enabled` (`__DATA_CONST`), found via the `if (xprr_tpro_enabled)` guard of the VM_REGION_FLAG_TPRO_ENABLED store | **Frida spawn support (opt-in, Frida set; port of mowisec/frida_patches_srd `tpro-off`).** libdyld asserts on every API entry that TPRO pages are read-only and aborts (`TPRO regions should not be writable on entry to dyld`); Frida's spawn handshake re-enters libdyld inside dyld's own TPRO window, so `frida -f` and spawn-gated apps abort. Clearing the flag takes the kernel's existing no-TPRO path for every process (global). Anchor: unique `adrp/ldr/cbz/ldr/cmp/b.lo/ldrh/orr #2/strh` window, decoded with Capstone; the flag must resolve into `__DATA_CONST` and hold 1, else fail closed. 26.4 `c0ecdb4b`: flag at file-off `0x7526D4` (1 → 0). See `Research/KernelCustomFirmwarePatches/patch_tpro_off.md`. | Frida set |
| JB-34 | B | `patchSyscallFilterOff` (record `kernel-exp-frida_syscall_filter_off`) | `_task_get_mach_trap_filter_mask`, `_task_get_mach_kobj_filter_mask`, `_mac_proc_check_syscall_unix` | **Frida in syscall-filtered processes (opt-in, Frida set; port of mowisec/frida_patches_srd `syscall-filter-off`).** Sandbox syscall filters (`syscall-unix/-mach/-mig`) deny the agent's own calls inside the target: attaching to trustd, apsd, cfprefsd, backboardd or runningboardd kills them, and in locationd `thread_get_state` returns `KERN_DENIED` (no threads for Stalker). The two mask accessors return NULL ("no filter", XNU `bsd_arm64.c:249`, `ipc_kobject.c:563`) and the MACF BSD check returns 0 (`systemcalls.c:162`); the rest of the sandbox is untouched. JB-07 (`kernel-boot-syscallmask`, which rewrites the masks as they are installed) does not reach these processes; this is the NULL-mask alternative that row mentions. Anchors: the inlined `bitstr_test` of each check (kobject one behind `cmn #1 ; b.eq`), and `and w1,#0xffff ; mov x0 ; bl ; mov ; cbnz w0` in unix_syscall; each must match once and the three functions must open `pacibsp ; stp`, else fail closed. 26.4 `c0ecdb4b`: file-off `0x1D43090`, `0x1D43120`, `0x24CCAE8` (2 words each). See `Research/KernelCustomFirmwarePatches/patch_syscall_filter_off.md`. | Frida set |
+| JB-35 | C | `patchAksUnlockBagCount5` (records `kernel-cfw-aks_unlock_bag.redirect` / `.cave`) | AppleSEPKeyStore keybag-unlock external-method handler (the one whose `IOExternalMethodArguments` count check is `cmp w8,#3 ; b.eq ; cmp w8,#4 ; b.ne BadArg`) | **Escrow-bag unlock / encrypted backups for an iOS 26.6-or-newer userland on the 26.4 kernel (`iOSBase: .atLeast(26, 6)`; pipeline `applyAksUnlockBag5`, not `applyIOS27`).** From iOS 26.6 on, the userland keybag unlock sends `inputScalarCount == 5` (scalars[3]=flags&1, scalars[4]=flags); the 26.4 AppleSEPKeyStore handler accepts only 3 or 4 and rejects 5 with `kIOReturnBadArgument`, so every escrow-bag unlock fails and `backup2 encryption` returns EscrowFailure. The count-4 path reads only scalars[3] (the same flag bit), so a count-5 call is handled correctly by it unchanged. Redirect the `cmp w8,#4` into a 6-word cave that accepts 4 or 5 (both → the original count-4 path) else takes the handler's own BadArgument branch. Anchor (structural): the 13-word count-dispatch block matched by its fixed words with the four branch words masked (opcode+condition kept, imm19/imm26 wildcarded); BadArgument/count-4 targets decoded from the anchor's own branches, no absolute offset. The `cset w25,ne` word is part of the fixed match and is what makes the block unique among the five keystore handlers that share this 3/4-count preamble — see caveat (2). **Self-guarding:** the anchor requires `cmp w8,#4 ; b.ne` (the 3/4-only reject shape), so on a kernel that already accepts 5 (Apple-native 26.6+, or this patch's own output) it finds no match and no-ops — hence no cloudOS bound is needed. Replacement bytes from the keystone-verified `ARM64Encoder.encodeCmpWImmediate`/`encodeBCond`/`encodeB`. Kernelcache is SPTM-content-measured, so apply at create time (not hot-swappable). **Version floor empirically pinned (2026-10-26)** by scanning native iPhone17,3 kernelcaches: the keybag handler is `cmp#3;b.eq ; cmp#4;b.ne` (3/4 only) on 18.6.2 / 26.1 / 26.4 / **26.5 (23F77)**, and becomes `cmp#3;b.eq ; cmp#4;b.eq ; cmp#5;b.ne` (accepts 5) on **26.6 (23G71)** / 26.6.1 / 27.0.1 — Apple's own 26.6+ handler is byte-identical to the shape this patch synthesizes. **Review caveats (not yet on-device validated):** (1) the dispatch-table index of the patched handler is 13, not the "selector 12" the introducing commit's comment states — cosmetic (the block, not the label, is patched), but the comment should be corrected; (2) uniqueness rests on the arbitrary `cset w25` register allocation, so a kernel rebuild that reallocates it would drop the match (fail-closed) — the robust key would be the IOExternalMethod dispatch-table entry for the real keybag-unlock selector, needing on-device confirmation of that selector number before retargeting. See `KernelCustomFirmwarePatchAksUnlockBag.swift`. | `26.6+` |
### EXP-Only Kernel Methods (Reference List)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Keystore/KernelCustomFirmwarePatchAksUnlockBag.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Keystore/KernelCustomFirmwarePatchAksUnlockBag.swift
new file mode 100644
index 00000000..9e36756a
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Keystore/KernelCustomFirmwarePatchAksUnlockBag.swift
@@ -0,0 +1,134 @@
+// KernelCustomFirmwarePatchAksUnlockBag.swift — CFW kernel patch: let the
+// AppleSEPKeyStore keybag-unlock handler accept iOS 27's 5-scalar call.
+//
+// An iOS 26.6-or-newer userland's keybag unlock always sends inputScalarCount == 5
+// (scalars[3] = flags & 1, scalars[4] = flags) — 26.5 and earlier send 4 — but the
+// 26.4-kernel handler accepts only 3 or 4:
+//
+// bti j
+// ldr w8, [x19, #0x28] ; scalarInputCount
+// cmp w8, #3 ; b.eq <count3>
+// cmp w8, #4 ; b.ne <BadArgument>
+// ldr w8, [x19, #0x50] ; structureInputCount
+// cbnz w8, <BadArgument>
+// ldr x8, [x19, #0x20] ; scalars
+// ldr x9, [x8, #0x18] ; scalars[3]
+// cmp x9, #0 ; cset w25, ne ; b <join>
+//
+// so every iOS 27 unlock returns kIOReturnBadArgument and escrow-bag unlock (what
+// `backup2 encryption` needs) fails. The count-4 path reads only scalars[3], which
+// iOS 27 fills with the same flag bit, so a count of 5 is routed to it unchanged.
+//
+// The `cmp w8, #4` is redirected into a cave that accepts 4 or 5 (both to the
+// original count-4 path) and otherwise branches to the handler's own BadArgument.
+//
+// Anchor: the 13-word count-dispatch block, matched by its fixed words with the
+// four branch words masked (opcode + condition kept, imm wildcarded). The
+// BadArgument and count-4 targets are read from the anchor's own branches, so no
+// absolute offset is baked in. The `cset w25, ne` word is part of the fixed match
+// and is what makes the block unique among the keystore handlers that share this
+// 3/4-count preamble — see the review note in the commit that introduced this.
+
+import Foundation
+import VPhonePatchKit
+
+extension KernelCustomFirmwarePatcher {
+ /// (mask, value) per anchor word, in VA order from the handler's `bti j`.
+ /// 0xFFFFFFFF pins the word; 0xFF00001F keeps a b.cond/cbnz opcode and
+ /// condition while wildcarding imm19; 0xFC000000 keeps a `b` opcode.
+ private static let aksAnchor: [(mask: UInt32, value: UInt32)] = [
+ (0xFFFF_FFFF, 0xD503_249F), // 0 bti j
+ (0xFFFF_FFFF, 0xB940_2A68), // 1 ldr w8,[x19,#0x28] (scalarInputCount)
+ (0xFFFF_FFFF, 0x7100_0D1F), // 2 cmp w8,#3
+ (0xFF00_001F, 0x5400_0000), // 3 b.eq <count3>
+ (0xFFFF_FFFF, 0x7100_111F), // 4 cmp w8,#4 (redirect site)
+ (0xFF00_001F, 0x5400_0001), // 5 b.ne <BadArgument>
+ (0xFFFF_FFFF, 0xB940_5268), // 6 ldr w8,[x19,#0x50] (structInputCount)
+ (0xFF00_001F, 0x3500_0008), // 7 cbnz w8,<BadArgument>
+ (0xFFFF_FFFF, 0xF940_1268), // 8 ldr x8,[x19,#0x20] (scalars)
+ (0xFFFF_FFFF, 0xF940_0D09), // 9 ldr x9,[x8,#0x18] (scalars[3])
+ (0xFFFF_FFFF, 0xF100_013F), // 10 cmp x9,#0
+ (0xFFFF_FFFF, 0x1A9F_07F9), // 11 cset w25,ne
+ (0xFC00_0000, 0x1400_0000), // 12 b <join>
+ ]
+
+ @discardableResult
+ func patchAksUnlockBagCount5() -> Bool {
+ log("\n[CFW]AppleSEPKeyStore aks_unlock_bag: accept scalarInputCount 5 (iOS 26.6+ userland)")
+
+ guard let (ks, ke) = kernTextRange else {
+ log(" [-] no kernel text range")
+ return false
+ }
+
+ var hits: [Int] = []
+ var off = ks
+ while off + Self.aksAnchor.count * 4 <= ke {
+ if anchorMatches(at: off) {
+ hits.append(off)
+ }
+ off += 4
+ }
+ guard hits.count == 1 else {
+ log(" [-] count-dispatch anchor not found uniquely (\(hits.count))")
+ return false
+ }
+ let anchor = hits[0]
+
+ let site = anchor + 0x10 // cmp w8,#4
+ let count4 = anchor + 0x18 // count-4 path entry (ldr w8,[x19,#0x50])
+ guard let (bad, _) = jbDecodeBranchTarget(at: anchor + 0x14), // b.ne <BadArgument>
+ let (cbnzBad, _) = jbDecodeBranchTarget(at: anchor + 0x1C), // cbnz w8,<BadArgument>
+ bad == cbnzBad
+ else {
+ log(" [-] could not decode BadArgument target")
+ return false
+ }
+
+ guard let cave = findCodeCave(size: 24) else {
+ log(" [-] no code cave")
+ return false
+ }
+
+ // site/cave/count4/bad are all in __TEXT_EXEC, so a branch delta computed
+ // in file-offset space equals the VA-space delta. Replacement bytes come
+ // from the keystone-verified ARM64Encoder helpers; Lok = cave + 0x14.
+ let lok = cave + 0x14
+ guard let cmp4 = ARM64Encoder.encodeCmpWImmediate(rn: 8, imm12: 4),
+ let eq4 = ARM64Encoder.encodeBCond(from: cave + 0x04, to: lok, condition: .eq),
+ let cmp5 = ARM64Encoder.encodeCmpWImmediate(rn: 8, imm12: 5),
+ let eq5 = ARM64Encoder.encodeBCond(from: cave + 0x0C, to: lok, condition: .eq),
+ let bBad = ARM64Encoder.encodeB(from: cave + 0x10, to: bad),
+ let bCount4 = ARM64Encoder.encodeB(from: lok, to: count4),
+ let redirect = ARM64Encoder.encodeB(from: site, to: cave)
+ else {
+ log(" [-] branch encoding failed")
+ return false
+ }
+
+ emit(
+ site,
+ redirect,
+ patchID: "kernel-cfw-aks_unlock_bag.redirect",
+ virtualAddress: fileOffsetToVA(site),
+ description: "cmp w8,#4 -> b cave [aks_unlock_bag accept scalarInputCount 5]",
+ )
+ emit(
+ cave,
+ cmp4 + eq4 + cmp5 + eq5 + bBad + bCount4,
+ patchID: "kernel-cfw-aks_unlock_bag.cave",
+ virtualAddress: fileOffsetToVA(cave),
+ description: "scalarInputCount 4 or 5 -> count-4 path, else BadArgument",
+ )
+ return true
+ }
+
+ // MARK: - Private helpers
+
+ private func anchorMatches(at off: Int) -> Bool {
+ for (i, w) in Self.aksAnchor.enumerated() where (buffer.readU32(at: off + i * 4) & w.mask) != w.value {
+ return false
+ }
+ return true
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index 3514570a..95eab0a0 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -25,6 +25,14 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
/// set (override with --target-os).
public var applyIOS27 = false
+ /// The AppleSEPKeyStore keybag-unlock count-5 acceptance. iOS 26.6 is where
+ /// Apple's external method began sending inputScalarCount == 5 (26.5 and
+ /// earlier send 4), so a 26.6-or-newer userland needs it on the 26.4 kernel —
+ /// not only a 27 base. The pipeline sets this from the iPhone base; the patch
+ /// anchor self-guards on a kernel that already accepts 5, so it no-ops where
+ /// unneeded. False here so a patcher built directly preserves the reference corpus.
+ public var applyAksUnlockBag5 = false
+
/// Opt-in Frida Stalker kernel relaxations. Set from the plan: `standard` blocks
/// both, `experimental` and a per-VM checkmark turn them on, and their own
/// cloudOS 26.4+ gate then decides whether they land. Baseline CFW/EXP firmware is
@@ -94,6 +102,14 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
patchParavirtUserClientsNarrow()
}
+ // AppleSEPKeyStore keybag unlock: accept the 5 scalars an iOS 26.6-or-newer
+ // userland sends (26.5 and earlier send 4). Gated on the base, not on
+ // applyIOS27, so a 26.6/26.6.1 base on the 26.4 kernel gets it too; the
+ // anchor self-guards on a kernel that already accepts 5.
+ if applyAksUnlockBag5 {
+ patchAksUnlockBagCount5()
+ }
+
// Group B
patchPostValidationAdditional()
patchProcSecurityPolicy()
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index b1e2ca44..d61d780f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -299,6 +299,17 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
applicability: ios27,
bootEssential: true,
),
+ VPhonePatchDeclaration(
+ identifier: "kernel-cfw-aks_unlock_bag",
+ title: "Keybag unlock arguments",
+ summary: "Accepts the five-argument keybag unlock an iOS 26.6-or-newer userland sends, so escrow unlock and encrypted backups work on the 26.4 kernel.",
+ target: .firmware(.kernelcache),
+ // iOS 26.6 is where Apple's keybag-unlock external method began
+ // sending inputScalarCount == 5 (26.5 and earlier send 4); the
+ // anchor self-guards on a kernel that already accepts 5, so no
+ // cloudOS bound is needed.
+ applicability: VPhonePatchApplicability(iOSBase: .atLeast(major: 26, minor: 6)),
+ ),
VPhonePatchDeclaration(
identifier: FirmwarePatchSetCatalog.paravirtUserClientsPatch,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index 6488177e..0c4d7b10 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -95,6 +95,14 @@ extension FirmwarePipeline {
// of those patches is written.
let applyIOS27 = baseIs27
+ // The AppleSEPKeyStore keybag-unlock external method began sending
+ // inputScalarCount == 5 in iOS 26.6 (26.5 and earlier send 4), so a
+ // 26.6-or-newer userland needs the count-5 acceptance patch on the
+ // 26.4-kernel hybrid — not just a 27 base. The patch's anchor self-guards
+ // on a kernel that already accepts 5, so no cloudOS condition is needed.
+ let applyAksUnlockBag5 = baseIs27
+ || (iOSBase?.major == 26 && (iOSBase?.minor ?? 0) >= 6)
+
// Frida Stalker relaxations, off unless the VM asked for them. Their own
// cloudOS 26.4+ gate decides whether they then land.
let applyFrida = FirmwareKernelFridaPatchSet.manifest.patches.contains {
@@ -326,6 +334,7 @@ extension FirmwarePipeline {
kernelCustomFirmwareFactories(
applyExcGuard: applyExcGuard,
applyIOS27: applyIOS27,
+ applyAksUnlockBag5: applyAksUnlockBag5,
applyFrida: applyFrida,
applyProMotion: applyProMotion,
applyTVTPROPagers: isEnabled(FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, fallback: false),
@@ -518,6 +527,7 @@ extension FirmwarePipeline {
private func kernelCustomFirmwareFactories(
applyExcGuard: Bool,
applyIOS27: Bool,
+ applyAksUnlockBag5: Bool,
applyFrida: Bool,
applyProMotion: Bool,
applyTVTPROPagers: Bool,
@@ -540,6 +550,7 @@ extension FirmwarePipeline {
factories.append { data, verbose in
let p = KernelCustomFirmwarePatcher(data: data, verbose: verbose)
p.applyIOS27 = applyIOS27
+ p.applyAksUnlockBag5 = applyAksUnlockBag5
p.applyFrida = applyFrida
p.applyProMotion = applyProMotion
p.applyTVTPROPagers = applyTVTPROPagers
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index f957c711..76545bac 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -537,7 +537,17 @@ struct ARM64EncoderKeystoneParityTests {
.init(source: "sub x30, sp, #0", keystone: 0xD100_03FE, encoded: ARM64Encoder.encodeSubImm12(rd: 30, rn: 31, imm12: 0), origin: "zero immediate"),
]
- static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases + x1ComparisonCases + x1LoweringCases + task3Cases
+ // Frozen from Keystone 0.9.2 (Homebrew `kstool -b arm64 "<insn>" <address>`) outside the repository.
+ static let aksUnlockBagCases: [ARM64EncodingCase] = [
+ .init(source: "cmp w8, #4", keystone: 0x7100_111F, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 8, imm12: 4), origin: "aks_unlock_bag count 4"),
+ .init(source: "cmp w8, #5", keystone: 0x7100_151F, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 8, imm12: 5), origin: "aks_unlock_bag count 5"),
+ .init(source: "b.eq #0x14 @0x4", keystone: 0x5400_0080, encoded: ARM64Encoder.encodeBCond(from: 0x4, to: 0x14, condition: .eq), origin: "aks_unlock_bag accept"),
+ .init(source: "b.ne #0x1000 @0x2000", keystone: 0x54FF_8001, encoded: ARM64Encoder.encodeBCond(from: 0x2000, to: 0x1000, condition: .ne), origin: "B.cond backward"),
+ .init(source: "b.le #0x1ffffc @0x100000", keystone: 0x547F_FFED, encoded: ARM64Encoder.encodeBCond(from: 0x10_0000, to: 0x1F_FFFC, condition: .le), origin: "B.cond max forward"),
+ .init(source: "b.hi #0x0 @0x100000", keystone: 0x5480_0008, encoded: ARM64Encoder.encodeBCond(from: 0x10_0000, to: 0, condition: .hi), origin: "B.cond max backward"),
+ ]
+
+ static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases + x1ComparisonCases + x1LoweringCases + task3Cases + aksUnlockBagCases
@Test func `Task3 encoders reject invalid registers and offsets`() {
for invalid in [UInt32(32), 100] {
@@ -674,6 +684,9 @@ struct ARM64EncoderRangeTests {
#expect(ARM64Encoder.encodeB(from: 0x8000004, to: 0) == nil, "one past -128 MB")
#expect(ARM64Encoder.encodeBL(from: 0, to: 1) == nil, "unaligned target")
#expect(ARM64Encoder.encodeBL(from: 0, to: 0x8000000) == nil, "one past +128 MB")
+ #expect(ARM64Encoder.encodeBCond(from: 0, to: 2, condition: .eq) == nil, "unaligned target")
+ #expect(ARM64Encoder.encodeBCond(from: 0, to: 0x10_0000, condition: .eq) == nil, "one past +1 MB")
+ #expect(ARM64Encoder.encodeBCond(from: 0x10_0004, to: 0, condition: .eq) == nil, "one past -1 MB")
}
@Test func `bit branch refuses bad operands`() {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelAksUnlockBagTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelAksUnlockBagTests.swift
new file mode 100644
index 00000000..cae9801c
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelAksUnlockBagTests.swift
@@ -0,0 +1,168 @@
+// KernelAksUnlockBagTests.swift — The aks_unlock_bag scalar-count patch
+// against the selector-12 count check as the vphone600 26.4 kernel ships it.
+//
+// Every word below is keystone 0.9.2 (Homebrew `kstool`, outside this
+// repository), assembled with the block at address 0 except `bti j`, which
+// keystone does not know and is the kernel's own word. The fixed words match
+// both 26.4 variants byte for byte (research 0xfffffe0007f35184, release
+// 0xfffffe0007eb7c44 after its own `bti j`).
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("kernel-cfw-aks_unlock_bag")
+struct KernelAksUnlockBagTests {
+ // MARK: - Synthetic kernel
+
+ /// The count check with its targets inside the block: count-3 path at
+ /// +0x34, join at +0x38, BadArgument at +0x3C.
+ static let stockBlock: [UInt32] = [
+ 0xD503_249F, // bti j
+ 0xB940_2A68, // ldr w8, [x19, #0x28]
+ 0x7100_0D1F, // cmp w8, #3
+ 0x5400_0140, // b.eq #0x34
+ 0x7100_111F, // cmp w8, #4
+ 0x5400_0141, // b.ne #0x3c
+ 0xB940_5268, // ldr w8, [x19, #0x50]
+ 0x3500_0108, // cbnz w8, #0x3c
+ 0xF940_1268, // ldr x8, [x19, #0x20]
+ 0xF940_0D09, // ldr x9, [x8, #0x18]
+ 0xF100_013F, // cmp x9, #0
+ 0x1A9F_07F9, // cset w25, ne
+ 0x1400_0002, // b #0x38
+ 0xD503_201F, // nop (count 3)
+ 0xD503_201F, // nop (join)
+ 0xD503_201F, // nop (BadArgument)
+ ]
+
+ static let siteOffset = 0x10
+ static let caveOffset = 0x40
+
+ /// The block, then a zeroed cave directly after it, inside a minimal arm64
+ /// kernel image with one `__TEXT_EXEC` segment.
+ static func kernel(withBlock block: [UInt32]) -> (data: Data, blockOff: Int) {
+ let textStart = 0x100
+ var text = [UInt8](repeating: 0xD4, count: 0x20)
+ let blockOff = textStart + text.count
+ for word in block {
+ withUnsafeBytes(of: word.littleEndian) { text.append(contentsOf: $0) }
+ }
+ text += [UInt8](repeating: 0, count: 0x20)
+ while text.count % 0x100 != 0 {
+ text.append(0xD4)
+ }
+
+ var image = Data()
+ func append32(_ value: UInt32) {
+ withUnsafeBytes(of: value.littleEndian) { image.append(contentsOf: $0) }
+ }
+ func append64(_ value: UInt64) {
+ withUnsafeBytes(of: value.littleEndian) { image.append(contentsOf: $0) }
+ }
+
+ append32(0xFEED_FACF) // magic
+ append32(0x0100_000C) // cputype: arm64
+ append32(2) // cpusubtype: arm64e
+ append32(2) // filetype
+ append32(1) // ncmds
+ append32(72) // sizeofcmds
+ append32(0) // flags
+ append32(0) // reserved
+ // LC_SEGMENT_64 __TEXT_EXEC
+ append32(0x19)
+ append32(72)
+ var segname = Data("__TEXT_EXEC".utf8).prefix(16)
+ segname.append(contentsOf: [UInt8](repeating: 0, count: 16 - segname.count))
+ image.append(segname)
+ append64(0xFFFF_FE00_0700_4000) // vmaddr
+ append64(UInt64(text.count)) // vmsize
+ append64(UInt64(textStart)) // fileoff
+ append64(UInt64(text.count)) // filesize
+ append32(5) // maxprot r-x
+ append32(5) // initprot r-x
+ append32(0) // nsects
+ append32(0) // flags
+
+ image.append(contentsOf: [UInt8](repeating: 0, count: textStart - image.count))
+ image.append(contentsOf: text)
+ return (image, blockOff)
+ }
+
+ static func words(_ data: Data) -> [UInt32] {
+ stride(from: 0, to: data.count, by: 4).map { data.loadLE(UInt32.self, at: $0) }
+ }
+
+ // MARK: - The patch
+
+ @Test func `routes count 4 and 5 to the count-4 path`() throws {
+ let (data, blockOff) = Self.kernel(withBlock: Self.stockBlock)
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
+ patcher.parseMachO()
+
+ #expect(patcher.patchAksUnlockBagCount5())
+ #expect(patcher.patches.count == 2)
+
+ let redirect = try #require(patcher.patches.first { $0.patchID == "kernel-cfw-aks_unlock_bag.redirect" })
+ #expect(redirect.fileOffset == blockOff + Self.siteOffset)
+ #expect(Self.words(redirect.patchedBytes) == [0x1400_000C]) // b #0x40
+
+ let cave = try #require(patcher.patches.first { $0.patchID == "kernel-cfw-aks_unlock_bag.cave" })
+ #expect(cave.fileOffset == blockOff + Self.caveOffset)
+ #expect(Self.words(cave.patchedBytes) == [
+ 0x7100_111F, // cmp w8, #4
+ 0x5400_0080, // b.eq #0x54
+ 0x7100_151F, // cmp w8, #5
+ 0x5400_0040, // b.eq #0x54
+ 0x17FF_FFFB, // b #0x3c (BadArgument)
+ 0x17FF_FFF1, // b #0x18 (count-4 path)
+ ])
+ }
+
+ @Test func `does not match a second time over patched bytes`() {
+ let (data, _) = Self.kernel(withBlock: Self.stockBlock)
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
+ patcher.parseMachO()
+ #expect(patcher.patchAksUnlockBagCount5())
+
+ let second = KernelCustomFirmwarePatcher(data: patcher.patchedData, verbose: false)
+ second.parseMachO()
+ #expect(!second.patchAksUnlockBagCount5())
+ #expect(second.patches.isEmpty)
+ }
+
+ @Test func `refuses a check whose struct-count branch goes elsewhere`() {
+ var block = Self.stockBlock
+ block[7] = 0x3500_0068 // cbnz w8, #0x28
+ let (data, _) = Self.kernel(withBlock: block)
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
+ patcher.parseMachO()
+
+ #expect(!patcher.patchAksUnlockBagCount5())
+ #expect(patcher.patches.isEmpty)
+ }
+
+ // MARK: - The real kernel
+
+ /// Gated on `VPHONE_VP600_KERNEL`, a machine-local kernelcache.*.vphone600
+ /// (IM4P or raw) from the cloudOS 26.4 restore.
+ @Test(.enabled(
+ if: ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"] != nil,
+ "VPHONE_VP600_KERNEL is not set; point it at a kernelcache.*.vphone600 to run",
+ ))
+ func `patches a real vphone600 kernel`() throws {
+ let path = try #require(ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"])
+ let (payload, _) = try IM4PHandler.load(contentsOf: URL(fileURLWithPath: path))
+
+ let patcher = KernelCustomFirmwarePatcher(data: payload, verbose: true)
+ patcher.parseMachO()
+ #expect(patcher.patchAksUnlockBagCount5())
+
+ let redirect = try #require(patcher.patches.first { $0.patchID == "kernel-cfw-aks_unlock_bag.redirect" })
+ let cave = try #require(patcher.patches.first { $0.patchID == "kernel-cfw-aks_unlock_bag.cave" })
+ #expect(redirect.beforeDisasm == "cmp w8, #4")
+ #expect(ARM64Encoder.encodeB(from: redirect.fileOffset, to: cave.fileOffset) == redirect.patchedBytes)
+ #expect(Array(Self.words(cave.patchedBytes)[0 ..< 4]) == [0x7100_111F, 0x5400_0080, 0x7100_151F, 0x5400_0040])
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index 5f8ad683..a0ab25f7 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -96,6 +96,16 @@ public enum ARM64Encoder {
return ARM64.encodeU32(insn)
}
+ /// Encode `B.cond`. The immediate is a signed 19-bit instruction offset (±1 MiB).
+ public static func encodeBCond(from pc: Int, to target: Int, condition: ARM64Condition) -> Data? {
+ let delta = target - pc
+ guard delta & 0x3 == 0 else { return nil }
+ let imm19 = delta >> 2
+ guard imm19 >= -(1 << 18), imm19 < (1 << 18) else { return nil }
+ let insn: UInt32 = 0x5400_0000 | ((UInt32(bitPattern: Int32(imm19)) & 0x7FFFF) << 5) | condition.rawValue
+ return ARM64.encodeU32(insn)
+ }
+
/// Encode `CBZ`/`CBNZ` for a general-purpose register.
///
/// The 32-bit form is used by the IOMFB display dispatcher so the loaded