Run a virtual iPhone on an Apple Silicon Mac.
Swift
Write fileset images back as standalone Mach-Os for a native KDK
Jacky5d6638a5d175
diff --git a/Research/Kernel/native_kdk_export.md b/Research/Kernel/native_kdk_export.mdnew file mode 100644index 00000000..0e5cf0ae--- /dev/null+++ b/Research/Kernel/native_kdk_export.md@@ -0,0 +1,192 @@+# Native KDK Mach-O export++`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.++The current contract is stripped collections with address-only synthetic binds.+Passing `addressOnlyBinds: false` fails explicitly. Original-symbol C++ alias/PAC+name inference and general shared-cache dylib export are outside this stage.+Nonempty export tries, code signatures, code-signing DRs and linker optimization+hints are rejected rather than preserved with obsolete LINKEDIT offsets.++## Export an image++The internal API takes a decompressed MH_FILESET and an image parsed from it:++```swift+// collection, image, symbols and references come from the extraction layer.+var writer = try KDKImageExport(+ collection: collection,+ image: image,+ baseAddress: baseAddress,+ symbols: symbols,+ references: references,+ addressOnlyBinds: true+)+let standaloneMachO = try writer.export()+```++Use zero as the KEXT base, and the collection's preferred load address for the+kernel. Before exporting `com.apple.kernel`, replace its LC_UNIXTHREAD in place+with the collection's LC_UNIXTHREAD, matching `extract.go`'s+`fixUnixThreadAddress`. This belongs to the caller, not the generic image writer.++Nonempty references select contiguous segment packing. Without references the+writer preserves cache VM addresses while packing file offsets. Input images+and collections stay immutable; repeated exports from the same writer reset+its scratch state and produce the same bytes.++## Reference and evidence++The port follows the MIT-licensed `File.Export` in go-macho PR #94. Its license+is retained in `FirmwarePatcher/KernelCache/KDK/LICENSE`. The external reference+build uses these pinned mpass99 commits, not the released upstream `ipsw`:++| Repository | Commit |+| --- | --- |+| ipsw | `7d81acd4b97e67c0a25b5ddc514ce2ad02e7d474` |+| go-macho | `a8b76580904cdec5a634a9bbc9e8e976d80ddf06` |+| arm64-cgo | `5cac24a3a47df0c29fe6f4ba956dd25b216e54b2` |+| go-dwarf | `bfc1862b701d882faf1cc421f90b960727991e15` |++On 2026-10-23 the writer reproduced **all 264 reference exports byte for byte**:+144 fileset images from `kernelcache.release.vphone600` and 120 from+`kernelcache.release.vresearch101`, including both kernels. The comparison+feeds the identical references/symbols/base/bind mode into Swift and Go. It does+not 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.++Corpus source: cached cloudOS 26.4 beta IPSW+`c0ecdb4b310cf5239ab2b248dd3098eec297dc5aa3bbe6ad-b80d96a0b616.ipsw`.+The decompressed input hashes are:++| Kernel | SHA-256 |+| --- | --- |+| vphone600 | `681801fe328b00ff8ec2e94a3d84bf9f9a7a1b954640d0c40f8dd02434270935` |+| vresearch101 | `fe345b332fc50586e21707be69accc63e7bc7a855178481a6436727cc24a4e8b` |++The source bytes, captured inputs, and Go exports are external test data. No+Apple firmware, Go runtime, Python, or Homebrew dependency is added to the+shipped bundle. The Go reference is only a development oracle.++## Run the tests++From the repository root, build through the workspace so shared Kit targets are+resolved, using the owning `FirmwarePatcherTests` scheme:++```zsh+xcodebuild -workspace VPhone.xcworkspace -scheme FirmwarePatcherTests \+ -configuration Debug -destination 'platform=macOS,arch=arm64' \+ -derivedDataPath /tmp/native-kdk-build test+```++`KDKExportFixtureTests` creates an entirely synthetic collection. It checks+contiguous layout, restored auth stubs and calls, authenticated binds/rebases,+indirect-symbol fallback, function-start remapping, repeatability, the+cache-address path, and malformed-command rejection. `KDKImageExportTests`+checks all four pointer layouts, signed bind addends, BRAA and OFF12 encodings,+Capstone decoding, and ADRP at high kernel addresses.++BRAA is checked against Apple clang because Keystone 0.9.2 rejects PAC+mnemonics. Independent assembly produced `braa x16, x17 = 0xD71F0A11`,+`braa x0, x1 = 0xD71F0801`, and `braa x30, sp = 0xD71F0BDF`.++The real-corpus test is opt-in. Set `KDK_CORPUS` to an external corpus root with+this layout (the fixture labels are deliberately stable):++```text+data/264beta/kernelcache.release.vphone600.decompressed+data/264beta/kernelcache.release.vresearch101.decompressed+parity/donor/inputs/<entryID>.json+parity/donor/out/<reference-output-path>+parity/research/inputs/<entryID>.json+parity/research/out/<reference-output-path>+```++With `KDK_CORPUS` set in the shell, run:++```zsh+TEST_RUNNER_KDK_PARITY_ROOT="$KDK_CORPUS" \+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+```++Xcode strips the `TEST_RUNNER_` prefix for the test process. To narrow a failure,+set `TEST_RUNNER_KDK_PARITY_ENTRY=com.apple.kernel`; the test then expects two+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 the+external 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+and `ipsws/patch_refactor_input` payloads in this new worktree. The main+checkout'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.++The complete `VPhone` scheme build passed, including `Bundle admission passed`.+Local acceptance data is retained under `.build/KDKParity` (ignored by Git),+with focused/full-test and bundle logs in its `validation` directory. Set+`KDK_CORPUS="$PWD/.build/KDKParity"` to replay the corpus from this worktree.++## Rebuild the external reference++Place the four pinned repositories in sibling directories named `ipsw`,+`go-macho`, `arm64-cgo`, and `go-dwarf`, outside this checkout. Apply+[`native_kdk_reference_inputs.diff`](native_kdk_reference_inputs.diff) to the+**external ipsw checkout**. It adds `KDK_DUMP_INPUTS`, which serializes each+`Export` call's entry ID, output path, base, address-only flag, extra symbols and+references before writing the reference binary. It changes no export behavior.++From that external ipsw checkout:++```zsh+cp go.mod go.ref.mod+cp go.sum go.ref.sum+go mod edit -modfile=go.ref.mod -replace github.com/blacktop/go-macho=../go-macho+go mod edit -modfile=go.ref.mod -replace github.com/blacktop/arm64-cgo=../arm64-cgo+go mod edit -modfile=go.ref.mod -replace github.com/blacktop/go-dwarf=../go-dwarf+go build -mod=mod -modfile=go.ref.mod -o ../ipsw-ref ./cmd/ipsw+```++Run `ipsw-ref kernel extract --kdk` for each decompressed collection, adding+`--symbols` followed by the symbol-map filename when one is available,+with `KDK_DUMP_INPUTS` pointing to that corpus's `inputs` directory and the output+root pointing to its `out` directory. Retain any explicit symbols input used+when building the reference corpus; the dump records the resulting writer+inputs, so writer parity does not depend on re-running symbol synthesis.++## Layout invariants++1. Build the segment map, resize `__auth_stubs`, and move later segments before+ copying commands. A containing segment wins over another segment's end;+ section positions move with their own segment to resolve adjacent ranges.+2. Keep the source header's `ncmds` and `sizeofcmds`, adjusting only for explicit+ command additions/removals, as the reference does. Place chained fixups after+ the last segment and split info immediately before function starts.+3. Copy source segment bytes through the collection's address map. Write auth+ stubs, relocate references, reconnect external branches, clear the packed+ `_kmod_info` address/size fields, then restore the FIPS HMAC-SHA256 seal.+4. Reconstruct chained fixups with 4 KiB pages and a four-byte next stride.+ Preserve PAC diversity/address-diversity/key; use low43/high8 for plain+ rebases, 16-bit ordinals and signed19 embedded addends for binds. Import order+ follows sections/atoms, including destructor-pair atom boundaries.+5. Rebuild LINKEDIT in reference order, align blobs to eight bytes, renumber+ 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`.diff --git a/Research/Kernel/native_kdk_reference_inputs.diff b/Research/Kernel/native_kdk_reference_inputs.diffnew file mode 100644index 00000000..544a8ca3--- /dev/null+++ b/Research/Kernel/native_kdk_reference_inputs.diff@@ -0,0 +1,84 @@+diff --git a/pkg/kernelcache/kdk/extract.go b/pkg/kernelcache/kdk/extract.go+index 7a08f98..b0eaa1e 100644+--- a/pkg/kernelcache/kdk/extract.go++++ b/pkg/kernelcache/kdk/extract.go+@@ -162,6 +162,9 @@ func Extract(kc *macho.File, cfg Config) error {+ if synthesized != nil {+ exportOpts = append(exportOpts, macho.WithAddressOnlyBinds())+ }++ if err := dumpExportInputs(cfg.Output, fse.EntryID, fname, entryBase, synthesized != nil, syms, references[fse.EntryID]); err != nil {++ return err++ }+ if err := mfse.Export(fname, dcf, entryBase, syms, exportOpts...); err != nil {+ return fmt.Errorf("failed to export KEXT %s: %v", fse.EntryID, err)+ }+diff --git a/pkg/kernelcache/kdk/dump_inputs.go b/pkg/kernelcache/kdk/dump_inputs.go+new file mode 100644+--- /dev/null++++ b/pkg/kernelcache/kdk/dump_inputs.go+@@ -0,0 +1,65 @@++package kdk++++// Parity hook for vphone-cli's Swift port (not upstream): with++// KDK_DUMP_INPUTS=<dir>, writes the inputs of every File.Export call as JSON.++++import (++ "encoding/json"++ "os"++ "path/filepath"++++ "github.com/blacktop/go-macho"++ "github.com/blacktop/go-macho/types"++)++++type dumpSymbol struct {++ Name string `json:"name"`++ IndirectName string `json:"indirectName,omitempty"`++ Type uint8 `json:"type"`++ Sect uint8 `json:"sect"`++ Desc uint16 `json:"desc"`++ Value uint64 `json:"value"`++}++++type dumpReference struct {++ Kind uint8 `json:"kind"`++ Source uint64 `json:"source"`++ Target uint64 `json:"target"`++ Extra uint64 `json:"extra,omitempty"`++}++++type dumpInputs struct {++ EntryID string `json:"entryID"`++ Output string `json:"output"`++ BaseAddress uint64 `json:"baseAddress"`++ AddressOnlyBinds bool `json:"addressOnlyBinds"`++ Symbols []dumpSymbol `json:"symbols"`++ References []dumpReference `json:"references"`++}++++func dumpExportInputs(root, entryID, output string, base uint64, addressOnly bool, syms []macho.Symbol, refs []*types.SplitInfoEntry) error {++ dir := os.Getenv("KDK_DUMP_INPUTS")++ if dir == "" {++ return nil++ }++ rel, err := filepath.Rel(root, output)++ if err != nil {++ return err++ }++ in := dumpInputs{EntryID: entryID, Output: rel, BaseAddress: base, AddressOnlyBinds: addressOnly,++ Symbols: []dumpSymbol{}, References: []dumpReference{}}++ for _, s := range syms {++ in.Symbols = append(in.Symbols, dumpSymbol{s.Name, s.IndirectName, uint8(s.Type), s.Sect, uint16(s.Desc), s.Value})++ }++ for _, r := range refs {++ in.References = append(in.References, dumpReference{uint8(r.Kind), r.SourceVmAddr, r.TargetVmAddr, r.ExtraVmAddr})++ }++ data, err := json.Marshal(in)++ if err != nil {++ return err++ }++ if err := os.MkdirAll(dir, 0o755); err != nil {++ return err++ }++ return os.WriteFile(filepath.Join(dir, entryID+".json"), data, 0o644)++}diff --git a/Research/README.md b/Research/README.mdindex 8aa9c28f..0c60f3e4 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 | [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 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) || 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/KDKExportFixups.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportFixups.swiftnew file mode 100644index 00000000..54f5fcf5--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportFixups.swift@@ -0,0 +1,184 @@+// ARM64E_KERNEL chained fixups: 4 KiB chain pages, 4-byte next stride.+import Foundation+import VPhonePatchKit++extension KDKImageExport {+ struct FixupPage: Hashable { var segment: Int+ var page: Int+ }++ /// Encode dyld's four ARM64e pointer layouts. PAC metadata occupies bits+ /// 32...50; plain rebases keep low43 + high8, binds carry signed19 addends.+ static func pointer(target: UInt64, ordinal: UInt16?, addend: Int64 = 0, auth: UInt64?, next: UInt64) throws -> UInt64 {+ guard next <= 0x7FF, addend >= -(1 << 18), addend < 1 << 18 else {+ throw PatcherError.invalidFormat("ARM64e chained pointer field overflow")+ }+ var word = next << 51+ if let auth {+ word |= 1 << 63 | (auth & 0x0007_FFFF_0000_0000)+ word |= ordinal.map(UInt64.init) ?? (target & 0xFFFF_FFFF)+ } else if let ordinal {+ word |= UInt64(ordinal) | ((UInt64(bitPattern: addend) & 0x7FFFF) << 32)+ } else {+ word |= target & 0x7FF_FFFF_FFFF+ word |= ((target >> 56) & 0xFF) << 43+ }+ if ordinal != nil {+ word |= 1 << 62+ }+ return word+ }++ func importOrder(_ fixups: [UInt64]) -> [UInt64] {+ let allSections = sections+ func sectionIndex(_ address: UInt64) -> Int? {+ allSections.firstIndex { $0.contains(address) }+ }+ var atoms: [Int: [UInt64]] = [:], vtables: [Int: [UInt64]] = [:]+ for symbol in source.symbols where symbol.isDefinedInSection && symbol.value != 0 {+ if let mapped = try? remap(symbol.value), let section = sectionIndex(mapped) {+ atoms[section, default: []].append(mapped)+ if symbol.name.hasPrefix("__ZTV") {+ vtables[section, default: []].append(mapped)+ }+ }+ }+ if fixups.count > 1 {+ for i in 0 ..< fixups.count - 1 {+ let first = fixups[i], second = fixups[i + 1]+ guard let section = sectionIndex(first), section == sectionIndex(second) else { continue }+ if rebases[first] != nil, rebases[second] != nil, first + 8 == second,+ let a = auths[first], let b = auths[second], (a >> 32) & 0xFFFF == 0x3771, (b >> 32) & 0xFFFF == 0x56B7+ {+ atoms[section, default: []].append(first)+ }+ if second > first + 8, binds[first] != nil, auths[first] != nil,+ binds[second] != nil, auths[second] == nil+ {+ let starts = vtables[section, default: []].sorted()+ if starts.contains(where: { $0 <= first }), !starts.contains(where: { $0 > first && $0 <= second }) {+ atoms[section, default: []].append(second)+ }+ }+ }+ }+ for index in atoms.keys {+ atoms[index]!.sort()+ }+ struct Order { var address: UInt64+ var section: UInt64+ var atom: UInt64+ var indirect: Bool+ }+ let orders = fixups.map { address -> Order in+ guard let index = sectionIndex(address) else { return Order(address: address, section: 0, atom: 0, indirect: false) }+ let s = allSections[index]+ return Order(address: address, section: s.address, atom: atoms[index]?.last(where: { $0 <= address }) ?? s.address, indirect: s.isSymbolPointers)+ }+ return orders.sorted { a, b in+ if a.section != b.section {+ return a.section < b.section+ }+ if a.indirect != b.indirect {+ return a.indirect+ }+ if a.indirect {+ return a.address < b.address+ }+ if a.atom != b.atom {+ return a.atom < b.atom+ }+ return a.address > b.address+ }.map(\.address)+ }++ mutating func chainedFixups() throws -> [UInt8] {+ let fixups = Set(binds.keys).union(rebases.keys).sorted()+ let weak = Set(source.symbols.filter { $0.isUndefined && $0.isWeakReference }.map(\.name))+ let weakDefs = Set(binds.values.filter(\.isWeakDefinition).map(\.name))+ var ordinals: [String: UInt16] = [:]+ var strings: [UInt8] = [0], imports: [UInt8] = []+ for address in importOrder(fixups) {+ guard let symbol = binds[address], ordinals[symbol.name] == nil else { continue }+ guard let ordinal = UInt16(exactly: ordinals.count), strings.count < 1 << 23 else { throw invalid("too many chained imports") }+ ordinals[symbol.name] = ordinal+ let flags: UInt32 = (weakDefs.contains(symbol.name) ? 0xFD : 0xFE) | (weak.contains(symbol.name) ? 0x100 : 0)+ imports.appendLE(flags | UInt32(strings.count) << 9)+ strings += symbol.name.utf8+ strings.append(0)+ }+ let segs = segments+ var pages: [FixupPage: [UInt64]] = [:]+ for address in fixups {+ guard let i = segs.firstIndex(where: { $0.contains(address) }) else { throw invalid("fixup outside segments") }+ pages[.init(segment: i, page: Int((address - segs[i].address) / 0x1000)), default: []].append(address)+ }+ var starts = [UInt8](repeating: 0, count: 4 + segs.count * 4)+ starts.setLE(UInt32(segs.count), at: 0)+ for (index, seg) in segs.enumerated() {+ guard let last = pages.keys.filter({ $0.segment == index }).map(\.page).max() else { continue }+ guard last < Int(UInt16.max) else { throw invalid("too many fixup pages") }+ var pageStarts: [UInt16] = [], overflow: [UInt16] = []+ for page in 0 ... last {+ let addresses = pages[.init(segment: index, page: page)] ?? []+ if addresses.isEmpty {+ pageStarts.append(0xFFFF)+ continue+ }+ var chains: [UInt16] = []+ for i in addresses.indices {+ if i == 0 || (addresses[i] - addresses[i - 1]) % 4 != 0 || (addresses[i] - addresses[i - 1]) / 4 > 0x7FF {+ chains.append(UInt16(addresses[i] - seg.address - UInt64(page) * 0x1000))+ }+ var next: UInt64 = 0+ if i + 1 < addresses.count {+ let delta = addresses[i + 1] - addresses[i]+ if delta % 4 == 0, delta / 4 <= 0x7FF {+ next = delta / 4+ }+ }+ let address = addresses[i]+ let symbol = binds[address]+ let target = (rebases[address] ?? baseAddress) &- (segs.first { $0.name == "__TEXT" }?.address ?? 0)+ let word = try Self.pointer(target: target, ordinal: symbol.flatMap { ordinals[$0.name] },+ addend: symbol?.bindAddend ?? 0, auth: auths[address], next: next)+ let off = try offset(address)+ try check(off, 8)+ data.setLE(word, at: off)+ }+ if chains.count == 1 {+ pageStarts.append(chains[0])+ } else {+ guard overflow.count < 0x8000 else { throw invalid("too many chain starts") }+ pageStarts.append(0x8000 | UInt16(overflow.count))+ chains[chains.count - 1] |= 0x8000+ overflow += chains+ }+ }+ starts.pad(to: 8)+ starts.setLE(UInt32(starts.count), at: 4 + index * 4)+ starts.appendLE(UInt32(22 + 2 * (pageStarts.count + overflow.count)))+ starts.appendLE(UInt16(0x1000))+ starts.appendLE(UInt16(7)) // ARM64E_KERNEL+ starts.appendLE(seg.address &- (segs.first { $0.name == "__TEXT" }?.address ?? 0))+ starts.appendLE(UInt32(0))+ starts.appendLE(UInt16(pageStarts.count))+ for start in pageStarts + overflow {+ starts.appendLE(start)+ }+ }+ let importsOffset = (32 + starts.count + 3) & ~3+ let stringsOffset = importsOffset + imports.count+ var out: [UInt8] = []+ for word: UInt32 in [0, 32, UInt32(importsOffset), UInt32(stringsOffset), UInt32(ordinals.count), 1, 0] {+ out.appendLE(word)+ }+ out.padTo(32)+ out += starts+ out.padTo(importsOffset)+ out += imports+ out += strings+ out.pad(to: 8)+ return out+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportLinkedit.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportLinkedit.swiftnew file mode 100644index 00000000..e069d3b7--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportLinkedit.swift@@ -0,0 +1,240 @@+// LINKEDIT reconstruction in File.Export order, including its symbol/string+// ordering and indirect-symbol fallback for stripped collections.+import Foundation+import VPhonePatchKit++extension KDKImageExport {+ struct SymbolTable {+ var entries: [KDKSymbol]+ var locals: UInt32+ var external: UInt32+ var undefined: UInt32+ var bytes: [UInt8]+ var strings: [UInt8]+ var indexMap: [Int]+ }++ func symbolTable() throws -> SymbolTable {+ struct Entry { var symbol: KDKSymbol+ var original: Int+ var nameOffset: UInt32 = 0+ var indirectOffset: UInt64 = 0+ }+ let imports = Set(source.symbols.filter(\.isUndefined).map(\.name))+ var groups = [[Entry](), [Entry](), [Entry]()]+ func add(_ original: KDKSymbol, index: Int) throws {+ var s = original+ if s.isDefinedInSection, s.value != 0 {+ s.value = try remap(s.value)+ }+ if index == -1, s.isUndefined {+ s.value = 0+ }+ let group = !s.isExternal ? 0 : (s.isUndefined ? 2 : 1)+ groups[group].append(Entry(symbol: s, original: index))+ }+ for symbol in symbols where !(symbol.isExternal && imports.contains(symbol.name)) {+ try add(symbol, index: -1)+ }+ for (index, symbol) in source.symbols.enumerated() where symbol.name != "<redacted>" {+ try add(symbol, index: index)+ }+ var strings = [UInt8](repeating: 0, count: 4)+ for g in [1, 2, 0] {+ for i in groups[g].indices {+ let s = groups[g][i].symbol+ if !s.name.isEmpty {+ groups[g][i].nameOffset = UInt32(strings.count)+ strings += s.name.utf8+ strings.append(0)+ }+ if s.isIndirect, !s.indirectName.isEmpty {+ groups[g][i].indirectOffset = UInt64(strings.count)+ strings += s.indirectName.utf8+ strings.append(0)+ }+ }+ }+ strings.pad(to: 8)+ var bytes: [UInt8] = [], map = [Int](repeating: -1, count: source.symbols.count)+ let entries = groups.flatMap(\.self)+ for (index, entry) in entries.enumerated() {+ let s = entry.symbol+ bytes.appendLE(entry.nameOffset)+ bytes.append(s.type)+ bytes.append(s.sect)+ bytes.appendLE(s.desc)+ bytes.appendLE(s.isIndirect ? entry.indirectOffset : s.value)+ if entry.original >= 0 {+ map[entry.original] = index+ }+ }+ return SymbolTable(entries: entries.map(\.symbol), locals: UInt32(groups[0].count), external: UInt32(groups[1].count),+ undefined: UInt32(groups[2].count), bytes: bytes, strings: strings, indexMap: map)+ }++ func indirectTable(_ table: SymbolTable) -> [UInt8] {+ var undefined: [String: UInt32] = [:]+ for (i, symbol) in table.entries.enumerated() where symbol.isUndefined {+ undefined[symbol.name] = UInt32(i)+ }+ let got = section("__DATA_CONST", "__auth_got")+ func fallback(_ entry: Int) -> UInt32? {+ for section in sections {+ let start = UInt64(section.reserved1), index = UInt64(entry)+ var slot: UInt64+ if section.isSymbolPointers {+ guard index >= start, index - start < section.size / 8 else { continue }+ slot = section.address + (index - start) * 8+ } else if section.name == "__auth_stubs", let got {+ guard index >= start, index - start < section.size / 16 else { continue }+ slot = got.address + (index - start) * 8+ } else {+ continue+ }+ return binds[slot].flatMap { undefined[$0.name] }+ }+ return nil+ }+ var out: [UInt8] = []+ for (entry, index) in source.indirectSymbols.enumerated() {+ if index & (KDKMachO.indirectSymbolLocal | KDKMachO.indirectSymbolAbsolute) != 0 {+ out.appendLE(index)+ } else if index < table.indexMap.count, table.indexMap[Int(index)] >= 0 {+ out.appendLE(UInt32(table.indexMap[Int(index)]))+ } else {+ out.appendLE(fallback(entry) ?? KDKMachO.indirectSymbolLocal)+ }+ }+ return out+ }++ func functionStarts() throws -> [UInt8]? {+ guard let cmd = source.command(KDKMachO.lcFunctionStarts) else { return nil }+ let bytes = try collection.bytes.bytes(Int(cmd.bytes.le(UInt32.self, 8)), Int(cmd.bytes.le(UInt32.self, 12)))+ var cursor = 0, address = source.baseAddress+ var starts: [UInt64] = []+ while cursor < bytes.count {+ var delta: UInt64 = 0, shift = 0+ var complete = false+ while cursor < bytes.count, shift < 64 {+ let byte = bytes[cursor]+ cursor += 1+ delta |= UInt64(byte & 0x7F) << shift+ if byte & 0x80 == 0 {+ complete = true+ break+ }+ shift += 7+ }+ if !complete || delta == 0 {+ break+ }+ address &+= delta+ try starts.append(remap(address))+ }+ var out: [UInt8] = []+ var previous = segments.first { $0.name == "__TEXT" }?.address ?? 0+ for start in Set(starts).sorted() {+ out.appendULEB128(start &- previous)+ previous = start+ }+ out.append(0)+ out.pad(to: 8)+ return out+ }++ mutating func rebuildLinkedit() throws {+ guard let leIndex = commands.firstIndex(where: { $0.segment?.name == "__LINKEDIT" }),+ let linkedit = commands[leIndex].segment,+ let symIndex = commands.firstIndex(where: { $0.command == KDKMachO.lcSymtab }),+ let dysymIndex = commands.firstIndex(where: { $0.command == KDKMachO.lcDysymtab })+ else {+ throw invalid("export requires LINKEDIT, SYMTAB and DYSYMTAB")+ }+ // These are DSC/general dylib features, not the stripped kernelcache+ // contract. Reject them before discarding any original LINKEDIT data.+ for command in commands where [KDKMachO.lcDyldExportsTrie, KDKMachO.lcCodeSignature,+ KDKMachO.lcDylibCodeSignDRs, KDKMachO.lcLinkerOptimizationHint].contains(command.command)+ {+ if command.bytes.le(UInt32.self, 12) != 0 {+ throw invalid("unsupported nonempty load command 0x\(String(command.command, radix: 16))")+ }+ }+ var link: [UInt8] = []+ func store(_ bytes: [UInt8], command: UInt32) {+ guard let index = commands.firstIndex(where: { $0.command == command }) else { return }+ commands[index].bytes.setLE(UInt32(linkedit.fileOffset) + UInt32(link.count), at: 8)+ commands[index].bytes.setLE(UInt32(bytes.count), at: 12)+ link += bytes+ link.pad(to: 8)+ }+ if packed {+ try store(chainedFixups(), command: KDKMachO.lcDyldChainedFixups)+ }+ for command in [KDKMachO.lcDyldExportsTrie, KDKMachO.lcDataInCode] {+ if let load = commands.first(where: { $0.command == command }) {+ let off = Int(load.bytes.le(UInt32.self, 8)), size = Int(load.bytes.le(UInt32.self, 12))+ try check(off, size)+ store(Array(data[off ..< off + size]), command: command)+ }+ }+ if packed {+ try store(splitInfo(), command: KDKMachO.lcSegmentSplitInfo)+ }+ if let starts = try functionStarts() {+ store(starts, command: KDKMachO.lcFunctionStarts)+ }+ for command in [KDKMachO.lcFunctionVariants, KDKMachO.lcFunctionVariantFixups] {+ if let load = commands.first(where: { $0.command == command }) {+ let off = Int(load.bytes.le(UInt32.self, 8)), size = Int(load.bytes.le(UInt32.self, 12))+ try check(off, size)+ store(Array(data[off ..< off + size]), command: command)+ }+ }+ if let i = commands.firstIndex(where: { $0.command == KDKMachO.lcDyldInfo || $0.command == KDKMachO.lcDyldInfoOnly }) {+ var payload: [UInt8] = []+ for field in stride(from: 8, through: 40, by: 8) {+ let off = Int(commands[i].bytes.le(UInt32.self, field)), size = Int(commands[i].bytes.le(UInt32.self, field + 4))+ if size > 0 {+ try check(off, size)+ commands[i].bytes.setLE(UInt32(linkedit.fileOffset) + UInt32(link.count + payload.count), at: field)+ payload += data[off ..< off + size]+ }+ }+ link += payload+ link.pad(to: 8)+ }+ let table = try symbolTable()+ let symOffset = UInt32(linkedit.fileOffset) + UInt32(link.count)+ link += table.bytes+ link.pad(to: 8)+ let indirectOffset = UInt32(linkedit.fileOffset) + UInt32(link.count)+ link += indirectTable(table)+ link.pad(to: 8)+ let stringOffset = UInt32(linkedit.fileOffset) + UInt32(link.count)+ link += table.strings+ link.pad(to: 8)+ for (off, value) in [(8, symOffset), (12, UInt32(table.entries.count)), (16, stringOffset), (20, UInt32(table.strings.count))] {+ commands[symIndex].bytes.setLE(value, at: off)+ }+ for (off, value): (Int, UInt32) in [(8, 0), (12, table.locals), (16, table.locals), (20, table.external),+ (24, table.locals + table.external), (28, table.undefined),+ (56, indirectOffset), (60, UInt32(source.indirectSymbols.count)),+ (64, 0), (68, 0), (72, 0), (76, 0)]+ {+ commands[dysymIndex].bytes.setLE(value, at: off)+ }+ // File.Export updates the in-memory empty DATA_IN_CODE offset after+ // writing its command; its serialized value stays at the earlier blob.+ commands[leIndex].segment?.fileSize = UInt64(link.count)+ commands[leIndex].segment?.memorySize = Self.aligned(UInt64(link.count))+ let start = Int(linkedit.fileOffset)+ data.padTo(start)+ data.replaceSubrange(start ..< data.count, with: link)+ var loadBytes: [UInt8] = []+ writeCommands(to: &loadBytes)+ try check(KDKMachO.headerSize, loadBytes.count)+ data.replaceSubrange(KDKMachO.headerSize ..< KDKMachO.headerSize + loadBytes.count, with: loadBytes)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportReferences.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportReferences.swiftnew file mode 100644index 00000000..67f139c8--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKExportReferences.swift@@ -0,0 +1,262 @@+// Reference relocation for the KDK writer. Kind values are dyld split-seg v2.+import Foundation+import VPhonePatchKit++extension KDKImageExport {+ func indirectSymbol(at address: UInt64) -> KDKSymbol? {+ guard let section = sections.first(where: { $0.contains(address) }), section.isSymbolPointers else { return nil }+ let entry = UInt64(section.reserved1) + (address - section.address) / 8+ guard entry < source.indirectSymbols.count else { return nil }+ let index = source.indirectSymbols[Int(entry)]+ guard index & KDKMachO.indirectSymbolLocal == 0, index < source.symbols.count else { return nil }+ return source.symbols[Int(index)]+ }++ mutating func adjustReferences() throws {+ var exactADRP: [UInt64: KDKReference] = [:]+ var pointerSymbols: [UInt64: KDKSymbol] = [:]+ var ambiguous = Set<UInt64>()+ var byAddress: [UInt64: KDKSymbol] = [:]+ var branches: [UInt64: KDKSymbol] = [:]+ for symbol in symbols where byAddress[symbol.value] == nil {+ byAddress[symbol.value] = symbol+ }+ for ref in references {+ if ref.kind == 6, ref.extra != 0,+ exactADRP[ref.extra].map({ ref.source < $0.source }) ?? true+ {+ exactADRP[ref.extra] = ref+ }+ if ref.kind == 2, !ambiguous.contains(ref.target), let address = try? remap(ref.source),+ let symbol = indirectSymbol(at: address)+ {+ if let old = pointerSymbols[ref.target], old.name != symbol.name {+ pointerSymbols.removeValue(forKey: ref.target)+ ambiguous.insert(ref.target)+ } else {+ pointerSymbols[ref.target] = symbol+ }+ }+ }+ for ref in references {+ let address = try remap(ref.source)+ let off = try offset(address)+ try check(off, ref.kind == 2 || ref.kind == 4 ? 8 : 4)+ if ref.kind == 2 {+ let raw = data.le(UInt64.self, off)+ if raw >> 63 != 0 {+ auths[address] = raw & 0x0007_FFFF_0000_0000+ }+ }+ let target = ref.kind == 5 ? exactADRP[ref.source]?.target ?? ref.target : ref.target+ var mapped = try? remap(target)+ if mapped == nil, ref.kind == 5 {+ let page = target & ~UInt64(0xFFF)+ if let m = mappings.first(where: { page <= $0.original.address + $0.original.memorySize && page + 0xFFF >= $0.original.address }) {+ mapped = m.start & ~UInt64(0xFFF)+ }+ }+ if let mapped {+ if ref.kind == 7, let sym = pointerSymbols[target], sym.isWeakDefinition {+ branches[address] = sym+ continue+ }+ // The reference asks its VM reader for both offsets, including+ // pointer targets. Preserve that validation and BR26 behavior.+ let targetOff = try offset(mapped)+ let adjustment = (mapped &- target) &- (address &- ref.source)+ switch ref.kind {+ case 2:+ if let sym = indirectSymbol(at: address), sym.isWeakDefinition {+ binds[address] = sym+ } else {+ rebases[address] = mapped+ }+ case 3:+ others[address] = mapped+ data.setLE(data.le(UInt32.self, off) &+ UInt32(truncatingIfNeeded: adjustment), at: off)+ case 4:+ others[address] = mapped+ data.setLE(data.le(UInt64.self, off) &+ adjustment, at: off)+ case 12:+ others[address] = mapped+ data.setLE(UInt32(truncatingIfNeeded: mapped &- segments.first(where: { $0.name == "__TEXT" })!.address), at: off)+ case 7:+ others[address] = mapped+ try writeBranch(at: off, delta: targetOff - off)+ case 5:+ others[address] = mapped+ let word = data.le(UInt32.self, off)+ guard word & 0x9F00_0000 == 0x9000_0000 else { throw invalid("ADRP reference does not address ADRP") }+ try write(ARM64Encoder.encodeADRP(rd: word & 31, pc: address, target: mapped), at: off)+ case 6:+ others[address] = mapped+ if ref.extra != 0, let chosen = exactADRP[ref.extra], let page = try? remap(chosen.target),+ page & ~UInt64(0xFFF) != mapped & ~UInt64(0xFFF)+ {+ continue+ }+ let word = data.le(UInt32.self, off)+ // Unknown OFF12 instruction forms are left intact by the+ // reference writer, but still recorded in split-seg info.+ if let encoded = ARM64Encoder.retargetPageOffset(word, offset: UInt32(mapped & 0xFFF)) {+ try write(encoded, at: off)+ }+ default: throw invalid("unsupported reference kind \(ref.kind)")+ }+ } else {+ var sym = indirectSymbol(at: address) ?? byAddress[target] ?? pointerSymbols[target]+ if sym == nil, auths[address] == nil, ref.kind == 2 {+ var best: UInt64 = 256+ for candidate in symbols where candidate.value != 0 && candidate.value <= target {+ let delta = target - candidate.value+ if delta < best {+ sym = candidate+ sym?.bindAddend = Int64(delta)+ best = delta+ }+ }+ }+ guard let sym else { others[address] = target+ continue+ }+ if ref.kind == 2 {+ binds[address] = sym+ } else if ref.kind == 7 {+ branches[address] = sym+ } else {+ others[address] = target+ }+ }+ }+ if let got = section("__DATA_CONST", "__auth_got"), let stubs = section("__TEXT_EXEC", "__auth_stubs") {+ var slots: [String: UInt64] = [:]+ for (address, symbol) in binds where got.contains(address) {+ slots[symbol.name] = min(slots[symbol.name] ?? address, address)+ }+ for (address, symbol) in branches {+ guard let slot = slots[symbol.name] else { continue }+ let target = stubs.address + (slot - got.address) / 8 * 16+ try writeBranch(at: offset(address), delta: Int(truncatingIfNeeded: target &- address))+ others[address] = target+ }+ }+ }++ mutating func writeBranch(at off: Int, delta: Int) throws {+ try check(off, 4)+ let word = data.le(UInt32.self, off)+ guard word & 0x7C00_0000 == 0x1400_0000 else { throw invalid("BR26 reference does not address B/BL") }+ try write(word & 0x8000_0000 == 0 ? ARM64Encoder.encodeB(from: 0, to: delta) : ARM64Encoder.encodeBL(from: 0, to: delta), at: off)+ }++ func finalReferences() throws -> [KDKReference] {+ func inImage(_ address: UInt64) -> Bool {+ segments.contains { $0.name != "__LINKEDIT" && address >= $0.address && address - $0.address <= $0.memorySize }+ }+ struct Key: Hashable { var source: UInt64+ var kind: UInt8+ }+ var seen = Set<Key>()+ var result: [KDKReference] = []+ func add(_ kind: UInt8, _ source: UInt64, _ target: UInt64) {+ if seen.insert(Key(source: source, kind: kind)).inserted {+ result.append(KDKReference(kind: kind, source: source, target: target))+ }+ }+ for ref in references {+ let address = try remap(ref.source)+ switch ref.kind {+ case 2, 13:+ if binds[address] == nil, let target = rebases[address], inImage(target) {+ add(auths[address] == nil ? 2 : 13, address, target)+ }+ case 6:+ guard var target = others[address], inImage(target) else { continue }+ let off = try offset(address)+ try check(off, 4)+ if let encoded = ARM64Encoder.decodePageOffset(data.le(UInt32.self, off)) {+ var page = target & ~UInt64(0xFFF)+ if ref.extra != 0, let adrp = try? remap(ref.extra), let t = others[adrp], inImage(t) {+ page = t & ~UInt64(0xFFF)+ }+ target = page | UInt64(encoded)+ if !inImage(target) {+ continue+ }+ }+ add(ref.kind, address, target)+ default:+ if let target = others[address], inImage(target) {+ add(ref.kind, address, target)+ }+ }+ }+ if let got = section("__DATA_CONST", "__auth_got"), let stubs = section("__TEXT_EXEC", "__auth_stubs"), got.size > 0, stubs.size > 0 {+ for i in 0 ..< got.size / 8 where i * 16 + 8 <= stubs.size {+ add(5, stubs.address + i * 16, got.address + i * 8)+ add(6, stubs.address + i * 16 + 4, got.address + i * 8)+ }+ }+ return result+ }++ func splitLocation(_ address: UInt64, allowEnd: Bool) -> (Int, UInt64)? {+ let all = sections+ if let i = all.firstIndex(where: { $0.contains(address) }) {+ return (i + 1, address - all[i].address)+ }+ if allowEnd {+ if let i = all.firstIndex(where: { $0.size == 0 && address == $0.address }) {+ return (i + 1, 0)+ }+ if let i = all.firstIndex(where: { $0.size > 0 && address == $0.address + $0.size }) {+ return (i + 1, all[i].size)+ }+ }+ if let seg = segments.first(where: { $0.contains(address) }), seg.name == "__TEXT" {+ return (0, address - seg.address)+ }+ return nil+ }++ func splitInfo() throws -> [UInt8] {+ var groups: [Int: [UInt64: [UInt8: [UInt64]]]] = [:]+ for ref in try finalReferences() {+ guard let (from, fromOffset) = splitLocation(ref.source, allowEnd: false),+ let (to, toOffset) = splitLocation(ref.target, allowEnd: true)+ else {+ throw invalid("split-info reference outside sections: \(ref)")+ }+ groups[from << 16 | to, default: [:]][toOffset, default: [:]][ref.kind, default: []].append(fromOffset)+ }+ var out: [UInt8] = [0x7F]+ out.appendULEB128(UInt64(groups.count))+ for combo in groups.keys.sorted() {+ let targets = groups[combo]!+ out.appendULEB128(UInt64(combo >> 16))+ out.appendULEB128(UInt64(combo & 0xFFFF))+ out.appendULEB128(UInt64(targets.count))+ var lastTarget: UInt64 = 0+ for target in targets.keys.sorted() {+ let kinds = targets[target]!+ out.appendULEB128(target - lastTarget)+ out.appendULEB128(UInt64(kinds.count))+ lastTarget = target+ for kind in kinds.keys.sorted() {+ let offsets = kinds[kind]!.sorted()+ out.appendULEB128(UInt64(kind))+ out.appendULEB128(UInt64(offsets.count))+ var previous: UInt64 = 0+ for off in offsets {+ out.appendULEB128(off - previous)+ previous = off+ }+ }+ }+ }+ out.append(0)+ out.pad(to: 8)+ return out+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKImageExport.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKImageExport.swiftnew file mode 100644index 00000000..8a6e09e0--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKImageExport.swift@@ -0,0 +1,368 @@+// Standalone fileset writer, ported from blacktop/go-macho#94, export.go+// a8b76580904cdec5a634a9bbc9e8e976d80ddf06 (MIT). See Research/Kernel/native_kdk_export.md.+// References and extra symbols are supplied by the caller; this layer does+// not recover references or synthesize names from a kernel collection.+import CryptoKit+import Foundation+import VPhonePatchKit++struct KDKReference: Codable, Hashable {+ var kind: UInt8+ var source: UInt64+ var target: UInt64+ var extra: UInt64 = 0++ enum CodingKeys: String, CodingKey { case kind, source, target, extra }+ init(kind: UInt8, source: UInt64, target: UInt64, extra: UInt64 = 0) {+ self.kind = kind+ self.source = source+ self.target = target+ self.extra = extra+ }++ init(from decoder: any Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ kind = try c.decode(UInt8.self, forKey: .kind)+ source = try c.decode(UInt64.self, forKey: .source)+ target = try c.decode(UInt64.self, forKey: .target)+ extra = try c.decodeIfPresent(UInt64.self, forKey: .extra) ?? 0+ }+}++struct KDKSegmentMapping {+ var original: KDKMachO.Segment+ var fileStart: UInt64+ var fileEnd: UInt64+ var start: UInt64+ var end: UInt64+}++/// One export owns all mutable state; the collection and input image are never+/// changed. The supported input is a stripped, little-endian ARM64 collection+/// with address-only synthetic binds (the own-cloudOS extraction path).+struct KDKImageExport {+ let collection: KDKKernelCollection+ let source: KDKImage+ let symbols: [KDKSymbol]+ let references: [KDKReference]+ var header: KDKMachO.Header+ var commands: [KDKMachO.LoadCommand] = []+ var mappings: [KDKSegmentMapping] = []+ var data: [UInt8] = []+ var binds: [UInt64: KDKSymbol] = [:]+ var rebases: [UInt64: UInt64] = [:]+ var others: [UInt64: UInt64] = [:]+ /// Original PAC fields, bits 32...50; no next/bind/auth bits.+ var auths: [UInt64: UInt64] = [:]+ let baseAddress: UInt64+ var packed: Bool {+ !references.isEmpty+ }++ var segments: [KDKMachO.Segment] {+ commands.compactMap(\.segment)+ }++ var sections: [KDKMachO.Section] {+ segments.flatMap(\.sections)+ }++ init(collection: KDKKernelCollection, image: KDKImage, baseAddress: UInt64,+ symbols: [KDKSymbol], references: [KDKReference], addressOnlyBinds: Bool) throws+ {+ guard image.header.cpuType == 0x0100_000C else {+ throw PatcherError.invalidFormat("native KDK writer requires ARM64")+ }+ guard addressOnlyBinds else {+ throw PatcherError.invalidFormat("native KDK writer currently requires address-only binds for stripped collections")+ }+ self.collection = collection+ source = image+ self.baseAddress = baseAddress+ self.symbols = symbols+ self.references = references+ header = image.header+ }++ mutating func export() throws -> Data {+ header = source.header+ mappings.removeAll(keepingCapacity: true)+ commands.removeAll(keepingCapacity: true)+ binds.removeAll(keepingCapacity: true)+ rebases.removeAll(keepingCapacity: true)+ others.removeAll(keepingCapacity: true)+ auths.removeAll(keepingCapacity: true)+ try layout()+ data = header.bytes+ writeCommands(to: &data)+ let loadsEnd = data.count+ for mapping in mappings where mapping.original.fileSize > 0 {+ data.padTo(Int(mapping.fileStart))+ let content = try collection.read(Int(min(mapping.original.fileSize, mapping.fileEnd - mapping.fileStart)), at: mapping.original.address)+ if mapping.original.name == "__TEXT" {+ guard loadsEnd <= content.count else { throw invalid("load commands exceed __TEXT") }+ data += content[loadsEnd...]+ } else {+ data += content+ }+ data.padTo(Int(mapping.fileEnd))+ }+ if source.isInCache {+ if packed {+ try writeAuthStubs()+ try adjustReferences()+ try restoreCacheFields()+ }+ try rebuildLinkedit()+ }+ return Data(data)+ }++ func invalid(_ message: String) -> PatcherError {+ .invalidFormat("KDK export \(source.identifier): \(message)")+ }++ static func aligned(_ value: UInt64, to alignment: UInt64 = KDKMachO.pageSize) -> UInt64 {+ (value + alignment - 1) / alignment * alignment+ }++ func remap(_ value: UInt64, file: Bool = false, linkedit: Bool = false) throws -> UInt64 {+ if linkedit, let m = mappings.first(where: { $0.original.name == "__LINKEDIT" }),+ value >= m.original.fileOffset, value - m.original.fileOffset <= m.original.fileSize+ {+ return m.fileStart + (value - m.original.fileOffset)+ }+ // Containing ranges win over adjacent one-past-the-end ranges.+ for allowEnd in [false, true] {+ for m in mappings {+ let start = file ? m.original.fileOffset : m.original.address+ let size = file ? m.original.fileSize : m.original.memorySize+ if value >= start, value - start < size || (allowEnd && value - start == size) {+ return (file ? m.fileStart : m.start) + (value - start)+ }+ }+ }+ throw invalid("cannot remap \(file ? "offset" : "address") 0x\(String(value, radix: 16))")+ }++ func offset(_ address: UInt64) throws -> Int {+ guard let seg = segments.first(where: { $0.contains(address) }),+ let value = Int(exactly: seg.fileOffset + (address - seg.address))+ else {+ throw invalid("address 0x\(String(address, radix: 16)) is outside exported segments")+ }+ return value+ }++ func section(_ segment: String, _ name: String) -> KDKMachO.Section? {+ sections.first { $0.segmentName == segment && $0.name == name }+ }++ func check(_ offset: Int, _ count: Int) throws {+ guard offset >= 0, count >= 0, offset <= data.count, count <= data.count - offset else {+ throw invalid("write/read outside export at \(offset), length \(count)")+ }+ }++ mutating func write(_ instruction: Data?, at offset: Int) throws {+ guard let instruction else { throw invalid("instruction cannot encode relocated target") }+ try check(offset, instruction.count)+ data.replaceSubrange(offset ..< offset + instruction.count, with: instruction)+ }++ func writeCommands(to out: inout [UInt8]) {+ for command in commands {+ if let segment = command.segment {+ KDKMachO.write(segment, to: &out)+ } else {+ out += command.bytes+ }+ }+ }++ mutating func layout() throws {+ var file: UInt64 = 0+ var address = baseAddress+ for seg in source.segments {+ let size = Self.aligned(seg.fileSize)+ let memory = Self.aligned(seg.memorySize)+ mappings.append(.init(original: seg, fileStart: file, fileEnd: file + size,+ start: packed ? address : seg.address,+ end: (packed ? address : seg.address) + memory))+ file += size+ address += memory+ }+ var sourceCommands = source.commands+ if packed, let got = source.segments.flatMap(\.sections).first(where: { $0.segmentName == "__DATA_CONST" && $0.name == "__auth_got" }),+ let index = sourceCommands.firstIndex(where: { $0.segment?.name == "__TEXT_EXEC" }),+ var segment = sourceCommands[index].segment,+ let stub = segment.sections.firstIndex(where: { $0.name == "__auth_stubs" }),+ let map = mappings.firstIndex(where: { $0.original.name == "__TEXT_EXEC" })+ {+ let size = got.size / 8 * 16+ segment.sections[stub].size = size+ sourceCommands[index].segment = segment+ mappings[map].fileEnd = mappings[map].fileStart + Self.aligned(segment.fileSize + size)+ mappings[map].end = mappings[map].start + Self.aligned(max(segment.memorySize, segment.fileSize + size))+ var last: UInt64 = 0+ for i in mappings.indices {+ if mappings[i].fileStart < last {+ let shift = last - mappings[i].fileStart+ mappings[i].fileStart += shift+ mappings[i].fileEnd += shift+ mappings[i].start += shift+ mappings[i].end += shift+ }+ last = mappings[i].fileEnd+ }+ }+ for var load in sourceCommands {+ if var seg = load.segment, let m = mappings.first(where: { $0.original.name == seg.name }) {+ seg.fileOffset = m.fileStart+ seg.fileSize = m.fileEnd - m.fileStart+ seg.address = m.start+ seg.memorySize = m.end - m.start+ for i in seg.sections.indices {+ var s = seg.sections[i]+ if s.offset != 0 {+ let off = UInt64(s.offset)+ s.offset = try UInt32(off >= m.original.fileOffset && off - m.original.fileOffset <= m.original.fileSize+ ? m.fileStart + (off - m.original.fileOffset) : remap(off, file: true))+ }+ s.address = try s.address >= m.original.address && s.address - m.original.address <= m.original.memorySize+ ? m.start + (s.address - m.original.address) : remap(s.address)+ if s.offset == 0, s.size != 0, !s.isZerofill {+ s.offset = UInt32(seg.fileOffset + (s.address - seg.address))+ }+ seg.sections[i] = s+ }+ load.segment = seg+ } else {+ let cmd = load.command+ if cmd == KDKMachO.lcSegmentSplitInfo || cmd == KDKMachO.lcMain {+ continue+ }+ var fields: [Int] = []+ var skipZero = false+ switch cmd {+ case KDKMachO.lcSymtab: fields = [8, 16]+ case KDKMachO.lcDysymtab: fields = [32, 40, 48, 56, 64, 72]+ skipZero = true+ case KDKMachO.lcDyldInfo, KDKMachO.lcDyldInfoOnly: fields = [8, 16, 24, 32, 40]+ skipZero = true+ case KDKMachO.lcDyldChainedFixups, KDKMachO.lcFunctionVariants:+ if !source.isInCache {+ fields = [8]+ }+ case KDKMachO.lcCodeSignature, KDKMachO.lcEncryptionInfo, KDKMachO.lcEncryptionInfo64,+ KDKMachO.lcFunctionStarts, KDKMachO.lcDataInCode, KDKMachO.lcFunctionVariantFixups,+ KDKMachO.lcDylibCodeSignDRs, KDKMachO.lcLinkerOptimizationHint, KDKMachO.lcDyldExportsTrie:+ fields = [8]+ case KDKMachO.lcFilesetEntry:+ try load.bytes.setLE(remap(load.bytes.le(UInt64.self, 16), file: true), at: 16)+ case KDKMachO.lcUnixThread:+ var pos = 8+ while pos < load.bytes.count {+ guard pos + 8 <= load.bytes.count,+ load.bytes.le(UInt32.self, pos) == KDKMachO.armThreadState64,+ load.bytes.le(UInt32.self, pos + 4) == 68,+ pos + 8 + 272 <= load.bytes.count else { throw invalid("unexpected ARM thread state") }+ let registers = pos + 8+ if load.bytes[registers ..< registers + 256].allSatisfy({ $0 == 0 }),+ load.bytes[registers + 264 ..< registers + 272].allSatisfy({ $0 == 0 }),+ let pc = try? remap(load.bytes.le(UInt64.self, registers + 256))+ {+ load.bytes.setLE(pc, at: registers + 256)+ }+ pos += 280+ }+ default: break+ }+ for field in fields {+ guard field + 4 <= load.bytes.count else { throw invalid("short load command") }+ let old = load.bytes.le(UInt32.self, field)+ if !skipZero || old != 0 {+ try load.bytes.setLE(UInt32(remap(UInt64(old), file: true, linkedit: true)), at: field)+ }+ }+ }+ commands.append(load)+ }+ header.flags &= ~KDKMachO.mhDylibInCache+ if packed {+ addLinkeditCommand(KDKMachO.lcDyldChainedFixups)+ addLinkeditCommand(KDKMachO.lcSegmentSplitInfo)+ let chained = commands.first { $0.command == KDKMachO.lcDyldChainedFixups }!+ let split = commands.first { $0.command == KDKMachO.lcSegmentSplitInfo }!+ commands.removeAll { $0.command == chained.command || $0.command == split.command }+ let last = commands.lastIndex { $0.segment != nil }+ if let last {+ commands.insert(chained, at: last + 1)+ } else {+ commands.append(chained)+ }+ let before = commands.firstIndex { $0.command == KDKMachO.lcFunctionStarts } ?? commands.count+ commands.insert(split, at: before)+ } else if source.isInCache, let i = commands.firstIndex(where: { $0.command == KDKMachO.lcDyldChainedFixups }) {+ header.commandCount -= 1+ header.commandsSize -= UInt32(commands[i].size)+ commands.remove(at: i)+ }+ // Deliberately keep the source header's counts, with only the explicit+ // add/remove adjustments above, matching the reference File.Export.+ }++ mutating func addLinkeditCommand(_ command: UInt32) {+ if let i = commands.firstIndex(where: { $0.command == command }) {+ header.commandCount -= 1+ header.commandsSize -= UInt32(commands[i].size)+ commands.remove(at: i)+ }+ var raw: [UInt8] = []+ for word: UInt32 in [command, 16, 0, 0] {+ raw.appendLE(word)+ }+ commands.append(.init(command: command, bytes: raw, segment: nil))+ header.commandCount += 1+ header.commandsSize += 16+ }++ mutating func writeAuthStubs() throws {+ guard let got = section("__DATA_CONST", "__auth_got"), let stubs = section("__TEXT_EXEC", "__auth_stubs"),+ got.size > 0, stubs.size > 0 else { return }+ for i in 0 ..< got.size / 8 {+ let pc = stubs.address + i * 16, target = got.address + i * 8+ let off = try offset(pc)+ try write(ARM64Encoder.encodeADRP(rd: 17, pc: pc, target: target), at: off)+ try write(ARM64Encoder.encodeAddImm12(rd: 17, rn: 17, imm12: UInt32(target & 0xFFF)), at: off + 4)+ try write(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 16, rn: 17, offset: 0), at: off + 8)+ try write(ARM64Encoder.encodeBRAA(rn: 16, rm: 17), at: off + 12)+ }+ }++ mutating func restoreCacheFields() throws {+ if let symbol = (source.symbols + symbols).first(where: { $0.name == "_kmod_info" && $0.isDefinedInSection }) {+ let start = try offset(remap(symbol.value)) + 0x9C+ try check(start, 16)+ data.replaceSubrange(start ..< start + 16, with: repeatElement(UInt8(0), count: 16))+ }+ if let seal = section("__TEXT", "__fips_hmacs") {+ guard seal.size >= 32, let text = section("__TEXT", "__text") ?? section("__TEXT_EXEC", "__text") else {+ throw invalid("cannot restore FIPS HMAC")+ }+ let off = Int(text.offset), count = Int(text.size)+ try check(off, count)+ try check(Int(seal.offset), 32)+ let mac = HMAC<SHA256>.authenticationCode(for: Data(data[off ..< off + count]), using: SymmetricKey(data: Data([0])))+ data.replaceSubrange(Int(seal.offset) ..< Int(seal.offset) + 32, with: Array(mac))+ }+ }+}++extension [UInt8] {+ mutating func padTo(_ end: Int) {+ if count < end {+ append(contentsOf: repeatElement(0, count: end - count))+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKMachO.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKMachO.swiftnew file mode 100644index 00000000..21810cad--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/KDKMachO.swift@@ -0,0 +1,613 @@+// KDKMachO.swift — The Mach-O images of a kernel collection, as the KDK export reads them.+//+// The export (`KDKImageExport`) rebuilds a fileset entry of an MH_FILESET+// kernelcache as the standalone Mach-O ld64 would have written. It is a port of+// blacktop/go-macho's `File.Export` (go-macho#94), and this file holds the parts+// of go-macho it reads through: an entry's load commands, segments, sections,+// symbols and indirect symbols, with addresses resolved through the+// collection's own segments, exactly as go-macho resolves them.+//+// Only what kernel collections contain is modelled: 64-bit little-endian+// Mach-O, with offsets of an entry's load commands relative to the collection.++import Foundation+import VPhonePatchKit++enum KDKMachO {+ // MARK: - Constants++ static let magic64: UInt32 = 0xFEED_FACF+ static let headerSize = 32+ static let segmentCommandSize = 72+ static let sectionSize = 80+ static let nlistSize = 16+ static let pointerSize: UInt64 = 8+ /// go-macho's page size for arm64 (16 KB).+ static let pageSize: UInt64 = 0x4000++ static let mhFileset: UInt32 = 0xC+ static let mhDylibInCache: UInt32 = 0x8000_0000++ static let lcSymtab: UInt32 = 0x2+ static let lcUnixThread: UInt32 = 0x5+ static let lcDysymtab: UInt32 = 0xB+ static let lcSegment64: UInt32 = 0x19+ static let lcUUID: UInt32 = 0x1B+ static let lcCodeSignature: UInt32 = 0x1D+ static let lcSegmentSplitInfo: UInt32 = 0x1E+ static let lcEncryptionInfo: UInt32 = 0x21+ static let lcDyldInfo: UInt32 = 0x22+ static let lcDyldInfoOnly: UInt32 = 0x8000_0022+ static let lcFunctionStarts: UInt32 = 0x26+ static let lcMain: UInt32 = 0x8000_0028+ static let lcDataInCode: UInt32 = 0x29+ static let lcSourceVersion: UInt32 = 0x2A+ static let lcDylibCodeSignDRs: UInt32 = 0x2B+ static let lcEncryptionInfo64: UInt32 = 0x2C+ static let lcLinkerOptimizationHint: UInt32 = 0x2E+ static let lcBuildVersion: UInt32 = 0x32+ static let lcDyldExportsTrie: UInt32 = 0x8000_0033+ static let lcDyldChainedFixups: UInt32 = 0x8000_0034+ static let lcFilesetEntry: UInt32 = 0x8000_0035+ static let lcFunctionVariants: UInt32 = 0x37+ static let lcFunctionVariantFixups: UInt32 = 0x38++ static let armThreadState64: UInt32 = 6+ /// `sizeof(arm_thread_state64_t)`: x0-x28, fp, lr, sp, pc, cpsr, pad.+ static let armThreadState64Size = 272++ static let indirectSymbolLocal: UInt32 = 0x8000_0000+ static let indirectSymbolAbsolute: UInt32 = 0x4000_0000++ // MARK: - Model++ struct Section {+ var name: String+ var segmentName: String+ var address: UInt64+ var size: UInt64+ var offset: UInt32+ var align: UInt32+ var relocationOffset: UInt32+ var relocationCount: UInt32+ var flags: UInt32+ var reserved1: UInt32+ var reserved2: UInt32+ var reserved3: UInt32++ var type: UInt32 {+ flags & 0xFF+ }++ var isNonLazySymbolPointers: Bool {+ type == 0x6+ }++ var isLazySymbolPointers: Bool {+ type == 0x7+ }++ var isSymbolPointers: Bool {+ isNonLazySymbolPointers || isLazySymbolPointers+ }++ /// S_ZEROFILL, S_GB_ZEROFILL or S_THREAD_LOCAL_ZEROFILL.+ var isZerofill: Bool {+ type == 0x1 || type == 0xC || type == 0x12+ }++ func contains(_ address: UInt64) -> Bool {+ self.address <= address && address < self.address &+ size+ }+ }++ struct Segment {+ var command: UInt32+ var commandSize: UInt32+ var name: String+ var address: UInt64+ var memorySize: UInt64+ var fileOffset: UInt64+ var fileSize: UInt64+ var maxProtection: UInt32+ var initialProtection: UInt32+ var sectionCount: UInt32+ var flags: UInt32+ var sections: [Section]++ /// go-macho's segment lookup: `[address, address + memorySize)`.+ func contains(_ address: UInt64) -> Bool {+ address >= self.address && address &- self.address < memorySize+ }+ }++ /// One load command as it appears in the image. Segments are parsed; every+ /// other command is kept as its bytes, which the export patches in place.+ struct LoadCommand {+ var command: UInt32+ var bytes: [UInt8]+ var segment: Segment?++ var size: Int {+ if let segment {+ return segmentCommandSize + segment.sections.count * sectionSize+ }+ return bytes.count+ }+ }++ struct Header {+ var magic: UInt32+ var cpuType: UInt32+ var cpuSubtype: UInt32+ var fileType: UInt32+ var commandCount: UInt32+ var commandsSize: UInt32+ var flags: UInt32+ var reserved: UInt32++ var bytes: [UInt8] {+ var out: [UInt8] = []+ out.reserveCapacity(headerSize)+ for field in [magic, cpuType, cpuSubtype, fileType, commandCount, commandsSize, flags, reserved] {+ out.appendLE(field)+ }+ return out+ }+ }++ // MARK: - Byte Access++ /// Little-endian reads with bounds checks, over the whole collection.+ struct Bytes {+ let data: Data++ var count: Int {+ data.count+ }++ func u8(_ offset: Int) throws -> UInt8 {+ guard offset >= 0, offset < data.count else { throw outOfBounds(offset, 1) }+ return data[data.startIndex + offset]+ }++ func u16(_ offset: Int) throws -> UInt16 {+ try check(offset, 2)+ return data.loadLE(UInt16.self, at: offset)+ }++ func u32(_ offset: Int) throws -> UInt32 {+ try check(offset, 4)+ return data.loadLE(UInt32.self, at: offset)+ }++ func u64(_ offset: Int) throws -> UInt64 {+ try check(offset, 8)+ return data.loadLE(UInt64.self, at: offset)+ }++ func bytes(_ offset: Int, _ count: Int) throws -> [UInt8] {+ try check(offset, count)+ return [UInt8](data[data.startIndex + offset ..< data.startIndex + offset + count])+ }++ func check(_ offset: Int, _ count: Int) throws {+ guard offset >= 0, count >= 0, offset <= data.count, count <= data.count - offset else {+ throw outOfBounds(offset, count)+ }+ }++ func outOfBounds(_ offset: Int, _ count: Int) -> PatcherError {+ .invalidFormat("kernelcache read of \(count) bytes at 0x\(String(offset, radix: 16)) is out of bounds")+ }+ }++ static func name(_ bytes: [UInt8]) -> String {+ let end = bytes.firstIndex(of: 0) ?? bytes.endIndex+ return String(decoding: bytes[..<end], as: UTF8.self)+ }++ static func fixedName(_ name: String) -> [UInt8] {+ var out = Array(name.utf8.prefix(16))+ out += [UInt8](repeating: 0, count: 16 - out.count)+ return out+ }++ // MARK: - Parsing++ /// The header and load commands at `offset` in `bytes`, with segments and+ /// sections parsed.+ static func loadCommands(in bytes: Bytes, at offset: Int) throws -> (Header, [LoadCommand]) {+ try bytes.check(offset, headerSize)+ let header = try Header(+ magic: bytes.u32(offset), cpuType: bytes.u32(offset + 4), cpuSubtype: bytes.u32(offset + 8),+ fileType: bytes.u32(offset + 12), commandCount: bytes.u32(offset + 16), commandsSize: bytes.u32(offset + 20),+ flags: bytes.u32(offset + 24), reserved: bytes.u32(offset + 28)+ )+ guard header.magic == magic64 else {+ throw PatcherError.invalidFormat("Mach-O at 0x\(String(offset, radix: 16)) is not 64-bit little-endian")+ }+ try bytes.check(offset + headerSize, Int(header.commandsSize))+ guard UInt64(header.commandCount) * 8 <= UInt64(header.commandsSize) else {+ throw PatcherError.invalidFormat("load command count exceeds sizeofcmds")+ }+ let commandsEnd = offset + headerSize + Int(header.commandsSize)+ var commands: [LoadCommand] = []+ var cursor = offset + headerSize+ for _ in 0 ..< header.commandCount {+ guard cursor <= commandsEnd - 8 else {+ throw PatcherError.invalidFormat("load command header exceeds sizeofcmds")+ }+ let command = try bytes.u32(cursor)+ let size = try Int(bytes.u32(cursor + 4))+ guard size >= 8 else {+ throw PatcherError.invalidFormat("load command 0x\(String(command, radix: 16)) has size \(size)")+ }+ guard size <= commandsEnd - cursor else {+ throw PatcherError.invalidFormat("load command exceeds sizeofcmds")+ }+ let minimum: Int = switch command {+ case lcSegment64: segmentCommandSize+ case lcSymtab: 24+ case lcDysymtab: 80+ case lcDyldInfo, lcDyldInfoOnly: 48+ case lcFilesetEntry: 32+ case lcUnixThread: 16+ case lcUUID: 24+ case lcCodeSignature, lcSegmentSplitInfo, lcEncryptionInfo, lcDyldChainedFixups,+ lcFunctionStarts, lcDataInCode, lcFunctionVariants, lcFunctionVariantFixups,+ lcDylibCodeSignDRs, lcEncryptionInfo64, lcLinkerOptimizationHint, lcDyldExportsTrie:+ 16+ default: 8+ }+ guard size >= minimum else {+ throw PatcherError.invalidFormat("short load command 0x\(String(command, radix: 16))")+ }+ let raw = try bytes.bytes(cursor, size)+ var load = LoadCommand(command: command, bytes: raw, segment: nil)+ if command == lcSegment64 {+ load.segment = try segment(raw)+ }+ commands.append(load)+ cursor += size+ }+ return (header, commands)+ }++ static func segment(_ raw: [UInt8]) throws -> Segment {+ guard raw.count >= segmentCommandSize else {+ throw PatcherError.invalidFormat("LC_SEGMENT_64 of \(raw.count) bytes")+ }+ let count = raw.le(UInt32.self, 64)+ guard raw.count >= segmentCommandSize + Int(count) * sectionSize else {+ throw PatcherError.invalidFormat("LC_SEGMENT_64 \(name(Array(raw[8 ..< 24]))) is too short for \(count) sections")+ }+ var sections: [Section] = []+ for index in 0 ..< Int(count) {+ let base = segmentCommandSize + index * sectionSize+ sections.append(Section(+ name: name(Array(raw[base ..< base + 16])),+ segmentName: name(Array(raw[base + 16 ..< base + 32])),+ address: raw.le(UInt64.self, base + 32),+ size: raw.le(UInt64.self, base + 40),+ offset: raw.le(UInt32.self, base + 48),+ align: raw.le(UInt32.self, base + 52),+ relocationOffset: raw.le(UInt32.self, base + 56),+ relocationCount: raw.le(UInt32.self, base + 60),+ flags: raw.le(UInt32.self, base + 64),+ reserved1: raw.le(UInt32.self, base + 68),+ reserved2: raw.le(UInt32.self, base + 72),+ reserved3: raw.le(UInt32.self, base + 76)+ ))+ }+ let address = raw.le(UInt64.self, 24), memorySize = raw.le(UInt64.self, 32)+ let fileOffset = raw.le(UInt64.self, 40), fileSize = raw.le(UInt64.self, 48)+ guard !address.addingReportingOverflow(memorySize).overflow,+ !fileOffset.addingReportingOverflow(fileSize).overflow,+ memorySize <= UInt64(Int.max) - KDKMachO.pageSize,+ fileSize <= UInt64(Int.max) - KDKMachO.pageSize+ else {+ throw PatcherError.invalidFormat("segment address or size overflow")+ }+ for section in sections {+ guard !section.address.addingReportingOverflow(section.size).overflow else {+ throw PatcherError.invalidFormat("section address or size overflow")+ }+ }+ return Segment(+ command: raw.le(UInt32.self, 0), commandSize: raw.le(UInt32.self, 4),+ name: name(Array(raw[8 ..< 24])),+ address: raw.le(UInt64.self, 24), memorySize: raw.le(UInt64.self, 32),+ fileOffset: raw.le(UInt64.self, 40), fileSize: raw.le(UInt64.self, 48),+ maxProtection: raw.le(UInt32.self, 56), initialProtection: raw.le(UInt32.self, 60),+ sectionCount: count, flags: raw.le(UInt32.self, 68), sections: sections+ )+ }++ static func write(_ segment: Segment, to out: inout [UInt8]) {+ out.appendLE(segment.command)+ out.appendLE(segment.commandSize)+ out += fixedName(segment.name)+ out.appendLE(segment.address)+ out.appendLE(segment.memorySize)+ out.appendLE(segment.fileOffset)+ out.appendLE(segment.fileSize)+ out.appendLE(segment.maxProtection)+ out.appendLE(segment.initialProtection)+ out.appendLE(segment.sectionCount)+ out.appendLE(segment.flags)+ for section in segment.sections {+ out += fixedName(section.name)+ out += fixedName(section.segmentName)+ out.appendLE(section.address)+ out.appendLE(section.size)+ out.appendLE(section.offset)+ out.appendLE(section.align)+ out.appendLE(section.relocationOffset)+ out.appendLE(section.relocationCount)+ out.appendLE(section.flags)+ out.appendLE(section.reserved1)+ out.appendLE(section.reserved2)+ out.appendLE(section.reserved3)+ }+ }++ /// The symbols of an LC_SYMTAB, named from its string table as go-macho does:+ /// a name offset past the table gives an empty name.+ static func symbols(_ symtab: [UInt8], in bytes: Bytes) throws -> [KDKSymbol] {+ let symbolOffset = Int(symtab.le(UInt32.self, 8))+ let count = Int(symtab.le(UInt32.self, 12))+ let stringOffset = Int(symtab.le(UInt32.self, 16))+ let stringSize = Int(symtab.le(UInt32.self, 20))+ try bytes.check(stringOffset, stringSize)+ try bytes.check(symbolOffset, count * nlistSize)+ let strings = bytes.data+ let stringBase = strings.startIndex + stringOffset+ func string(_ offset: UInt64) -> String {+ guard offset < UInt64(stringSize) else { return "" }+ let start = stringBase + Int(offset)+ let end = strings[start ..< stringBase + stringSize].firstIndex(of: 0) ?? stringBase + stringSize+ return String(decoding: strings[start ..< end], as: UTF8.self)+ }+ var symbols: [KDKSymbol] = []+ symbols.reserveCapacity(count)+ for index in 0 ..< count {+ let base = symbolOffset + index * nlistSize+ let type = try bytes.u8(base + 4)+ let value = try bytes.u64(base + 8)+ var symbol = try KDKSymbol(+ name: string(UInt64(bytes.u32(base))), type: type, sect: bytes.u8(base + 5),+ desc: bytes.u16(base + 6), value: value+ )+ if symbol.isIndirect {+ symbol.indirectName = string(value)+ }+ symbols.append(symbol)+ }+ return symbols+ }++ static func indirectSymbols(_ dysymtab: [UInt8], in bytes: Bytes) throws -> [UInt32] {+ let offset = Int(dysymtab.le(UInt32.self, 56))+ let count = Int(dysymtab.le(UInt32.self, 60))+ try bytes.check(offset, count * 4)+ return try (0 ..< count).map { try bytes.u32(offset + $0 * 4) }+ }+}++// MARK: - Symbols++/// A symbol table entry, or a symbol the extraction adds to an image.+struct KDKSymbol: Equatable {+ var name: String+ var indirectName = ""+ var type: UInt8+ var sect: UInt8+ var desc: UInt16+ var value: UInt64+ /// For a pointer bound to `name + bindAddend` (set by the export only).+ var bindAddend: Int64 = 0++ init(name: String, indirectName: String = "", type: UInt8, sect: UInt8, desc: UInt16, value: UInt64) {+ self.name = name+ self.indirectName = indirectName+ self.type = type+ self.sect = sect+ self.desc = desc+ self.value = value+ }++ static let typeExternal: UInt8 = 0x01+ static let typeAbsolute: UInt8 = 0x02+ static let typeIndirect: UInt8 = 0x0A+ static let typeSection: UInt8 = 0x0E++ var isExternal: Bool {+ type & 0x01 != 0+ }++ var isUndefined: Bool {+ type & 0x0E == 0+ }++ var isDefinedInSection: Bool {+ type & 0x0E == 0x0E+ }++ var isIndirect: Bool {+ type & 0x0E == 0x0A+ }++ var isWeakReference: Bool {+ desc & 0x40 != 0+ }++ var isWeakDefinition: Bool {+ desc & 0x80 != 0+ }+}++// MARK: - Kernel Collection++/// An MH_FILESET kernelcache: its segments, which resolve every address of+/// every entry, and its fileset entries.+struct KDKKernelCollection {+ struct Entry {+ let identifier: String+ let address: UInt64+ let fileOffset: UInt64+ }++ let bytes: KDKMachO.Bytes+ let header: KDKMachO.Header+ let commands: [KDKMachO.LoadCommand]+ let entries: [Entry]++ init(_ data: Data) throws {+ let data = data.startIndex == 0 ? data : Data(data)+ bytes = KDKMachO.Bytes(data: data)+ (header, commands) = try KDKMachO.loadCommands(in: bytes, at: 0)+ guard header.fileType == KDKMachO.mhFileset else {+ throw PatcherError.invalidFormat("the kernelcache is not an MH_FILESET kernel collection")+ }+ let collectionSize = data.count+ entries = try commands.filter { $0.command == KDKMachO.lcFilesetEntry }.map { load in+ let raw = load.bytes+ guard raw.count >= 32 else { throw PatcherError.invalidFormat("LC_FILESET_ENTRY of \(raw.count) bytes") }+ let nameOffset = Int(raw.le(UInt32.self, 24))+ guard nameOffset >= 32, nameOffset < raw.count else { throw PatcherError.invalidFormat("LC_FILESET_ENTRY names no entry") }+ guard raw.le(UInt64.self, 16) <= UInt64(collectionSize - KDKMachO.headerSize) else {+ throw PatcherError.invalidFormat("fileset entry header is outside the collection")+ }+ return Entry(+ identifier: KDKMachO.name(Array(raw[nameOffset...])),+ address: raw.le(UInt64.self, 8), fileOffset: raw.le(UInt64.self, 16)+ )+ }+ }++ var segments: [KDKMachO.Segment] {+ commands.compactMap(\.segment)+ }++ /// The collection's preferred load address, its __TEXT.+ var baseAddress: UInt64 {+ segments.first { $0.name == "__TEXT" }?.address ?? 0+ }++ /// The file offset of `address`, through the collection's segments.+ func offset(of address: UInt64) throws -> UInt64 {+ for segment in segments where segment.contains(address) {+ return segment.fileOffset + (address - segment.address)+ }+ throw PatcherError.invalidFormat("address 0x\(String(address, radix: 16)) is not in the kernelcache")+ }++ /// `count` bytes at `address`, read from the file as go-macho's address+ /// reader does: from the address's file offset onwards.+ func read(_ count: Int, at address: UInt64) throws -> [UInt8] {+ guard let offset = try Int(exactly: offset(of: address)) else {+ throw PatcherError.invalidFormat("kernelcache file offset exceeds host integer range")+ }+ return try bytes.bytes(offset, count)+ }++ /// The collection header's own LC_UNIXTHREAD.+ var unixThread: KDKMachO.LoadCommand? {+ let threads = commands.filter { $0.command == KDKMachO.lcUnixThread }+ return threads.count == 1 ? threads[0] : nil+ }++ func image(_ identifier: String) throws -> KDKImage {+ guard let entry = entries.first(where: { $0.identifier == identifier }) else {+ throw PatcherError.fileNotFound("fileset entry \(identifier) in the kernelcache")+ }+ return try KDKImage(entry: entry, in: self)+ }+}++/// A fileset entry: its header and load commands as the collection holds them,+/// with every offset in them relative to the collection.+struct KDKImage {+ let identifier: String+ var header: KDKMachO.Header+ var commands: [KDKMachO.LoadCommand]+ var symbols: [KDKSymbol]+ var indirectSymbols: [UInt32]++ init(entry: KDKKernelCollection.Entry, in collection: KDKKernelCollection) throws {+ identifier = entry.identifier+ (header, commands) = try KDKMachO.loadCommands(in: collection.bytes, at: Int(entry.fileOffset))+ if let symtab = commands.first(where: { $0.command == KDKMachO.lcSymtab }) {+ symbols = try KDKMachO.symbols(symtab.bytes, in: collection.bytes)+ } else {+ symbols = []+ }+ if let dysymtab = commands.first(where: { $0.command == KDKMachO.lcDysymtab }) {+ indirectSymbols = try KDKMachO.indirectSymbols(dysymtab.bytes, in: collection.bytes)+ } else {+ indirectSymbols = []+ }+ }++ var segments: [KDKMachO.Segment] {+ commands.compactMap(\.segment)+ }++ func command(_ command: UInt32) -> KDKMachO.LoadCommand? {+ commands.first { $0.command == command }+ }++ var isInCache: Bool {+ header.flags & KDKMachO.mhDylibInCache != 0+ }++ /// The image's preferred load address, its __TEXT.+ var baseAddress: UInt64 {+ segments.first { $0.name == "__TEXT" }?.address ?? 0+ }+}++// MARK: - Little-Endian Helpers++extension [UInt8] {+ func le<T: FixedWidthInteger>(_: T.Type, _ offset: Int) -> T {+ var value: T = 0+ for index in 0 ..< MemoryLayout<T>.size {+ value |= T(self[offset + index]) << (8 * index)+ }+ return value+ }++ mutating func setLE<T: FixedWidthInteger>(_ value: T, at offset: Int) {+ for index in 0 ..< MemoryLayout<T>.size {+ self[offset + index] = UInt8(truncatingIfNeeded: value >> (8 * index))+ }+ }++ mutating func appendLE<T: FixedWidthInteger>(_ value: T) {+ for index in 0 ..< MemoryLayout<T>.size {+ append(UInt8(truncatingIfNeeded: value >> (8 * index)))+ }+ }++ mutating func appendULEB128(_ value: UInt64) {+ var value = value+ repeat {+ var byte = UInt8(value & 0x7F)+ value >>= 7+ if value != 0 {+ byte |= 0x80+ }+ append(byte)+ } while value != 0+ }++ /// Zero bytes up to a multiple of `alignment`.+ mutating func pad(to alignment: Int) {+ let remainder = count % alignment+ if remainder != 0 {+ append(contentsOf: [UInt8](repeating: 0, count: alignment - remainder))+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSE b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSEnew file mode 100644index 00000000..ed0d0f6d--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KDK/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2020-2026 blacktop++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, 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 THE+SOFTWARE.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKExportFixtureTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKExportFixtureTests.swiftnew file mode 100644index 00000000..cd65dbe1--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKExportFixtureTests.swift@@ -0,0 +1,131 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++struct KDKExportFixtureTests {+ static let base: UInt64 = 0xFFFF_FE00_0000_0000++ static func fixture() throws -> (KDKKernelCollection, KDKImage, [KDKSymbol], [KDKReference]) {+ let base = Self.base+ func section(_ segment: String, _ name: String, _ off: UInt32, _ size: UInt64, flags: UInt32 = 0, reserved: UInt32 = 0) -> KDKMachO.Section {+ .init(name: name, segmentName: segment, address: base + UInt64(off), size: size, offset: size == 0 ? 0 : off,+ align: 3, relocationOffset: 0, relocationCount: 0, flags: flags, reserved1: reserved, reserved2: 0, reserved3: 0)+ }+ func segment(_ name: String, _ off: UInt64, _ size: UInt64, _ sections: [KDKMachO.Section] = []) -> [UInt8] {+ var bytes: [UInt8] = []+ KDKMachO.write(.init(command: KDKMachO.lcSegment64, commandSize: UInt32(72 + 80 * sections.count), name: name,+ address: base + off, memorySize: size, fileOffset: off, fileSize: size,+ maxProtection: 7, initialProtection: 3, sectionCount: UInt32(sections.count), flags: 0, sections: sections), to: &bytes)+ return bytes+ }+ func command(_ words: [UInt32]) -> [UInt8] {+ var bytes: [UInt8] = []+ for word in words {+ bytes.appendLE(word)+ }+ return bytes+ }+ func header(_ type: UInt32, _ loads: [[UInt8]]) -> [UInt8] {+ KDKMachO.Header(magic: KDKMachO.magic64, cpuType: 0x0100_000C, cpuSubtype: 2, fileType: type,+ commandCount: UInt32(loads.count), commandsSize: UInt32(loads.flatMap(\.self).count),+ flags: type == 0xC ? 0 : KDKMachO.mhDylibInCache, reserved: 0).bytes + loads.flatMap(\.self)+ }+ var entry = command([KDKMachO.lcFilesetEntry, 56])+ entry.appendLE(base + 0x1000)+ entry.appendLE(UInt64(0x1000))+ entry += command([32, 0])+ entry += Array("com.test.kext\0".utf8)+ entry.padTo(56)+ let imageLoads = [+ segment("__TEXT", 0x1000, 0x4000),+ segment("__TEXT_EXEC", 0x8000, 0x1000, [section("__TEXT_EXEC", "__text", 0x8100, 0x100), section("__TEXT_EXEC", "__auth_stubs", 0x9000, 0)]),+ segment("__DATA_CONST", 0xA000, 0x1000, [section("__DATA_CONST", "__auth_got", 0xA000, 16, flags: 6)]),+ segment("__LINKEDIT", 0xC000, 0x200),+ command([KDKMachO.lcSymtab, 24, 0xC000, 1, 0xC010, 16]),+ command([KDKMachO.lcDysymtab, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0xC020, 2, 0, 0, 0, 0]),+ command([KDKMachO.lcFunctionStarts, 16, 0xC030, 8]),+ ]+ var bytes = [UInt8](repeating: 0, count: 0xD000)+ let top = header(0xC, [segment("__TEXT", 0, 0xD000), entry])+ bytes.replaceSubrange(0 ..< top.count, with: top)+ let image = header(0xB, imageLoads)+ bytes.replaceSubrange(0x1000 ..< 0x1000 + image.count, with: image)+ bytes.setLE(UInt32(1), at: 0xC000)+ bytes.replaceSubrange(0xC010 ..< 0xC020, with: [0] + Array("<redacted>\0".utf8) + [UInt8](repeating: 0, count: 4))+ let ext: UInt64 = 0xFFFF_FE00_0002_0000+ bytes.setLE(UInt64(0x8000_1234_0002_0000), at: 0xA000)+ bytes.setLE(UInt64(0x8000_5678_0000_8100), at: 0xA008)+ let branch = try #require(ARM64Encoder.encodeBL(from: 0x8100, to: 0x20000))+ bytes.replaceSubrange(0x8100 ..< 0x8104, with: branch)+ try bytes.replaceSubrange(0x8104 ..< 0x8108, with: #require(ARM64Encoder.encodeADRP(rd: 8, pc: base + 0x8104, target: base + 0xA000)))+ try bytes.replaceSubrange(0x8108 ..< 0x810C, with: #require(ARM64Encoder.encodeAddImm12(rd: 8, rn: 8, imm12: 0)))+ var starts: [UInt8] = []+ starts.appendULEB128(0x7100)+ starts.append(0)+ starts.pad(to: 8)+ bytes.replaceSubrange(0xC030 ..< 0xC038, with: starts)+ let collection = try KDKKernelCollection(Data(bytes))+ let symbols: [KDKSymbol] = [.init(name: "_entry", type: 0xE, sect: 1, desc: 0, value: base + 0x8100),+ .init(name: "_external", type: 1, sect: 0, desc: 0, value: ext)]+ let refs: [KDKReference] = [.init(kind: 7, source: base + 0x8100, target: ext),+ .init(kind: 5, source: base + 0x8104, target: base + 0xA000),+ .init(kind: 6, source: base + 0x8108, target: base + 0xA000, extra: base + 0x8104),+ .init(kind: 2, source: base + 0xA000, target: ext),+ .init(kind: 2, source: base + 0xA008, target: base + 0x8100)]+ return try (collection, collection.image("com.test.kext"), symbols, refs)+ }++ @Test func packedExportRestoresStandaloneReferences() throws {+ var (collection, image, symbols, refs) = try Self.fixture()+ // A stripped indirect table has no trustworthy symbol identity.+ image.symbols = []+ var writer = try KDKImageExport(collection: collection, image: image, baseAddress: 0, symbols: symbols, references: refs, addressOnlyBinds: true)+ let output = try writer.export()+ let (header, commands) = try KDKMachO.loadCommands(in: .init(data: output), at: 0)+ #expect(header.flags & KDKMachO.mhDylibInCache == 0)+ #expect(header.commandCount == image.header.commandCount + 2)+ #expect(commands[4].command == KDKMachO.lcDyldChainedFixups)+ #expect(commands[commands.count - 2].command == KDKMachO.lcSegmentSplitInfo)+ let bytes = [UInt8](output)+ #expect(ARM64Encoder.decodeBranchTarget(insn: bytes.le(UInt32.self, 0x4100), pc: 0x4100) == 0x5000)+ #expect(bytes.le(UInt32.self, 0x500C) == 0xD71F_0A11)+ #expect(bytes.le(UInt64.self, 0x8000) == 0xC010_1234_0000_0000) // auth bind, next = 2+ #expect(bytes.le(UInt64.self, 0x8008) == 0x8000_5678_0000_4100) // auth rebase+ let sym = try #require(commands.first { $0.command == KDKMachO.lcSymtab })+ let syms = try KDKMachO.symbols(sym.bytes, in: .init(data: output))+ #expect(syms.map(\.name) == ["_entry", "_external"])+ #expect(syms.map(\.value) == [0x4100, 0])+ let dysym = try #require(commands.first { $0.command == KDKMachO.lcDysymtab })+ #expect(try KDKMachO.indirectSymbols(dysym.bytes, in: .init(data: output)) == [1, KDKMachO.indirectSymbolLocal])+ let function = try #require(commands.first { $0.command == KDKMachO.lcFunctionStarts })+ let start = Int(function.bytes.le(UInt32.self, 8))+ #expect(Array(bytes[start ..< start + 4]) == [0x80, 0x82, 1, 0])+ let linkedit = try #require(commands.compactMap(\.segment).first { $0.name == "__LINKEDIT" })+ #expect(UInt64(output.count) == linkedit.fileOffset + linkedit.fileSize)+ #expect(try writer.export() == output)+ // Repeat from the same immutable input, in a different reference order.+ refs.reverse()+ var second = try KDKImageExport(collection: collection, image: image, baseAddress: 0, symbols: symbols, references: refs, addressOnlyBinds: true)+ #expect(try second.export() == output)+ }++ @Test func cacheAddressExportKeepsVMAddresses() throws {+ let (collection, image, symbols, _) = try Self.fixture()+ var writer = try KDKImageExport(collection: collection, image: image, baseAddress: 0, symbols: symbols, references: [], addressOnlyBinds: true)+ let output = try writer.export()+ let (_, commands) = try KDKMachO.loadCommands(in: .init(data: output), at: 0)+ #expect(commands.compactMap(\.segment).map(\.address) == image.segments.map(\.address))+ #expect(!commands.contains { $0.command == KDKMachO.lcDyldChainedFixups })+ }++ @Test func malformedCommandsThrowInsteadOfTrapping() throws {+ let (collection, _, _, _) = try Self.fixture()+ var data = [UInt8](collection.bytes.data)+ data.setLE(UInt32.max, at: 36)+ #expect(throws: PatcherError.self) { try KDKKernelCollection(Data(data)) }+ data = [UInt8](collection.bytes.data)+ data.setLE(UInt32.max, at: 16)+ #expect(throws: PatcherError.self) { try KDKKernelCollection(Data(data)) }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKImageExportTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKImageExportTests.swiftnew file mode 100644index 00000000..8fffef4c--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KDKImageExportTests.swift@@ -0,0 +1,123 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++struct KDKImageExportTests {+ @Test func pointerLayouts() throws {+ #expect(try KDKImageExport.pointer(target: 0xFE00_0000_0123_4567, ordinal: nil, auth: nil, next: 3) == 0x001F_F000_0123_4567)+ #expect(try KDKImageExport.pointer(target: 0, ordinal: 7, addend: -4, auth: nil, next: 2) == 0x4017_FFFC_0000_0007)+ #expect(try KDKImageExport.pointer(target: 0x4000, ordinal: nil, auth: 0x0005_1234_0000_0000, next: 5) == 0x802D_1234_0000_4000)+ #expect(try KDKImageExport.pointer(target: 0, ordinal: 9, auth: 0x0002_BEEF_0000_0000, next: 1) == 0xC00A_BEEF_0000_0009)+ #expect(throws: PatcherError.self) { try KDKImageExport.pointer(target: 0, ordinal: 0, addend: 1 << 18, auth: nil, next: 0) }+ #expect(throws: PatcherError.self) { try KDKImageExport.pointer(target: 0, ordinal: nil, auth: nil, next: 0x800) }+ }++ @Test func braaAndKernelADRP() throws {+ // xcrun clang -arch arm64e (2026-10-23), verified independently of+ // this encoder. Keystone 0.9.2 rejects BRAA; it cannot be the oracle.+ let cases: [(UInt32, UInt32, UInt32)] = [(16, 17, 0xD71F_0A11), (0, 1, 0xD71F_0801), (30, 31, 0xD71F_0BDF)]+ for (rn, rm, expected) in cases {+ let encoded = try #require(ARM64Encoder.encodeBRAA(rn: rn, rm: rm))+ #expect([UInt8](encoded).le(UInt32.self, 0) == expected)+ let decoded = try #require(ARM64Disassembler().disassembleOne(encoded, at: 0))+ #expect(decoded.mnemonic == "braa")+ }+ #expect(ARM64Encoder.encodeBRAA(rn: 31, rm: 0) == nil)+ #expect(ARM64Encoder.encodeBRAA(rn: 0, rm: 32) == nil)+ let low = ARM64Encoder.encodeADRP(rd: 17, pc: 0x4000, target: 0xA123)+ let high = ARM64Encoder.encodeADRP(rd: 17, pc: 0xFFFF_FE00_0000_4000, target: 0xFFFF_FE00_0000_A123)+ #expect(low == high)+ #expect(high != nil)+ }++ @Test func off12RetainsInstructionAndScale() throws {+ // Independent clang encodings of ldr/str/ldrsw/ldr q/add (see guide).+ let cases: [(UInt32, UInt32, UInt32)] = [+ (0x3940_0020, 0x123, 0x3944_8C20), // ldrb w0, [x1, #0x123]+ (0x7940_0020, 0x246, 0x7944_8C20), // ldrh+ (0xB940_0020, 0x48C, 0xB944_8C20), // ldr w0+ (0xF940_0020, 0x918, 0xF944_8C20), // ldr x0+ (0x3DC0_0020, 0x230, 0x3DC0_8C20), // ldr q0+ (0x9100_0020, 0x123, 0x9104_8C20), // add x0, x1+ ]+ for (word, offset, expected) in cases {+ let encoded = try #require(ARM64Encoder.retargetPageOffset(word, offset: offset))+ let actual = [UInt8](encoded).le(UInt32.self, 0)+ #expect(actual == expected)+ #expect(ARM64Encoder.decodePageOffset(actual) == offset)+ #expect(ARM64Disassembler().disassembleOne(encoded, at: 0) != nil)+ }+ #expect(ARM64Encoder.retargetPageOffset(0xD503_201F, offset: 4) == nil)+ }++ /// Opt-in external corpus: no Apple firmware or extracted binaries checked+ /// in. Xcode passes TEST_RUNNER_KDK_PARITY_ROOT to the test process as+ /// KDK_PARITY_ROOT. Each JSON is the reference Export call's complete input.+ @Test(.enabled(if: ProcessInfo.processInfo.environment["KDK_PARITY_ROOT"] != nil))+ func referenceCorpusByteParity() throws {+ let root = try URL(fileURLWithPath: #require(ProcessInfo.processInfo.environment["KDK_PARITY_ROOT"]))+ let selected = ProcessInfo.processInfo.environment["KDK_PARITY_ENTRY"]+ let fm = FileManager.default+ struct Symbol: Decodable {+ var name: String+ var indirectName: String?+ var type: UInt8+ var sect: UInt8+ var desc: UInt16+ var value: UInt64+ var valueModel: 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 addressOnlyBinds: Bool+ var symbols: [Symbol]+ var references: [KDKReference]+ }+ var verified = 0+ for (label, kernel) in [("donor", "vphone600"), ("research", "vresearch101")] {+ let collectionURL = root.appending(path: "data/264beta/kernelcache.release.\(kernel).decompressed")+ let collection = try KDKKernelCollection(Data(contentsOf: collectionURL, options: .mappedIfSafe))+ 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 }+ #expect(files.count == collection.entries.count)+ for file in files {+ let input = try JSONDecoder().decode(Input.self, from: Data(contentsOf: file))+ if let selected, selected != input.entryID {+ continue+ }+ var image = try collection.image(input.entryID)+ // extract.go performs this before calling Export; the dump hook+ // intentionally captures Export arguments, not this preparation.+ 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: input.symbols.map(\.valueModel), references: input.references,+ addressOnlyBinds: input.addressOnlyBinds)+ let actual = try writer.export()+ let expected = try Data(contentsOf: corpus.appending(path: "out").appending(path: input.output))+ if actual != expected {+ let difference = zip(actual, expected).enumerated().first { $0.element.0 != $0.element.1 }?.offset ?? min(actual.count, expected.count)+ let destination = root.appending(path: "swift-\(label)-\(input.entryID)")+ try actual.write(to: destination)+ Issue.record("\(label)/\(input.entryID): first difference 0x\(String(difference, radix: 16)), Swift \(actual.count) vs Go \(expected.count) bytes; wrote \(destination.path)")+ return+ }+ verified += 1+ if verified % 20 == 0 {+ print("KDK parity: \(verified) images verified")+ }+ }+ }+ #expect(verified == (selected == nil ? 264 : 2))+ print("KDK parity: all \(verified) exports are byte-identical")+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swiftindex 0e8aebc9..5f8ad683 100644--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift@@ -161,6 +161,13 @@ public enum ARM64Encoder {return ARM64.encodeU32(insn)}+ /// BRAA Xn, Xm (Xm == 31 means SP). Apple clang -arch arm64e checked;+ /// Keystone 0.9.2 does not support pointer-authentication mnemonics.+ public static func encodeBRAA(rn: UInt32, rm: UInt32) -> Data? {+ guard rn < 31, rm < 32 else { return nil }+ return ARM64.encodeU32(0xD71F_0800 | (rn << 5) | rm)+ }+// MARK: - ADRP / ADD Encoding/// Encode ADRP instruction.@@ -171,7 +178,7 @@ public enum ARM64Encoder {public static func encodeADRP(rd: UInt32, pc: UInt64, target: UInt64) -> Data? {let pcPage = pc & ~0xFFFlet targetPage = target & ~0xFFF- let pageDelta = Int64(targetPage) - Int64(pcPage)+ let pageDelta = Int64(bitPattern: targetPage &- pcPage)let immVal = pageDelta >> 12guard immVal >= -(1 << 20), immVal < (1 << 20) else { return nil }let imm21 = UInt32(bitPattern: Int32(immVal)) & 0x1FFFFF@@ -360,3 +367,32 @@ public enum ARM64Encoder {return UInt64(Int64(pc) + offset)}}++public extension ARM64Encoder {+ /// Scale of the unsigned imm12 load/store family, including SIMD Q loads.+ /// This changes only an existing instruction's immediate, never its opcode.+ private static func pageOffsetScale(_ instruction: UInt32) -> UInt32? {+ if instruction & 0x3B00_0000 == 0x3900_0000 {+ let size = instruction >> 30+ if size == 0, instruction & 0x0480_0000 == 0x0480_0000 {+ return 16+ }+ return 1 << size+ }+ if instruction & 0xFFC0_0000 == 0x9100_0000 {+ return 1+ }+ return nil+ }++ static func decodePageOffset(_ instruction: UInt32) -> UInt32? {+ guard let scale = pageOffsetScale(instruction) else { return nil }+ return ((instruction >> 10) & 0xFFF) * scale+ }++ /// Same truncation of low alignment bits as the cache export's OFF12 fixup.+ static func retargetPageOffset(_ instruction: UInt32, offset: UInt32) -> Data? {+ guard offset < 4096, let scale = pageOffsetScale(instruction) else { return nil }+ return ARM64.encodeU32((instruction & 0xFFC0_03FF) | ((offset / scale) << 10))+ }+}