Run a virtual iPhone on an Apple Silicon Mac.
Swift
Extract the kernelcache mix's KDKs natively, without ipsw
Jacky0fbecbed5276
diff --git a/Documents/Guides/compatibility.md b/Documents/Guides/compatibility.mdindex c13fac0b..c8123eff 100644--- a/Documents/Guides/compatibility.md+++ b/Documents/Guides/compatibility.md@@ -25,7 +25,7 @@ These are the two iPhone17,3 combinations exercised with the native JB pipelineThe cloudOS 26.4 beta image (`26.4-23E5207q`) is the newest one that contains `vphone600ap`, the identity the guest's kernel, SEP and device tree come from, and it stays the recommended cloudOS: it needs nothing beyond vphone-cli. Every cloudOS release after it was checked on 2026-10-03 and lists only the PCC boards and `vresearch101ap`: `iPhone99,11` is gone from `SupportedProductTypes`, and there is no `kernelcache.*.vphone600`, `sep-firmware.vphone600` or `DeviceTree.vphone600ap`.-On such a cloudOS the research board stands in (the Research Board patch set): `fw patch` turns its device tree and SEP into vphone600's and rebuilds its kernelcache with the vphone600 virtualisation kexts, from a recipe for that kernelcache. That needs an `ipsw` with `kernel extract --kdk` and root for the link (`vphone-cli fw kernelcache`; see [the recipes](../../VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md)). `fw prepare` refuses a cloudOS no recipe covers. `fw catalog` lists each iOS release's own cloudOS beside the recommended one, and Launchpad offers it under Firmware.+On such a cloudOS the research board stands in (the Research Board patch set): `fw patch` turns its device tree and SEP into vphone600's and rebuilds its kernelcache with the vphone600 virtualisation kexts, from a recipe for that kernelcache. KDK extraction is native; the link still needs root (`vphone-cli fw kernelcache`; see [the recipes](../../VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md)). `fw prepare` refuses a cloudOS no recipe covers. `fw catalog` lists each iOS release's own cloudOS beside the recommended one, and Launchpad offers it under Firmware.iOS 18.1 to 18.7.2 run the same way on their own release's cloudOS, with the userland of the iPhone XS family's IPSWs (`vm create --device iPhone11,6`, the Minimal preset; `fw catalog --device iPhone11,6` lists them). Their kernels are kernel-first: from macOS 26.4 on, another Mac or a macOS VM running macOS 15 or 26.0 to 26.3 links the mix over ssh (`VPHONE_KMUTIL_SSH`, see [Creating and running](create-and-run.md)); Launchpad offers them as the iPhone XS Max, with that Mac as the macOS builder. 18.1, 18.5 and 18.7.2 are checked on VMs; the other four recipes have not been booted yet.diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.mdindex 3b6b0d94..d337ba24 100644--- a/Documents/Guides/create-and-run.md+++ b/Documents/Guides/create-and-run.md@@ -24,7 +24,7 @@ By default that pipeline builds a [template](#templates) rather than the VM itse`fw prepare` creates a temporary vphone VM with no network device, starts it in DFU, and restores the selected cloudOS IPSW using this project's restore backend. It mounts the restored System volume read-only, extracts the GPU bundle, then removes the temporary VM. This first restore supplies the GPU driver for the second, hybrid iPhone restore. The extracted bundle is cached per cloudOS build in `~/.vphone/gpu-drivers/`, so later machines on the same cloudOS skip the temporary restore. `vm create` and `fw prepare` also accept `--gpu-driver-bundle /path/to/AppleParavirtGPUMetalIOGPUFamily.bundle` to reuse a previously extracted bundle without the temporary restore. The CLI checks its iPhoneOS platform version against the selected cloudOS version. Each restore obtains its own ticket online.-A cloudOS after the 26.4 beta has no vphone600 components, and the research board stands in ([Compatibility](compatibility.md)). Its kernelcache is rebuilt with the vphone600 virtualisation kexts, which needs an `ipsw` with `kernel extract --kdk` and root for the link. Run the whole creation as `sudo VPHONE_IPSW=/path/to/ipsw vphone-cli vm create ...`, or stage the mix as yourself after `fw prepare` with `VPHONE_IPSW=/path/to/ipsw vphone-cli fw kernelcache <vm>`, link it with `sudo vphone-cli fw kernelcache <vm>`, and continue with `fw patch` as usual.+A cloudOS after the 26.4 beta has no vphone600 components, and the research board stands in ([Compatibility](compatibility.md)). Its kernelcache is rebuilt with the vphone600 virtualisation kexts. KDK extraction runs natively; only the kmutil link needs root. After `fw prepare`, stage the mix as yourself with `vphone-cli fw kernelcache <vm>`, link it with `sudo vphone-cli fw kernelcache <vm> --link-only`, and continue with `fw patch` as usual. The old `--ipsw` argument remains accepted but ignored in 2.12.x.A kernel only boots in the layout Apple linked it with, and kmutil takes the layout from the Mac it runs on: macOS 26.4 and later link the iOS 26.4+ kernelcaches (kernel-last), macOS 15 and 26.0–26.3 the older ones (kernel-first). When this Mac has the other layout, another Mac or a macOS VM links the mix over ssh: set `VPHONE_KMUTIL_SSH=<user>@<host>` (and `VPHONE_KMUTIL_SSH_PASSWORD=<password>` without ssh keys and passwordless sudo there) for `fw kernelcache` or the creation. The staged volume is uploaded to that Mac's `/private/var/tmp`, linked there as root and removed; nothing on this Mac needs root for it. Remote Login must be on, and the user must be allowed to use sudo.@@ -141,6 +141,8 @@ Launchpad 2.9 creates machines from templates by default. New Machine opens on aUnder Firmware, a release that also runs on its own cloudOS (`fw catalog`'s third column) offers that cloudOS beside the recommended one, with the `ipsw` that stages the kernelcache mix. The creation then stages the mix as you and has the helper link it as root, which asks for authorization once.+The 2.12 Launchpad interface still shows its legacy ipsw selector for older compatible bundles. Native Core Bundle extraction ignores the selected tool path; the CLI no longer needs it.+The iPhone XS Max runs iOS 18.1 to 18.7.2, each on its own release's cloudOS, with the Minimal preset and no template. Its pairings always rebuild the kernelcache, so Firmware asks for the `ipsw`, and for the macOS builder: `user@host` of a Mac or macOS VM running macOS 15 or 26.0 to 26.3 with Remote Login on, and its password for ssh and sudo (empty with ssh keys and passwordless sudo). Launchpad keeps the builder like the `ipsw`, but not the password, which reaches `vphone-cli` only in its environment (`VPHONE_KMUTIL_SSH_PASSWORD`). The creation then stages and links the mix as you, over ssh; from macOS 26.4 on the builder is required, on an older Mac without one the helper links it as root.The creation runs `vm template find` first. When a current template matches, it clones the machine (`vm create --template <id> --skip-first-boot`) and boots it. When none does, it builds the template in a temporary machine of the same library, named `template-` and eight hex digits, with its usual steps (restore, then `cfw install` through the helper), then `vm template trim`, the headless `vm template setup --strict` and `vm template adopt --iphone-source … --cloudos-source … --expect <id>`, and clones the machine from the result. The setup boot fails when an app it should remove stays, and the adopt fails when the build's key comes out other than the one `find` computed, so a build is never saved under an id later creations would not find. Each is a step of its own with its duration, and a failed one shows the reason `vphone-cli` gave.diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex c26e9ab6..e6d7c66c 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -3806,7 +3806,7 @@ it finds the recipe in `Contents/Resources/kernelcache_recipes` by SHA-256, then1. extracts the donor, the vphone600 kernelcache of the 26.4 beta (23E5207q,read once from its cloudOS IPSW), and the base into KDKs with- `ipsw kernel extract --kdk --symbols`, naming the stripped symbols from the+ the native `KDKExtraction` pipeline, naming the stripped symbols from therecipe's maps;2. keeps the recipe's bundle list: the base without its research-board-onlykexts, plus the donor kexts that link against the base kernel;@@ -3824,7 +3824,7 @@ the new layout) and saves the preset's kernel patches into itin `FirmwareOriginals`. Mixes are cached in `~/.vphone/kernelcache/mix`, keyedby the kernelcaches, the maps and bundle list and the builder layout.-Only the link needs root, and root runs no `ipsw`. `fw kernelcache <vm>` stages+Only the link needs root; native extraction runs as the invoking user. `fw kernelcache <vm>` stagesthe mix as the user (both extractions and the volume) and links it under sudo:root copies the staged volume into a fresh root-only directory, walking it bydescriptor, refusing every symbolic link but the KDK's pointer to the volume's@@ -3837,13 +3837,19 @@ Apple linked the base in, read from the base's own prelink info, so a mix nolonger depends on where it is built. The 26.6 mix then has the segment layoutof the hand-built research mix that booted.-Requirements: an `ipsw` with `kernel extract --kdk`, named by `VPHONE_IPSW`-(vphone-cli does not ship it); root; and for every base here (26.4–26.7, all+Requirements: root for linking; and for every base here (26.4–26.7, all`kernel-last`) the kmutil of macOS 26.4 or later. `fw prepare` now pairs acloudOS without vphone600ap and refuses one whose kernelcache no recipe covers.`cfw update-kernel` refuses on a mixed kernel, whose originals are the researchboard's.+Native extraction checked on 2026-10-23: all 264 fileset images of the 26.4+beta vphone600 and vresearch101 collections match the pinned reference in+recovered references, synthesized symbols and exported bytes. The full KDK+trees match 313/263 files, with plist values compared semantically. See+[native KDK extraction](Kernel/native_kdk_export.md). This replaces the external+extractor only; no new kmutil link or guest boot was performed for this change.+Checked on 2026-10-19: a `minimal` VM of iOS 26.6 on cloudOS 26.6 (23G71) restoresand boots, and vphoned answers. Checked on 2026-10-20 with the standard preset:iOS 26.5 (23F77) on cloudOS 26.5 (23F75) and iOS 26.4 (23E246) on cloudOS 26.4diff --git a/Research/Kernel/native_kdk_export.md b/Research/Kernel/native_kdk_export.mdindex 0e5cf0ae..56112f1c 100644--- a/Research/Kernel/native_kdk_export.md+++ b/Research/Kernel/native_kdk_export.md@@ -1,10 +1,10 @@-# Native KDK Mach-O export+# Native KDK extraction-`KDKImageExport` converts one kernel-collection fileset image into a standalone-ARM64 Mach-O, given the recovered references and extra symbols. This is the-writer stage of the native KDK extraction work. `KernelCacheMixer` still calls-the external `ipsw` extractor; reference recovery, symbol synthesis, KDK plist-and pseudo-extension generation are subsequent stages.+`KDKExtraction` reconstructs a KDK directly from a decompressed kernel+collection: it recovers references, synthesizes cross-image symbols, writes+standalone Mach-Os with `KDKImageExport`, and recreates bundle plists and KPI+pseudo-extensions. `KernelCacheMixer` uses this native implementation and+in-process gzip decompression. It does not execute an external `ipsw`.The current contract is stripped collections with address-only synthetic binds.Passing `addressOnlyBinds: false` fails explicitly. Original-symbol C++ alias/PAC@@ -42,7 +42,8 @@ its scratch state and produce the same bytes.## Reference and evidenceThe port follows the MIT-licensed `File.Export` in go-macho PR #94. Its license-is retained in `FirmwarePatcher/KernelCache/KDK/LICENSE`. The external reference+is retained in `FirmwarePatcher/KernelCache/KDK/LICENSE` and packaged as+`Contents/Resources/Licenses/native-kdk-MIT.txt`. The external referencebuild uses these pinned mpass99 commits, not the released upstream `ipsw`:| Repository | Commit |@@ -57,8 +58,12 @@ On 2026-10-23 the writer reproduced **all 264 reference exports byte for byte**:`kernelcache.release.vresearch101`, including both kernels. The comparisonfeeds the identical references/symbols/base/bind mode into Swift and Go. It doesnot use the reference output to construct Swift output. This proves the writer-for these inputs; it does not validate the future native reference finder or a-rebuilt collection's boot behavior.+for these inputs; a separate native recovery test now reconstructs all inputs+from the collections and checks reference sets, symbol arrays and final bytes.+Both collections match all 264 images with zero unresolved imports. Full KDK+tree tests also match 313 donor files and 263 research files: executable bytes+are identical, while plist fields and values are equal (XML formatting is not+part of the contract). No new kmutil link or VM boot was performed.Corpus source: cached cloudOS 26.4 beta IPSW`c0ecdb4b310cf5239ab2b248dd3098eec297dc5aa3bbe6ad-b80d96a0b616.ipsw`.@@ -115,7 +120,10 @@ xcodebuild -workspace VPhone.xcworkspace -scheme FirmwarePatcherTests \-configuration Debug -destination 'platform=macOS,arch=arm64' \-derivedDataPath /tmp/native-kdk-build \-only-testing:FirmwarePatcherTests/KDKImageExportTests \- -only-testing:FirmwarePatcherTests/KDKExportFixtureTests test+ -only-testing:FirmwarePatcherTests/KDKExportFixtureTests \+ -only-testing:FirmwarePatcherTests/KDKRecoveryTests \+ -only-testing:FirmwarePatcherTests/KDKRecoveryFlowTests \+ -only-testing:FirmwarePatcherTests/KDKExtractionTests test```Xcode strips the `TEST_RUNNER_` prefix for the test process. To narrow a failure,@@ -124,10 +132,11 @@ exports, one per collection. A mismatch reports the first byte offset and saves`swift-<corpus>-<entryID>` in the corpus root. The default test run skips theexternal corpus rather than silently treating absent firmware as success.-The focused validation on 2026-10-23 passed 13 test functions across the KDK-and ARM64 encoder suites, including all 264 external exports. A full scheme run-also executed the new tests successfully but reported 134 issues among 696-tests: existing suites require missing `ipsws/ref_extract` DSC/Mach-O fixtures+The final native integration validation on 2026-10-23 passed **86 tests in 12+suites**, including the mixer's shipped gzip symbol-map path, all native+recovery/export/tree comparisons and the patch-set contract suites. The+writer-stage validation also passed the ARM64 encoder suite. Its full scheme+run reported 134 issues among 696 tests: existing suites require missing `ipsws/ref_extract` DSC/Mach-O fixturesand `ipsws/patch_refactor_input` payloads in this new worktree. The maincheckout's DSC directory is empty and the patch-refactor inputs are absent too.That run is recorded as failed, not as a clean full-suite validation.@@ -183,10 +192,36 @@ inputs, so writer parity does not depend on re-running symbol synthesis.symbols and indirect symbols, and truncate the obsolete original tail.Symbol records are local/defined/undefined; strings are defined/undefined/local.-## Next integration step--Recover references and synthesize symbols natively, then feed this writer and-reuse the unchanged byte-parity test boundary. Add KDK bundle metadata and KPI-pseudo-extensions before switching `KernelCacheMixer`. Keep `--ipsw` accepted-as a no-op within the existing 2.12 series; removing it requires the planned-2.13 compatibility bump and raised Launchpad `minimumBundleComponents`.+## Native recovery and integration++`KDKRecovery` decodes collection pointer chains, LC_FUNCTION_STARTS, ADRP and+cross-section branches, unwind image offsets, static-if/copyio deltas and EH+frame references. OFF12 recovery follows register copies, conditional paths,+jump tables and outlined helpers. Leaf callees that clobber a tracked register+end the path; outlined ADRPs can hand their value back to callers. Foreign+noreturn analysis prevents a call to a terminating function from inventing+consumers in the next block. The pinned reference's query order and failed+jump-table-reader behavior are preserved for reproducibility.++`KDKLinkSymbols` applies transitive dependency visibility to kernel KPI names,+keeps duplicate known KEXT names local, reserves vtable/metaclass and alias+names, and supplies every KEXT's `_kmod_info`. Production extraction refuses+unresolved imports. Metadata paths are constrained to the newly created KDK;+partial exports are removed on failure and the final directory is published+only after success. Host artifacts use the repository's 0777 permission rule.++`KernelCacheMixer` revision 4 keys the mix and donor extraction on+`KDKExtraction.revision`, so pre-native cache entries are rebuilt. It records+`extractor.version` instead of the external executable hash. Staging remains+unprivileged; root only links a staged volume through the existing descriptor+based copy. `checkMixable` reports missing staging before a root pipeline starts.++`fw kernelcache --ipsw <path>` and the Swift `stage(ipsw:)` argument are accepted+but ignored throughout 2.12.x. `VPHONE_IPSW` is not read. The legacy Launchpad+UI still exposes its ipsw selector and can pass the path; Core ignores it.+Removing that UI and the compatibility argument across both products belongs+to the planned 2.13 transition with its `minimumBundleComponents` update.++Validation covers the two pinned 26.4 beta collections. Other recipe generations+and a fresh native-extraction -> kmutil -> guest boot remain separate acceptance+gates; old boot evidence is not evidence of this new extraction path.diff --git a/Research/README.md b/Research/README.mdindex 0c60f3e4..0d42b68b 100644--- a/Research/README.md+++ b/Research/README.md@@ -17,7 +17,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-| --- | --- || Guest orientation | [SpringBoard language-change wedge and virtual gravity](Guest/springboard_orientation_stuck.md) || Firmware and boot chain | [Manifest and origins](Firmware/firmware_manifest_and_origins.md), [iBoot patches](Firmware/iboot_patches.md), [TXM full chain](Firmware/txm_fullchain_analysis.md), [TXM JB patches](Firmware/txm_jb_patches.md), [selector 24](Firmware/txm_selector24_analysis.md), [variant differences](Firmware/txm_variant_diff.md) |-| Kernel | [Native KDK export writer and byte-parity tests](Kernel/native_kdk_export.md), [CFW overview](Kernel/kernel_jb_patch_notes.md), [patcher verification](Kernel/kernel_patcher_verification.md), [FairPlay kexts](Kernel/kernel_fairplay_kexts.md), [base validation 1–5](Kernel/kernel_patch_base_first5_validation.md), [11–15](Kernel/kernel_patch_base_11_15_validation.md), [16–20](Kernel/kernel_patch_base_16_20_validation.md), [sandbox hooks](Kernel/kernel_patch_sandbox_hooks_17_26_validation.md), [individual patch notes](KernelCustomFirmwarePatches/README.md) |+| Kernel | [Native KDK extraction and byte-parity tests](Kernel/native_kdk_export.md), [CFW overview](Kernel/kernel_jb_patch_notes.md), [patcher verification](Kernel/kernel_patcher_verification.md), [FairPlay kexts](Kernel/kernel_fairplay_kexts.md), [base validation 1–5](Kernel/kernel_patch_base_first5_validation.md), [11–15](Kernel/kernel_patch_base_11_15_validation.md), [16–20](Kernel/kernel_patch_base_16_20_validation.md), [sandbox hooks](Kernel/kernel_patch_sandbox_hooks_17_26_validation.md), [individual patch notes](KernelCustomFirmwarePatches/README.md) || Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) || Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) || Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md), [guest MAC, fixed address, port forwarding and names](Host/network_fixed_address.md), [machine identity and `vm clone --new-identity`](Host/machine_identity_and_clone.md) |diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExtraction.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExtraction.swiftnew file mode 100644index 00000000..f4128d47--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExtraction.swift@@ -0,0 +1,226 @@+// Native KDK extraction: recover inputs, export executables, and reconstruct+// bundle metadata. The destination appears only after all entries succeed.+import CryptoKit+import Foundation+import VPhoneCoreKit+import VPhonePatchKit++enum KDKExtraction {+ /// Included in extraction and mix cache keys. Bump when output changes.+ static let revision = "native-kdk-1"++ static func extract(_ payload: Data, to parent: URL, known: [UInt64: [String]] = [:],+ progress: (String) -> Void = { _ in }) throws -> URL+ {+ let collection = try KDKKernelCollection(payload)+ let recovery = try KDKRecovery(collection)+ let infos = try collection.prelinkInfo()+ guard let first = collection.entries.first(where: { $0.identifier != "com.apple.kernel" }),+ let info = infos.first(where: { $0["CFBundleIdentifier"] as? String == first.identifier }),+ let version = info["DTPlatformVersion"] as? String,+ let build = info["DTPlatformBuild"] as? String,+ let platform = info["DTPlatformName"] as? String+ else {+ throw PatcherError.invalidFormat("kernelcache lacks KDK platform metadata")+ }+ let name = "KDK_\(version)_\(build).kdk"+ let destination = try child(parent, name)+ let fm = FileManager.default+ guard !fm.fileExists(atPath: destination.path) else { throw PatcherError.invalidFormat("KDK already exists: \(destination.path)") }+ try fm.createDirectory(at: parent, withIntermediateDirectories: true)+ let staging = parent.appending(path: ".kdk-\(UUID().uuidString)")+ try fm.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])+ defer { try? fm.removeItem(at: staging) }+ progress("Recovering references from \(collection.entries.count) fileset images")+ let references = try recovery.recover()+ let symbols = try recovery.synthesizeSymbols(references: references, known: known)+ // Unlike an exploratory exporter, the production mix must not silently+ // leave unresolved absolute pointers pointing into the old collection.+ guard symbols.unresolved.isEmpty else {+ let examples = symbols.unresolved.prefix(5).map { "\($0.0) -> 0x\(String($0.1, radix: 16))" }.joined(separator: ", ")+ throw PatcherError.invalidFormat("native KDK has \(symbols.unresolved.count) unresolved imports: \(examples)")+ }+ let library = staging.appending(path: "System/Library"), extensions = library.appending(path: "Extensions")+ var identity = build + version+ if let uuid = collection.commands.first(where: { $0.command == KDKMachO.lcUUID }) {+ identity = uuidString(Array(uuid.bytes[8 ..< 24])).uppercased()+ }+ var systemInfo = ["BuildID": buildID(identity), "ProductBuildVersion": build,+ "ProductUserVisibleVersion": version, "ProductVersion": version]+ if let product = ["macosx": "macOS", "iphoneos": "iPhoneOS", "watchos": "Watch OS", "appletvos": "Apple TVOS", "xros": "xrOS"][platform] {+ systemInfo["ProductName"] = product+ }+ try writePlist(systemInfo, to: library.appending(path: "CoreServices/SystemVersion.plist"))+ for entry in collection.entries {+ var image = recovery.images[entry.identifier]!+ let output: URL+ let base: UInt64+ if entry.identifier == "com.apple.kernel" {+ guard let thread = collection.unixThread,+ image.commands.filter({ $0.command == KDKMachO.lcUnixThread }).count == 1,+ let index = image.commands.firstIndex(where: { $0.command == KDKMachO.lcUnixThread })+ else {+ throw PatcherError.invalidFormat("expected one kernel and collection LC_UNIXTHREAD")+ }+ image.commands[index] = thread+ base = collection.baseAddress+ output = library.appending(path: "Kernels/kernel")+ } else {+ guard let info = infos.first(where: { $0["CFBundleIdentifier"] as? String == entry.identifier }) else {+ throw PatcherError.invalidFormat("missing prelink metadata for \(entry.identifier)")+ }+ let paths = try bundleLayout(extensions, identifier: entry.identifier, info: info)+ guard let executable = paths.executable else { throw PatcherError.invalidFormat("no executable path for \(entry.identifier)") }+ base = 0+ output = executable+ try writePlist(standaloneInfo(info), to: paths.plist)+ }+ var writer = try KDKImageExport(collection: collection, image: image, baseAddress: base,+ symbols: (symbols.exports[entry.identifier] ?? []) + (symbols.imports[entry.identifier] ?? []),+ references: references[entry.identifier] ?? [], addressOnlyBinds: true)+ try write(writer.export(), to: output)+ progress("Exported \(entry.identifier)")+ }+ for info in infos where info["_PrelinkExecutableRelativePath"] == nil {+ guard let id = info["CFBundleIdentifier"] as? String, !id.isEmpty else { continue }+ let paths = try bundleLayout(extensions, identifier: id, info: info)+ try writePlist(standaloneInfo(info), to: paths.plist)+ }+ try pseudoExtensions(extensions, kernel: recovery.images["com.apple.kernel"]!, collection: collection, infos: infos)+ try VPhoneHostFilePermissions.makeAccessible(at: staging)+ try fm.moveItem(at: staging, to: destination)+ progress("Created \(name)")+ return destination+ }++ struct BundlePaths { var bundle: URL+ var plist: URL+ var executable: URL?+ }++ static func child(_ root: URL, _ relative: String) throws -> URL {+ guard !relative.isEmpty, !relative.hasPrefix("/"), !relative.contains("\0"),+ !relative.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0 == ".." || $0 == "." || $0.isEmpty })+ else {+ throw PatcherError.invalidFormat("unsafe KDK relative path: \(relative)")+ }+ return root.appending(path: relative)+ }++ static func bundleLayout(_ extensions: URL, identifier: String, info: [String: Any]) throws -> BundlePaths {+ let prefix = "/System/Library/Extensions/"+ var relative = identifier + ".kext"+ if let path = info["_PrelinkBundlePath"] as? String, path.hasPrefix(prefix) {+ relative = String(path.dropFirst(prefix.count))+ }+ let bundle = try child(extensions, relative)+ var executable = info["_PrelinkExecutableRelativePath"] as? String ?? ""+ var contents = executable.hasPrefix("Contents/")+ if executable.isEmpty {+ if let platform = info["DTPlatformName"] as? String {+ contents = platform == "macosx"+ } else {+ contents = (info["CFBundleSupportedPlatforms"] as? [String] ?? []).contains("MacOSX")+ }+ if let name = info["CFBundleExecutable"] as? String, !name.isEmpty {+ executable = (contents ? "Contents/MacOS/" : "") + name+ }+ }+ return try .init(bundle: bundle, plist: bundle.appending(path: contents ? "Contents/Info.plist" : "Info.plist"),+ executable: executable.isEmpty ? nil : child(bundle, executable))+ }++ static func standaloneInfo(_ info: [String: Any]) -> [String: Any] {+ info.filter { !$0.key.hasPrefix("_Prelink") && !["_InfoPlistDigest", "OSBundleUUID", "CFBundleNumericVersion"].contains($0.key) }+ }++ static func write(_ data: Data, to url: URL) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try data.write(to: url, options: .atomic)+ }++ static func writePlist(_ plist: [String: Any], to url: URL) throws {+ try write(PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0), to: url)+ }++ static func uuidString(_ bytes: [UInt8]) -> String {+ let hex = bytes.map { String(format: "%02x", $0) }+ return [hex[0 ..< 4].joined(), hex[4 ..< 6].joined(), hex[6 ..< 8].joined(), hex[8 ..< 10].joined(), hex[10 ..< 16].joined()].joined(separator: "-")+ }++ static func buildID(_ identity: String) -> String {+ // UUID v5, OID namespace, identical to google/uuid.NewSHA1.+ var namespace = UUID(uuidString: "6ba7b812-9dad-11d1-80b4-00c04fd430c8")!.uuid+ var material = withUnsafeBytes(of: &namespace) { Data($0) }+ material += Data(identity.utf8)+ var hash = Array(Insecure.SHA1.hash(data: material).prefix(16))+ hash[6] = (hash[6] & 15) | 0x50+ hash[8] = (hash[8] & 0x3F) | 0x80+ return uuidString(hash)+ }++ static func pseudoExtensions(_ extensions: URL, kernel: KDKImage, collection: KDKKernelCollection, infos: [[String: Any]]) throws {+ var sets: [String: [String]] = [:]+ if let section = kernel.sections.first(where: { $0.segmentName == "__LINKINFO" && $0.name == "__symbolsets" }) {+ let plist = try collection.plist(at: section.address, count: section.size)+ for set in plist["SymbolsSets"] as? [[String: Any]] ?? [] {+ let id = set["CFBundleIdentifier"] as? String ?? ""+ for symbol in set["Symbols"] as? [[String: Any]] ?? [] {+ if let name = symbol["SymbolName"] as? String, !name.isEmpty {+ sets[id, default: []].append(name)+ }+ }+ }+ }+ var version = ""+ for info in infos {+ guard info["OSKernelResource"] as? Bool == true, let executable = info["CFBundleExecutable"] as? String,+ !executable.isEmpty, info["_PrelinkExecutableRelativePath"] == nil else { continue }+ let id = info["CFBundleIdentifier"] as? String ?? ""+ if version.isEmpty {+ version = info["CFBundleVersion"] as? String ?? ""+ }+ let paths = try bundleLayout(extensions, identifier: id, info: info)+ let uuid = info["OSBundleUUID"] as? Data+ try write(pseudoMachO(uuid: uuid?.count == 16 ? Array(uuid!) : [], symbols: sets[id] ?? []), to: child(paths.bundle, executable))+ }+ let system = extensions.appending(path: "System.kext/Info.plist")+ if version.isEmpty || FileManager.default.fileExists(atPath: system.path) {+ return+ }+ try writePlist([+ "CFBundleDevelopmentRegion": "English", "CFBundleGetInfoString": "System Resource Pseudoextension, Apple Inc, " + version,+ "CFBundleIdentifier": "com.apple.kernel", "CFBundleInfoDictionaryVersion": "6.0", "CFBundleName": "System Resource Pseudoextension",+ "CFBundlePackageType": "KEXT", "CFBundleShortVersionString": version, "CFBundleSignature": "????", "CFBundleVersion": version,+ "OSBundleAllowUserLoad": true, "OSBundleCompatibleVersion": version, "OSBundleRequired": "Root", "OSKernelResource": true,+ ], to: system)+ }++ static func pseudoMachO(uuid: [UInt8], symbols: [String]) -> Data {+ var strings: [UInt8] = [0x20, 0], table: [UInt8] = []+ for name in symbols.sorted() {+ table.appendLE(UInt32(strings.count))+ table += [1, 0]+ table.appendLE(UInt16(0))+ table.appendLE(UInt64(0))+ strings += name.utf8+ strings.append(0)+ }+ strings.pad(to: 8)+ let size = UInt64(table.count + strings.count)+ var output = KDKMachO.Header(magic: KDKMachO.magic64, cpuType: 0x0100_000C, cpuSubtype: 2, fileType: 0xB,+ commandCount: 3, commandsSize: 120, flags: 2, reserved: 0).bytes+ KDKMachO.write(.init(command: KDKMachO.lcSegment64, commandSize: 72, name: "__LINKEDIT", address: 0,+ memorySize: KDKImageExport.aligned(size), fileOffset: 0x1000, fileSize: size,+ maxProtection: 1, initialProtection: 1, sectionCount: 0, flags: 4, sections: []), to: &output)+ for word: UInt32 in [KDKMachO.lcSymtab, 24, 0x1000, UInt32(symbols.count), 0x1000 + UInt32(table.count), UInt32(strings.count), KDKMachO.lcUUID, 24] {+ output.appendLE(word)+ }+ output += uuid.prefix(16)+ output.padTo(32 + 120)+ output.padTo(0x1000)+ output += table+ output += strings+ return Data(output)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKInstruction.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKInstruction.swiftnew file mode 100644index 00000000..f2896a22--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKInstruction.swift@@ -0,0 +1,109 @@+// Raw predicates used by reference dataflow recovery, matching the pinned+// arm64-cgo scanner. This is analysis only: all emitted instructions go through+// ARM64Encoder. ADRP/B/BL candidates are additionally decoded with Capstone.+import VPhonePatchKit++enum KDKInstruction {+ static func sign(_ value: UInt64, _ bits: Int) -> Int64 {+ Int64(bitPattern: value << (64 - bits)) >> (64 - bits)+ }++ static func adrp(_ word: UInt32, _ pc: UInt64) -> UInt64 {+ let imm = UInt64((word >> 29) & 3) | UInt64((word >> 5) & 0x7FFFF) << 2+ return (pc & ~UInt64(0xFFF)) &+ UInt64(bitPattern: sign(imm, 21) << 12)+ }++ static func branch(_ word: UInt32, _ pc: UInt64) -> UInt64? {+ let delta: Int64+ if ARM64Inst.isBorBL(word) {+ delta = sign(UInt64(word & 0x03FF_FFFF) << 2, 28)+ } else if word & 0xFF00_0010 == 0x5400_0000 || word & 0x7E00_0000 == 0x3400_0000 {+ delta = sign(UInt64((word >> 5) & 0x7FFFF) << 2, 21)+ } else if word & 0x7E00_0000 == 0x3600_0000 {+ delta = sign(UInt64((word >> 5) & 0x3FFF) << 2, 16)+ } else {+ return nil+ }+ return pc &+ UInt64(bitPattern: delta)+ }++ static func ret(_ w: UInt32) -> Bool {+ w & 0xFFFF_FC1F == 0xD65F_0000 || w == 0xD65F_0BFF || w == 0xD65F_0FFF+ }++ static func brk(_ w: UInt32) -> Bool {+ w & 0xFFE0_001F == 0xD420_0000+ }++ static func br(_ w: UInt32) -> Bool {+ w & 0xFFFF_FC1F == 0xD61F_0000+ }++ static func blr(_ w: UInt32) -> Bool {+ w & 0xFFFF_FC1F == 0xD63F_0000+ }++ static func b(_ w: UInt32) -> Bool {+ w & 0xFC00_0000 == 0x1400_0000+ }++ static func authJump(_ w: UInt32) -> Bool {+ w & 0xFEFF_F000 == 0xD61F_0000 && !br(w)+ }++ static func authCall(_ w: UInt32) -> Bool {+ w & 0xFEFF_F000 == 0xD63F_0000 && !blr(w)+ }++ static func linear(_ w: UInt32) -> Bool {+ branch(w, 0) == nil && !blr(w) && !br(w) && w & 0xFFFF_FC1F != 0xD65F_0000+ }++ static func add(_ w: UInt32) -> Bool {+ w & 0xFF00_0000 == 0x9100_0000 || w & 0xFF20_0000 == 0x8B00_0000+ }++ static func store(_ w: UInt32) -> Bool {+ w & 0xFFC0_0000 == 0xF800_0000 || w & 0xFFC0_0000 == 0xF900_0000+ }++ static func storePair(_ w: UInt32) -> Bool {+ w & 0xFE00_0000 == 0xA800_0000 && w & 0x0040_0000 == 0+ }++ static func writes(_ w: UInt32, _ register: UInt32) -> Bool {+ let rt = ARM64Inst.rd(w), rn = ARM64Inst.rn(w), rt2 = (w >> 10) & 31+ if w & 0x0A00_0000 == 0x0800_0000 {+ let simd = w & 0x0400_0000 != 0+ if w & 0x3A00_0000 == 0x2800_0000 {+ let load = w & 0x0040_0000 != 0, mode = (w >> 23) & 3+ return ((mode == 1 || mode == 3) && rn == register) || (load && !simd && (rt == register || rt2 == register))+ }+ if w & 0x3B00_0000 == 0x1800_0000 {+ return !simd && rt == register+ }+ if w & 0x3B00_0000 == 0x3900_0000 {+ return !simd && (w >> 22) & 3 != 0 && rt == register+ }+ if w & 0x3B20_0000 == 0x3800_0000 {+ let mode = (w >> 10) & 3+ return ((mode == 1 || mode == 3) && rn == register) || (!simd && (w >> 22) & 3 != 0 && rt == register)+ }+ if w & 0x3B20_0C00 == 0x3820_0800 {+ return !simd && (w >> 22) & 3 != 0 && rt == register+ }+ return rt == register || ARM64Inst.rm(w) == register+ }+ if w & 0x0E00_0000 == 0x0E00_0000 {+ if w & 0x5F20_FC00 == 0x1E20_0000 {+ return rt == register+ }+ if w & 0xBFE0_8400 == 0x0E00_0400 {+ let imm = (w >> 11) & 15+ return w & 0x2000_0000 == 0 && (imm == 5 || imm == 7) && rt == register+ }+ return false+ }+ return rt == register+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKLinkSymbols.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKLinkSymbols.swiftnew file mode 100644index 00000000..5d7ae5ba--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKLinkSymbols.swift@@ -0,0 +1,286 @@+// Cross-image names for stripped collections, from ipsw#1372 symbols.go.+import Foundation+import VPhonePatchKit++struct KDKLinkSymbols {+ var imports: [String: [KDKSymbol]] = [:]+ var exports: [String: [KDKSymbol]] = [:]+ var unresolved: [(String, UInt64)] = []++ static func loadKnown(_ data: Data) throws -> [UInt64: [String]] {+ guard let raw = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw PatcherError.invalidFormat("invalid KDK symbol map") }+ var result: [UInt64: [String]] = [:]+ for (key, value) in raw {+ let address: UInt64? = if key.hasPrefix("0x") || key.hasPrefix("0X") {+ UInt64(key.dropFirst(2), radix: 16)+ } else if key.hasPrefix("0o") {+ UInt64(key.dropFirst(2), radix: 8)+ } else if key.hasPrefix("0b") {+ UInt64(key.dropFirst(2), radix: 2)+ } else if key.count > 1, key.first == "0" {+ UInt64(key, radix: 8)+ } else {+ UInt64(key)+ }+ guard let address, let names = (value as? [String]) ?? (value as? String).map({ [$0] }) else {+ throw PatcherError.invalidFormat("invalid symbol map entry: \(key)")+ }+ result[address] = names+ }+ return result+ }+}++extension KDKKernelCollection {+ func plist(at address: UInt64, count: UInt64) throws -> [String: Any] {+ var data = try read(Int(count), at: address)+ while data.last == 0 {+ data.removeLast()+ }+ guard let result = try PropertyListSerialization.propertyList(from: Data(data), format: nil) as? [String: Any] else {+ throw PatcherError.invalidFormat("KDK metadata is not a dictionary plist")+ }+ return result+ }++ func prelinkInfo() throws -> [[String: Any]] {+ guard let segment = segments.first(where: { $0.name == "__PRELINK_INFO" }) else { throw PatcherError.invalidFormat("missing __PRELINK_INFO") }+ return try plist(at: segment.address, count: segment.fileSize)["_PrelinkInfoDictionary"] as? [[String: Any]] ?? []+ }+}++extension KDKRecovery {+ struct SymbolRange {+ var entry: String+ var index: UInt8+ var section: KDKMachO.Section+ }++ func synthesizeSymbols(references: [String: [KDKReference]], known: [UInt64: [String]] = [:]) throws -> KDKLinkSymbols {+ let kernelID = "com.apple.kernel"+ guard let kernel = images[kernelID], kernel.symbols.isEmpty else {+ throw PatcherError.invalidFormat("native KDK symbol synthesis requires a stripped kernel")+ }+ let infos = try collection.prelinkInfo()+ var ranges: [SymbolRange] = []+ for id in images.keys.sorted() {+ for (index, section) in images[id]!.sections.enumerated() where section.size > 0 {+ guard let ordinal = UInt8(exactly: index + 1) else { throw PatcherError.invalidFormat("too many Mach-O sections") }+ ranges.append(.init(entry: id, index: ordinal, section: section))+ }+ }+ ranges.sort { $0.section.address < $1.section.address }+ let starts = ranges.map(\.section.address)+ func lookup(_ address: UInt64) -> SymbolRange? {+ let i = starts.upperBound(address) - 1+ return i >= 0 && ranges[i].section.contains(address) ? ranges[i] : nil+ }+ var needs: [(String, UInt64)] = []+ for (id, refs) in references {+ var seen = Set<UInt64>()+ for ref in refs where ref.kind == 2 || ref.kind == 7 {+ guard let owner = lookup(ref.target), owner.entry != id, seen.insert(ref.target).inserted else { continue }+ needs.append((id, ref.target))+ }+ }+ needs.sort { ($0.0, $0.1) < ($1.0, $1.1) }+ let functionStarts = functions.mapValues { $0.map(\.start).sorted() }+ func positionName(_ owner: SymbolRange, _ target: UInt64) -> String {+ func trim(_ name: String) -> String {+ String(name.drop(while: { $0 == "_" }))+ }+ let section = trim(owner.section.segmentName) + "." + trim(owner.section.name)+ if owner.section.flags & 0x8000_0400 != 0 {+ let functions = functionStarts[owner.entry] ?? [], i = functions.upperBound(target) - 1+ if i >= 0, functions[i] >= owner.section.address {+ return section + ".f\(i)" + (functions[i] == target ? "" : "_" + String(target - functions[i], radix: 16))+ }+ }+ return section + ".d" + String(target - owner.section.address, radix: 16)+ }+ var sets: [[String: Any]] = [], fallback = ""+ if let section = kernel.sections.first(where: { $0.segmentName == "__LINKINFO" && $0.name == "__symbolsets" }) {+ let plist = try collection.plist(at: section.address, count: section.size)+ sets = plist["SymbolsSets"] as? [[String: Any]] ?? []+ fallback = (plist["WeakRefFallbackSymbol"] as? [String: Any])?["SymbolName"] as? String ?? ""+ }+ var setNames: [String: [String]] = [:], privatePrefixes: [String] = [], reserved = Set<String>()+ for set in sets {+ let id = set["CFBundleIdentifier"] as? String ?? ""+ for symbol in set["Symbols"] as? [[String: Any]] ?? [] {+ let name = symbol["SymbolName"] as? String ?? "", prefix = symbol["SymbolPrefix"] as? String ?? "", alias = symbol["AliasTarget"] as? String ?? ""+ if !prefix.isEmpty {+ if id == "com.apple.kpi.private" {+ privatePrefixes.append(prefix)+ }+ } else if !alias.isEmpty {+ reserved.insert(name)+ reserved.insert(alias)+ } else if !name.isEmpty {+ setNames[id, default: []].append(name)+ }+ }+ }+ if !fallback.isEmpty {+ reserved.insert(fallback)+ }+ var dependencies: [String: [String]] = [:]+ for info in infos {+ if let id = info["CFBundleIdentifier"] as? String, let libs = info["OSBundleLibraries"] as? [String: Any] {+ dependencies[id] = libs.keys.sorted()+ }+ }+ var deps: [String: [String]] = [:]+ for (id, direct) in dependencies {+ var seen: Set<String> = [id], queue = direct, index = 0, closure: [String] = []+ while index < queue.count {+ let dep = queue[index]+ index += 1+ if !seen.insert(dep).inserted {+ continue+ }+ closure.append(dep)+ queue += dependencies[dep] ?? []+ }+ deps[id] = closure.sorted()+ }+ var result = KDKLinkSymbols(), defined: [String: UInt64] = [:], namesAt: [UInt64: [String]] = [:]+ func define(_ owner: SymbolRange, _ name: String, _ target: UInt64) {+ if defined[name] != nil {+ return+ }+ defined[name] = target+ namesAt[target, default: []].append(name)+ result.exports[owner.entry, default: []].append(.init(name: name, type: 0xF, sect: owner.index, desc: 0, value: target))+ }+ var knownOwners: [String: Set<String>] = [:]+ let knownAddresses = known.keys.filter { lookup($0) != nil }.sorted()+ for address in knownAddresses {+ let owner = lookup(address)!+ for name in known[address]! {+ knownOwners[name, default: []].insert(owner.entry)+ }+ }+ let textStart = kernel.sections.first { $0.segmentName == "__TEXT_EXEC" && $0.name == "__text" }?.address ?? 0+ for address in knownAddresses {+ let owner = lookup(address)!+ for name in known[address]! where !name.isEmpty && name != "_kmod_info" {+ if reserved.contains(name), address == textStart {+ continue+ }+ if owner.entry != kernelID, knownOwners[name, default: []].count > 1 {+ result.exports[owner.entry, default: []].append(.init(name: name, type: 0xE, sect: owner.index, desc: 0, value: address))+ } else {+ define(owner, name, address)+ }+ }+ }+ func knownImport(_ importer: String, _ owner: SymbolRange, _ target: UInt64) -> String? {+ for name in known[target] ?? [] where defined[name] == target {+ if owner.entry != kernelID {+ return name+ }+ for dep in deps[importer] ?? [] {+ if setNames[dep, default: []].contains(name) {+ return name+ }+ if dep == "com.apple.kpi.private", privatePrefixes.contains(where: { name.hasPrefix($0) }) {+ return name+ }+ }+ }+ return nil+ }+ func unique(_ name: String, _ target: UInt64) -> String {+ var candidate = name, suffix = 1+ while let address = defined[candidate], address != target {+ candidate = "\(name).\(suffix)"+ suffix += 1+ }+ return candidate+ }+ func vtable(_ name: String) -> Bool {+ name.hasPrefix("__ZTV") || name.contains("10gMetaClassE") || name.contains("10superClassE") || name.contains("9MetaClassE")+ }+ var nextName: [String: Int] = [:]+ for (importer, target) in needs {+ let owner = lookup(target)!+ var name = knownImport(importer, owner, target)+ if name == nil, owner.entry != kernelID {+ name = unique("_kc.\(owner.entry)." + positionName(owner, target), target)+ } else if name == nil {+ if deps[importer, default: []].contains("com.apple.kpi.private"), let prefix = privatePrefixes.first {+ name = unique(prefix + "_kc." + positionName(owner, target), target)+ } else {+ for candidate in namesAt[target] ?? [] {+ for dep in deps[importer] ?? [] where setNames[dep, default: []].contains(candidate) {+ name = candidate+ }+ }+ for dep in deps[importer] ?? [] {+ let names = setNames[dep] ?? []+ while name == nil, nextName[dep, default: 0] < names.count {+ let candidate = names[nextName[dep, default: 0]]+ nextName[dep, default: 0] += 1+ if defined[candidate] == nil, !reserved.contains(candidate), !vtable(candidate) {+ name = candidate+ }+ }+ }+ }+ }+ guard let name else { result.unresolved.append((importer, target))+ continue+ }+ if let other = defined[name], other != target {+ throw PatcherError.invalidFormat("ambiguous synthesized import \(name)")+ }+ define(owner, name, target)+ result.imports[importer, default: []].append(.init(name: name, type: 1, sect: 0, desc: 0, value: target))+ }+ if let text = kernel.sections.first(where: { $0.segmentName == "__TEXT_EXEC" && $0.name == "__text" }), let textOwner = lookup(text.address) {+ for name in reserved.sorted() {+ var isAliasTarget = false, aliasAddress: UInt64 = 0+ for set in sets {+ for symbol in set["Symbols"] as? [[String: Any]] ?? [] where symbol["AliasTarget"] as? String == name {+ isAliasTarget = true+ if let alias = symbol["SymbolName"] as? String, let address = defined[alias], aliasAddress == 0, lookup(address)?.entry == kernelID {+ aliasAddress = address+ }+ }+ }+ if let address = defined[name], lookup(address)?.entry == kernelID {+ continue+ }+ if aliasAddress != 0, let owner = lookup(aliasAddress) {+ if defined[name] != nil {+ result.exports[kernelID, default: []].append(.init(name: name, type: 0xF, sect: owner.index, desc: 0, value: aliasAddress))+ } else {+ define(owner, name, aliasAddress)+ }+ } else if isAliasTarget || name == fallback {+ if defined[name] != nil {+ result.exports[kernelID, default: []].append(.init(name: name, type: 0xF, sect: textOwner.index, desc: 0, value: text.address))+ } else {+ define(textOwner, name, text.address)+ }+ }+ }+ }+ for info in infos {+ guard let id = info["CFBundleIdentifier"] as? String, images[id] != nil,+ let number = info["_PrelinkKmodInfo"] as? NSNumber else { continue }+ let address = number.uint64Value+ if let owner = lookup(address), owner.entry == id {+ result.exports[id, default: []].append(.init(name: "_kmod_info", type: 0xF, sect: owner.index, desc: 0, value: address))+ }+ }+ for id in result.exports.keys {+ result.exports[id]!.sort { $0.name < $1.name }+ }+ for id in result.imports.keys {+ result.imports[id]!.sort { $0.name < $1.name }+ }+ return result+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecovery.swiftnew file mode 100644index 00000000..fd82b8b5--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecovery.swift@@ -0,0 +1,267 @@+// Reference recovery for stripped kernel collections. Port of ipsw#1372 at+// 7d81acd4b97e67c0a25b5ddc514ce2ad02e7d474; see LICENSE. No external tools.+import Foundation+import VPhonePatchKit++struct KDKFunction {+ var start: UInt64+ var end: UInt64+ func contains(_ address: UInt64) -> Bool {+ start <= address && address < end+ }+}++struct KDKCode {+ var section: KDKMachO.Section+ var bytes: [UInt8]+ func word(_ address: UInt64) -> UInt32? {+ guard address >= section.address, address - section.address < UInt64(bytes.count),+ bytes.count - Int(address - section.address) >= 4 else { return nil }+ return bytes.le(UInt32.self, Int(address - section.address))+ }+}++extension KDKImage {+ var sections: [KDKMachO.Section] {+ segments.flatMap(\.sections)+ }++ var codeSections: [KDKMachO.Section] {+ sections.filter { $0.size > 0 && !$0.name.contains("stubs") && $0.flags & 0x8000_0400 != 0 }+ }++ func functions(in collection: KDKKernelCollection) throws -> [KDKFunction] {+ guard let load = command(KDKMachO.lcFunctionStarts) else {+ throw PatcherError.invalidFormat("KDK recovery requires LC_FUNCTION_STARTS: \(identifier)")+ }+ var cursor = try KDKCursor(collection.bytes.bytes(Int(load.bytes.le(UInt32.self, 8)), Int(load.bytes.le(UInt32.self, 12))))+ guard !cursor.bytes.isEmpty else { return [] }+ var start = try baseAddress &+ (cursor.uleb())+ var result: [KDKFunction] = []+ while cursor.position < cursor.bytes.count {+ let delta = try cursor.uleb()+ if delta == 0 {+ break+ }+ result.append(.init(start: start, end: start &+ delta))+ start &+= delta+ }+ if let sec = sections.first(where: { $0.contains(start) }) {+ result.append(.init(start: start, end: sec.address + sec.size))+ }+ return result+ }+}++/// Bounded readers for metadata rather than unchecked Data subscripts.+struct KDKCursor {+ let bytes: [UInt8]+ var position = 0+ init(_ bytes: [UInt8], at position: Int = 0) {+ self.bytes = bytes+ self.position = position+ }++ mutating func read<T: FixedWidthInteger>(_ type: T.Type) throws -> T {+ let size = MemoryLayout<T>.size+ guard position >= 0, position <= bytes.count, size <= bytes.count - position else {+ throw PatcherError.invalidFormat("truncated KDK metadata at \(position)")+ }+ defer { position += size }+ return bytes.le(type, position)+ }++ mutating func uleb() throws -> UInt64 {+ var result: UInt64 = 0+ for shift in stride(from: 0, through: 63, by: 7) {+ let byte = try read(UInt8.self)+ if shift == 63, byte > 1 {+ throw PatcherError.invalidFormat("KDK ULEB128 overflow")+ }+ result |= UInt64(byte & 0x7F) << shift+ if byte & 0x80 == 0 {+ return result+ }+ }+ throw PatcherError.invalidFormat("unterminated KDK ULEB128")+ }++ mutating func sleb() throws -> Int64 {+ var value: UInt64 = 0, shift = 0+ var byte: UInt8 = 0+ repeat {+ guard shift < 64 else { throw PatcherError.invalidFormat("KDK SLEB128 overflow") }+ byte = try read(UInt8.self)+ value |= UInt64(byte & 0x7F) << shift+ shift += 7+ } while byte & 0x80 != 0+ if shift < 64, byte & 0x40 != 0 {+ value |= ~UInt64(0) << shift+ }+ return Int64(bitPattern: value)+ }++ mutating func string() throws -> String {+ let start = position+ while try read(UInt8.self) != 0 {}+ return String(decoding: bytes[start ..< position - 1], as: UTF8.self)+ }+}++extension [UInt64] {+ func upperBound(_ address: UInt64) -> Int {+ var low = 0, high = count+ while low < high {+ let mid = (low + high) / 2+ if self[mid] <= address {+ low = mid + 1+ } else {+ high = mid+ }+ }+ return low+ }+}++final class KDKRecovery {+ let collection: KDKKernelCollection+ var images: [String: KDKImage] = [:]+ var functions: [String: [KDKFunction]] = [:]+ var code: [String: [KDKCode]] = [:]+ var branchTargets = Set<UInt64>()+ var allCode: [KDKCode] = []+ var allCodeStarts: [UInt64] = []+ var allFunctions: [KDKFunction] = []+ var allFunctionStarts: [UInt64] = []+ var foreignReturns: [UInt64: Bool] = [:]+ let disassembler = ARM64Disassembler()++ init(_ collection: KDKKernelCollection) throws {+ self.collection = collection+ for entry in collection.entries {+ let image = try collection.image(entry.identifier)+ let funcs = try image.functions(in: collection)+ images[entry.identifier] = image+ functions[entry.identifier] = funcs+ allFunctions += funcs+ branchTargets.formUnion(funcs.map(\.start))+ branchTargets.formUnion(image.symbols.filter { !$0.isUndefined && $0.value != 0 }.map(\.value))+ code[entry.identifier] = try image.codeSections.map { try .init(section: $0, bytes: collection.read(Int($0.size), at: $0.address)) }+ }+ allCode = code.values.flatMap(\.self).sorted { $0.section.address < $1.section.address }+ allCodeStarts = allCode.map(\.section.address)+ allFunctions.sort { $0.start < $1.start }+ allFunctionStarts = allFunctions.map(\.start)+ }++ func recover() throws -> [String: [KDKReference]] {+ let pointers = try pointerReferences()+ var result: [String: [KDKReference]] = [:]+ for entry in collection.entries {+ let image = images[entry.identifier]!+ var refs = pointers[entry.identifier] ?? []+ refs += try metadataReferences(image)+ for section in code[entry.identifier] ?? [] {+ var adrps: [UInt64: UInt64] = [:]+ for off in stride(from: 0, to: section.bytes.count - 3, by: 4) {+ let word = section.bytes.le(UInt32.self, off), pc = section.section.address + UInt64(off)+ if ARM64Inst.isADRP(word) {+ let target = KDKInstruction.adrp(word, pc)+ if image.segments.contains(where: { (target & ~UInt64(0xFFF)) < $0.address + $0.memorySize && $0.address < (target & ~UInt64(0xFFF)) + 0x1000 }),+ disassembler.disassembleOne(ARM64.encodeU32(word), at: pc)?.mnemonic == "adrp"+ {+ adrps[pc] = target+ refs.append(.init(kind: 5, source: pc, target: target))+ }+ } else if ARM64Inst.isBorBL(word), let target = KDKInstruction.branch(word, pc) {+ let owner = image.sections.first { $0.contains(target) }+ if owner?.address == section.section.address {+ continue+ }+ if !branchTargets.contains(target), (owner?.flags ?? 0) & 0x8000_0400 == 0 {+ continue+ }+ if let decoded = disassembler.disassembleOne(ARM64.encodeU32(word), at: pc),+ decoded.mnemonic == "b" || decoded.mnemonic == "bl"+ {+ refs.append(.init(kind: 7, source: pc, target: target))+ }+ }+ }+ refs += recoverOff12(image, section, adrps)+ }+ result[entry.identifier] = refs.sorted { ($0.source, $0.kind, $0.extra, $0.target) < ($1.source, $1.kind, $1.extra, $1.target) }+ }+ return result+ }++ func pointerReferences() throws -> [String: [KDKReference]] {+ guard let load = collection.commands.first(where: { $0.command == KDKMachO.lcDyldChainedFixups }) else { return [:] }+ let bytes = try KDKMachO.Bytes(data: Data(collection.bytes.bytes(Int(load.bytes.le(UInt32.self, 8)), Int(load.bytes.le(UInt32.self, 12)))))+ let start = try Int(bytes.u32(4)), count = try Int(bytes.u32(start))+ try bytes.check(start + 4, count * 4)+ let ranges = images.flatMap { id, image in image.sections.filter { $0.size > 0 }.map { (id, $0.address, $0.size) } }.sorted { $0.1 < $1.1 }+ let starts = ranges.map(\.1)+ var result: [String: [KDKReference]] = [:]+ for i in 0 ..< count {+ let relative = try Int(bytes.u32(start + 4 + i * 4))+ if relative == 0 {+ continue+ }+ let record = start + relative+ let pageSize = try UInt64(bytes.u16(record + 4)), format = try bytes.u16(record + 6)+ let segmentOffset = try bytes.u64(record + 8), pages = try Int(bytes.u16(record + 20))+ guard pageSize > 0, format == 8 || format == 7 else { throw PatcherError.invalidFormat("unsupported collection chain format \(format)") }+ let recordSize = try Int(bytes.u32(record))+ try bytes.check(record, recordSize)+ guard recordSize >= 22 + pages * 2 else { throw PatcherError.invalidFormat("truncated collection chain starts") }+ for page in 0 ..< pages {+ let first = try bytes.u16(record + 22 + page * 2)+ if first == 0xFFFF {+ continue+ }+ var chains = [first]+ if first & 0x8000 != 0 {+ chains = []+ var index = Int(first & 0x7FFF)+ while true {+ guard 22 + index * 2 + 2 <= recordSize else { throw PatcherError.invalidFormat("bad multi-chain index") }+ let value = try bytes.u16(record + 22 + index * 2)+ chains.append(value & 0x7FFF)+ index += 1+ if value & 0x8000 != 0 {+ break+ }+ }+ }+ for chain in chains {+ let pageOffset = segmentOffset + UInt64(page) * pageSize+ var offset = pageOffset + UInt64(chain)+ while true {+ guard offset >= pageOffset, offset - pageOffset < pageSize else { throw PatcherError.invalidFormat("collection fixup leaves its page") }+ let raw = try collection.bytes.u64(Int(offset))+ let source = collection.baseAddress + offset+ let owner = starts.upperBound(source) - 1+ if owner >= 0, source - ranges[owner].1 < ranges[owner].2 {+ var target: UInt64?+ if format == 8 {+ target = raw & 0x3FFF_FFFF+ } else if raw & (1 << 62) == 0 {+ target = raw & (raw >> 63 == 1 ? 0xFFFF_FFFF : 0x7FF_FFFF_FFFF)+ }+ if let target {+ result[ranges[owner].0, default: []].append(.init(kind: 2, source: source, target: collection.baseAddress &+ target))+ }+ }+ let next = (raw >> 51) & (format == 8 ? 0xFFF : 0x7FF)+ if next == 0 {+ break+ }+ offset += next * 4+ }+ }+ }+ }+ return result+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecoveryFlow.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecoveryFlow.swiftnew file mode 100644index 00000000..48f5b103--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecoveryFlow.swift@@ -0,0 +1,292 @@+import Foundation+import VPhonePatchKit++extension KDKRecovery {+ final class FlowContext {+ let code: KDKCode+ let functions: [KDKFunction]+ let starts: [UInt64]+ var returnSites: [UInt64: [UInt64]] = [:]+ var viaReturn = Set<UInt64>()+ var adrpFunction: UInt64 = 0+ let panicAddresses: Set<UInt64>+ init(code: KDKCode, functions: [KDKFunction], symbols: [KDKSymbol]) {+ self.code = code+ self.functions = functions.filter { code.section.contains($0.start) }.sorted { $0.start < $1.start }+ starts = self.functions.map(\.start)+ panicAddresses = Set(symbols.filter { $0.name == "_panic" }.map(\.value))+ for off in stride(from: 0, to: max(0, code.bytes.count - 3), by: 4) {+ let word = code.bytes.le(UInt32.self, off), pc = code.section.address + UInt64(off)+ if ARM64Inst.isBL(word), let target = KDKInstruction.branch(word, pc), code.section.contains(target) {+ returnSites[target, default: []].append(pc + 4)+ }+ }+ }++ func function(_ address: UInt64) -> KDKFunction? {+ let i = starts.upperBound(address) - 1+ return i >= 0 && functions[i].contains(address) ? functions[i] : nil+ }+ }++ func recoverOff12(_ image: KDKImage, _ code: KDKCode, _ adrps: [UInt64: UInt64]) -> [KDKReference] {+ let context = FlowContext(code: code, functions: functions[image.identifier] ?? [], symbols: image.symbols)+ var result: [KDKReference] = []+ for source in adrps.keys.sorted() {+ let register = ARM64Inst.rd(code.word(source)!)+ context.viaReturn.removeAll(keepingCapacity: true)+ context.adrpFunction = context.function(source)?.start ?? 0+ var returns: [UInt64: Bool] = [:], visited: [UInt64: Set<UInt32>] = [:]+ let usages = track(context, at: source + 4, register: register, target: adrps[source]!, returns: &returns, visited: &visited)+ let function = (functions[image.identifier] ?? []).first { $0.contains(source) }+ for (consumer, target) in usages {+ if let function, !function.contains(consumer), !context.viaReturn.contains(consumer) {+ continue+ }+ result.append(.init(kind: 6, source: consumer, target: target, extra: source))+ }+ }+ return result+ }++ func track(_ context: FlowContext, at address: UInt64, register: UInt32, target: UInt64,+ returns: inout [UInt64: Bool], visited: inout [UInt64: Set<UInt32>]) -> [UInt64: UInt64]+ {+ let code = context.code+ var result: [UInt64: UInt64] = [:]+ // Keep the reader position separate: the reference's failed jump-table+ // recognizer rewinds its reader. Preserve this until differential tests+ // justify changing that behavior in both implementations.+ var reader = address+ for i in 0 ..< 10000 {+ guard let word = code.word(reader) else { break }+ reader += 4+ let pc = address + UInt64(i) * 4+ if visited[pc, default: []].contains(register) {+ break+ }+ visited[pc, default: []].insert(register)+ if let offset = ARM64Encoder.decodePageOffset(word) {+ if ARM64Inst.rn(word) == register {+ result[pc] = target &+ UInt64(offset)+ }+ } else if KDKInstruction.ret(word) {+ if let function = context.function(pc), function.start == context.adrpFunction {+ for site in context.returnSites[function.start] ?? [] {+ let usages = track(context, at: site, register: register, target: target, returns: &returns, visited: &visited)+ for (source, target) in usages {+ result[source] = target+ context.viaReturn.insert(source)+ }+ }+ }+ break+ } else if KDKInstruction.brk(word) {+ break+ } else if ARM64Inst.isBL(word) || KDKInstruction.blr(word) || KDKInstruction.authCall(word) {+ if register < 8 {+ break+ }+ guard ARM64Inst.isBL(word), let callee = KDKInstruction.branch(word, pc) else {+ if register >= 19, register <= 28 {+ continue+ }+ break+ }+ let (written, known) = calleeWrites(code, at: callee, register: register)+ if written || (!known && register <= 18) {+ break+ }+ var returnVisited = Set<UInt64>()+ if !mayReturn(context, at: callee, returns: &returns, visited: &returnVisited) {+ break+ }+ continue+ } else if KDKInstruction.br(word) {+ if followJumpTable(context, word: word, reader: &reader, register: register, target: target,+ result: &result, returns: &returns, visited: &visited)+ {+ break+ }+ } else if KDKInstruction.authJump(word) {+ break+ } else if !KDKInstruction.linear(word) {+ if let branch = KDKInstruction.branch(word, pc), code.word(branch) != nil {+ let usages = track(context, at: branch, register: register, target: target, returns: &returns, visited: &visited)+ result.merge(usages) { _, new in new }+ }+ if KDKInstruction.b(word) {+ break+ }+ continue+ } else if word & 0x7FE0_FFE0 == 0x2A00_03E0, ARM64Inst.rm(word) == register {+ let usages = track(context, at: pc + 4, register: ARM64Inst.rd(word), target: target, returns: &returns, visited: &visited)+ result.merge(usages) { _, new in new }+ }+ if KDKInstruction.writes(word, register) {+ break+ }+ }+ return result+ }++ func calleeWrites(_ code: KDKCode, at start: UInt64, register: UInt32) -> (Bool, Bool) {+ var pc = start+ for _ in 0 ..< 64 {+ guard let word = code.word(pc) else { return (false, false) }+ if KDKInstruction.ret(word) {+ return (false, true)+ }+ if !KDKInstruction.linear(word) || KDKInstruction.authJump(word) || KDKInstruction.authCall(word) {+ return (false, false)+ }+ let stack = word & 0x0A00_0000 == 0x0800_0000 && ARM64Inst.rn(word) == 31+ if stack, KDKInstruction.store(word) || KDKInstruction.storePair(word),+ ARM64Inst.rd(word) == register || (KDKInstruction.storePair(word) && (word >> 10) & 31 == register)+ {+ return (false, false)+ }+ if !stack, KDKInstruction.writes(word, register) {+ return (true, true)+ }+ pc += 4+ }+ return (false, false)+ }++ func followJumpTable(_ context: FlowContext, word branch: UInt32, reader: inout UInt64, register: UInt32, target: UInt64,+ result: inout [UInt64: UInt64], returns: inout [UInt64: Bool], visited: inout [UInt64: Set<UInt32>]) -> Bool+ {+ func back(_ n: UInt64) -> Bool {+ guard reader >= context.code.section.address + n * 4 else { return false }+ reader -= n * 4+ return true+ }+ func read() -> UInt32? {+ let word = context.code.word(reader)+ if word != nil {+ reader += 4+ }+ return word+ }+ let branchRegister = ARM64Inst.rn(branch)+ guard back(2), let add = read(), KDKInstruction.add(add), branchRegister == ARM64Inst.rd(add) else { return false }+ let offsetRegister = ARM64Inst.rm(add)+ guard back(2) else { return false }+ let adrAddress = reader+ guard back(1), let load = read(), load & 0xFFE0_FC00 == 0xB8A0_7800, offsetRegister == ARM64Inst.rd(load) else { return false }+ let baseRegister = ARM64Inst.rn(load), indexRegister = ARM64Inst.rm(load)+ guard back(2), let tableAdd = read(), KDKInstruction.add(tableAdd), baseRegister == ARM64Inst.rd(tableAdd) else { return false }+ let tableOffset = UInt64(ARM64Encoder.decodePageOffset(tableAdd) ?? 0)+ guard back(2), let adrp = read(), ARM64Inst.isADRP(adrp), ARM64Inst.rn(tableAdd) == ARM64Inst.rd(adrp) else { return false }+ // The pinned reference passes the reader's post-instruction address.+ let table = KDKInstruction.adrp(adrp, reader) &+ tableOffset+ guard back(3), let compare = read(), compare & 0x7F80_001F == 0x7100_001F, indexRegister == ARM64Inst.rn(compare) else { return false }+ let count = UInt64((compare >> 10) & 0xFFF) << (((compare >> 22) & 1) == 1 ? 12 : 0)+ guard context.code.word(table) != nil else { return true }+ reader = table+ for _ in 0 ..< count {+ guard let raw = read() else { break }+ let destination = adrAddress &+ UInt64(bitPattern: Int64(Int32(bitPattern: raw)))+ guard context.code.word(destination) != nil else { continue }+ let usages = track(context, at: destination, register: register, target: target, returns: &returns, visited: &visited)+ result.merge(usages) { _, new in new }+ }+ return true+ }++ func mayReturn(_ context: FlowContext, at start: UInt64, returns: inout [UInt64: Bool], visited: inout Set<UInt64>) -> Bool {+ if let known = returns[start] {+ return known+ }+ if context.panicAddresses.contains(start) {+ returns[start] = false+ return false+ }+ if context.code.word(start) == nil {+ let result = foreignMayReturn(start, depth: 0)+ returns[start] = result+ return result+ }+ var pc = start+ for _ in 0 ..< 1000 {+ guard let word = context.code.word(pc) else { break }+ if !visited.insert(pc).inserted {+ return false+ }+ if KDKInstruction.ret(word) || KDKInstruction.brk(word) || KDKInstruction.authJump(word) {+ returns[start] = true+ return true+ } else if ARM64Inst.isBL(word) || KDKInstruction.blr(word) {+ guard ARM64Inst.isBL(word), let callee = KDKInstruction.branch(word, pc) else { return true }+ if !mayReturn(context, at: callee, returns: &returns, visited: &visited) {+ returns[start] = false+ return false+ }+ } else if !KDKInstruction.linear(word) {+ guard let target = KDKInstruction.branch(word, pc) else { return true }+ if mayReturn(context, at: target, returns: &returns, visited: &visited) {+ returns[start] = true+ return true+ }+ if KDKInstruction.b(word) {+ returns[start] = false+ return false+ }+ }+ pc += 4+ }+ return true+ }++ func foreignMayReturn(_ start: UInt64, depth: Int) -> Bool {+ if let known = foreignReturns[start] {+ return known+ }+ let index = allFunctionStarts.upperBound(start) - 1+ guard index >= 0, allFunctions[index].start == start, depth <= 8 else { return true }+ let function = allFunctions[index]+ foreignReturns[start] = true // recursion assumes returning until proven otherwise+ var result = false, seen = Set<UInt64>(), work = [start]+ while !work.isEmpty, !result {+ var pc = work.removeLast()+ while !result {+ guard function.contains(pc), seen.insert(pc).inserted else { break }+ let codeIndex = allCodeStarts.upperBound(pc) - 1+ guard codeIndex >= 0, let word = allCode[codeIndex].word(pc) else { result = true+ break+ }+ if KDKInstruction.ret(word) {+ result = true+ } else if KDKInstruction.brk(word) {+ break+ } else if KDKInstruction.br(word) || KDKInstruction.authJump(word) {+ result = true+ } else if ARM64Inst.isBL(word) {+ if let target = KDKInstruction.branch(word, pc), !foreignMayReturn(target, depth: depth + 1) {+ break+ }+ pc += 4+ continue+ } else if KDKInstruction.b(word) {+ let target = KDKInstruction.branch(word, pc)!+ if !function.contains(target) {+ result = foreignMayReturn(target, depth: depth + 1)+ break+ }+ pc = target+ continue+ } else {+ if let target = KDKInstruction.branch(word, pc) {+ work.append(target)+ }+ pc += 4+ continue+ }+ break+ }+ }+ foreignReturns[start] = result+ return result+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecoveryMetadata.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecoveryMetadata.swiftnew file mode 100644index 00000000..1d91a172--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKRecoveryMetadata.swift@@ -0,0 +1,132 @@+import Foundation+import VPhonePatchKit++extension KDKRecovery {+ func metadataReferences(_ image: KDKImage) throws -> [KDKReference] {+ var result: [KDKReference] = []+ for section in image.sections {+ if section.segmentName == "__BOOTDATA", section.name == "__static_if" {+ let bytes = try collection.read(Int(section.size), at: section.address)+ for off in stride(from: 0, to: max(0, bytes.count - 3), by: 16) {+ let source = section.address + UInt64(off)+ let delta = Int64(bytes.le(Int32.self, off))+ result.append(.init(kind: 3, source: source, target: source &+ UInt64(bitPattern: delta)))+ }+ } else if section.segmentName == "__TEXT", section.name == "__copyio_vectors" {+ let bytes = try collection.read(Int(section.size), at: section.address)+ for off in stride(from: 0, to: max(0, bytes.count - 7), by: 8) {+ result.append(.init(kind: 4, source: section.address + UInt64(off), target: section.address &+ bytes.le(UInt64.self, off)))+ }+ } else if section.segmentName == "__TEXT", section.name == "__unwind_info" {+ let bytes = try KDKMachO.Bytes(data: Data(collection.read(Int(section.size), at: section.address)))+ try bytes.check(0, 28)+ let personality = try Int(bytes.u32(12)), personalityCount = try Int(bytes.u32(16))+ for i in 0 ..< personalityCount {+ let off = personality + i * 4+ try result.append(.init(kind: 12, source: section.address + UInt64(off), target: image.baseAddress + UInt64(bytes.u32(off))))+ }+ let index = try Int(bytes.u32(20)), count = try Int(bytes.u32(24))+ var firstLSDA = 0, lastLSDA = 0+ for i in 0 ..< count {+ let off = index + i * 12+ let target = try image.baseAddress + UInt64(bytes.u32(off)) + (i == count - 1 ? 1 : 0)+ result.append(.init(kind: 12, source: section.address + UInt64(off), target: target))+ lastLSDA = try Int(bytes.u32(off + 8))+ if i == 0 {+ firstLSDA = lastLSDA+ }+ }+ for off in stride(from: firstLSDA, to: lastLSDA, by: 4) {+ try result.append(.init(kind: 12, source: section.address + UInt64(off), target: image.baseAddress + UInt64(bytes.u32(off))))+ }+ } else if section.segmentName == "__TEXT", section.name == "__eh_frame" {+ result += try ehFrameReferences(collection.read(Int(section.size), at: section.address), address: section.address)+ }+ }+ return result+ }++ /// Only CIE encodings and FDE initial locations are required, not CFI+ /// execution. Respect the CIE's pointer encoding instead of assuming sdata8.+ func ehFrameReferences(_ bytes: [UInt8], address: UInt64) throws -> [KDKReference] {+ var cursor = KDKCursor(bytes)+ var encodings: [Int: UInt8] = [:]+ var result: [KDKReference] = []+ while cursor.position < bytes.count {+ let start = cursor.position+ let length = try cursor.read(UInt32.self)+ if length == 0 {+ break+ }+ guard length != UInt32.max else { throw PatcherError.invalidFormat("DWARF64 EH frame not supported by kernel export") }+ let end = cursor.position + Int(length)+ guard end <= bytes.count else { throw PatcherError.invalidFormat("truncated EH frame") }+ let idOffset = cursor.position+ let id = try cursor.read(UInt32.self)+ if id == 0 {+ let version = try cursor.read(UInt8.self), augmentation = try cursor.string()+ if version >= 4 {+ guard try cursor.read(UInt8.self) == 8, try cursor.read(UInt8.self) == 0 else { throw PatcherError.invalidFormat("unsupported EH address size") }+ }+ _ = try cursor.uleb()+ _ = try cursor.sleb()+ if version == 1 {+ _ = try cursor.read(UInt8.self)+ } else {+ _ = try cursor.uleb()+ }+ var encoding: UInt8 = 0+ if !augmentation.isEmpty {+ guard augmentation.first == "z" else { throw PatcherError.invalidFormat("unsupported EH augmentation") }+ let size = try Int(cursor.uleb()), augEnd = cursor.position + size+ guard augEnd <= end else { throw PatcherError.invalidFormat("truncated EH augmentation") }+ for character in augmentation.dropFirst() {+ switch character {+ case "L": _ = try cursor.read(UInt8.self)+ case "P":+ let enc = try cursor.read(UInt8.self)+ _ = try encodedPointer(&cursor, encoding: enc, address: address)+ case "R": encoding = try cursor.read(UInt8.self)+ case "S", "B", "G": break+ default: throw PatcherError.invalidFormat("unsupported EH augmentation \(character)")+ }+ }+ guard cursor.position == augEnd else { throw PatcherError.invalidFormat("EH augmentation size mismatch") }+ }+ encodings[start] = encoding+ } else {+ let cie = idOffset - Int(id)+ guard let encoding = encodings[cie] else { throw PatcherError.invalidFormat("missing EH CIE") }+ let initial = try encodedPointer(&cursor, encoding: encoding, address: address)+ result.append(.init(kind: 3, source: address + UInt64(start + 4), target: address + UInt64(cie)))+ // Preserve the reference writer's ld64 split-info kind. Source+ // locations are 64-bit on the supported arm64 collection corpus.+ result.append(.init(kind: 4, source: address + UInt64(start + 8), target: initial))+ }+ guard cursor.position <= end else { throw PatcherError.invalidFormat("EH fields exceed entry") }+ cursor.position = end+ }+ return result+ }++ func encodedPointer(_ cursor: inout KDKCursor, encoding: UInt8, address: UInt64) throws -> UInt64 {+ let field = address + UInt64(cursor.position)+ let value: UInt64+ switch encoding & 0xF {+ case 0, 4: value = try cursor.read(UInt64.self)+ case 1: value = try cursor.uleb()+ case 2: value = try UInt64(cursor.read(UInt16.self))+ case 3: value = try UInt64(cursor.read(UInt32.self))+ case 9: value = try UInt64(bitPattern: cursor.sleb())+ case 10: value = try UInt64(bitPattern: Int64(cursor.read(Int16.self)))+ case 11: value = try UInt64(bitPattern: Int64(cursor.read(Int32.self)))+ case 12: value = try cursor.read(UInt64.self)+ default: throw PatcherError.invalidFormat("unsupported EH pointer encoding \(encoding)")+ }+ switch encoding & 0x70 {+ case 0: return value+ case 0x10: return field &+ value+ default: throw PatcherError.invalidFormat("unsupported EH relative pointer encoding \(encoding)")+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSE b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSEindex ed0d0f6d..c7152356 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSE+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSE@@ -19,3 +19,13 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.++Reference recovery and symbol synthesis are derived from ipsw:+Copyright (c) 2018-2026 blacktop+Under the same MIT License above.++Instruction analysis includes arm64-cgo predicates:+Copyright © 2021-2026 blacktop+EH frame field decoding follows go-dwarf:+Copyright (c) 2022-2023 blacktop+Both are under the same MIT License above.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swiftindex 45649b00..d049c1e6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift@@ -17,11 +17,11 @@//// The maps are research results: BinDiff symbolication against a symbolicated// KDK of the same family, plus verified fixes (see the README beside the-// recipes). Extracting needs an `ipsw` with `kernel extract --kdk`, which-// vphone-cli does not ship: `VPHONE_IPSW` names it.+// recipes). Extraction runs natively in this process; kmutil still performs the link.import Foundationimport Img4tool+import VPhoneArchiveKitimport VPhoneCoreKitimport VPhonePatchKit@@ -48,8 +48,9 @@ public final class KernelCacheMixer {}/// Bump when the steps change, so cached mixes are rebuilt.- static let revision = 3+ static let revision = 4+ /// Legacy source-compatibility constant. Native extraction does not read it.public static let ipswEnvironmentVariable = "VPHONE_IPSW"public init(@@ -110,8 +111,8 @@ public final class KernelCacheMixer {guard try geteuid() == 0 || mixer.linksRemotely(input) else {throw PatcherError.invalidFormat(linkInstructions(staged: state == .staged))}- if state == .missing {- _ = try ipsw()+ if state == .missing, geteuid() == 0 {+ throw PatcherError.invalidFormat(linkInstructions(staged: false))}}@@ -143,7 +144,7 @@ public final class KernelCacheMixer {/// The mixed kernelcache (an IMG4 `krnl` container) for a research board/// one: from the cache, linked from a staged volume (root), or staged and- /// linked in one go (root with `VPHONE_IPSW`).+ /// linked from a volume staged by the invoking user.public func mix(_ input: Input) throws -> Data {let (base, paths) = try locations(for: input)log(" [kc] base \(base.id) (\(base.productVersion)), donors \(base.donors.joined(separator: ", "))")@@ -161,17 +162,17 @@ public final class KernelCacheMixer {}/// Extracts both kernelcaches and stages the volume kmutil links, as the- /// invoking user: the one step that runs `ipsw`. Does nothing when the mix+ /// invoking user, entirely in process. Does nothing when the mix/// or its volume is already in the cache.- public func stage(_ input: Input, ipsw ipswPath: String? = nil) throws {+ /// The legacy ipsw argument is accepted as a no-op throughout 2.12.x.+ public func stage(_ input: Input, ipsw _: String? = nil) throws {let (base, paths) = try locations(for: input)guard !FileManager.default.fileExists(atPath: paths.mixed.path), !Self.isStaged(paths.staged) else { return }guard geteuid() != 0 else {- throw PatcherError.invalidFormat("Stage the kernelcache as your user first with `VPHONE_IPSW=<ipsw> vphone-cli fw kernelcache <vm>`, then run `sudo vphone-cli fw kernelcache <vm> --link-only`. External extraction tools never run as root.")+ throw PatcherError.invalidFormat("Stage the kernelcache as your user first with `vphone-cli fw kernelcache <vm>`, then run `sudo vphone-cli fw kernelcache <vm> --link-only`. Extraction writes to the invoking user's cache; root only links a staged volume.")}let location = try KernelCollectionBuilder.location(for: base)let donors = try base.donors.map { try recipes.donor(id: $0) }- let ipsw = try Self.ipsw(ipswPath)let fm = FileManager.defaulttry? fm.removeItem(at: paths.staged)@@ -179,7 +180,7 @@ public final class KernelCacheMixer {try fm.createDirectory(at: work, withIntermediateDirectories: true)log(" [kc] staging in \(paths.staged.path)")- let donorKDKs = try donors.map { try donorKDK($0, restoreTree: input.restoreTree, ipsw: ipsw) }+ let donorKDKs = try donors.map { try donorKDK($0, restoreTree: input.restoreTree) }let payload = try Self.payload(of: input.kernelcache)try Self.check(payload, base.kernel.decompressedSHA256, "decompressed \(base.kernel.file)")let decompressed = work.appending(path: "\(base.kernel.file).decompressed")@@ -187,7 +188,7 @@ public final class KernelCacheMixer {log(" [kc] extracting the base kernelcache with its symbol map")let baseKDK = try extract(kernelcache: decompressed, symbols: base.symbolsURL, kdk: base.kernel.kdk,- into: work.appending(path: "base"), ipsw: ipsw.url,+ into: work.appending(path: "base"),)let identifiers = try base.kextIdentifiers()@@ -200,7 +201,7 @@ public final class KernelCacheMixer {log(" [kc] mix: \(identifiers.count) kexts, \(removed.count) research board kexts removed, \(addedText)")try KernelCacheKDK.makeVolume(kdk: mixKDK, identifiers: identifiers, output: paths.staged.appending(path: "volume"))try fm.removeItem(at: work)- try Data(ipsw.hash.utf8).write(to: paths.staged.appending(path: "ipsw.sha256"))+ try Data(KDKExtraction.revision.utf8).write(to: paths.staged.appending(path: "extractor.version"))try Data().write(to: paths.staged.appending(path: Self.stagedMarker))// Under sudo, so the user's later runs can replace it.if geteuid() == 0 {@@ -213,7 +214,7 @@ public final class KernelCacheMixer {}}- /// Links a staged volume, as root, and caches the result. Runs no `ipsw`:+ /// Links a staged volume, as root, and caches the result:/// the volume is copied into a directory only root can reach, with nothing/// in it that points outside, and kmutil links that copy.@discardableResult@@ -227,7 +228,7 @@ public final class KernelCacheMixer {throw PatcherError.invalidFormat(Self.linkInstructions(staged: Self.isStaged(paths.staged)))}guard Self.isStaged(paths.staged) else {- throw PatcherError.fileNotFound("the staged \(base.id) kernelcache volume in \(paths.staged.path); run `vphone-cli fw kernelcache` with \(Self.ipswEnvironmentVariable) first")+ throw PatcherError.fileNotFound("the staged \(base.id) kernelcache volume in \(paths.staged.path); run `vphone-cli fw kernelcache` as your user first")}let payload = try Self.payload(of: input.kernelcache)@@ -370,7 +371,7 @@ public final class KernelCacheMixer {let link = "sudo vphone-cli fw kernelcache <vm>"return staged? "the kernelcache mix is staged; linking it needs root (kmutil only reads kexts owned by root). Run `\(link)`, or this command with sudo."- : "the kernelcache mix is not built yet. Stage it as your user with `\(ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache <vm>`, then link it with `\(link) --link-only`."+ : "the kernelcache mix is not built yet. Stage it as your user with `vphone-cli fw kernelcache <vm>`, then link it with `\(link) --link-only`."}// MARK: - Steps@@ -400,27 +401,33 @@ public final class KernelCacheMixer {return try Data(contentsOf: url)}- /// `ipsw kernel extract --kdk` into `directory`, returning the KDK named- /// `kdk`. A kernelcache whose kexts carry no `DTPlatformBuild` gives- /// `KDK_<version>_.kdk`; the recipe supplies the build.- func extract(kernelcache: URL, symbols: URL?, kdk: String, into directory: URL, ipsw: URL) throws -> URL {+ /// Extract natively. A kernelcache whose kexts carry no DTPlatformBuild+ /// gives KDK_<version>_.kdk; the recipe supplies the build.+ func extract(kernelcache: URL, symbols: URL?, kdk: String, into directory: URL) throws -> URL {let fm = FileManager.defaulttry? fm.removeItem(at: directory)try fm.createDirectory(at: directory, withIntermediateDirectories: true)- let log = directory.appending(path: "extract.log")- var arguments = ["kernel", "extract", "--kdk", "--force"]+ var messages: [String] = []+ defer { try? messages.joined(separator: "\n").write(to: directory.appending(path: "extract.log"), atomically: true, encoding: .utf8) }+ var known: [UInt64: [String]] = [:]if let symbols {- let compressed = directory.appending(path: "symbols.json.gz")- try fm.copyItem(at: symbols, to: compressed)- try Self.run("/usr/bin/gzip", ["-d", compressed.path], log: log)- arguments += ["--symbols", directory.appending(path: "symbols.json").path]+ let json = directory.appending(path: "symbols.json")+ try VPhoneArchiveWriter.decompress(symbols, to: json)+ known = try KDKLinkSymbols.loadKnown(Data(contentsOf: json))+ try fm.removeItem(at: json)+ }+ do {+ _ = try KDKExtraction.extract(Data(contentsOf: kernelcache, options: .mappedIfSafe), to: directory, known: known) {+ messages.append($0)+ }+ } catch {+ messages.append("ERROR: \(error)")+ throw error}- arguments += [kernelcache.path, "-o", directory.path]- try Self.run(ipsw.path, arguments, environment: ["NO_COLOR": "1"], log: log)let produced = try fm.contentsOfDirectory(atPath: directory.path).filter { $0.hasPrefix("KDK_") && $0.hasSuffix(".kdk") }guard produced.count == 1, let name = produced.first else {- throw PatcherError.fileNotFound("the KDK `ipsw kernel extract --kdk` wrote into \(directory.path) (found \(produced))")+ throw PatcherError.fileNotFound("the native KDK extraction wrote into \(directory.path) (found \(produced))")}var url = directory.appending(path: name)if name != kdk {@@ -440,7 +447,7 @@ public final class KernelCacheMixer {}/// The donor's KDK, extracted once into `donors/<id>`.- func donorKDK(_ donor: KernelCacheDonor, restoreTree: URL, ipsw: (url: URL, hash: String)) throws -> URL {+ func donorKDK(_ donor: KernelCacheDonor, restoreTree: URL) throws -> URL {let fm = FileManager.defaultlet directory = cacheDirectory.appending(path: "donors/\(donor.id)")let kdk = directory.appending(path: "extract/\(donor.kernel.kdk)")@@ -449,7 +456,7 @@ public final class KernelCacheMixer {if let symbols = donor.symbolsURL {keyMaterial += try Data(contentsOf: symbols)}- keyMaterial += Data(ipsw.hash.utf8)+ keyMaterial += Data(KDKExtraction.revision.utf8)let key = KernelCacheRecipes.sha256(keyMaterial)if (try? String(contentsOf: marker, encoding: .utf8)) == key, fm.fileExists(atPath: kdk.path) {log(" [kc] using the cached donor KDK \(kdk.path)")@@ -464,7 +471,7 @@ public final class KernelCacheMixer {log(" [kc] extracting the donor kernelcache \(donor.id)")let extracted = try extract(kernelcache: decompressed, symbols: donor.symbolsURL, kdk: donor.kernel.kdk,- into: directory.appending(path: "extract"), ipsw: ipsw.url,+ into: directory.appending(path: "extract"),)try key.write(to: marker, atomically: true, encoding: .utf8)return extracted@@ -504,9 +511,7 @@ public final class KernelCacheMixer {// MARK: - Helpers/// What decides the output: the kernelcaches, maps and bundle list, the- /// layout and this file's steps. Not the ipsw, which the root link does not- /// run: a stage records which one made it (`ipsw.sha256`), and removing- /// `~/.vphone/kernelcache` rebuilds everything.+ /// layout, native extractor revision and this file's steps.func cacheKey(base: KernelCacheBase, donors: [KernelCacheDonor]) throws -> String {var material = Data("\(Self.identity(base.kernel))|".utf8)for donor in donors {@@ -515,7 +520,7 @@ public final class KernelCacheMixer {for url in [base.symbolsURL, base.kextsURL] + donors.compactMap(\.symbolsURL) {material += try Data(contentsOf: url)}- material += Data("\(Self.revision)|\(base.builderLayout.rawValue)".utf8)+ material += Data("\(Self.revision)|\(base.builderLayout.rawValue)|\(KDKExtraction.revision)".utf8)// A recipe with its own source order is keyed on it too.if base.sources != nil {material += Data("|\(base.kextSources.joined(separator: ","))".utf8)@@ -541,25 +546,6 @@ public final class KernelCacheMixer {return data}- /// The `ipsw` given, or else named by `VPHONE_IPSW`, with `kernel extract --kdk`.- static func ipsw(_ given: String? = nil) throws -> (url: URL, hash: String) {- let hint = "The kernelcache mix needs an ipsw with `kernel extract --kdk`; set \(ipswEnvironmentVariable) to its path "- + "(under sudo: `sudo \(ipswEnvironmentVariable)=<path> vphone-cli ...`)."- guard let path = given ?? ProcessInfo.processInfo.environment[ipswEnvironmentVariable], !path.isEmpty else {- throw PatcherError.fileNotFound("ipsw. \(hint)")- }- let url = URL(fileURLWithPath: path)- guard FileManager.default.isExecutableFile(atPath: url.path),- let help = try? VPhoneProcessRunner.runCapturing(url, ["kernel", "extract", "--help"]),- help.stdout.contains("--kdk"), help.stdout.contains("--symbols")- else {- throw PatcherError.invalidFormat("\(path) is not an ipsw with `kernel extract --kdk --symbols`. \(hint)")- }- // Its own hash, not `ipsw version`, which a local build leaves empty.- let binary = try Data(contentsOf: url, options: .mappedIfSafe)- return (url, KernelCacheRecipes.sha256(binary))- }-/// Runs a tool with its output in `log`, which a failure quotes the end of.static func run(_ executable: String, _ arguments: [String], environment: [String: String] = [:], log: URL) throws {let fm = FileManager.defaultdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheRecipes.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheRecipes.swiftindex 0ce40af8..bffbaa5a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheRecipes.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheRecipes.swift@@ -18,7 +18,7 @@ public struct KernelCacheFile: Decodable, Sendable {public let sha256: String/// SHA-256 of the decompressed kernel collection.public let decompressedSHA256: String- /// The KDK `ipsw kernel extract --kdk` makes of it.+ /// The KDK the native extractor makes of it.public let kdk: Stringfunc matches(sha: String) -> Bool {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swiftindex 87ab9847..94fde934 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift@@ -41,7 +41,7 @@ public enum FirmwareResearchBoardPatchSet {VPhonePatchDeclaration(identifier: kernelMix,title: "Virtualisation kexts",- summary: "Rebuilds the research board's kernelcache with the paravirtual GPU, touch, audio and other iPhone virtualisation kexts of the 26.4 beta vphone600 kernelcache, from a recipe for that release. Needs root and an ipsw with `kernel extract --kdk` (VPHONE_IPSW).",+ summary: "Rebuilds the research board's kernelcache with the paravirtual GPU, touch, audio and other iPhone virtualisation kexts of the 26.4 beta vphone600 kernelcache, from a recipe for that release. Extracts the KDK natively; linking it with kmutil needs root.",target: .firmware(.kernelcache),bootEssential: true,),diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKExtractionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKExtractionTests.swiftnew file mode 100644index 00000000..85baac2e--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKExtractionTests.swift@@ -0,0 +1,93 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++struct KDKExtractionTests {+ @Test func `bundle paths and metadata`() throws {+ let root = URL(fileURLWithPath: "/tmp/KDK/Extensions")+ let info: [String: Any] = [+ "CFBundleIdentifier": "com.test.plugin", "CFBundleExecutable": "Plugin",+ "_PrelinkBundlePath": "/System/Library/Extensions/Parent.kext/Contents/PlugIns/Plugin.kext",+ "_PrelinkExecutableRelativePath": "Contents/MacOS/Plugin", "OSBundleUUID": Data([1]), "CFBundleNumericVersion": 3,+ ]+ let paths = try KDKExtraction.bundleLayout(root, identifier: "com.test.plugin", info: info)+ #expect(paths.plist.path == "/tmp/KDK/Extensions/Parent.kext/Contents/PlugIns/Plugin.kext/Contents/Info.plist")+ #expect(paths.executable?.lastPathComponent == "Plugin")+ #expect(KDKExtraction.standaloneInfo(info).count == 2)+ #expect(info.count == 6)+ for path in ["/tmp/escape", "../escape", "A/../../escape", "A//B", "A/./B", ""] {+ #expect(throws: PatcherError.self) { try KDKExtraction.child(root, path) }+ }+ let codeless = try KDKExtraction.bundleLayout(root, identifier: "com.test.personality", info: ["DTPlatformName": "macosx"])+ #expect(codeless.plist.path.hasSuffix(".kext/Contents/Info.plist"))+ #expect(codeless.executable == nil)+ }++ @Test func `pseudo executable retains UUID and symbols`() throws {+ let uuid = Array(UInt8(0) ..< 16)+ let data = KDKExtraction.pseudoMachO(uuid: uuid, symbols: ["_z", "_a"])+ let (header, commands) = try KDKMachO.loadCommands(in: .init(data: data), at: 0)+ #expect(header.fileType == 0xB)+ #expect(header.commandCount == 3)+ #expect(header.cpuSubtype == 2)+ #expect(Array(commands[2].bytes[8 ..< 24]) == uuid)+ let symbols = try KDKMachO.symbols(commands[1].bytes, in: .init(data: data))+ #expect(symbols.map(\.name) == ["_a", "_z"])+ #expect(symbols.allSatisfy { $0.isExternal && $0.isUndefined && $0.value == 0 })+ }++ @Test(.enabled(if: ProcessInfo.processInfo.environment["KDK_PARITY_ROOT"] != nil))+ func `complete KDK trees match reference`() throws {+ let root = try URL(fileURLWithPath: #require(ProcessInfo.processInfo.environment["KDK_PARITY_ROOT"]))+ let fm = FileManager.default+ let temporary = fm.temporaryDirectory.appending(path: "KDK-extraction-\(UUID().uuidString)")+ defer { try? fm.removeItem(at: temporary) }+ for (label, kernel) in [("donor", "vphone600"), ("research", "vresearch101")] {+ let source = root.appending(path: "data/264beta/kernelcache.release.\(kernel).decompressed")+ let corpus = root.appending(path: "parity/\(label)")+ let symbolURL = corpus.appending(path: "symbols.json")+ let known = fm.fileExists(atPath: symbolURL.path) ? try KDKLinkSymbols.loadKnown(Data(contentsOf: symbolURL)) : [:]+ let output: URL+ if label == "donor" {+ var repository = URL(fileURLWithPath: #filePath)+ for _ in 0 ..< 5 {+ repository.deleteLastPathComponent()+ }+ let recipes = KernelCacheRecipes(root: repository.appending(path: "VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes"))+ let donor = try recipes.donor(id: "vphone600_26.4_23E5207q")+ let mixer = KernelCacheMixer(recipes: recipes, cacheDirectory: temporary.appending(path: "cache"), verbose: false)+ output = try mixer.extract(kernelcache: source, symbols: donor.symbolsURL, kdk: donor.kernel.kdk, into: temporary.appending(path: label))+ } else {+ output = try KDKExtraction.extract(Data(contentsOf: source), to: temporary.appending(path: label), known: known)+ }+ let expected = corpus.appending(path: "out").appending(path: output.lastPathComponent)+ func files(_ directory: URL) throws -> Set<String> {+ let enumerator = try #require(fm.enumerator(atPath: directory.path))+ return Set((enumerator.allObjects as? [String] ?? []).filter { path in+ var isDirectory: ObjCBool = false+ return fm.fileExists(atPath: directory.appending(path: path).path, isDirectory: &isDirectory) && !isDirectory.boolValue+ })+ }+ let paths = try files(expected)+ #expect(try files(output) == paths)+ for path in paths.sorted() {+ let actual = try Data(contentsOf: output.appending(path: path))+ let reference = try Data(contentsOf: expected.appending(path: path))+ if path.hasSuffix(".plist") {+ let a = try PropertyListSerialization.propertyList(from: actual, format: nil) as? NSDictionary+ let b = try PropertyListSerialization.propertyList(from: reference, format: nil) as? NSDictionary+ #expect(a == b, "\(label)/\(path): plist values differ")+ } else {+ #expect(actual == reference, "\(label)/\(path): executable bytes differ")+ }+ let permissions = try fm.attributesOfItem(atPath: output.appending(path: path).path)[.posixPermissions] as? NSNumber+ #expect(permissions?.intValue == 0o777)+ }+ #expect(throws: PatcherError.self) {+ try KDKExtraction.extract(Data(contentsOf: source), to: temporary.appending(path: label), known: known)+ }+ print("KDK tree parity: \(label), \(paths.count) files, all executable bytes and plist values match")+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKRecoveryFlowTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKRecoveryFlowTests.swiftnew file mode 100644index 00000000..0a1759d9--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKRecoveryFlowTests.swift@@ -0,0 +1,97 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++struct KDKRecoveryFlowTests {+ func code(_ instructions: [UInt64: Data], functions: [KDKFunction]) -> KDKRecovery.FlowContext {+ var bytes = [UInt8](repeating: 0, count: 0x200)+ for (pc, data) in instructions {+ bytes.replaceSubrange(Int(pc - 0x1000) ..< Int(pc - 0x1000) + data.count, with: data)+ }+ let section = KDKMachO.Section(name: "__text", segmentName: "__TEXT_EXEC", address: 0x1000, size: 0x200,+ offset: 0, align: 2, relocationOffset: 0, relocationCount: 0, flags: 0x8000_0400,+ reserved1: 0, reserved2: 0, reserved3: 0)+ return .init(code: .init(section: section, bytes: bytes), functions: functions, symbols: [])+ }++ func recovery() throws -> KDKRecovery {+ try KDKRecovery(KDKExportFixtureTests.fixture().0)+ }++ func track(_ recovery: KDKRecovery, _ context: KDKRecovery.FlowContext, start: UInt64, register: UInt32) -> [UInt64: UInt64] {+ var returns: [UInt64: Bool] = [:], visited: [UInt64: Set<UInt32>] = [:]+ return recovery.track(context, at: start, register: register, target: 0x8000, returns: &returns, visited: &visited)+ }++ @Test func `outlined callee clobber stops tracking`() throws {+ let recovery = try recovery()+ let functions = [KDKFunction(start: 0x1000, end: 0x1010), KDKFunction(start: 0x1100, end: 0x1110)]+ var instructions: [UInt64: Data] = try [+ 0x1004: #require(ARM64Encoder.encodeBL(from: 0x1004, to: 0x1100)),+ 0x1008: #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: 0x20)),+ 0x100C: ARM64.ret, 0x1100: ARM64.ret,+ ]+ #expect(track(recovery, code(instructions, functions: functions), start: 0x1004, register: 19)[0x1008] == 0x8020)+ instructions[0x1100] = try #require(ARM64Encoder.encodeADRP(rd: 19, pc: 0x1100, target: 0x9000))+ instructions[0x1104] = ARM64.ret+ #expect(track(recovery, code(instructions, functions: functions), start: 0x1004, register: 19).isEmpty)+ }++ @Test func `outlined ADRP hands register back to caller`() throws {+ let recovery = try recovery()+ let context = try code([+ 0x1000: #require(ARM64Encoder.encodeBL(from: 0x1000, to: 0x1100)),+ 0x1004: #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 24, offset: 0x28)),+ 0x1008: ARM64.ret,+ 0x1100: #require(ARM64Encoder.encodeADRP(rd: 24, pc: 0x1100, target: 0x8000)),+ 0x1104: ARM64.ret,+ ], functions: [.init(start: 0x1000, end: 0x1010), .init(start: 0x1100, end: 0x1110)])+ context.adrpFunction = 0x1100+ #expect(track(recovery, context, start: 0x1104, register: 24)[0x1004] == 0x8028)+ #expect(context.viaReturn.contains(0x1004))+ }++ @Test func `foreign non returning loop ends dataflow`() throws {+ let recovery = try recovery()+ let foreignContext = try code([0x1100: #require(ARM64Encoder.encodeB(from: 0x1100, to: 0x1100))], functions: [.init(start: 0x1100, end: 0x1104)])+ recovery.allCode = [foreignContext.code]+ recovery.allCodeStarts = [0x1000]+ recovery.allFunctions = [.init(start: 0x1100, end: 0x1104)]+ recovery.allFunctionStarts = [0x1100]+ #expect(!recovery.foreignMayReturn(0x1100, depth: 0))+ }++ @Test func `instruction predicates agree with capstone`() throws {+ let encodings = [+ ARM64Encoder.encodeADRP(rd: 19, pc: 0x1000, target: 0x8000),+ ARM64Encoder.encodeAddImm12(rd: 20, rn: 19, imm12: 0x28),+ ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: 0x20),+ ARM64Encoder.encodeLdrWUnsignedOffset(rt: 1, rn: 19, offset: 4),+ ARM64Encoder.encodeStrXUnsignedOffset(rt: 20, rn: 19, offset: 8),+ ARM64Encoder.encodeStpX(rt1: 19, rt2: 20, rn: 31, offset: 16),+ ARM64Encoder.encodeCmpWImmediate(rn: 0, imm12: 1),+ ]+ let decoder = ARM64Disassembler()+ for data in encodings {+ let data = try #require(data)+ let word = [UInt8](data).le(UInt32.self, 0)+ let instruction = try #require(decoder.disassembleOne(data, at: 0x1000))+ for register in 0 ..< 31 {+ let decodedWrite = instruction.detail?.operands.contains {+ $0.type == .register && $0.writesRegister && ($0.reg == .x(register) || $0.reg == .w(register))+ } ?? false+ #expect(KDKInstruction.writes(word, UInt32(register)) == decodedWrite, "\(instruction.mnemonic), x\(register)")+ }+ }+ for data in [ARM64Encoder.encodeB(from: 0x1000, to: 0x800), ARM64Encoder.encodeBL(from: 0x1000, to: 0x2000),+ ARM64Encoder.encodeCompareBranch(nonzero: true, register: 1, from: 0x1000, to: 0x1080),+ ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 2, bit: 40, from: 0x1000, to: 0xFC0)]+ {+ let data = try #require(data)+ let decoded = try #require(decoder.disassembleOne(data, at: 0x1000))+ let target = try #require(decoded.detail?.operands.last(where: { $0.type == .immediate })?.imm)+ #expect(KDKInstruction.branch([UInt8](data).le(UInt32.self, 0), 0x1000) == UInt64(bitPattern: target))+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKRecoveryTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKRecoveryTests.swiftnew file mode 100644index 00000000..071e1977--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKRecoveryTests.swift@@ -0,0 +1,117 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++struct KDKRecoveryTests {+ @Test func `symbol map formats`() throws {+ let data = Data(#"{"0xfffffe0000000000":"_one","18446741874686296065":["_two","_alias"]}"#.utf8)+ let map = try KDKLinkSymbols.loadKnown(data)+ #expect(map[0xFFFF_FE00_0000_0000] == ["_one"])+ #expect(map[0xFFFF_FE00_0000_0001] == ["_two", "_alias"])+ #expect(throws: PatcherError.self) { try KDKLinkSymbols.loadKnown(Data(#"{"no-address":"_bad"}"#.utf8)) }+ #expect(throws: PatcherError.self) { try KDKLinkSymbols.loadKnown(Data(#"{"0x1234":42}"#.utf8)) }+ }++ @Test func `bounded ULEB`() throws {+ var cursor = KDKCursor([0xE5, 0x8E, 0x26])+ #expect(try cursor.uleb() == 624_485)+ var malformed = KDKCursor([0x80])+ #expect(throws: PatcherError.self) { try malformed.uleb() }+ var overflow = KDKCursor(Array(repeating: UInt8(0xFF), count: 10))+ #expect(throws: PatcherError.self) { try overflow.uleb() }+ }++ @Test(.enabled(if: ProcessInfo.processInfo.environment["KDK_PARITY_ROOT"] != nil))+ func `recovered inputs and exports match reference`() throws {+ let root = try URL(fileURLWithPath: #require(ProcessInfo.processInfo.environment["KDK_PARITY_ROOT"]))+ struct Symbol: Decodable {+ var name: String+ var indirectName: String?+ var type: UInt8+ var sect: UInt8+ var desc: UInt16+ var value: UInt64+ var model: KDKSymbol {+ .init(name: name, indirectName: indirectName ?? "", type: type, sect: sect, desc: desc, value: value)+ }+ }+ struct Input: Decodable {+ var entryID: String+ var output: String+ var baseAddress: UInt64+ var symbols: [Symbol]+ var references: [KDKReference]+ }+ let fm = FileManager.default+ var verified = 0+ for (label, kernel) in [("donor", "vphone600"), ("research", "vresearch101")] {+ print("KDK native recovery starting: \(label)")+ let collection = try KDKKernelCollection(Data(contentsOf: root.appending(path: "data/264beta/kernelcache.release.\(kernel).decompressed"), options: .mappedIfSafe))+ let recovery = try KDKRecovery(collection)+ let references = try recovery.recover()+ let corpus = root.appending(path: "parity/\(label)")+ let files = try fm.contentsOfDirectory(at: corpus.appending(path: "inputs"), includingPropertiesForKeys: nil)+ .filter { $0.pathExtension == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }+ let inputs = try files.map { try JSONDecoder().decode(Input.self, from: Data(contentsOf: $0)) }+ var differences = 0+ for input in inputs {+ let expected = Set(input.references), actual = Set(references[input.entryID] ?? [])+ if actual != expected {+ let missing = expected.subtracting(actual).sorted { ($0.source, $0.kind, $0.extra) < ($1.source, $1.kind, $1.extra) }+ let extra = actual.subtracting(expected).sorted { ($0.source, $0.kind, $0.extra) < ($1.source, $1.kind, $1.extra) }+ print("KDK recovery difference \(label)/\(input.entryID): missing \(missing.count), extra \(extra.count)")+ for r in missing.prefix(5) {+ print(" missing kind=\(r.kind) source=\(String(r.source, radix: 16)) target=\(String(r.target, radix: 16)) extra=\(String(r.extra, radix: 16))")+ }+ for r in extra.prefix(5) {+ print(" extra kind=\(r.kind) source=\(String(r.source, radix: 16)) target=\(String(r.target, radix: 16)) extra=\(String(r.extra, radix: 16))")+ }+ let payload = ["missing": missing, "extra": extra]+ try JSONEncoder().encode(payload).write(to: root.appending(path: "recovery-\(label)-\(input.entryID).json"))+ differences += 1+ }+ }+ guard differences == 0 else { Issue.record("\(label): reference differences in \(differences) images")+ return+ }+ let knownURL = corpus.appending(path: "symbols.json")+ let known = fm.fileExists(atPath: knownURL.path) ? try KDKLinkSymbols.loadKnown(Data(contentsOf: knownURL)) : [:]+ let symbols = try recovery.synthesizeSymbols(references: references, known: known)+ for input in inputs {+ let generated = (symbols.exports[input.entryID] ?? []) + (symbols.imports[input.entryID] ?? [])+ let expected = input.symbols.map(\.model)+ guard generated == expected else {+ let difference = zip(generated, expected).enumerated().first { $0.element.0 != $0.element.1 }?.offset ?? min(generated.count, expected.count)+ print("KDK symbol difference \(label)/\(input.entryID) at \(difference), native \(generated.count), reference \(expected.count)")+ if difference < generated.count {+ print("native: \(generated[difference])")+ }+ if difference < expected.count {+ print("reference: \(expected[difference])")+ }+ Issue.record("symbol synthesis differs: \(input.entryID)")+ return+ }+ var image = try #require(recovery.images[input.entryID])+ if input.entryID == "com.apple.kernel", let thread = collection.unixThread,+ let i = image.commands.firstIndex(where: { $0.command == KDKMachO.lcUnixThread })+ {+ image.commands[i] = thread+ }+ var writer = try KDKImageExport(collection: collection, image: image, baseAddress: input.baseAddress,+ symbols: generated, references: references[input.entryID] ?? [], addressOnlyBinds: true)+ let output = try writer.export(), golden = try Data(contentsOf: corpus.appending(path: "out").appending(path: input.output))+ guard output == golden else {+ try output.write(to: root.appending(path: "native-\(label)-\(input.entryID)"))+ Issue.record("native export differs: \(label)/\(input.entryID)")+ return+ }+ verified += 1+ }+ print("KDK native recovery verified: \(label), \(inputs.count) images; unresolved \(symbols.unresolved.count)")+ }+ #expect(verified == 264)+ print("KDK native recovery: all 264 reference sets, symbol arrays and output binaries match")+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex daa22f2a..b743db9d 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -205,7 +205,7 @@ struct VPhoneFirmwareCatalogCommand: ParsableCommand {let ownColumn = entry.pairings.contains { $0.matchingCloudOS != nil }print("\(os.padding(toLength: width, withPad: " ", startingAt: 0)) "+ "recommended cloudOS".padding(toLength: recommendedWidth, withPad: " ", startingAt: 0)- + (ownColumn ? " own cloudOS (research board: root, VPHONE_IPSW)" : ""))+ + (ownColumn ? " own cloudOS (research board: root for link)" : ""))for e in entry.pairings {let ios = e.ios.name.padding(toLength: width, withPad: " ", startingAt: 0)if let own = e.matchingCloudOS {@@ -696,23 +696,23 @@ extension VPhoneLibraryOption {// MARK: - kernelcache/// Builds the kernelcache mix of a VM on a cloudOS without vphone600-/// components, in the two steps that need different users: staging runs `ipsw`-/// and is the invoking user's, linking runs kmutil and is root's. `fw patch`+/// components, in two steps: native extraction stages the volume as the user+/// and linking runs kmutil as root. `fw patch`/// then takes the mix from the cache. See KernelCacheMixer.struct VPhoneFirmwareKernelcacheCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "kernelcache",- abstract: "Build a research board VM's kernelcache mix: stage it as yourself (VPHONE_IPSW), link it with sudo",+ abstract: "Build a research board VM's kernelcache mix: stage it natively as yourself, link it with sudo",)@OptionGroup var lib: VPhoneLibraryOption@Argument(help: "VM name") var name: String?@Flag(help: ArgumentHelp(- "Only link a staged volume; never stage, so no ipsw runs (the Launchpad helper's root run)",+ "Only link a staged volume; never stage (the Launchpad helper's root run)",visibility: .hidden,))var linkOnly = false- @Option(help: ArgumentHelp("The ipsw to stage with (default: $VPHONE_IPSW)", valueName: "path"))+ @Option(help: ArgumentHelp("Legacy compatibility option; native extraction ignores this path", valueName: "path", visibility: .hidden))var ipsw: String?@Option(name: .customLong("work-parent"), help: ArgumentHelp("Private kernelcache work directory", visibility: .hidden))var workParent = "/private/var/tmp"@@ -735,7 +735,7 @@ struct VPhoneFirmwareKernelcacheCommand: ParsableCommand {if geteuid() == 0 {if state == .missing {guard !linkOnly else {- throw ValidationError("\(name)'s kernelcache mix is not staged. Stage it first, as yourself: \(KernelCacheMixer.ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache \(name)")+ throw ValidationError("\(name)'s kernelcache mix is not staged. Stage it first, as yourself: vphone-cli fw kernelcache \(name)")}try mixer.stage(input, ipsw: ipsw)}@@ -750,7 +750,7 @@ struct VPhoneFirmwareKernelcacheCommand: ParsableCommand {}if state == .missing {guard !linkOnly else {- throw ValidationError("\(name)'s kernelcache mix is not staged. Stage it first: \(KernelCacheMixer.ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache \(name)")+ throw ValidationError("\(name)'s kernelcache mix is not staged. Stage it first: vphone-cli fw kernelcache \(name)")}try mixer.stage(input, ipsw: ipsw)}diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 87713d3f..ac1c997f 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -147,6 +147,11 @@ fi/bin/rm -rf "$resources/kernelcache_recipes"/bin/cp -R "$root/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes" "$resources/"+# Native KDK extraction ports MIT-licensed reference algorithms.+/bin/mkdir -p "$resources/Licenses"+/bin/cp "$root/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSE" \+ "$resources/Licenses/native-kdk-MIT.txt"+"${0:a:h}/SyncStrings.sh"/usr/bin/xcrun xcstringstool compile \"$root/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings" \diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex 4f348bfb..2b157a69 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -116,6 +116,10 @@ for manifest in "$resources/kernelcache_recipes/bases/"*/manifest.json; do}donedone+[[ -s "$resources/Licenses/native-kdk-MIT.txt" ]] || {+ print -u2 "Missing native KDK extraction licence"+ exit 1+}# New machines copy this ROM. Without it vm new would fail, and OpenAVB is# distributed only with its licences. The ROM window is 512 KiB.for name in OpenAVB.bin LICENSE APSL-2.0.txt; dodiff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md b/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.mdindex 2115e73e..f2c6a4ad 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md@@ -46,8 +46,8 @@ kexts whose imports have no counterpart there (15 donor kexts instead of 18).## Requirements-- An `ipsw` with `kernel extract --kdk` (blacktop/ipsw), named by `VPHONE_IPSW`.- vphone-cli does not ship it, and runs it only as the invoking user.+- KDK extraction is native to VPhone.bundle; no external `ipsw` is required.+ The recipe's gzip symbol map is decompressed in process.- Root for the link: kmutil only reads kexts owned by root:wheel, and links thehost's own kexts in place of any others without a word.- A kmutil of the base's `builderLayout`: macOS 26.4 or later for the iOS 26 bases,@@ -59,7 +59,11 @@ kexts whose imports have no counterpart there (15 donor kexts instead of 18).and the volume, in `~/.vphone/kernelcache/staged`), and under sudo links it:root copies the volume into a directory of its own, refusing any link out ofit, and runs kmutil on the copy. `fw patch` then takes the mix from the cache;-run as `sudo VPHONE_IPSW=<ipsw> vphone-cli fw patch` it does both itself.+stage first as the invoking user, then run the link or `fw patch` under sudo.++`fw kernelcache --ipsw <path>` remains accepted as an ignored compatibility+argument in 2.12.x. The native extractor revision participates in both donor+and mix cache keys, so older external-tool extractions are rebuilt.Mixed kernelcaches are cached in `~/.vphone/kernelcache/mix`, keyed by the recipe,with kmutil's log beside each. Remove `~/.vphone/kernelcache` to rebuild them.