Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Persist Task3 shader caches with the owning executable's cdhash

Arbifoxfda482532062
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index da4d1938..54198466 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -761,7 +761,7 @@ Apple's ROM and this patch. See `Firmware/openavb_boot_rom.md`.
| JB-29 | C | `patch_fpfs_scoped_vnode_open` | Sandbox MACF `mpo_vnode_check_open` (`ops[267]`) → per-process trampoline code cave | **iOS-27 random-respring fix (fpfs balloon).** JB-09 blanket-neuters `mpo_vnode_check_open` (`ops[267]` → allow) so processes can read `/var/jb`. But FileProvider's fpfs parent-walk (`fpfs_pkg_fd_lookup` → `openbyid` climbing via `getattrlistat(ATTR_CMN_PAROBJID)`) uses the stock check's EACCES at the domain-container boundary as its terminus; neutered, the walk climbs unbounded → `ResolverService` (FileProviderResolver) balloons to ~12 GB → `vm-compressor-space-shortage` jetsam → backboardd killed → **respring** (seen on 27b4/24A5390f). Fix keeps the global bypass and enforces the real check for the FileProvider daemons only: on 27, `ops[267]` is left un-neutered (removed from JB-09's blanket list — conditional `if !applyIOS27` in `patchSandboxHooksExtended`), then retargeted to a 20-insn code-cave trampoline that inlines `current_proc` (`mrs tpidr_el1` → `ldr [+0x3F0]` uthread → `ldr [+0x18]` proc), loads `p_comm` (`+0x56C`), compares the first 8 bytes to `"Resolver"`/`"fileprov"`, and on match `b`s to the real `vnode_check_open` (restores the terminus) else returns allow (`mov x0,#0 ; ret` → `/var/jb` reads + Sileo/TrollStore icons unaffected). Register-only (x8–x10), no frame/call (~18 insns/open). Struct offsets recovered via the VZ gdb stub on vphone600; cave bytes from the Keystone-backed `ARM64Encoder`, verified by Capstone round-trip; the `ops[267]` retarget preserves the auth-rebase high bits (same encoder family as JB-09). **VALIDATED on-device (2026-07-23, `17,3_27.0_24A5390f` + cloudOS 26.4, JB, `setup_machine` deploy): resprings stop; Sileo/TrollStoreLite icons render.** Backward-compat: a 26.5 base is unaffected (`ops[267]` still blanket-neutered there) — verified byte-identical kernelcache pre-vs-post (`cmp` clean, `sha256` unchanged). See `KernelJBPatchFpfsScopedOpen.swift`. | Y |
| JB-30 | B | `patchParavirtDisplayRefreshRate` (record `kernel-cfw-display_promotion`; introduced as `kernel-exp-display_refresh_120hz`, renamed when `standard` turned it on) | `AppleParavirtDisplay::createDisplayAttributes` (AppleParavirtGPUIOGPUFamily), the per-mode timing element call | **ProMotion: 120 Hz display timing (on in `standard` since 2026-10-09; it shipped opt-in from 2.4.2).** The host VM service builds its one `PGDisplayMode` with a constant 60.0 Hz and writes it into the display shared state page as a 16-byte entry (u16 width, u16 height, u32 refresh in 16.16 Hz, flags); the guest turns each entry into an IOAV timing element with `ldurh w1,[xN,#-8]; ldurh w2,[xN,#-6]; ldur w3,[xN,#-4]; bl`. The `ldur w3` becomes `movz w3,#120,lsl #16`. Anchor: the `createDisplayAttributes` logger cstring (all refs in one function) + the only w1/w2/w3 load triple off one base at -8/-6/-4 ahead of a call. Gated by `KernelCustomFirmwarePatcher.applyProMotion`, set from the plan. See `Research/Guest/display_refresh_rate.md`. | Y |
| JB-31 | C | `patchParavirtUserClientsNarrow` (records `kernel-cfw-paravirt_user_clients.redirect` / `.cave`; introduced as `kernel-exp-paravirt_user_clients`, renamed when `standard` turned it on) | Same IOUserClient Sandbox gate; the deny block's `ldr Xt,[sp,#imm]` eight bytes before the fail-log `adrp` | **Paravirtual device access on a 26.x / 18.x base (on in `standard` since 2026-10-04; it shipped opt-in).** Narrow replacement for the broad gate-off: at the deny point the class-name C string is already in x0, so a code-cave trampoline reads its first eight bytes and branches to the gate's NotPermitted allow target only for `ApplePar` / `AppleVid` / `AppleVir` / `IOSurfac` (AppleParavirt\*, AppleVideoToolboxParavirt\*, AppleVirtIO\*, IOSurfaceAcceleratorParavirtClient); every other denial runs the displaced `ldr` and falls through to the real deny. Fixes `MTLCreateSystemDefaultDevice()` nil in daemons/CLI and the VideoToolbox/ANE/IOSurface denials (upstream issue #22) without opening the rest. Cave words verified by clang/as + capstone round-trip; the two `b` words via `ARM64Encoder`. Gated by `KernelCustomFirmwarePatcher.applyParavirtUserClients`, set from the plan when `applyIOS27` is false. See `Research/Guest/gpu_acceleration.md`. | Y |
-| JB-32 | B | `patchParavirtTask3Version` (records `kernel-exp-paravirt_gpu_task3.request` / `.features`) | `setupVersion` in AppleParavirtGPUIOGPUFamily: the version request `mov wR,#imm` and the `mov x0, xGranted; bl` that computes the guest's own features | **Paravirtual GPU binary version 252 (Task3), opt-in research (blocked in every shipped preset, added 2026-10-19).** The cloudOS 26.4 kext asks the host for 245; the host's `getAPVFeaturesForVersion` adds supportsDisplayBrightnessCaps at 250, supportsHDRContentHeadroom at 251 and supportsTask3 at 252, and Task3 makes `-[PGRemoteTask calculateCachePathAndExtension:taskRoot:]` name a task's host shader cache after bytes 0x28–0x3b of the guest task root page when they are not all zero. The request immediate becomes 252, and the guest's feature computation is fed the original immediate, because the guest's own table stops at the version it was built for and would step back down. Anchor: the `setupVersion` logger cstring (all refs in one function), a lone `mov wR,#imm` stored to a just-loaded device base, the 32-bit readback of the same displacement, and the `mov x0, xGranted` immediately before a `bl`. Replacement words via `ARM64Encoder.encodeMovzW`. Gated by `KernelCustomFirmwarePatcher.applyParavirtTask3`. Verified on `Lychee` (iPhone17,3 27.0.1, cloudOS 26.4, macOS 27.0.1 host): both sites found once, host logs `Guest requested binary version: 252, setting binary version to: 252`, 0 GPU restarts, and task cache directories keep random names because the guest still writes zeros there. A host that does not know 252 makes the kext step down from that host's maximum minus one; not tested. See `Research/Guest/gpu_acceleration.md`. | Y |
+| JB-32 | B/C | `patchParavirtTask3Version` (`kernel-exp-paravirt_gpu_task3.request`, `.features`, `.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, opt-in.** Phase 1 (2026-10-19) requests binary version 252 while computing guest features from the original 245. 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 an opted-in install. Replacements use ARM64Encoder; new encoders have Keystone 0.9.2 parity tests. Gated by applyParavirtTask3 and blocked in shipped presets. 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. Animation stutter remains. Measurements, cdhash checks and crash analysis are in `Research/Guest/gpu_acceleration.md`. Older hosts remain untested. | Y |
### EXP-Only Kernel Methods (Reference List)
diff --git a/Research/Guest/gpu_acceleration.md b/Research/Guest/gpu_acceleration.md
index 588d31c9..71fb6b93 100644
--- a/Research/Guest/gpu_acceleration.md
+++ b/Research/Guest/gpu_acceleration.md
@@ -556,11 +556,153 @@ and closes normally, and task directories still have 20-character random names,
because the key bytes are zero. On its own it changes nothing visible; it is
the switch the identity write needs.
-Phase 2, not done: write a stable per-program identity (20 bytes, such as a hash
-of the process's code signature or name) at `0x28` when the kext fills the
-header. The kext never touches process identity, and the kernel has no symbols,
-so this needs a code-cave patch calling kernel functions found by semantic
-anchors.
+#### Task3 executable identity implementation, 2026-10-20
+
+Phase 2 extends the same opt-in declaration with `.identity_hook` and
+`.identity_code`. All four sites are discovered and encoded before any write;
+an unresolved site aborts a selected Task3 operation. It remains opt-in under
+`kernel-exp-paravirt_gpu_task3`; the runtime coverage below is one host/guest
+combination. Lychee explicitly enables it in its patch selection.
+
+The key is the owning executable's **20-byte code-signing cdhash**. It is neither
+a process name nor a PID, and it is obtained from the task recorded by the GPU
+task's superclass, rather than `current_proc()`. Concurrent tasks for the same
+executable intentionally share an identity; different executable builds have
+different identities. A missing proc or cdhash leaves twenty zero bytes, which
+retains the host's ephemeral fallback. No host cache files are mixed or copied.
+
+Reveal procedure (cloudOS 26.4 `kernelcache.research.vphone600`, XNU
+12377.100.591.502.1, UUID `784F88D3-2AF5-3D4A-AB00-365607646E44`):
+
+1. Anchor the GPU task initializer with `Failed to create Page Table Lock`.
+ Its root header tail has stores at offsets 8, 16, 20, 28 and 36; hook the
+ descriptor load immediately after that tail, before descriptor preparation
+ and host task registration. Observed initializer `0xfffffe0007ec6b54`, hook
+ `0xfffffe0007ec6e18`, root pointer x8, self x19, displaced
+ `ldr x0,[x19,#0x228]`. The allocation is a fresh 16 KiB page, although its
+ header view is 40 bytes; the host separately reads 60 bytes for Task3. The
+ matcher follows the sized allocation's saved return into the same descriptor
+ ivar and requires at least 60 bytes of backing storage.
+2. Follow the initializer's superclass vtable call, checking that it receives
+ the original x2 task argument. In `IOGPUTask::init` at
+ `0xfffffe00085df244`, the task is retained and stored at self+0x28. Derive
+ this displacement from the store of the saved incoming task argument; it
+ is not an assumed IOGPU or XNU structure layout.
+3. Anchor `flow_divert_get_app_data` with `(%u): failed to get the cdhash`.
+ The call whose null result reaches that log, followed by the 20-byte CDHASH
+ TLV append, identifies `cs_get_cdhash` at `0xfffffe0009199c4c`. Its body
+ matches `bsd/kern/kern_cs.c`: CS_SIGNED test, authenticated text-vnode load,
+ `ubc_cs_blob_get`, null check, pointer to the blob's cdhash. It returns a
+ pointer, not a copied hash.
+4. That same caller's `proc_task` sequence reveals the `proc_struct_size`
+ global (`0xfffffe00096f94b0` in this image). Find the inverse getter through
+ references to that global: subtract it from incoming task, validate the
+ proc zone, test `TF_HASPROC` (0x00800000), return proc or null. This is
+ `get_bsdtask_info` at `0xfffffe0008d7f140`, matching
+ `osfmk/kern/bsd_kern.c`. It is a leaf without a PAC prologue, so a generic
+ preceding-PAC function finder is unsuitable for this helper.
+
+The trampoline clears the key, saves x0–x18 and LR in a 160-byte aligned stack
+frame, calls both helpers with null checks, copies exactly five 32-bit words to
+root+0x28, restores registers and SP, replays the descriptor load and resumes.
+The original next block does not consume incoming NZCV before its virtual
+descriptor call. No original header bytes are changed. Kernel addresses above
+are research observations only; the patch uses Capstone operands, in-image
+xrefs and decoded kernelcache rebases, without these addresses or offsets.
+
+REA/Hopper evidence: task initializer
+`ev_97a491f7966123b66da8c5af9fa362bff268001ed04d1852c8d29f0131e0852e`,
+flow-divert caller
+`ev_bf9605f45f5e2ee44e2ec3ffad5da9c09169a458c131844a3a8f566c681865fb`,
+cdhash getter
+`ev_ca619a3011ec225a768642db3ad6537ef2258616da2141359e3dcb838d46b707`.
+Kernel collection SHA-256
+`86895a2eebeb7fcfb68bcd60f2d7e685687faea07ee31166fb58c872b38e0d92`.
+The symbol database's linked JSON dumps are absent in this checkout; no
+external symbol dump is required by the implementation. Hopper merged some
+neighboring functions; bounded Capstone disassembly established actual entry
+points. Static evidence establishes code behavior, not runtime cache reuse.
+
+Validation procedure: encoder parity against Keystone 0.9.2 and Capstone,
+fixture discovery and no-write failure tests, trampoline execution with
+deliberately clobbered volatile registers, then install with `cfw update-kernel`.
+On Lychee, verify version 252, persistent 40-hex task keys across full reboots,
+per-program separation, Settings animation rounds, Camera, host/guest compiler
+activity and the per-boot `Trying to restart GPU` count. Performance conclusions
+require those runtime checks; warm-state animation limits above still apply.
+
+Local validation: 61 targeted tests across encoder, catalogue, version,
+selection, declaration, plan, gate and Task3 suites passed. The final Task3 pass
+also tests both missing anchors and confirms that no Task3 bytes are emitted.
+The complete `VPhone` bundle build and bundle admission passed. After macOS
+administrator authorization, `cfw update-kernel Lychee` installed all four
+Task3 sites, with no undeclared patch records. The temporary lowered free-space
+check was used only by the installation test bundle on this volume (31 GiB
+free), then restored to 50 GiB in source. Runtime tests use the separately
+installed final bundle `2.10.1-local.e2defa6e`, which retains the 50 GiB check.
+
+Runtime method: macOS 27.0.1 host, iOS 27.0.1 (24A446) guest with cloudOS
+26.4 (23E5207q) driver, five CPUs, 8 GiB RAM, existing guest cache-reuse marker
+enabled. Start with an empty host ECID cache, perform five Settings open/home
+rounds (three-second pauses), launch Camera for ten seconds, shut down the
+guest, and start a fresh VM process. No host files are seeded or copied. Each
+boot logs negotiated version 252. Host compiler counts select only
+`ParentProcessName=com_apple_gpusw_Paravirtualized_*`; fixed display conversion
+work in the Virtualization process and unrelated host programs are excluded.
+The guest compiler capture lasts 55 seconds around the application tests;
+host capture includes boot through shutdown. Both compile counters count log
+events, not unique shaders.
+
+Two identities independently checked against guest binaries with
+`codesign -d --verbose=4`:
+
+| Executable | cdhash and retained host directory suffix |
+| --- | --- |
+| backboardd | `e5543fa5f8667c6cb0d0da787f1b029a9ee3350d` |
+| SpringBoard | `73c64934fd90e09f461a339f84dad665f0669885` |
+
+Preferences itself did not create a directory matching its executable hash in
+these runs; CoreAnimation work is performed by the rendering servers. Nine
+distinct `task-<40 hex>` directories survived the first shutdown and were
+reused on the next boot. Host GPU task process IDs change between boots, so
+this is disk persistence rather than retained task-service memory.
+
+| Full boot | Retained keys | Host GPU compiles, whole run | Host GPU compiles, Settings rounds | Guest compiles, 55 s | GPU restarts | First home on time | Home rounds 2–5 |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| 01, empty host cache | 9 | 631 | 121 | 64 | 0 | 44.4% | 61–72% |
+| 02, reused | same 9 | 17 | 5 | 11 | 0 | 61.8% | 66–74% |
+| 03, reused | same 9 | 12 | **0** | 22 | 0 | 59.2% | 63–72% |
+
+Camera reached the foreground and returned home in all three runs. The
+backboardd host `functions.list` grew from 31,404 to 32,692 to 34,036 bytes as
+additional variants were learned. SpringBoard's stayed at 4,412 bytes. Guest
+compiles were attributed to backboardd and include Camera and late work;
+remaining variants still compile, so neither counter is promised to reach zero
+for an arbitrary workload. The eight fixed host display conversion compiles
+per run are outside these task caches.
+
+Frame figures use the guest `CARenderServerGetFrameCounter` probe, aligned to
+host command windows at probe launch, and count observed inter-sample gaps
+between zero and one second as on time when at most 20 ms. They include pauses
+inside each open/home command window, are not animation FPS, and are only a
+small repeated-workload comparison on this machine. The cold host run already
+had the guest cache-reuse change; this is not an unpatched-versus-patched A/B.
+The host compilation reduction and key retention directly establish cache
+reuse. The remaining frame gaps establish that **persistent caches do not
+eliminate all animation lag**. Scheduling, VM rendering and other work remain.
+
+No new crash reports appeared during the first two application-test windows.
+The third produced a Passbook widget `SIGTRAP`: `_assertionFailure` →
+`swift_unexpectedError` → FinanceKit+7,719,608. Its fault, frames and image UUIDs
+match an existing October 18 report, predating this identity patch. No new
+backboardd or cameracaptured crash appeared. A fourth full boot then launched
+Notes, Calendar, Reminders, Settings, Safari, News, Podcasts, Tips, Music,
+Camera and Contacts, returning home between launches. All eleven foreground
+checks passed, with zero GPU restarts and no new crash reports during the
+application-test window. Lychee was shut down normally afterward. The temporary
+installation bundle with the lowered disk check was removed from Launchpad.
+Raw runtime captures and the Swift report driver are local scratch artifacts under
+`/tmp/vphone-shader-cache-hopper/`, not shipped components.
## Heap Textures Have No CPU Layout
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtTask3.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtTask3.swift
index 2a37e00f..a967d026 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtTask3.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtTask3.swift
@@ -1,6 +1,7 @@
// KernelCustomFirmwarePatchParavirtTask3.swift — CFW kernel patch: ask the host
// for paravirtual GPU binary version 252 while the guest keeps the features of
-// the version it was built for.
+// the version it was built for, and fill each task's Task3 executable identity
+// before the host registers it. Both parts share one opt-in declaration.
//
// Background: the guest GPU kext (AppleParavirtGPUIOGPUFamily) negotiates a
// binary version with ParavirtualizedGraphics at start-up, and the host derives
@@ -80,12 +81,21 @@ extension KernelCustomFirmwarePatcher {
return false
}
guard let request = ARM64Encoder.encodeMovzW(rd: hit.rd, imm16: Self.paravirtTask3Version),
- let guestVersion = ARM64Encoder.encodeMovzW(rd: 0, imm16: hit.version)
+ let guestVersion = ARM64Encoder.encodeMovzW(rd: 0, imm16: hit.version),
+ let identity = paravirtTaskIdentity(),
+ let cave = findCodeCave(size: 256),
+ let code = pvIdentityCode(identity, at: cave), code.count <= 256,
+ let branch = ARM64Encoder.encodeB(from: identity.hook, to: cave)
else {
- log(" [-] could not encode the version constants")
+ log(" [-] Task3 discovery or encoding failed; no Task3 sites written")
return false
}
+ emit(cave, code, patchID: FirmwarePatchSetCatalog.paravirtTask3Patch + ".identity_code",
+ virtualAddress: fileOffsetToVA(cave), description: "copy the owning executable's 20-byte cdhash into TaskRoot+0x28")
+ emit(identity.hook, branch, patchID: FirmwarePatchSetCatalog.paravirtTask3Patch + ".identity_hook",
+ virtualAddress: fileOffsetToVA(identity.hook), description: "write Task3 identity before descriptor preparation and task registration")
+
emit(
hit.request,
request,
@@ -172,3 +182,283 @@ extension KernelCustomFirmwarePatcher {
return nil
}
}
+
+// MARK: - Task3 executable identity
+
+extension KernelCustomFirmwarePatcher {
+ private struct ParavirtTaskIdentity {
+ let hook: Int
+ let selfRegister: UInt32
+ let rootRegister: UInt32
+ let descriptorOffset: UInt32
+ let ownerOffset: UInt32
+ let getBSDTaskInfo: Int
+ let getCDHash: Int
+ }
+
+ /// Discover every dependency before emitting any of the indivisible Task3 sites.
+ /// XNU sources: kern_cs.c::cs_get_cdhash, flow_divert.c::flow_divert_get_app_data,
+ /// bsd_kern.c::get_bsdtask_info. No task/proc layout offsets are assumed here.
+ private func paravirtTaskIdentity() -> ParavirtTaskIdentity? {
+ guard let anchor = buffer.findString("%s: Failed to create Page Table Lock\n") else {
+ log(" [-] Task3 task initializer anchor absent")
+ return nil
+ }
+ let starts = Set(findStringRefs(anchor).compactMap { pvFunctionStart($0.adrpOff) })
+ guard starts.count == 1, let start = starts.first,
+ let selfReg = pvIncomingRegister(0, at: start),
+ let taskReg = pvIncomingRegister(2, at: start),
+ let ownerOffset = pvOwnerOffset(start: start, selfReg: selfReg, taskReg: taskReg)
+ else {
+ log(" [-] Task3 owning task could not be recovered from the superclass initializer")
+ return nil
+ }
+
+ var hooks: [(Int, UInt32, UInt32)] = []
+ for off in stride(from: start, to: min(start + 0x1000, buffer.count - 40), by: 4) {
+ // The original TaskRoot header ends at 0x28. Match its complete tail,
+ // including the unaligned fields, then displace the descriptor load.
+ guard let pair = disasAt(off), pair.mnemonic == "stp",
+ let p = pair.detail?.operands, p.count == 3,
+ pair.detail?.writeback == false, p[0].type == .register, p[0].reg == .w(0),
+ let version = plainMoveW(at: off - 4), version.1 == 2,
+ p[1].type == .register, p[1].reg == .w(Int(version.0)),
+ p[2].type == .memory, p[2].mem.disp == 0, p[2].mem.index == .invalid,
+ let root = pvXNumber(p[2].mem.base), root < 18,
+ pvMemory(off + 4, "str", .xzr, .x(Int(root)), 8),
+ pvMemory(off + 8, "str", .wzr, .x(Int(root)), 0x10),
+ let field = disasAt(off + 12)?.detail?.operands, field.count == 2,
+ disasAt(off + 12)?.mnemonic == "ldr", field[1].mem.base == .x(Int(selfReg)),
+ pvMemory(off + 16, "stur", field[0].reg, .x(Int(root)), 0x14),
+ pvMemory(off + 20, "stur", .xzr, .x(Int(root)), 0x1c),
+ pvMemory(off + 24, "str", .wzr, .x(Int(root)), 0x24),
+ let load = disasAt(off + 28), load.mnemonic == "ldr", load.detail?.writeback == false,
+ let l = load.detail?.operands, l.count == 2, l[0].reg == .x(0),
+ l[1].type == .memory, l[1].mem.base == .x(Int(selfReg)), l[1].mem.index == .invalid,
+ l[1].mem.disp >= 0,
+ pvDescriptorHasKeySpace(start: start, end: off, selfReg: selfReg, descriptorOffset: l[1].mem.disp),
+ pvMemory(off + 32, "ldr", .x(16), .x(0), 0)
+ else { continue }
+ hooks.append((off + 28, root, UInt32(l[1].mem.disp)))
+ }
+ guard hooks.count == 1, let hook = hooks.first, let helpers = pvIdentityHelpers() else {
+ log(" [-] Task3 header or kernel identity helpers not resolved uniquely")
+ return nil
+ }
+ return ParavirtTaskIdentity(
+ hook: hook.0, selfRegister: selfReg, rootRegister: hook.1,
+ descriptorOffset: hook.2, ownerOffset: ownerOffset,
+ getBSDTaskInfo: helpers.bsd, getCDHash: helpers.hash
+ )
+ }
+
+ /// Follow the sized allocation's saved return value to this descriptor ivar.
+ /// The bounded header view is only 40 bytes; its backing allocation must
+ /// independently have room for the host's 60-byte Task3 root read.
+ private func pvDescriptorHasKeySpace(start: Int, end: Int, selfReg: UInt32, descriptorOffset: Int32) -> Bool {
+ for off in stride(from: start, to: end, by: 4) {
+ guard let size = plainMoveW(at: off), size.0 == 2, size.1 >= 60,
+ pvBranch(off + 4, mnemonic: "bl") != nil,
+ let move = disasAt(off + 8), move.mnemonic == "mov",
+ let p = move.detail?.operands, p.count == 2, p[1].reg == .x(0),
+ let saved = pvXNumber(p[0].reg), saved >= 19
+ else { continue }
+ if stride(from: off + 12, through: min(off + 64, end), by: 4).contains(where: {
+ pvMemory($0, "str", .x(Int(saved)), .x(Int(selfReg)), descriptorOffset)
+ }) { return true }
+ }
+ return false
+ }
+
+ private func pvFunctionStart(_ at: Int) -> Int? {
+ for off in stride(from: at & ~3, through: max(0, at - 0x4000), by: -4) {
+ if disasAt(off)?.mnemonic == "pacibsp" { return off }
+ }
+ return nil
+ }
+
+ private func pvXNumber(_ reg: ARM64Register) -> UInt32? {
+ (0 ... 30).first { ARM64Register.x($0) == reg }.map(UInt32.init)
+ }
+
+ private func pvMove(_ at: Int, _ to: ARM64Register, _ from: ARM64Register) -> Bool {
+ guard let i = disasAt(at), i.mnemonic == "mov", let p = i.detail?.operands, p.count == 2 else { return false }
+ return p[0].type == .register && p[0].reg == to && p[1].type == .register && p[1].reg == from
+ }
+
+ private func pvMemory(_ at: Int, _ mnemonic: String, _ reg: ARM64Register, _ base: ARM64Register, _ disp: Int32) -> Bool {
+ guard let i = disasAt(at), i.mnemonic == mnemonic, i.detail?.writeback == false,
+ let p = i.detail?.operands, p.count == 2 else { return false }
+ return p[0].type == .register && p[0].reg == reg && p[1].type == .memory
+ && p[1].mem.base == base && p[1].mem.index == .invalid && p[1].mem.disp == disp
+ }
+
+ private func pvIncomingRegister(_ arg: Int, at start: Int) -> UInt32? {
+ for off in stride(from: start + 4, to: start + 0x80, by: 4) {
+ guard let i = disasAt(off) else { return nil }
+ if i.isCall { return nil }
+ if i.mnemonic == "mov", let p = i.detail?.operands, p.count == 2,
+ p[1].type == .register, p[1].reg == .x(arg), let reg = pvXNumber(p[0].reg), reg >= 19 {
+ return reg
+ }
+ }
+ return nil
+ }
+
+ /// ADRP followed by a 64-bit load of a global. Values are file coordinates,
+ /// as are Capstone's PC-relative operands in the kernel patcher.
+ private func pvGlobalLoad(_ at: Int) -> (global: Int, register: ARM64Register)? {
+ guard let a = disasAt(at), a.mnemonic == "adrp", let p = a.detail?.operands, p.count == 2,
+ p[1].type == .immediate,
+ let l = disasAt(at + 4), l.mnemonic == "ldr", l.detail?.writeback == false,
+ let q = l.detail?.operands, q.count == 2, pvXNumber(q[0].reg) != nil,
+ q[1].type == .memory, q[1].mem.base == p[0].reg, q[1].mem.index == .invalid
+ else { return nil }
+ let global = Int(p[1].imm) + Int(q[1].mem.disp)
+ guard global >= 0, global + 8 <= buffer.count else { return nil }
+ return (global, q[0].reg)
+ }
+
+ private func pvBranch(_ at: Int, mnemonic: String) -> Int? {
+ guard let i = disasAt(at), i.mnemonic == mnemonic,
+ let last = i.detail?.operands.last, last.type == .immediate else { return nil }
+ let target = Int(last.imm)
+ return jbIsInCodeRange(target) ? target : nil
+ }
+
+ /// Follow the superclass vtable, then recover the store of its incoming task
+ /// argument. Both authenticated and unauthenticated kernelcache rebases use
+ /// a base-relative 30-bit target; reject binds and out-of-image pointers.
+ private func pvRebase(_ at: Int) -> Int? {
+ guard at >= 0, at + 8 <= buffer.count else { return nil }
+ let raw = buffer.readU64(at: at)
+ guard raw & (1 << 62) == 0 else { return nil }
+ let target = Int(raw & 0x3fff_ffff)
+ return target > 0 && target < buffer.count ? target : nil
+ }
+
+ private func pvOwnerOffset(start: Int, selfReg: UInt32, taskReg: UInt32) -> UInt32? {
+ var offsets = Set<UInt32>()
+ for off in stride(from: start, to: start + 0x200, by: 4) {
+ guard let g = pvGlobalLoad(off), let table = pvRebase(g.global),
+ let l = disasAt(off + 8), l.mnemonic == "ldr", l.detail?.writeback == true,
+ let p = l.detail?.operands, p.count == 2, p[1].type == .memory,
+ p[1].mem.base == g.register, p[1].mem.index == .invalid,
+ let parent = pvRebase(table + Int(p[1].mem.disp)), jbIsInCodeRange(parent),
+ disasAt(parent)?.mnemonic == "pacibsp",
+ let call = (1 ... 10).map({ off + 8 + $0 * 4 }).first(where: {
+ disasAt($0)?.mnemonic == "blraa" && disasAt($0)?.detail?.operands.first?.reg == p[0].reg
+ }), call > off + 8,
+ stride(from: off + 12, to: call, by: 4).contains(where: { pvMove($0, .x(2), .x(Int(taskReg))) }),
+ stride(from: off + 12, to: call, by: 4).contains(where: { pvMove($0, .x(0), .x(Int(selfReg))) }),
+ let parentSelf = pvIncomingRegister(0, at: parent),
+ let parentTask = pvIncomingRegister(2, at: parent)
+ else { continue }
+ for store in stride(from: parent + 4, to: parent + 0x200, by: 4) {
+ guard let i = disasAt(store), i.mnemonic == "str", i.detail?.writeback == false,
+ let q = i.detail?.operands, q.count == 2, q[0].reg == .x(Int(parentTask)),
+ q[1].type == .memory, q[1].mem.base == .x(Int(parentSelf)), q[1].mem.index == .invalid,
+ q[1].mem.disp > 0, q[1].mem.disp % 8 == 0,
+ pvBranch(store - 4, mnemonic: "bl") != nil,
+ pvMove(store - 8, .x(0), .x(Int(parentTask)))
+ else { continue }
+ offsets.insert(UInt32(q[1].mem.disp))
+ }
+ }
+ return offsets.count == 1 ? offsets.first : nil
+ }
+
+ private func pvIdentityHelpers() -> (bsd: Int, hash: Int)? {
+ guard let string = buffer.findString("(%u): failed to get the cdhash\n") else { return nil }
+ let refs = findStringRefs(string)
+ guard refs.count == 1, let ref = refs.first, let start = pvFunctionStart(ref.adrpOff) else { return nil }
+ var hashes = Set<Int>()
+ for off in stride(from: start, to: ref.adrpOff, by: 4) {
+ guard let target = pvBranch(off, mnemonic: "bl"),
+ let failure = pvBranch(off + 4, mnemonic: "cbz"),
+ disasAt(off + 4)?.detail?.operands.first?.reg == .x(0),
+ failure <= ref.adrpOff, failure >= ref.adrpOff - 32,
+ pvMove(off + 8, .x(3), .x(0)),
+ (3 ... 9).contains(where: { plainMoveW(at: off + $0 * 4).map { $0.0 == 2 && $0.1 == 20 } == true })
+ else { continue }
+ hashes.insert(target)
+ }
+ guard hashes.count == 1, let hash = hashes.first,
+ disasAt(hash)?.mnemonic == "pacibsp" else { return nil }
+
+ // Source-backed proc_task(p): test P_LHASTASK, load proc_struct_size,
+ // add it to p, then test the returned task. This supplies the global
+ // referenced by the inverse get_bsdtask_info() without a fixed address.
+ var sizes = Set<Int>()
+ for off in stride(from: ref.addOff + 4, through: ref.addOff + 80, by: 4) {
+ guard let g = pvGlobalLoad(off), let add = disasAt(off + 8), add.mnemonic == "add",
+ let p = add.detail?.operands, p.count == 3, p[0].reg == .x(0), p[1].reg == g.register,
+ pvXNumber(p[2].reg) != nil, pvBranch(off + 12, mnemonic: "cbz") != nil,
+ let test = disasAt(off - 4), test.mnemonic == "tbz", let q = test.detail?.operands,
+ q.count == 3, q[1].type == .immediate, q[1].imm == 1
+ else { continue }
+ sizes.insert(g.global)
+ }
+ guard sizes.count == 1, let size = sizes.first else { return nil }
+ var getters = Set<Int>()
+ for off in adrpIndex[UInt64(size) & ~0xfff] ?? [] {
+ guard let g = pvGlobalLoad(off), g.global == size,
+ let sub = disasAt(off + 8), sub.mnemonic == "subs", let p = sub.detail?.operands,
+ p.count == 3, p[0].reg == .x(1), p[1].reg == .x(0), p[2].reg == g.register,
+ let tail = pvBranch(off + 12, mnemonic: "b.eq"), tail > off, tail < off + 0x100,
+ let load = disasAt(tail), load.mnemonic == "ldr", let l = load.detail?.operands,
+ l.count == 2, l[1].type == .memory, l[1].mem.base == .x(0),
+ let test = disasAt(tail + 4), test.mnemonic == "tst", let t = test.detail?.operands,
+ t.count == 2, t[0].reg == l[0].reg, t[1].type == .immediate, t[1].imm == 0x0080_0000,
+ let select = disasAt(tail + 8), select.mnemonic == "csel", select.detail?.conditionCode == .eq,
+ let s = select.detail?.operands, s.count == 3,
+ s[0].reg == .x(0), s[1].reg == .xzr, s[2].reg == .x(1),
+ disasAt(tail + 12)?.mnemonic == "ret"
+ else { continue }
+ getters.insert(off)
+ }
+ guard getters.count == 1, let bsd = getters.first else { return nil }
+ log(String(format: " [+] Task3 helpers: get_bsdtask_info @ 0x%X, cs_get_cdhash @ 0x%X", bsd, hash))
+ return (bsd, hash)
+ }
+
+ /// Inline trampoline: preserve every volatile GPR and LR, obtain the owning
+ /// task's cdhash, copy exactly 20 bytes, replay the displaced descriptor load.
+ /// A missing proc/hash leaves a zero key and the host's ephemeral fallback.
+ private func pvIdentityCode(_ site: ParavirtTaskIdentity, at cave: Int) -> Data? {
+ var words: [Data?] = []
+ func put(_ word: Data?) { words.append(word) }
+ let root = site.rootRegister
+ put(ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: root, offset: 0x28))
+ put(ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: root, offset: 0x30))
+ put(ARM64Encoder.encodeStrWUnsignedOffset(rt: 31, rn: root, offset: 0x38))
+ put(ARM64Encoder.encodeSubImm12(rd: 31, rn: 31, imm12: 160))
+ for reg in stride(from: UInt32(0), through: 16, by: 2) {
+ put(ARM64Encoder.encodeStpX(rt1: reg, rt2: reg + 1, rn: 31, offset: Int32(reg * 8)))
+ }
+ put(ARM64Encoder.encodeStpX(rt1: 18, rt2: 30, rn: 31, offset: 144))
+ put(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: site.selfRegister, offset: site.ownerOffset))
+ put(ARM64Encoder.encodeBL(from: cave + words.count * 4, to: site.getBSDTaskInfo))
+ let noProc = words.count; put(nil)
+ put(ARM64Encoder.encodeBL(from: cave + words.count * 4, to: site.getCDHash))
+ let noHash = words.count; put(nil)
+ put(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 9, rn: 31, offset: root * 8))
+ for offset in stride(from: UInt32(0), to: 20, by: 4) {
+ put(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 10, rn: 0, offset: offset))
+ put(ARM64Encoder.encodeStrWUnsignedOffset(rt: 10, rn: 9, offset: 0x28 + offset))
+ }
+ let done = cave + words.count * 4
+ for index in [noProc, noHash] {
+ words[index] = ARM64Encoder.encodeCompareBranch(nonzero: false, register: 0, from: cave + index * 4, to: done, width64: true)
+ }
+ for reg in UInt32(0) ... 18 {
+ put(ARM64Encoder.encodeLdrXUnsignedOffset(rt: reg, rn: 31, offset: reg * 8))
+ }
+ put(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 30, rn: 31, offset: 152))
+ put(ARM64Encoder.encodeAddImm12(rd: 31, rn: 31, imm12: 160))
+ put(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: site.selfRegister, offset: site.descriptorOffset))
+ put(ARM64Encoder.encodeB(from: cave + words.count * 4, to: site.hook + 4))
+ guard words.allSatisfy({ $0 != nil }) else { return nil }
+ return words.compactMap { $0 }.reduce(into: Data()) { $0.append($1) }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index aed4c1f1..5154fd96 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -123,9 +123,13 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
patchParavirtDisplayRefreshRate()
}
- // Opt-in: ask the host for the Task3 binary version.
+ // Opt-in: negotiate Task3 and identify the executable before registration.
if applyParavirtTask3 {
- patchParavirtTask3Version()
+ guard patchParavirtTask3Version() else {
+ throw NSError(domain: "FirmwarePatcher.ParavirtTask3", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "Cannot resolve the complete Task3 shader-cache patch; kernel was not installed",
+ ])
+ }
}
// Group C
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index c851d1b5..db8af570 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -322,11 +322,12 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
VPhonePatchDeclaration(
identifier: FirmwarePatchSetCatalog.paravirtTask3Patch,
- title: "GPU Task3 version",
+ title: "GPU Task3 shader cache",
summary: """
Research: the guest GPU driver asks the host for binary version 252 \
- (Task3) while keeping its own features, so the host can key each \
- guest process's shader cache instead of starting it empty.
+ (Task3) while keeping its own features, and writes the owning \
+ executable's code-signing hash into each task root. The host \
+ retains a separate shader cache for each executable across boots.
""",
target: .firmware(.kernelcache),
),
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index 68fe3e93..f957c711 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -522,7 +522,38 @@ struct ARM64EncoderKeystoneParityTests {
.init(source: "autib1716", keystone: 0xD503_21DF, encoded: ARM64.autib1716, origin: "Keystone hint #14"),
]
- static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases + x1ComparisonCases + x1LoweringCases
+ // Keystone 0.9.2, ks_asm via a scratch C driver linked to libkeystone.a.
+ static let task3Cases: [ARM64EncodingCase] = [
+ .init(source: "ldr x0, [x19, #0x28]", keystone: 0xF940_1660, encoded: ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: 40), origin: "Task3 owner"),
+ .init(source: "ldr x30, [sp, #152]", keystone: 0xF940_4FFE, encoded: ARM64Encoder.encodeLdrXUnsignedOffset(rt: 30, rn: 31, offset: 152), origin: "Task3 LR restore"),
+ .init(source: "ldr xzr, [x0, #32760]", keystone: 0xF97F_FC1F, encoded: ARM64Encoder.encodeLdrXUnsignedOffset(rt: 31, rn: 0, offset: 32760), origin: "maximum offset"),
+ .init(source: "ldr x9, [sp]", keystone: 0xF940_03E9, encoded: ARM64Encoder.encodeLdrXUnsignedOffset(rt: 9, rn: 31, offset: 0), origin: "zero offset"),
+ .init(source: "str w10, [x9, #40]", keystone: 0xB900_292A, encoded: ARM64Encoder.encodeStrWUnsignedOffset(rt: 10, rn: 9, offset: 40), origin: "Task3 hash copy"),
+ .init(source: "str wzr, [x8, #56]", keystone: 0xB900_391F, encoded: ARM64Encoder.encodeStrWUnsignedOffset(rt: 31, rn: 8, offset: 56), origin: "Task3 zero fallback"),
+ .init(source: "str w0, [sp]", keystone: 0xB900_03E0, encoded: ARM64Encoder.encodeStrWUnsignedOffset(rt: 0, rn: 31, offset: 0), origin: "SP and zero offset"),
+ .init(source: "str w30, [x29, #16380]", keystone: 0xB93F_FFBE, encoded: ARM64Encoder.encodeStrWUnsignedOffset(rt: 30, rn: 29, offset: 16380), origin: "maximum offset"),
+ .init(source: "sub sp, sp, #160", keystone: 0xD102_83FF, encoded: ARM64Encoder.encodeSubImm12(rd: 31, rn: 31, imm12: 160), origin: "Task3 aligned frame"),
+ .init(source: "sub x0, x1, #4095", keystone: 0xD13F_FC20, encoded: ARM64Encoder.encodeSubImm12(rd: 0, rn: 1, imm12: 4095), origin: "maximum immediate"),
+ .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
+
+ @Test func `Task3 encoders reject invalid registers and offsets`() {
+ for invalid in [UInt32(32), 100] {
+ #expect(ARM64Encoder.encodeLdrXUnsignedOffset(rt: invalid, rn: 0, offset: 0) == nil)
+ #expect(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: invalid, offset: 0) == nil)
+ #expect(ARM64Encoder.encodeStrWUnsignedOffset(rt: invalid, rn: 0, offset: 0) == nil)
+ #expect(ARM64Encoder.encodeStrWUnsignedOffset(rt: 0, rn: invalid, offset: 0) == nil)
+ #expect(ARM64Encoder.encodeSubImm12(rd: invalid, rn: 0, imm12: 0) == nil)
+ #expect(ARM64Encoder.encodeSubImm12(rd: 0, rn: invalid, imm12: 0) == nil)
+ }
+ #expect(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 0, offset: 4) == nil)
+ #expect(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 0, offset: 32768) == nil)
+ #expect(ARM64Encoder.encodeStrWUnsignedOffset(rt: 0, rn: 0, offset: 2) == nil)
+ #expect(ARM64Encoder.encodeStrWUnsignedOffset(rt: 0, rn: 0, offset: 16384) == nil)
+ #expect(ARM64Encoder.encodeSubImm12(rd: 0, rn: 0, imm12: 4096) == nil)
+ }
@Test func `new X1 encoders refuse unencodable operands`() {
#expect(ARM64Encoder.encodeMaddSubX(subtract: false, rd: 32, rn: 0, rm: 0, ra: 0) == nil)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelParavirtTask3Tests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelParavirtTask3Tests.swift
new file mode 100644
index 00000000..5af544c8
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelParavirtTask3Tests.swift
@@ -0,0 +1,139 @@
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("Paravirtual GPU Task3")
+struct KernelParavirtTask3Tests {
+ // The raw vphone600 research kernel is operator supplied, never redistributed.
+ static var fixture: String? { ProcessInfo.processInfo.environment["VPHONE_TASK3_KERNEL"] }
+
+ private func prepared(_ data: Data) -> KernelCustomFirmwarePatcher {
+ let patcher = KernelCustomFirmwarePatcher(data: data)
+ patcher.parseMachO()
+ patcher.buildADRPIndex()
+ return patcher
+ }
+
+ @Test(.enabled(if: fixture != nil))
+ func `discovers the complete patch in the supplied kernel`() throws {
+ let data = try Data(contentsOf: URL(fileURLWithPath: #require(Self.fixture)))
+ let patcher = prepared(data)
+ #expect(patcher.patchParavirtTask3Version())
+ #expect(patcher.patches.count == 4)
+ let ids = Set(patcher.patches.map(\.patchID))
+ let prefix = FirmwarePatchSetCatalog.paravirtTask3Patch
+ #expect(ids == Set(["request", "features", "identity_hook", "identity_code"].map { prefix + "." + $0 }))
+
+ let code = try #require(patcher.patches.first { $0.patchID == prefix + ".identity_code" })
+ let hook = try #require(patcher.patches.first { $0.patchID == prefix + ".identity_hook" })
+ for availability in [(true, true), (false, true), (true, false)] {
+ try executeTrampoline(code, hook: hook, procAvailable: availability.0, hashAvailable: availability.1)
+ }
+
+ let second = prepared(patcher.patchedData)
+ #expect(!second.patchParavirtTask3Version())
+ #expect(second.patches.isEmpty)
+ }
+
+ /// Execute the emitted instructions with hostile caller-saved register
+ /// clobbers at the two helper calls. This catches stack/LR/root-pointer
+ /// mistakes and over-copying that a disassembly snapshot would miss.
+ private func executeTrampoline(_ code: PatchRecord, hook: PatchRecord, procAvailable: Bool, hashAvailable: Bool) throws {
+ let decoder = ARM64Disassembler()
+ let instructions = decoder.disassemble(code.patchedBytes, at: UInt64(code.fileOffset))
+ let original = try #require(decoder.disassemble(hook.originalBytes, at: UInt64(hook.fileOffset)).first)
+ let displaced = try #require(original.detail?.operands)
+ let selfReg = displaced[1].mem.base
+ let rootReg = try #require(instructions.first?.detail?.operands.last?.mem.base)
+ let taskLoad = try #require(instructions.first {
+ $0.mnemonic == "ldr" && $0.detail?.operands.last?.mem.base == selfReg
+ })
+ let ownerOffset = try #require(taskLoad.detail?.operands.last?.mem.disp)
+ var registers = Dictionary(uniqueKeysWithValues: (0 ... 30).map { (ARM64Register.x($0), UInt64(0x100 + $0)) })
+ registers[selfReg] = 0x300000
+ registers[rootReg] = 0x200000
+ let saved = registers
+ var sp: UInt64 = 0x100000
+ var memory: [UInt64: UInt8] = [:]
+ func readRegister(_ r: ARM64Register) -> UInt64 {
+ if r == .sp { return sp }
+ if let n = (0 ... 30).first(where: { ARM64Register.w($0) == r }) {
+ return registers[.x(n), default: 0] & 0xffff_ffff
+ }
+ return registers[r, default: 0]
+ }
+ func writeRegister(_ r: ARM64Register, _ value: UInt64) {
+ if r == .sp { sp = value }
+ else if let n = (0 ... 30).first(where: { ARM64Register.w($0) == r }) { registers[.x(n)] = value & 0xffff_ffff }
+ else if r != .xzr && r != .wzr { registers[r] = value }
+ }
+ func store(_ address: UInt64, _ value: UInt64, _ count: Int) {
+ for byte in 0 ..< count { memory[address + UInt64(byte)] = UInt8(truncatingIfNeeded: value >> (byte * 8)) }
+ }
+ func load(_ address: UInt64, _ count: Int) -> UInt64 {
+ (0 ..< count).reduce(0) { $0 | UInt64(memory[address + UInt64($1), default: 0]) << ($1 * 8) }
+ }
+ func address(_ operand: ARM64Operand) -> UInt64 { readRegister(operand.mem.base) &+ UInt64(bitPattern: Int64(operand.mem.disp)) }
+ store(0x300000 + UInt64(ownerOffset), 0x400000, 8)
+ store(0x300000 + UInt64(displaced[1].mem.disp), 0xdeadbeef, 8)
+ for byte in 0 ..< 80 { memory[0x200000 + UInt64(byte)] = 0xcc }
+ let hash = (0 ..< 20).map { UInt8($0 + 1) }
+ for byte in 0 ..< 20 { memory[0x600000 + UInt64(byte)] = hash[byte] }
+ var pc = code.fileOffset
+ var calls = 0
+ for _ in 0 ..< 150 {
+ if pc == hook.fileOffset + 4 { break }
+ let i = try #require(instructions.first { $0.address == UInt64(pc) })
+ let p = try #require(i.detail?.operands)
+ var next = pc + 4
+ switch i.mnemonic {
+ case "sub", "add":
+ let left = readRegister(p[1].reg), right = UInt64(p[2].imm)
+ writeRegister(p[0].reg, i.mnemonic == "add" ? left &+ right : left &- right)
+ case "stp":
+ store(address(p[2]), readRegister(p[0].reg), 8)
+ store(address(p[2]) + 8, readRegister(p[1].reg), 8)
+ case "ldr", "str":
+ let width = (0 ... 30).contains { ARM64Register.w($0) == p[0].reg } || p[0].reg == .wzr ? 4 : 8
+ if i.mnemonic == "ldr" { writeRegister(p[0].reg, load(address(p[1]), width)) }
+ else { store(address(p[1]), readRegister(p[0].reg), width) }
+ case "bl":
+ #expect(readRegister(.x(0)) == (calls == 0 ? 0x400000 : 0x500000))
+ for reg in 0 ... 17 { registers[.x(reg)] = UInt64(0x700000 + reg) }
+ registers[.x(30)] = UInt64(pc + 4)
+ registers[.x(0)] = calls == 0 ? (procAvailable ? 0x500000 : 0) : (hashAvailable ? 0x600000 : 0)
+ calls += 1
+ case "cbz":
+ if readRegister(p[0].reg) == 0 { next = Int(p[1].imm) }
+ case "b": next = Int(p[0].imm)
+ default: Issue.record("Unexpected trampoline instruction: \(i)")
+ }
+ pc = next
+ }
+ #expect(pc == hook.fileOffset + 4)
+ #expect(sp == 0x100000)
+ #expect(calls == (procAvailable ? 2 : 1))
+ for reg in 1 ... 30 { #expect(registers[.x(reg)] == saved[.x(reg)]) }
+ #expect(registers[.x(0)] == 0xdeadbeef)
+ let key = (0 ..< 20).map { memory[0x200028 + UInt64($0), default: 0] }
+ #expect(key == (procAvailable && hashAvailable ? hash : Array(repeating: 0, count: 20)))
+ #expect((0 ..< 40).allSatisfy { memory[0x200000 + UInt64($0)] == 0xcc })
+ #expect((60 ..< 80).allSatisfy { memory[0x200000 + UInt64($0)] == 0xcc })
+ }
+
+ @Test(.enabled(if: fixture != nil), arguments: [
+ "%s: Failed to create Page Table Lock\n",
+ "(%u): failed to get the cdhash\n",
+ ])
+ func `missing identity anchor leaves every Task3 site unchanged`(text: String) throws {
+ var data = try Data(contentsOf: URL(fileURLWithPath: #require(Self.fixture)))
+ let anchor = Data(text.utf8)
+ let range = try #require(data.range(of: anchor))
+ data[range.lowerBound] = 0
+ let patcher = prepared(data)
+ #expect(!patcher.patchParavirtTask3Version())
+ #expect(patcher.patches.isEmpty)
+ #expect(patcher.patchedData == data)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index 1028df7b..0e8aebc9 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -191,6 +191,12 @@ public enum ARM64Encoder {
return ARM64.encodeU32(insn)
}
+ /// SUB Xd, Xn, #imm12; register 31 denotes SP, without changing flags.
+ public static func encodeSubImm12(rd: UInt32, rn: UInt32, imm12: UInt32) -> Data? {
+ guard rd < 32, rn < 32, imm12 < 4096 else { return nil }
+ return ARM64.encodeU32(0xD100_0000 | (imm12 << 10) | (rn << 5) | rd)
+ }
+
/// Encode MOVZ Wd, #imm16 (32-bit).
///
/// Format: `[31] = 0 (sf)`, `[30:29] = 10`, `[28:23] = 100101`,
@@ -281,8 +287,20 @@ public enum ARM64Encoder {
return ARM64.encodeU32(insn)
}
+ /// LDR Xt, [Xn, #offset]; rn 31 is SP, scaled by eight.
+ public static func encodeLdrXUnsignedOffset(rt: UInt32, rn: UInt32, offset: UInt32) -> Data? {
+ guard rt < 32, rn < 32, offset % 8 == 0, offset / 8 < 4096 else { return nil }
+ return ARM64.encodeU32(0xF940_0000 | ((offset / 8) << 10) | (rn << 5) | rt)
+ }
+
// MARK: - Stores
+ /// STR Wt, [Xn, #offset]; rn 31 is SP, scaled by four.
+ public static func encodeStrWUnsignedOffset(rt: UInt32, rn: UInt32, offset: UInt32) -> Data? {
+ guard rt < 32, rn < 32, offset % 4 == 0, offset / 4 < 4096 else { return nil }
+ return ARM64.encodeU32(0xB900_0000 | ((offset / 4) << 10) | (rn << 5) | rt)
+ }
+
/// Encode `STR Xt, [Xn, #offset]` — 64-bit store, unsigned scaled offset.
///
/// The unsigned immediate uses `opc = 00`; `imm12` is