Run a virtual iPhone on an Apple Silicon Mac.
Swift
refactor: split firmware patch discovery code
Lakr8009b6b142e7
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader+Results.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader+Results.swiftnew file mode 100644index 00000000..0442ef46--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader+Results.swift@@ -0,0 +1,78 @@+extension CustomFirmwareCacheLoaderPatcher {+ // MARK: - Results++ /// The boot-arg string the gate is built around, and the code that loads it.+ public struct Anchor: Sendable, Equatable {+ /// Which of ``anchorTokens`` matched.+ public let token: String+ /// The whole null-terminated string the token sits inside.+ public let text: String+ /// `"__TEXT,__cstring"` and the like — where the string was found.+ public let sectionName: String+ /// File offset of the string's FIRST byte, which is what code addresses.+ public let stringFileOffset: Int+ public let stringVMA: UInt64+ /// Address of the matched substring, which differs from ``stringVMA``+ /// whenever the token is not itself the start of the string.+ public let matchVMA: UInt64+ /// File offset of the ADRP that forms the string's address.+ public let referenceFileOffset: Int+ public let referenceVMA: UInt64+ }++ /// The conditional branch that skips the unsecure-cache path — or the NOP a+ /// previous run already left in its place.+ public struct Gate: Sendable, Equatable {+ public let fileOffset: Int+ public let vma: UInt64+ /// Capstone's mnemonic: `cbz`/`cbnz`/`tbz`/`tbnz`/`b.<cond>`, or `nop`+ /// when this binary has already been patched.+ public let mnemonic: String+ public let operandString: String+ /// The call whose return value the gate tests, when one was found. The+ /// fallback path leaves this `nil`.+ public let callFileOffset: Int?+ public let callVMA: UInt64?+ /// Where the branch jumps when it is taken, i.e. past the unsecure path.+ /// `nil` once the gate is a NOP and there is no target left to read.+ public let targetVMA: UInt64?++ /// True when the site already holds this patch's own output.+ public var wasAlreadyNOP: Bool {+ mnemonic == "nop"+ }++ /// How the gate reads in disassembly.+ public var text: String {+ operandString.isEmpty ? mnemonic : "\(mnemonic) \(operandString)"+ }+ }++ /// What a run did.+ public enum Outcome: String, Sendable, Equatable {+ /// The gate already held a NOP. Nothing was written.+ case alreadyPatched+ /// `dryRun` was set, so the site was located and reported only.+ case wouldPatch+ /// The branch was replaced with a NOP.+ case patched+ }++ /// The outcome of one run, and the site it acted on.+ public struct Report: Sendable {+ public let outcome: Outcome+ public let anchor: Anchor+ public let gate: Gate+ /// The write, in the shape the Python's reference capture records it.+ /// `nil` unless bytes actually changed.+ public let record: PatchRecord?+ /// Slot hashes recomputed, empty unless `reattestsCodeSignature` was set.+ public let reattestedSlots: [CustomFirmwareSlotRehash]++ /// Sites whose bytes this run changed. The parity number: the Python+ /// writes exactly one, and so must this.+ public var sitesWritten: Int {+ record == nil ? 0 : 1+ }+ }+}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader+StringAnchor.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader+StringAnchor.swiftnew file mode 100644index 00000000..5650ec03--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader+StringAnchor.swift@@ -0,0 +1,151 @@+import Capstone+import Foundation++extension CustomFirmwareCacheLoaderPatcher {+ // MARK: - The boot-arg string++ /// One `anchorTokens` match, resolved to the whole C string around it.+ struct StringHit: Sendable, Equatable {+ let token: String+ let text: String+ let sectionName: String+ let stringFileOffset: Int+ let stringVMA: UInt64+ let matchVMA: UInt64+ }++ /// Every token match, most specific token first and, within a token,+ /// `__TEXT,__cstring` before the rest.+ ///+ /// Searching sections rather than the raw file — which is what the Python+ /// does — is what keeps a byte sequence inside the code signature or the+ /// link-edit tables from being mistaken for a string literal.+ static func stringHits(in data: Data, sections: [String: MachOSectionInfo]) -> [StringHit] {+ // A zerofill section has no file bytes, and its `offset` field is 0;+ // searching it would walk the Mach-O header instead.+ let searchable = sections.values+ .filter { $0.fileOffset > 0 && $0.size > 0 }+ .filter { Int($0.fileOffset) + Int($0.size) <= data.count }+ .sorted {+ let cstring = "__cstring"+ if ($0.sectionName == cstring) != ($1.sectionName == cstring) {+ return $0.sectionName == cstring+ }+ return $0.fileOffset < $1.fileOffset+ }++ var hits: [StringHit] = []+ for token in anchorTokens {+ let needle = Array(token.utf8)+ for section in searchable {+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard let match = firstOccurrence(of: needle, in: data, from: start, to: end) else {+ continue+ }+ let stringStart = cStringStart(in: data, containing: match, notBefore: start)+ let stringEnd = cStringEnd(in: data, from: stringStart, notAfter: end)+ hits.append(StringHit(+ token: token,+ text: String(decoding: data[stringStart ..< stringEnd], as: UTF8.self),+ sectionName: "\(section.segmentName),\(section.sectionName)",+ stringFileOffset: stringStart,+ stringVMA: section.address + UInt64(stringStart - start),+ matchVMA: section.address + UInt64(match - start),+ ))+ break+ }+ }+ return hits+ }++ static func firstOccurrence(of needle: [UInt8], in data: Data, from: Int, to: Int) -> Int? {+ guard !needle.isEmpty, to - from >= needle.count else { return nil }+ for offset in from ... (to - needle.count) {+ var matched = true+ for (index, byte) in needle.enumerated() where data[offset + index] != byte {+ matched = false+ break+ }+ if matched {+ return offset+ }+ }+ return nil+ }++ /// The first byte of the null-terminated string containing `offset`.+ ///+ /// Code forms the address of a literal's START, never of a substring inside+ /// it, so a token that matched mid-string has to be walked back before its+ /// address can be looked for.+ static func cStringStart(in data: Data, containing offset: Int, notBefore floor: Int) -> Int {+ var position = offset - 1+ while position >= floor, data[position] != 0 {+ position -= 1+ }+ return position + 1+ }++ static func cStringEnd(in data: Data, from start: Int, notAfter ceiling: Int) -> Int {+ var position = start+ while position < ceiling, data[position] != 0 {+ position += 1+ }+ return position+ }++ // MARK: - The string xref++ /// The ADRP of the first ADRP+ADD pair in `__TEXT,__text` that forms+ /// `targetVMA`.+ ///+ /// The pair need not be adjacent — the compiler interleaves other setup+ /// between them — so an ADRP is remembered per destination register and+ /// matched against a later ADD that reads it. Everything is read from+ /// Capstone's decoded operands: the ADRP's immediate is already the absolute+ /// page, and the ADD's is the page offset.+ static func findStringReference(+ in data: Data,+ text: MachOSectionInfo,+ targetVMA: UInt64,+ ) -> (fileOffset: Int, vma: UInt64)? {+ let targetPage = Int64(targetVMA & ~0xFFF)+ let targetPageOffset = Int64(targetVMA & 0xFFF)+ let disassembler = ARM64Disassembler()++ // ADRP destination register -> (instruction index, address, page).+ var pendingADRP: [UInt32: (index: Int, fileOffset: Int, vma: UInt64, page: Int64)] = [:]++ for (index, offset) in wordOffsets(of: text).enumerated() {+ let vma = text.address + UInt64(offset - Int(text.fileOffset))+ guard let instruction = disassembler.disassembleOne(in: data, at: offset, address: vma),+ let operands = instruction.aarch64?.operands+ else { continue }++ switch instruction.mnemonic {+ case "adrp":+ guard operands.count >= 2,+ operands[0].type == AARCH64_OP_REG,+ operands[1].type == AARCH64_OP_IMM+ else { continue }+ pendingADRP[UInt32(operands[0].reg.rawValue)] = (index, offset, vma, operands[1].imm)++ case "add":+ guard operands.count >= 3,+ operands[1].type == AARCH64_OP_REG,+ operands[2].type == AARCH64_OP_IMM,+ let adrp = pendingADRP[UInt32(operands[1].reg.rawValue)],+ adrp.page == targetPage,+ operands[2].imm == targetPageOffset,+ index - adrp.index <= maxADRPToADDInstructions+ else { continue }+ return (adrp.fileOffset, adrp.vma)++ default:+ continue+ }+ }+ return nil+ }+}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader.swiftindex 84f920cd..658e395f 100644--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader.swift+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheloader.swift@@ -88,83 +88,6 @@ public enum CustomFirmwareCacheLoaderPatcher {/// The no-call fallback window, used only when no call follows the xref.static let maxFallbackInstructions = 32- // MARK: - Results-- /// The boot-arg string the gate is built around, and the code that loads it.- public struct Anchor: Sendable, Equatable {- /// Which of ``anchorTokens`` matched.- public let token: String- /// The whole null-terminated string the token sits inside.- public let text: String- /// `"__TEXT,__cstring"` and the like — where the string was found.- public let sectionName: String- /// File offset of the string's FIRST byte, which is what code addresses.- public let stringFileOffset: Int- public let stringVMA: UInt64- /// Address of the matched substring, which differs from ``stringVMA``- /// whenever the token is not itself the start of the string.- public let matchVMA: UInt64- /// File offset of the ADRP that forms the string's address.- public let referenceFileOffset: Int- public let referenceVMA: UInt64- }-- /// The conditional branch that skips the unsecure-cache path — or the NOP a- /// previous run already left in its place.- public struct Gate: Sendable, Equatable {- public let fileOffset: Int- public let vma: UInt64- /// Capstone's mnemonic: `cbz`/`cbnz`/`tbz`/`tbnz`/`b.<cond>`, or `nop`- /// when this binary has already been patched.- public let mnemonic: String- public let operandString: String- /// The call whose return value the gate tests, when one was found. The- /// fallback path leaves this `nil`.- public let callFileOffset: Int?- public let callVMA: UInt64?- /// Where the branch jumps when it is taken, i.e. past the unsecure path.- /// `nil` once the gate is a NOP and there is no target left to read.- public let targetVMA: UInt64?-- /// True when the site already holds this patch's own output.- public var wasAlreadyNOP: Bool {- mnemonic == "nop"- }-- /// How the gate reads in disassembly.- public var text: String {- operandString.isEmpty ? mnemonic : "\(mnemonic) \(operandString)"- }- }-- /// What a run did.- public enum Outcome: String, Sendable, Equatable {- /// The gate already held a NOP. Nothing was written.- case alreadyPatched- /// `dryRun` was set, so the site was located and reported only.- case wouldPatch- /// The branch was replaced with a NOP.- case patched- }-- /// The outcome of one run, and the site it acted on.- public struct Report: Sendable {- public let outcome: Outcome- public let anchor: Anchor- public let gate: Gate- /// The write, in the shape the Python's reference capture records it.- /// `nil` unless bytes actually changed.- public let record: PatchRecord?- /// Slot hashes recomputed, empty unless `reattestsCodeSignature` was set.- public let reattestedSlots: [CustomFirmwareSlotRehash]-- /// Sites whose bytes this run changed. The parity number: the Python- /// writes exactly one, and so must this.- public var sitesWritten: Int {- record == nil ? 0 : 1- }- }-/// Where progress goes when the caller does not say. The Python prints to/// stdout and `cfw_install*.sh` captures that, so this does too.public static let stdoutLog: @Sendable (String) -> Void = { print($0) }@@ -373,153 +296,6 @@ public enum CustomFirmwareCacheLoaderPatcher {)}- // MARK: - The boot-arg string-- /// One `anchorTokens` match, resolved to the whole C string around it.- struct StringHit: Sendable, Equatable {- let token: String- let text: String- let sectionName: String- let stringFileOffset: Int- let stringVMA: UInt64- let matchVMA: UInt64- }-- /// Every token match, most specific token first and, within a token,- /// `__TEXT,__cstring` before the rest.- ///- /// Searching sections rather than the raw file — which is what the Python- /// does — is what keeps a byte sequence inside the code signature or the- /// link-edit tables from being mistaken for a string literal.- static func stringHits(in data: Data, sections: [String: MachOSectionInfo]) -> [StringHit] {- // A zerofill section has no file bytes, and its `offset` field is 0;- // searching it would walk the Mach-O header instead.- let searchable = sections.values- .filter { $0.fileOffset > 0 && $0.size > 0 }- .filter { Int($0.fileOffset) + Int($0.size) <= data.count }- .sorted {- let cstring = "__cstring"- if ($0.sectionName == cstring) != ($1.sectionName == cstring) {- return $0.sectionName == cstring- }- return $0.fileOffset < $1.fileOffset- }-- var hits: [StringHit] = []- for token in anchorTokens {- let needle = Array(token.utf8)- for section in searchable {- let start = Int(section.fileOffset)- let end = start + Int(section.size)- guard let match = firstOccurrence(of: needle, in: data, from: start, to: end) else {- continue- }- let stringStart = cStringStart(in: data, containing: match, notBefore: start)- let stringEnd = cStringEnd(in: data, from: stringStart, notAfter: end)- hits.append(StringHit(- token: token,- text: String(decoding: data[stringStart ..< stringEnd], as: UTF8.self),- sectionName: "\(section.segmentName),\(section.sectionName)",- stringFileOffset: stringStart,- stringVMA: section.address + UInt64(stringStart - start),- matchVMA: section.address + UInt64(match - start),- ))- break- }- }- return hits- }-- static func firstOccurrence(of needle: [UInt8], in data: Data, from: Int, to: Int) -> Int? {- guard !needle.isEmpty, to - from >= needle.count else { return nil }- for offset in from ... (to - needle.count) {- var matched = true- for (index, byte) in needle.enumerated() where data[offset + index] != byte {- matched = false- break- }- if matched {- return offset- }- }- return nil- }-- /// The first byte of the null-terminated string containing `offset`.- ///- /// Code forms the address of a literal's START, never of a substring inside- /// it, so a token that matched mid-string has to be walked back before its- /// address can be looked for.- static func cStringStart(in data: Data, containing offset: Int, notBefore floor: Int) -> Int {- var position = offset - 1- while position >= floor, data[position] != 0 {- position -= 1- }- return position + 1- }-- static func cStringEnd(in data: Data, from start: Int, notAfter ceiling: Int) -> Int {- var position = start- while position < ceiling, data[position] != 0 {- position += 1- }- return position- }-- // MARK: - The string xref-- /// The ADRP of the first ADRP+ADD pair in `__TEXT,__text` that forms- /// `targetVMA`.- ///- /// The pair need not be adjacent — the compiler interleaves other setup- /// between them — so an ADRP is remembered per destination register and- /// matched against a later ADD that reads it. Everything is read from- /// Capstone's decoded operands: the ADRP's immediate is already the absolute- /// page, and the ADD's is the page offset.- static func findStringReference(- in data: Data,- text: MachOSectionInfo,- targetVMA: UInt64,- ) -> (fileOffset: Int, vma: UInt64)? {- let targetPage = Int64(targetVMA & ~0xFFF)- let targetPageOffset = Int64(targetVMA & 0xFFF)- let disassembler = ARM64Disassembler()-- // ADRP destination register -> (instruction index, address, page).- var pendingADRP: [UInt32: (index: Int, fileOffset: Int, vma: UInt64, page: Int64)] = [:]-- for (index, offset) in wordOffsets(of: text).enumerated() {- let vma = text.address + UInt64(offset - Int(text.fileOffset))- guard let instruction = disassembler.disassembleOne(in: data, at: offset, address: vma),- let operands = instruction.aarch64?.operands- else { continue }-- switch instruction.mnemonic {- case "adrp":- guard operands.count >= 2,- operands[0].type == AARCH64_OP_REG,- operands[1].type == AARCH64_OP_IMM- else { continue }- pendingADRP[UInt32(operands[0].reg.rawValue)] = (index, offset, vma, operands[1].imm)-- case "add":- guard operands.count >= 3,- operands[1].type == AARCH64_OP_REG,- operands[2].type == AARCH64_OP_IMM,- let adrp = pendingADRP[UInt32(operands[1].reg.rawValue)],- adrp.page == targetPage,- operands[2].imm == targetPageOffset,- index - adrp.index <= maxADRPToADDInstructions- else { continue }- return (adrp.fileOffset, adrp.vma)-- default:- continue- }- }- return nil- }-// MARK: - The gate/// The conditional branch that consumes the boot-arg lookup's result.diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod+ObjCMetadata.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod+ObjCMetadata.swiftnew file mode 100644index 00000000..656fb4aa--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod+ObjCMetadata.swift@@ -0,0 +1,256 @@+import Foundation++extension CustomFirmwareDiskimagesiod {+ // MARK: - ObjC metadata++ /// selector cstring → selref → method-list entry → IMP.+ static func resolveIMPViaObjCMetadata(+ in data: Data,+ sections: [String: MachOSectionInfo],+ ) throws -> (impVA: UInt64, anchor: Anchor) {+ guard let selectorVA = selectorStringVA(in: data, sections: sections) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): selector '\(selector)' not present in the image",+ )+ }++ // A method-list `name` field points at the uniqued `SEL *` (the selref)+ // on every toolchain that emits `__objc_selrefs`, and straight at the+ // cstring in a "direct selector" list. Both are accepted, exactly as+ // the Python does, so a missing selref is not fatal on its own.+ var targets: Set<UInt64> = [selectorVA]+ if let selrefsSection = section(sections, "__DATA_CONST,__objc_selrefs", "__DATA,__objc_selrefs", "__AUTH_CONST,__objc_selrefs"),+ let selrefVA = selectorReferenceVA(+ in: data,+ selrefs: selrefsSection,+ selectorVA: selectorVA,+ imageBase: imageBase(sections),+ )+ {+ targets.insert(selrefVA)+ }++ // Preferred: a structural walk of the packed relative method lists.+ if let methlist = sections[methodListSectionKey] {+ let imps = relativeMethodListIMPs(in: data, section: methlist, naming: targets)+ if let impVA = try single(imps, strategy: methodListSectionKey) {+ return (impVA, .relativeMethodList)+ }+ }++ // Fallback: the Python's own strategy, a 4-byte-strided scan, over the+ // same sections it tries. It covers two cases the structural walk does+ // not — a `__TEXT,__objc_methlist` whose list chain this parser cannot+ // follow to the end, and the older layout where method lists are+ // embedded in `class_ro_t` records inside an `__objc_const` section and+ // so are not packed back to back. Running it over the method-list+ // section too is what keeps this port from ever being *less* capable+ // than the Python it replaces. Every candidate still has to resolve to+ // a single agreed-upon IMP, and that IMP still has to pass ``makeSite``.+ for key in scannedSectionKeys {+ guard let scanned = sections[key] else { continue }+ let imps = scanRelativeMethodEntryIMPs(in: data, section: scanned, naming: targets)+ if let impVA = try single(imps, strategy: key) {+ return (impVA, .methodListScan)+ }+ }++ throw PatcherError.patchSiteNotFound(+ "\(method): no ObjC method-list entry names '\(selector)'",+ )+ }++ /// The single distinct IMP in `candidates`, `nil` when there are none.+ ///+ /// More than one distinct IMP means the image names this selector from+ /// several implementations and the patch has no unambiguous target — which+ /// stops the install rather than picking one.+ static func single(_ candidates: [UInt64], strategy: String) throws -> UInt64? {+ let distinct = Set(candidates)+ guard let first = distinct.first else { return nil }+ guard distinct.count == 1 else {+ let list = distinct.sorted().map { "0x\(hex($0))" }.joined(separator: ", ")+ throw PatcherError.invalidFormat(+ "\(method): \(strategy) names '\(selector)' from \(distinct.count) "+ + "implementations (\(list)) — no unambiguous target",+ )+ }+ return first+ }++ /// Virtual address of the selector cstring.+ ///+ /// Looked for in `__TEXT,__objc_methname` first — the section that exists+ /// for exactly this — then `__TEXT,__cstring`, then anywhere in the file,+ /// which is the Python's only search. A hit has to start a string (the+ /// preceding byte is NUL, or it is the first byte of its section) so a+ /// selector that is the tail of a longer one cannot match.+ static func selectorStringVA(in data: Data, sections: [String: MachOSectionInfo]) -> UInt64? {+ let needle = Data(selector.utf8) + [0]++ for key in stringSectionKeys {+ guard let section = sections[key] else { continue }+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard start >= 0, end <= data.count, start < end else { continue }+ guard let found = firstStringStart(of: needle, in: data, range: start ..< end) else { continue }+ return section.address + UInt64(found - start)+ }++ guard let found = firstStringStart(of: needle, in: data, range: 0 ..< data.count) else { return nil }+ return virtualAddress(ofFileOffset: found, sections: sections)+ }++ /// First occurrence of `needle` in `range` that begins a C string.+ static func firstStringStart(of needle: Data, in data: Data, range: Range<Int>) -> Int? {+ var searchFrom = range.lowerBound+ while searchFrom < range.upperBound,+ let found = data.range(of: needle, in: searchFrom ..< range.upperBound)+ {+ if found.lowerBound == range.lowerBound || data[found.lowerBound - 1] == 0 {+ return found.lowerBound+ }+ searchFrom = found.lowerBound + 1+ }+ return nil+ }++ /// The `__objc_selrefs` slot pointing at `selectorVA`.+ ///+ /// The slot holds a *chained fixup*, not a linked address, so the raw+ /// quadword rarely equals the target. Four interpretations are tried in+ /// decreasing strictness, and the first that matches anywhere in the+ /// section wins:+ ///+ /// 1. the value itself — an already-linked or non-chained image;+ /// 2. `DYLD_CHAINED_PTR_64` rebase: the low 36 bits are an offset from the+ /// image's preferred base, the rest are `high8` / `next` / `bind`;+ /// 3. the low 48 bits, for the older 8-byte fixup spellings;+ /// 4. the low 32 bits, which is the Python's catch-all.+ static func selectorReferenceVA(+ in data: Data,+ selrefs: MachOSectionInfo,+ selectorVA: UInt64,+ imageBase: UInt64,+ ) -> UInt64? {+ let start = Int(selrefs.fileOffset)+ let count = Int(selrefs.size)+ guard start >= 0, start + count <= data.count else { return nil }++ let matchers: [(UInt64) -> Bool] = [+ { $0 == selectorVA },+ { imageBase &+ ($0 & chainedRebaseTargetMask) == selectorVA },+ { ($0 & 0x0000_FFFF_FFFF_FFFF) == selectorVA },+ { ($0 & 0xFFFF_FFFF) == (selectorVA & 0xFFFF_FFFF) },+ ]+ for matches in matchers {+ var offset = 0+ while offset + 8 <= count {+ if matches(data.loadLE(UInt64.self, at: start + offset)) {+ return selrefs.address + UInt64(offset)+ }+ offset += 8+ }+ }+ return nil+ }++ // MARK: - Method lists++ /// Walk `__TEXT,__objc_methlist` as what it is: relative method lists laid+ /// end to end, each one 8-byte aligned.+ ///+ /// A list is `{uint32 entsizeAndFlags, uint32 count}` followed by `count`+ /// entries of `entsizeAndFlags & 0xFFFC` bytes. Bit 31 marks the relative+ /// form, whose entry is three `int32` fields — `name`, `types`, `imp` —+ /// each relative to *its own* address.+ ///+ /// Returns the IMP virtual address of every entry whose `name` field+ /// resolves into `targets`.+ static func relativeMethodListIMPs(+ in data: Data,+ section: MachOSectionInfo,+ naming targets: Set<UInt64>,+ ) -> [UInt64] {+ let base = Int(section.fileOffset)+ let size = Int(section.size)+ guard base >= 0, size > 0, base + size <= data.count else { return [] }++ var found: [UInt64] = []+ var offset = 0+ while offset + methodListHeaderSize <= size {+ let header = data.loadLE(UInt32.self, at: base + offset)+ let count = Int(data.loadLE(UInt32.self, at: base + offset + 4))+ let entrySize = Int(header & methodListEntrySizeMask)+ guard header & relativeMethodListFlag != 0,+ entrySize == relativeMethodEntrySize,+ count > 0,+ methodListHeaderSize + entrySize * count <= size - offset+ else { break }++ let entriesStart = offset + methodListHeaderSize+ for index in 0 ..< count {+ let entryOffset = entriesStart + index * entrySize+ if let impVA = relativeMethodEntryIMP(+ in: data,+ fileOffset: base + entryOffset,+ virtualAddress: section.address + UInt64(entryOffset),+ naming: targets,+ ) {+ found.append(impVA)+ }+ }++ offset = alignUp(entriesStart + entrySize * count, to: methodListAlignment)+ }+ return found+ }++ /// The Python's strategy, kept for the layouts the structural walk cannot+ /// parse: treat every 4-byte-aligned word in `section` as the `name` field+ /// of a relative method entry and keep the ones that resolve into `targets`.+ static func scanRelativeMethodEntryIMPs(+ in data: Data,+ section: MachOSectionInfo,+ naming targets: Set<UInt64>,+ ) -> [UInt64] {+ let base = Int(section.fileOffset)+ let size = Int(section.size)+ guard base >= 0, size >= relativeMethodEntrySize, base + size <= data.count else { return [] }++ var found: [UInt64] = []+ var offset = 0+ while offset + relativeMethodEntrySize <= size {+ if let impVA = relativeMethodEntryIMP(+ in: data,+ fileOffset: base + offset,+ virtualAddress: section.address + UInt64(offset),+ naming: targets,+ ) {+ found.append(impVA)+ }+ offset += 4+ }+ return found+ }++ /// `imp` of the relative method entry at `fileOffset`, when its `name`+ /// field resolves into `targets`.+ static func relativeMethodEntryIMP(+ in data: Data,+ fileOffset: Int,+ virtualAddress: UInt64,+ naming targets: Set<UInt64>,+ ) -> UInt64? {+ guard fileOffset >= 0, fileOffset + relativeMethodEntrySize <= data.count else { return nil }+ let nameRelative = Int32(bitPattern: data.loadLE(UInt32.self, at: fileOffset))+ let nameVA = UInt64(bitPattern: Int64(bitPattern: virtualAddress) &+ Int64(nameRelative))+ guard targets.contains(nameVA) else { return nil }++ let impFieldOffset = fileOffset + 8+ let impFieldVA = virtualAddress &+ 8+ let impRelative = Int32(bitPattern: data.loadLE(UInt32.self, at: impFieldOffset))+ return UInt64(bitPattern: Int64(bitPattern: impFieldVA) &+ Int64(impRelative))+ }++}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod.swiftindex 44cda8bb..30521d76 100644--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod.swift+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod.swift@@ -369,258 +369,6 @@ public enum CustomFirmwareDiskimagesiod {return site}- // MARK: - ObjC metadata-- /// selector cstring → selref → method-list entry → IMP.- static func resolveIMPViaObjCMetadata(- in data: Data,- sections: [String: MachOSectionInfo],- ) throws -> (impVA: UInt64, anchor: Anchor) {- guard let selectorVA = selectorStringVA(in: data, sections: sections) else {- throw PatcherError.patchSiteNotFound(- "\(component): selector '\(selector)' not present in the image",- )- }-- // A method-list `name` field points at the uniqued `SEL *` (the selref)- // on every toolchain that emits `__objc_selrefs`, and straight at the- // cstring in a "direct selector" list. Both are accepted, exactly as- // the Python does, so a missing selref is not fatal on its own.- var targets: Set<UInt64> = [selectorVA]- if let selrefsSection = section(sections, "__DATA_CONST,__objc_selrefs", "__DATA,__objc_selrefs", "__AUTH_CONST,__objc_selrefs"),- let selrefVA = selectorReferenceVA(- in: data,- selrefs: selrefsSection,- selectorVA: selectorVA,- imageBase: imageBase(sections),- )- {- targets.insert(selrefVA)- }-- // Preferred: a structural walk of the packed relative method lists.- if let methlist = sections[methodListSectionKey] {- let imps = relativeMethodListIMPs(in: data, section: methlist, naming: targets)- if let impVA = try single(imps, strategy: methodListSectionKey) {- return (impVA, .relativeMethodList)- }- }-- // Fallback: the Python's own strategy, a 4-byte-strided scan, over the- // same sections it tries. It covers two cases the structural walk does- // not — a `__TEXT,__objc_methlist` whose list chain this parser cannot- // follow to the end, and the older layout where method lists are- // embedded in `class_ro_t` records inside an `__objc_const` section and- // so are not packed back to back. Running it over the method-list- // section too is what keeps this port from ever being *less* capable- // than the Python it replaces. Every candidate still has to resolve to- // a single agreed-upon IMP, and that IMP still has to pass ``makeSite``.- for key in scannedSectionKeys {- guard let scanned = sections[key] else { continue }- let imps = scanRelativeMethodEntryIMPs(in: data, section: scanned, naming: targets)- if let impVA = try single(imps, strategy: key) {- return (impVA, .methodListScan)- }- }-- throw PatcherError.patchSiteNotFound(- "\(method): no ObjC method-list entry names '\(selector)'",- )- }-- /// The single distinct IMP in `candidates`, `nil` when there are none.- ///- /// More than one distinct IMP means the image names this selector from- /// several implementations and the patch has no unambiguous target — which- /// stops the install rather than picking one.- static func single(_ candidates: [UInt64], strategy: String) throws -> UInt64? {- let distinct = Set(candidates)- guard let first = distinct.first else { return nil }- guard distinct.count == 1 else {- let list = distinct.sorted().map { "0x\(hex($0))" }.joined(separator: ", ")- throw PatcherError.invalidFormat(- "\(method): \(strategy) names '\(selector)' from \(distinct.count) "- + "implementations (\(list)) — no unambiguous target",- )- }- return first- }-- /// Virtual address of the selector cstring.- ///- /// Looked for in `__TEXT,__objc_methname` first — the section that exists- /// for exactly this — then `__TEXT,__cstring`, then anywhere in the file,- /// which is the Python's only search. A hit has to start a string (the- /// preceding byte is NUL, or it is the first byte of its section) so a- /// selector that is the tail of a longer one cannot match.- static func selectorStringVA(in data: Data, sections: [String: MachOSectionInfo]) -> UInt64? {- let needle = Data(selector.utf8) + [0]-- for key in stringSectionKeys {- guard let section = sections[key] else { continue }- let start = Int(section.fileOffset)- let end = start + Int(section.size)- guard start >= 0, end <= data.count, start < end else { continue }- guard let found = firstStringStart(of: needle, in: data, range: start ..< end) else { continue }- return section.address + UInt64(found - start)- }-- guard let found = firstStringStart(of: needle, in: data, range: 0 ..< data.count) else { return nil }- return virtualAddress(ofFileOffset: found, sections: sections)- }-- /// First occurrence of `needle` in `range` that begins a C string.- static func firstStringStart(of needle: Data, in data: Data, range: Range<Int>) -> Int? {- var searchFrom = range.lowerBound- while searchFrom < range.upperBound,- let found = data.range(of: needle, in: searchFrom ..< range.upperBound)- {- if found.lowerBound == range.lowerBound || data[found.lowerBound - 1] == 0 {- return found.lowerBound- }- searchFrom = found.lowerBound + 1- }- return nil- }-- /// The `__objc_selrefs` slot pointing at `selectorVA`.- ///- /// The slot holds a *chained fixup*, not a linked address, so the raw- /// quadword rarely equals the target. Four interpretations are tried in- /// decreasing strictness, and the first that matches anywhere in the- /// section wins:- ///- /// 1. the value itself — an already-linked or non-chained image;- /// 2. `DYLD_CHAINED_PTR_64` rebase: the low 36 bits are an offset from the- /// image's preferred base, the rest are `high8` / `next` / `bind`;- /// 3. the low 48 bits, for the older 8-byte fixup spellings;- /// 4. the low 32 bits, which is the Python's catch-all.- static func selectorReferenceVA(- in data: Data,- selrefs: MachOSectionInfo,- selectorVA: UInt64,- imageBase: UInt64,- ) -> UInt64? {- let start = Int(selrefs.fileOffset)- let count = Int(selrefs.size)- guard start >= 0, start + count <= data.count else { return nil }-- let matchers: [(UInt64) -> Bool] = [- { $0 == selectorVA },- { imageBase &+ ($0 & chainedRebaseTargetMask) == selectorVA },- { ($0 & 0x0000_FFFF_FFFF_FFFF) == selectorVA },- { ($0 & 0xFFFF_FFFF) == (selectorVA & 0xFFFF_FFFF) },- ]- for matches in matchers {- var offset = 0- while offset + 8 <= count {- if matches(data.loadLE(UInt64.self, at: start + offset)) {- return selrefs.address + UInt64(offset)- }- offset += 8- }- }- return nil- }-- // MARK: - Method lists-- /// Walk `__TEXT,__objc_methlist` as what it is: relative method lists laid- /// end to end, each one 8-byte aligned.- ///- /// A list is `{uint32 entsizeAndFlags, uint32 count}` followed by `count`- /// entries of `entsizeAndFlags & 0xFFFC` bytes. Bit 31 marks the relative- /// form, whose entry is three `int32` fields — `name`, `types`, `imp` —- /// each relative to *its own* address.- ///- /// Returns the IMP virtual address of every entry whose `name` field- /// resolves into `targets`.- static func relativeMethodListIMPs(- in data: Data,- section: MachOSectionInfo,- naming targets: Set<UInt64>,- ) -> [UInt64] {- let base = Int(section.fileOffset)- let size = Int(section.size)- guard base >= 0, size > 0, base + size <= data.count else { return [] }-- var found: [UInt64] = []- var offset = 0- while offset + methodListHeaderSize <= size {- let header = data.loadLE(UInt32.self, at: base + offset)- let count = Int(data.loadLE(UInt32.self, at: base + offset + 4))- let entrySize = Int(header & methodListEntrySizeMask)- guard header & relativeMethodListFlag != 0,- entrySize == relativeMethodEntrySize,- count > 0,- methodListHeaderSize + entrySize * count <= size - offset- else { break }-- let entriesStart = offset + methodListHeaderSize- for index in 0 ..< count {- let entryOffset = entriesStart + index * entrySize- if let impVA = relativeMethodEntryIMP(- in: data,- fileOffset: base + entryOffset,- virtualAddress: section.address + UInt64(entryOffset),- naming: targets,- ) {- found.append(impVA)- }- }-- offset = alignUp(entriesStart + entrySize * count, to: methodListAlignment)- }- return found- }-- /// The Python's strategy, kept for the layouts the structural walk cannot- /// parse: treat every 4-byte-aligned word in `section` as the `name` field- /// of a relative method entry and keep the ones that resolve into `targets`.- static func scanRelativeMethodEntryIMPs(- in data: Data,- section: MachOSectionInfo,- naming targets: Set<UInt64>,- ) -> [UInt64] {- let base = Int(section.fileOffset)- let size = Int(section.size)- guard base >= 0, size >= relativeMethodEntrySize, base + size <= data.count else { return [] }-- var found: [UInt64] = []- var offset = 0- while offset + relativeMethodEntrySize <= size {- if let impVA = relativeMethodEntryIMP(- in: data,- fileOffset: base + offset,- virtualAddress: section.address + UInt64(offset),- naming: targets,- ) {- found.append(impVA)- }- offset += 4- }- return found- }-- /// `imp` of the relative method entry at `fileOffset`, when its `name`- /// field resolves into `targets`.- static func relativeMethodEntryIMP(- in data: Data,- fileOffset: Int,- virtualAddress: UInt64,- naming targets: Set<UInt64>,- ) -> UInt64? {- guard fileOffset >= 0, fileOffset + relativeMethodEntrySize <= data.count else { return nil }- let nameRelative = Int32(bitPattern: data.loadLE(UInt32.self, at: fileOffset))- let nameVA = UInt64(bitPattern: Int64(bitPattern: virtualAddress) &+ Int64(nameRelative))- guard targets.contains(nameVA) else { return nil }-- let impFieldOffset = fileOffset + 8- let impFieldVA = virtualAddress &+ 8- let impRelative = Int32(bitPattern: data.loadLE(UInt32.self, at: impFieldOffset))- return UInt64(bitPattern: Int64(bitPattern: impFieldVA) &+ Int64(impRelative))- }-// MARK: - Recordingprivate static func makeRecord(site: Site, patched: Data) -> PatchRecord {diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsam.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsam.swiftindex 35cf569b..150f7777 100644--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsam.swift+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsam.swift@@ -68,7 +68,6 @@// `CustomFirmwareMachOCodeSignature`, short tail slot included, and the result passes// `codesign -v`.-import Capstoneimport Foundationpublic enum CustomFirmwareJetsamPatcher {@@ -109,9 +108,6 @@ public enum CustomFirmwareJetsamPatcher {/// a return block.static let returnBlockProbeInstructions = 8- /// `ARM64Disassembler` is stateless across calls and `Sendable`.- private static let disassembler = ARM64Disassembler()-// MARK: - Outcome/// What one run did.@@ -318,348 +314,4 @@ public enum CustomFirmwareJetsamPatcher {rehashes: rehashes,)}-- // MARK: - Image-- /// The parts of the Mach-O this patch reads: `__TEXT,__text`, and every- /// file-backed section, so a string hit can be turned into a VA.- struct Image {- let data: Data- let textOffset: Int- let textSize: Int- let textVMA: UInt64- /// File-backed sections, in file order. Zero-fill sections (`__bss`,- /// `__common`) are dropped: their `fileOffset` is 0, so leaving them in- /// lets one claim the range `[0, size)` and mislocate a hit in the- /// Mach-O header.- let sections: [MachOSectionInfo]-- init(data rawData: Data) throws {- // Zero-base so the integer subscripts used throughout are valid.- let data = rawData.startIndex == 0 ? rawData : Data(rawData)- guard data.count > 32, data.loadLE(UInt32.self, at: 0) == 0xFEED_FACF else {- throw PatcherError.invalidFormat("launchd jetsam: not a 64-bit Mach-O")- }- let parsed = MachOParser.parseSections(from: data)- guard let text = parsed["__TEXT,__text"] else {- throw PatcherError.invalidFormat("launchd jetsam: __TEXT,__text not found")- }- guard Int(text.fileOffset) + Int(text.size) <= data.count else {- throw PatcherError.invalidFormat("launchd jetsam: __TEXT,__text runs past the file")- }- self.data = data- textOffset = Int(text.fileOffset)- textSize = Int(text.size)- textVMA = text.address- sections = parsed.values- .filter { $0.fileOffset != 0 && $0.size != 0 }- .sorted { $0.fileOffset < $1.fileOffset }- }-- var textEnd: Int {- textOffset + textSize- }-- func isInText(_ offset: Int) -> Bool {- offset >= textOffset && offset < textEnd- }-- /// VA of a `__TEXT,__text` file offset. `__text` is one contiguous- /// mapping, so the two differ by a constant.- func virtualAddress(ofTextOffset offset: Int) -> UInt64 {- textVMA &+ UInt64(offset - textOffset)- }-- /// The file-backed section containing `offset`, if any.- func section(containing offset: Int) -> MachOSectionInfo? {- sections.first {- offset >= Int($0.fileOffset) && offset < Int($0.fileOffset) + Int($0.size)- }- }- }-- // MARK: - Reveal-- /// Everything step 4 needs, plus what the log prints about how it got there.- struct Site {- let anchor: String- let stringVMA: UInt64- let xrefOffset: Int- let functionOffset: Int- let gateOffset: Int- let returnBlockOffset: Int- /// True when `gateOffset` already holds the unconditional branch.- let isAlreadyPatched: Bool- }-- /// Walk the anchors in order, taking the first that resolves all the way to- /// a gate. An anchor that resolves partway — present but with no xref, or- /// an xref with no qualifying branch — is abandoned for the next one, which- /// is what the reference does.- static func locate(in image: Image, log: ((String) -> Void)? = nil) throws -> Site? {- for anchor in panicStringAnchors {- guard let hit = image.data.range(of: Data(anchor.utf8))?.lowerBound else { continue }- guard let section = image.section(containing: hit) else { continue }-- let stringOffset = cStringStart(in: image.data, containing: hit, sectionStart: Int(section.fileOffset))- let stringVMA = section.address &+ UInt64(stringOffset - Int(section.fileOffset))-- guard let xrefOffset = findADRPADDReference(to: stringVMA, in: image) else {- log?(" [.] anchor '\(anchor)' has no ADRP+ADD xref in __TEXT,__text")- continue- }-- let functionOffset = functionStart(before: xrefOffset, in: image)- guard let gate = findReturnGate(from: functionOffset, to: xrefOffset, in: image) else {- log?(String(format: " [.] anchor '%@' has no return-block gate in [0x%X, 0x%X)",- anchor, functionOffset, xrefOffset))- continue- }-- return Site(- anchor: anchor,- stringVMA: stringVMA,- xrefOffset: xrefOffset,- functionOffset: functionOffset,- gateOffset: gate.offset,- returnBlockOffset: gate.target,- isAlreadyPatched: gate.isUnconditional,- )- }- return nil- }-- /// Start of the NUL-terminated C string containing `offset`.- ///- /// Code references a string's first byte, so a substring anchor has to be- /// widened to the whole string before its address means anything.- static func cStringStart(in data: Data, containing offset: Int, sectionStart: Int) -> Int {- var position = offset - 1- while position >= sectionStart, data[position] != 0 {- position -= 1- }- return position + 1- }-- /// File offset of the ADRP in the first `ADRP Rd, page` / `ADD Rd, Rd, #off`- /// pair in `__TEXT,__text` that computes `targetVMA`.- ///- /// The pair need not be adjacent — the compiler interleaves other setup- /// between them — so the most recent ADRP per destination register is kept- /// and matched against a later ADD that reads it, within eight instructions.- ///- /// Decoded from the instruction words rather than through Capstone: this is- /// the one scan that covers all of `__text` (93k instructions in launchd),- /// and the two opcode predicates below are exact. `ARM64Inst` documents the- /// same split — raw predicates for the hot loops, Capstone once a specific- /// instruction is in hand, which is what every semantic test in this file- /// uses.- static func findADRPADDReference(to targetVMA: UInt64, in image: Image) -> Int? {- let targetPage = targetVMA & ~0xFFF- let targetPageOffset = UInt32(targetVMA & 0xFFF)-- // Rd -> (instruction index, page the ADRP produced)- var pending: [UInt32: (index: Int, page: UInt64)] = [:]-- var offset = image.textOffset- var index = 0- while offset + 4 <= image.textEnd {- let word = image.data.loadLE(UInt32.self, at: offset)-- if ARM64Inst.isADRP(word) {- pending[ARM64Inst.rd(word)] = (index, adrpPage(word, at: image.virtualAddress(ofTextOffset: offset)))- } else if isAddImm64(word) {- let rn = ARM64Inst.rn(word)- if let adrp = pending[rn],- adrp.page == targetPage,- ARM64Inst.addSubImm12(word) == targetPageOffset,- index - adrp.index <= 8- {- return image.textOffset + (adrp.index * 4)- }- }-- offset += 4- index += 1- }- return nil- }-- /// Page address an ADRP at `pc` produces.- static func adrpPage(_ word: UInt32, at pc: UInt64) -> UInt64 {- let immhi = (word >> 5) & 0x7FFFF- let immlo = (word >> 29) & 0x3- let imm21 = (immhi << 2) | immlo- // Sign-extend the 21-bit immediate, then scale by the 4 KiB page.- let signed = Int64(Int32(bitPattern: imm21 << 11) >> 11)- return (pc & ~0xFFF) &+ UInt64(bitPattern: signed << 12)- }-- /// `ADD Xd, Xn, #imm12` with `LSL #0` — `[31:22] = 1001000100`.- ///- /// Requiring `sh == 0` is what keeps `add xd, xn, #imm, lsl #12` out; a- /// shifted-register `add` has a different `[28:24]` and never reaches here.- static func isAddImm64(_ word: UInt32) -> Bool {- (word & 0xFFC0_0000) == 0x9100_0000- }-- /// First instruction of the function containing `offset`.- ///- /// `PACIBSP` is the prologue of every non-leaf arm64e function, and it is- /// the only instruction that can only appear at a function's entry, which- /// makes it the one reliable boundary here. A `ret` is not: this function's- /// own success epilogue returns *before* the failure path the xref sits in,- /// so a backward scan for `ret` stops inside the function it is trying to- /// delimit.- ///- /// With no prologue in range this falls back to the reference's blind- /// window, so a function that does not sign its link register still gets- /// the reference's behaviour rather than none.- static func functionStart(before offset: Int, in image: Image) -> Int {- let floor = max(image.textOffset, offset - maxFunctionPrologueScan)- var scan = offset - 4- while scan >= floor {- if image.data.loadLE(UInt32.self, at: scan) == ARM64.pacibspU32 {- return scan- }- scan -= 4- }- return max(image.textOffset, offset - fallbackScanWindow)- }-- /// The gate: the earliest branch in `[start, end)` whose target is a return- /// block of the same function.- ///- /// Unconditional `b`s are collected alongside the conditional ones so that- /// the shape this patch *writes* is recognised on a second run. An- /// unconditional one earlier than every conditional candidate is a previous- /// run's work — there is nothing left to do, and rewriting the next- /// conditional branch instead (which is what the reference does) would put- /// a second, unasked-for patch into pid 1.- ///- /// The limit of that signal, stated so nobody has to rediscover it: a- /// compiler-emitted `b` to the epilogue, earlier in this window than any- /// conditional gate, would read as already-patched on a *pristine* image and- /// the patch would never be applied. There is none on iOS 27.0 / 24A435 —- /// `gateIsTheEarliestQualifyingBranch` walks the window and proves it — and- /// `revealStepsAreSelfConsistent` asserts `!isAlreadyPatched` on the pristine- /// binary, so a firmware that grows one fails the suite rather than quietly- /// shipping an unpatched pid 1.- static func findReturnGate(- from start: Int,- to end: Int,- in image: Image,- ) -> (offset: Int, target: Int, isUnconditional: Bool)? {- var liveGate: (offset: Int, target: Int)?- var patchedGate: (offset: Int, target: Int)?-- var offset = start- while offset + 4 <= end {- defer { offset += 4 }- guard let insn = disassembler.disassembleOne(in: image.data, at: offset) else { continue }-- let unconditional = insn.mnemonic == "b"- guard unconditional || conditionalBranchMnemonics.contains(insn.mnemonic) else { continue }- guard let target = branchTarget(insn), image.isInText(target) else { continue }- guard isReturnBlock(target, in: image) else { continue }-- if unconditional {- if patchedGate == nil {- patchedGate = (offset, target)- }- } else if liveGate == nil {- liveGate = (offset, target)- }- if liveGate != nil, patchedGate != nil {- break- }- }-- switch (liveGate, patchedGate) {- case let (live?, patched?):- return patched.offset < live.offset- ? (patched.offset, patched.target, true)- : (live.offset, live.target, false)- case let (live?, nil):- return (live.offset, live.target, false)- case let (nil, patched?):- return (patched.offset, patched.target, true)- case (nil, nil):- return nil- }- }-- /// Branch destination as a file offset, from Capstone's typed operands.- ///- /// Every branch form here carries its destination as its last immediate:- /// `b`/`b.<cond>` have only one operand, `cbz`/`cbnz` a register then the- /// target, `tbz`/`tbnz` a register, a bit number, then the target. Reading- /// the last immediate covers all three without parsing operand text. The- /// instruction was decoded at its own file offset, so the immediate is a- /// file offset too.- static func branchTarget(_ insn: Instruction) -> Int? {- guard let detail = insn.aarch64 else { return nil }- for operand in detail.operands.reversed() where operand.type == AARCH64_OP_IMM {- return Int(operand.imm)- }- return nil- }-- /// True when the instruction returns from the function — `ret`, `retaa`,- /// `retab`, by Capstone's own classification rather than a mnemonic prefix.- ///- /// The prefix test this replaces (`hasPrefix("ret")`) is close enough on- /// this image and wrong in principle; the group is what Capstone decoded- /// the instruction to mean.- static func isReturn(_ insn: Instruction) -> Bool {- insn.groups.contains(UInt8(CS_GRP_RET.rawValue))- }-- /// True when control leaves the block here without falling through: an- /// unconditional jump (`b`, `br`, `braa`, …) or a call (`bl`, `blr`,- /// `blraa`, …).- ///- /// A conditional branch is deliberately not one of these. It falls through,- /// so the return can still be the instruction after it, which is what makes- /// a compare-and-return epilogue a return block.- ///- /// Groups again, not prefixes: `hasPrefix("br")` also swallows `brk`, which- /// is a breakpoint (`CS_GRP_INT`) and ends nothing, and `hasPrefix("bl")`- /// would only reach the authenticated calls by accident.- static func leavesBlock(_ insn: Instruction) -> Bool {- if insn.groups.contains(UInt8(CS_GRP_CALL.rawValue)) {- return true- }- return insn.groups.contains(UInt8(CS_GRP_JUMP.rawValue))- && !conditionalBranchMnemonics.contains(insn.mnemonic)- }-- /// True when the block at `offset` returns from the function.- ///- /// Decodes forward until the block returns, until control leaves it some- /// other way (so it is not a return block), or until the end of `__text` or- /// the probe limit.- static func isReturnBlock(_ offset: Int, in image: Image) -> Bool {- for step in 0 ..< returnBlockProbeInstructions {- let probe = offset + step * 4- guard probe + 4 <= image.textEnd else { return false }- guard let insn = disassembler.disassembleOne(in: image.data, at: probe) else { continue }- if isReturn(insn) {- return true- }- if leavesBlock(insn) {- return false- }- }- return false- }-- // MARK: - Logging-- /// `mnemonic operands` for a single instruction, for the record's- /// before/after fields. Text only — nothing matches on it.- static func describe(_ bytes: Data, at offset: Int) -> String {- guard let insn = disassembler.disassembleOne(bytes, at: UInt64(offset)) else { return bytes.hex }- return insn.operandString.isEmpty ? insn.mnemonic : "\(insn.mnemonic) \(insn.operandString)"- }}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsamDiscovery.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsamDiscovery.swiftnew file mode 100644index 00000000..f99a4d7e--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareJetsamDiscovery.swift@@ -0,0 +1,353 @@+// CustomFirmwareJetsamDiscovery.swift — Locate the jetsam guard in launchd.++import Capstone+import Foundation++extension CustomFirmwareJetsamPatcher {+ /// `ARM64Disassembler` is stateless across calls and `Sendable`.+ private static let disassembler = ARM64Disassembler()++ // MARK: - Image++ /// The parts of the Mach-O this patch reads: `__TEXT,__text`, and every+ /// file-backed section, so a string hit can be turned into a VA.+ struct Image {+ let data: Data+ let textOffset: Int+ let textSize: Int+ let textVMA: UInt64+ /// File-backed sections, in file order. Zero-fill sections (`__bss`,+ /// `__common`) are dropped: their `fileOffset` is 0, so leaving them in+ /// lets one claim the range `[0, size)` and mislocate a hit in the+ /// Mach-O header.+ let sections: [MachOSectionInfo]++ init(data rawData: Data) throws {+ // Zero-base so the integer subscripts used throughout are valid.+ let data = rawData.startIndex == 0 ? rawData : Data(rawData)+ guard data.count > 32, data.loadLE(UInt32.self, at: 0) == 0xFEED_FACF else {+ throw PatcherError.invalidFormat("launchd jetsam: not a 64-bit Mach-O")+ }+ let parsed = MachOParser.parseSections(from: data)+ guard let text = parsed["__TEXT,__text"] else {+ throw PatcherError.invalidFormat("launchd jetsam: __TEXT,__text not found")+ }+ guard Int(text.fileOffset) + Int(text.size) <= data.count else {+ throw PatcherError.invalidFormat("launchd jetsam: __TEXT,__text runs past the file")+ }+ self.data = data+ textOffset = Int(text.fileOffset)+ textSize = Int(text.size)+ textVMA = text.address+ sections = parsed.values+ .filter { $0.fileOffset != 0 && $0.size != 0 }+ .sorted { $0.fileOffset < $1.fileOffset }+ }++ var textEnd: Int {+ textOffset + textSize+ }++ func isInText(_ offset: Int) -> Bool {+ offset >= textOffset && offset < textEnd+ }++ /// VA of a `__TEXT,__text` file offset. `__text` is one contiguous+ /// mapping, so the two differ by a constant.+ func virtualAddress(ofTextOffset offset: Int) -> UInt64 {+ textVMA &+ UInt64(offset - textOffset)+ }++ /// The file-backed section containing `offset`, if any.+ func section(containing offset: Int) -> MachOSectionInfo? {+ sections.first {+ offset >= Int($0.fileOffset) && offset < Int($0.fileOffset) + Int($0.size)+ }+ }+ }++ // MARK: - Reveal++ /// Everything step 4 needs, plus what the log prints about how it got there.+ struct Site {+ let anchor: String+ let stringVMA: UInt64+ let xrefOffset: Int+ let functionOffset: Int+ let gateOffset: Int+ let returnBlockOffset: Int+ /// True when `gateOffset` already holds the unconditional branch.+ let isAlreadyPatched: Bool+ }++ /// Walk the anchors in order, taking the first that resolves all the way to+ /// a gate. An anchor that resolves partway — present but with no xref, or+ /// an xref with no qualifying branch — is abandoned for the next one, which+ /// is what the reference does.+ static func locate(in image: Image, log: ((String) -> Void)? = nil) throws -> Site? {+ for anchor in panicStringAnchors {+ guard let hit = image.data.range(of: Data(anchor.utf8))?.lowerBound else { continue }+ guard let section = image.section(containing: hit) else { continue }++ let stringOffset = cStringStart(in: image.data, containing: hit, sectionStart: Int(section.fileOffset))+ let stringVMA = section.address &+ UInt64(stringOffset - Int(section.fileOffset))++ guard let xrefOffset = findADRPADDReference(to: stringVMA, in: image) else {+ log?(" [.] anchor '\(anchor)' has no ADRP+ADD xref in __TEXT,__text")+ continue+ }++ let functionOffset = functionStart(before: xrefOffset, in: image)+ guard let gate = findReturnGate(from: functionOffset, to: xrefOffset, in: image) else {+ log?(String(format: " [.] anchor '%@' has no return-block gate in [0x%X, 0x%X)",+ anchor, functionOffset, xrefOffset))+ continue+ }++ return Site(+ anchor: anchor,+ stringVMA: stringVMA,+ xrefOffset: xrefOffset,+ functionOffset: functionOffset,+ gateOffset: gate.offset,+ returnBlockOffset: gate.target,+ isAlreadyPatched: gate.isUnconditional,+ )+ }+ return nil+ }++ /// Start of the NUL-terminated C string containing `offset`.+ ///+ /// Code references a string's first byte, so a substring anchor has to be+ /// widened to the whole string before its address means anything.+ static func cStringStart(in data: Data, containing offset: Int, sectionStart: Int) -> Int {+ var position = offset - 1+ while position >= sectionStart, data[position] != 0 {+ position -= 1+ }+ return position + 1+ }++ /// File offset of the ADRP in the first `ADRP Rd, page` / `ADD Rd, Rd, #off`+ /// pair in `__TEXT,__text` that computes `targetVMA`.+ ///+ /// The pair need not be adjacent — the compiler interleaves other setup+ /// between them — so the most recent ADRP per destination register is kept+ /// and matched against a later ADD that reads it, within eight instructions.+ ///+ /// Decoded from the instruction words rather than through Capstone: this is+ /// the one scan that covers all of `__text` (93k instructions in launchd),+ /// and the two opcode predicates below are exact. `ARM64Inst` documents the+ /// same split — raw predicates for the hot loops, Capstone once a specific+ /// instruction is in hand, which is what every semantic test in this file+ /// uses.+ static func findADRPADDReference(to targetVMA: UInt64, in image: Image) -> Int? {+ let targetPage = targetVMA & ~0xFFF+ let targetPageOffset = UInt32(targetVMA & 0xFFF)++ // Rd -> (instruction index, page the ADRP produced)+ var pending: [UInt32: (index: Int, page: UInt64)] = [:]++ var offset = image.textOffset+ var index = 0+ while offset + 4 <= image.textEnd {+ let word = image.data.loadLE(UInt32.self, at: offset)++ if ARM64Inst.isADRP(word) {+ pending[ARM64Inst.rd(word)] = (index, adrpPage(word, at: image.virtualAddress(ofTextOffset: offset)))+ } else if isAddImm64(word) {+ let rn = ARM64Inst.rn(word)+ if let adrp = pending[rn],+ adrp.page == targetPage,+ ARM64Inst.addSubImm12(word) == targetPageOffset,+ index - adrp.index <= 8+ {+ return image.textOffset + (adrp.index * 4)+ }+ }++ offset += 4+ index += 1+ }+ return nil+ }++ /// Page address an ADRP at `pc` produces.+ static func adrpPage(_ word: UInt32, at pc: UInt64) -> UInt64 {+ let immhi = (word >> 5) & 0x7FFFF+ let immlo = (word >> 29) & 0x3+ let imm21 = (immhi << 2) | immlo+ // Sign-extend the 21-bit immediate, then scale by the 4 KiB page.+ let signed = Int64(Int32(bitPattern: imm21 << 11) >> 11)+ return (pc & ~0xFFF) &+ UInt64(bitPattern: signed << 12)+ }++ /// `ADD Xd, Xn, #imm12` with `LSL #0` — `[31:22] = 1001000100`.+ ///+ /// Requiring `sh == 0` is what keeps `add xd, xn, #imm, lsl #12` out; a+ /// shifted-register `add` has a different `[28:24]` and never reaches here.+ static func isAddImm64(_ word: UInt32) -> Bool {+ (word & 0xFFC0_0000) == 0x9100_0000+ }++ /// First instruction of the function containing `offset`.+ ///+ /// `PACIBSP` is the prologue of every non-leaf arm64e function, and it is+ /// the only instruction that can only appear at a function's entry, which+ /// makes it the one reliable boundary here. A `ret` is not: this function's+ /// own success epilogue returns *before* the failure path the xref sits in,+ /// so a backward scan for `ret` stops inside the function it is trying to+ /// delimit.+ ///+ /// With no prologue in range this falls back to the reference's blind+ /// window, so a function that does not sign its link register still gets+ /// the reference's behaviour rather than none.+ static func functionStart(before offset: Int, in image: Image) -> Int {+ let floor = max(image.textOffset, offset - maxFunctionPrologueScan)+ var scan = offset - 4+ while scan >= floor {+ if image.data.loadLE(UInt32.self, at: scan) == ARM64.pacibspU32 {+ return scan+ }+ scan -= 4+ }+ return max(image.textOffset, offset - fallbackScanWindow)+ }++ /// The gate: the earliest branch in `[start, end)` whose target is a return+ /// block of the same function.+ ///+ /// Unconditional `b`s are collected alongside the conditional ones so that+ /// the shape this patch *writes* is recognised on a second run. An+ /// unconditional one earlier than every conditional candidate is a previous+ /// run's work — there is nothing left to do, and rewriting the next+ /// conditional branch instead (which is what the reference does) would put+ /// a second, unasked-for patch into pid 1.+ ///+ /// The limit of that signal, stated so nobody has to rediscover it: a+ /// compiler-emitted `b` to the epilogue, earlier in this window than any+ /// conditional gate, would read as already-patched on a *pristine* image and+ /// the patch would never be applied. There is none on iOS 27.0 / 24A435 —+ /// `gateIsTheEarliestQualifyingBranch` walks the window and proves it — and+ /// `revealStepsAreSelfConsistent` asserts `!isAlreadyPatched` on the pristine+ /// binary, so a firmware that grows one fails the suite rather than quietly+ /// shipping an unpatched pid 1.+ static func findReturnGate(+ from start: Int,+ to end: Int,+ in image: Image,+ ) -> (offset: Int, target: Int, isUnconditional: Bool)? {+ var liveGate: (offset: Int, target: Int)?+ var patchedGate: (offset: Int, target: Int)?++ var offset = start+ while offset + 4 <= end {+ defer { offset += 4 }+ guard let insn = disassembler.disassembleOne(in: image.data, at: offset) else { continue }++ let unconditional = insn.mnemonic == "b"+ guard unconditional || conditionalBranchMnemonics.contains(insn.mnemonic) else { continue }+ guard let target = branchTarget(insn), image.isInText(target) else { continue }+ guard isReturnBlock(target, in: image) else { continue }++ if unconditional {+ if patchedGate == nil {+ patchedGate = (offset, target)+ }+ } else if liveGate == nil {+ liveGate = (offset, target)+ }+ if liveGate != nil, patchedGate != nil {+ break+ }+ }++ switch (liveGate, patchedGate) {+ case let (live?, patched?):+ return patched.offset < live.offset+ ? (patched.offset, patched.target, true)+ : (live.offset, live.target, false)+ case let (live?, nil):+ return (live.offset, live.target, false)+ case let (nil, patched?):+ return (patched.offset, patched.target, true)+ case (nil, nil):+ return nil+ }+ }++ /// Branch destination as a file offset, from Capstone's typed operands.+ ///+ /// Every branch form here carries its destination as its last immediate:+ /// `b`/`b.<cond>` have only one operand, `cbz`/`cbnz` a register then the+ /// target, `tbz`/`tbnz` a register, a bit number, then the target. Reading+ /// the last immediate covers all three without parsing operand text. The+ /// instruction was decoded at its own file offset, so the immediate is a+ /// file offset too.+ static func branchTarget(_ insn: Instruction) -> Int? {+ guard let detail = insn.aarch64 else { return nil }+ for operand in detail.operands.reversed() where operand.type == AARCH64_OP_IMM {+ return Int(operand.imm)+ }+ return nil+ }++ /// True when the instruction returns from the function — `ret`, `retaa`,+ /// `retab`, by Capstone's own classification rather than a mnemonic prefix.+ ///+ /// The prefix test this replaces (`hasPrefix("ret")`) is close enough on+ /// this image and wrong in principle; the group is what Capstone decoded+ /// the instruction to mean.+ static func isReturn(_ insn: Instruction) -> Bool {+ insn.groups.contains(UInt8(CS_GRP_RET.rawValue))+ }++ /// True when control leaves the block here without falling through: an+ /// unconditional jump (`b`, `br`, `braa`, …) or a call (`bl`, `blr`,+ /// `blraa`, …).+ ///+ /// A conditional branch is deliberately not one of these. It falls through,+ /// so the return can still be the instruction after it, which is what makes+ /// a compare-and-return epilogue a return block.+ ///+ /// Groups again, not prefixes: `hasPrefix("br")` also swallows `brk`, which+ /// is a breakpoint (`CS_GRP_INT`) and ends nothing, and `hasPrefix("bl")`+ /// would only reach the authenticated calls by accident.+ static func leavesBlock(_ insn: Instruction) -> Bool {+ if insn.groups.contains(UInt8(CS_GRP_CALL.rawValue)) {+ return true+ }+ return insn.groups.contains(UInt8(CS_GRP_JUMP.rawValue))+ && !conditionalBranchMnemonics.contains(insn.mnemonic)+ }++ /// True when the block at `offset` returns from the function.+ ///+ /// Decodes forward until the block returns, until control leaves it some+ /// other way (so it is not a return block), or until the end of `__text` or+ /// the probe limit.+ static func isReturnBlock(_ offset: Int, in image: Image) -> Bool {+ for step in 0 ..< returnBlockProbeInstructions {+ let probe = offset + step * 4+ guard probe + 4 <= image.textEnd else { return false }+ guard let insn = disassembler.disassembleOne(in: image.data, at: probe) else { continue }+ if isReturn(insn) {+ return true+ }+ if leavesBlock(insn) {+ return false+ }+ }+ return false+ }++ // MARK: - Logging++ /// `mnemonic operands` for a single instruction, for the record's+ /// before/after fields. Text only — nothing matches on it.+ static func describe(_ bytes: Data, at offset: Int) -> String {+ guard let insn = disassembler.disassembleOne(bytes, at: UInt64(offset)) else { return bytes.hex }+ return insn.operandString.isEmpty ? insn.mnemonic : "\(insn.mnemonic) \(insn.operandString)"+ }+}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swiftnew file mode 100644index 00000000..3d31ae13--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swift@@ -0,0 +1,309 @@+import Foundation++extension CustomFirmwareMobileactivationd {+ // MARK: - Anchoring++ /// Resolve the IMP of ``method``, by symbol and by ObjC metadata.+ ///+ /// Both routes are independent: one reads `LC_SYMTAB`, the other walks+ /// `__objc_methname` -> `__objc_selrefs` -> relative method list. When both+ /// answer they must give the same address.+ public static func locateIMP(in data: Data) throws -> Anchor {+ let data = data.startIndex == 0 ? data : Data(data)+ let segments = MachOParser.parseSegments(from: data)+ guard !segments.isEmpty else {+ throw PatcherError.invalidFormat("not a 64-bit Mach-O, or it carries no LC_SEGMENT_64")+ }++ let bySymbol = symbolVirtualAddress(in: data)+ let byMetadata = objcMetadataVirtualAddress(in: data, segments: segments)++ let source: AnchorSource+ let virtualAddress: UInt64+ switch (bySymbol, byMetadata) {+ case let (symbol?, metadata?):+ guard symbol == metadata else {+ throw PatcherError.invalidFormat(+ "\(method): symbol table says 0x\(hex(symbol)) but the ObjC method list "+ + "says 0x\(hex(metadata)) — refusing to guess which is the IMP",+ )+ }+ source = .symbolTableAndObjCMetadata+ virtualAddress = symbol+ case let (symbol?, nil):+ source = .symbolTable+ virtualAddress = symbol+ case let (nil, metadata?):+ source = .objcMetadata+ virtualAddress = metadata+ case (nil, nil):+ throw PatcherError.patchSiteNotFound(+ "\(method): neither LC_SYMTAB nor the ObjC method lists carry it",+ )+ }++ guard let fileOffset = MachOParser.vaToFileOffset(virtualAddress, segments: segments) else {+ throw PatcherError.invalidFormat(+ "\(method): VA 0x\(hex(virtualAddress)) maps to no segment",+ )+ }+ guard let section = executableSection(containing: virtualAddress, in: data) else {+ throw PatcherError.invalidFormat(+ "\(method): VA 0x\(hex(virtualAddress)) is not inside an executable section — "+ + "the anchor resolved to data, not code",+ )+ }++ return Anchor(+ virtualAddress: virtualAddress,+ fileOffset: fileOffset,+ source: source,+ section: section,+ )+ }++ /// The VA of the `LC_SYMTAB` entry whose name is exactly ``method``.+ ///+ /// Exact, not a substring: `_objc_msgSend$should_hactivate` and+ /// `_OBJC_IVAR_$_DeviceType._should_hactivate` both contain the selector and+ /// neither is the IMP. N_STAB debug entries are skipped — the same address+ /// arrives twice on this binary, once as N_SECT and once as N_FUN — and the+ /// symbol must be section-defined with a non-zero value.+ static func symbolVirtualAddress(in data: Data) -> UInt64? {+ guard let symtab = MachOParser.parseSymtab(from: data) else { return nil }+ // <mach-o/nlist.h>: N_STAB masks off the debug entries, N_TYPE selects+ // the kind, and N_SECT is the one kind that means "defined in a section".+ let nStab: UInt8 = 0xE0+ let nTypeMask: UInt8 = 0x0E+ let nSect: UInt8 = 0x0E++ for index in 0 ..< symtab.nsyms {+ let entry = symtab.symoff + index * 16 // sizeof(nlist_64)+ guard entry + 16 <= data.count else { break }++ let typeByte = data[entry + 4]+ guard typeByte & nStab == 0, typeByte & nTypeMask == nSect else { continue }++ let strx = Int(data.loadLE(UInt32.self, at: entry))+ let value = data.loadLE(UInt64.self, at: entry + 8)+ guard value != 0, strx < symtab.strsize else { continue }++ guard let name = cString(in: data, at: symtab.stroff + strx,+ limit: symtab.stroff + symtab.strsize) else { continue }+ if name == method {+ return value+ }+ }+ return nil+ }++ /// The VA of the IMP, walked out of the ObjC metadata:+ /// `__objc_methname` selector -> `__objc_selrefs` entry -> the relative+ /// method-list entry whose `name` field points at that selref -> its `imp`.+ static func objcMetadataVirtualAddress(+ in data: Data,+ segments: [MachOSegmentInfo],+ ) -> UInt64? {+ let sections = MachOParser.parseSections(from: data)+ guard let imageBase = segments.first(where: { $0.name == "__TEXT" })?.vmAddr else {+ return nil+ }+ guard let selectorVA = selectorVirtualAddress(in: data, sections: sections) else {+ return nil+ }+ guard let selrefVA = selectorReferenceVirtualAddress(+ to: selectorVA, in: data, sections: sections, imageBase: imageBase,+ ) else { return nil }++ return methodImplementation(+ forSelectorReference: selrefVA, in: data, sections: sections,+ )+ }++ /// The selector string's VA — the whole string ``selector``, not a suffix of+ /// a longer one.+ ///+ /// `DeviceType`'s property-attribute string `TB,R,N,V_should_hactivate`+ /// names the backing ivar and sits earlier in the very same section, so a+ /// plain `memmem` for `should_hactivate\0` — what the Python does — hits its+ /// tail first. Requiring the preceding byte to be the previous string's NUL+ /// is what separates a whole selector from a suffix of something longer.+ static func selectorVirtualAddress(+ in data: Data,+ sections: [String: MachOSectionInfo],+ ) -> UInt64? {+ let candidates = ["__TEXT,__objc_methname", "__DATA,__objc_methname"]+ guard let section = candidates.compactMap({ sections[$0] }).first else { return nil }++ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard start >= 0, end <= data.count, start < end else { return nil }++ let needle = Data(selector.utf8) + Data([0])+ var cursor = start+ while cursor + needle.count <= end {+ guard let found = data[cursor ..< end].range(of: needle) else { return nil }+ let offset = found.lowerBound+ // The first string in the section needs no separator before it.+ if offset == start || data[offset - 1] == 0 {+ return section.address + UInt64(offset - start)+ }+ cursor = offset + 1+ }+ return nil+ }++ /// The `__objc_selrefs` slot that points at `selectorVA`.+ ///+ /// The slots are chained-fixup rebases on this stack, not plain pointers, so+ /// the raw word is matched three ways: as-is (an already-bound pointer), as a+ /// 36-bit rebase target relative to the image base, and as an absolute 36-bit+ /// target. Whichever form the binary uses, the resolved address has to be the+ /// selector's.+ static func selectorReferenceVirtualAddress(+ to selectorVA: UInt64,+ in data: Data,+ sections: [String: MachOSectionInfo],+ imageBase: UInt64,+ ) -> UInt64? {+ let candidates = [+ "__DATA,__objc_selrefs",+ "__DATA_CONST,__objc_selrefs",+ "__AUTH_CONST,__objc_selrefs",+ ]+ guard let section = candidates.compactMap({ sections[$0] }).first else { return nil }++ let start = Int(section.fileOffset)+ let count = Int(section.size)+ guard start >= 0, start + count <= data.count else { return nil }++ // dyld_chained_ptr_64_rebase.target is 36 bits wide.+ let targetMask: UInt64 = (1 << 36) - 1++ for slot in stride(from: 0, to: count - 7, by: 8) {+ let raw = data.loadLE(UInt64.self, at: start + slot)+ let target = raw & targetMask+ if raw == selectorVA || target == selectorVA || imageBase &+ target == selectorVA {+ return section.address + UInt64(slot)+ }+ }+ return nil+ }++ /// The IMP of the relative-method-list entry whose `name` field resolves to+ /// `selrefVA`.+ ///+ /// iOS 16+ stores "small" method lists — three `int32`s per entry, each+ /// relative to its own field's address — in `__TEXT,__objc_methlist`. The+ /// Python looks in `__objc_const`, which is why its fallback never fires.+ /// Both are searched here, so an older layout still resolves.+ static func methodImplementation(+ forSelectorReference selrefVA: UInt64,+ in data: Data,+ sections: [String: MachOSectionInfo],+ ) -> UInt64? {+ let candidates = [+ "__TEXT,__objc_methlist",+ "__DATA,__objc_const",+ "__DATA_CONST,__objc_const",+ "__AUTH_CONST,__objc_const",+ ]+ for name in candidates {+ guard let section = sections[name] else { continue }+ if let imp = methodImplementation(+ forSelectorReference: selrefVA, in: data, section: section,+ ) {+ return imp+ }+ }+ return nil+ }++ /// Walk one section as a run of relative method lists.+ ///+ /// Each list is `{ uint32 entsizeAndFlags; uint32 count; }` followed by+ /// `count` 12-byte entries, and the next list starts at the following 8-byte+ /// boundary. A header that is not a 12-byte-entry small list ends the walk:+ /// past it the bytes are no longer method lists, and matching an "entry" in+ /// them would be matching noise.+ static func methodImplementation(+ forSelectorReference selrefVA: UInt64,+ in data: Data,+ section: MachOSectionInfo,+ ) -> UInt64? {+ let smallMethodListFlag: UInt32 = 0x8000_0000+ let entrySizeMask: UInt32 = 0x0000_FFFC+ let entrySize = 12++ let base = Int(section.fileOffset)+ let size = Int(section.size)+ guard base >= 0, base + size <= data.count else { return nil }++ var cursor = 0+ while cursor + 8 <= size {+ let header = data.loadLE(UInt32.self, at: base + cursor)+ let count = Int(data.loadLE(UInt32.self, at: base + cursor + 4))+ guard header & smallMethodListFlag != 0,+ Int(header & entrySizeMask) == entrySize,+ count > 0,+ cursor + 8 + count * entrySize <= size+ else { return nil }++ for index in 0 ..< count {+ let entry = cursor + 8 + index * entrySize+ let entryVA = section.address + UInt64(entry)+ let nameDelta = Int(data.loadLE(Int32.self, at: base + entry))+ guard UInt64(bitPattern: Int64(entryVA) + Int64(nameDelta)) == selrefVA else {+ continue+ }+ // { name, types, imp } — the imp field is 8 bytes in, and its+ // delta is relative to the imp field's own address.+ let impField = entryVA + 8+ let impDelta = Int(data.loadLE(Int32.self, at: base + entry + 8))+ return UInt64(bitPattern: Int64(impField) + Int64(impDelta))+ }+ cursor += 8 + count * entrySize+ cursor = (cursor + 7) & ~7+ }+ return nil+ }++ /// `segment,section` of the executable section containing `va`, or nil when+ /// the address is not in one.+ ///+ /// Executability is read off the segment's `initprot`, not off the segment's+ /// name, so this keeps working if the IMP ever lives somewhere other than+ /// `__TEXT,__text`.+ static func executableSection(containing va: UInt64, in data: Data) -> String? {+ let vmProtExecute: UInt32 = 0x4+ var executableSegments: Set<String> = []++ let ncmds = data.loadLE(UInt32.self, at: 16)+ var offset = 32 // sizeof(mach_header_64)+ for _ in 0 ..< ncmds {+ guard offset + 8 <= data.count else { break }+ let cmd = data.loadLE(UInt32.self, at: offset)+ let cmdsize = Int(data.loadLE(UInt32.self, at: offset + 4))+ guard cmdsize > 0 else { break }+ if cmd == 0x19, offset + 64 <= data.count { // LC_SEGMENT_64+ let initprot = data.loadLE(UInt32.self, at: offset + 60)+ if initprot & vmProtExecute != 0 {+ let raw = data[offset + 8 ..< offset + 24]+ executableSegments.insert(+ String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self),+ )+ }+ }+ offset += cmdsize+ }++ for (key, section) in MachOParser.parseSections(from: data)+ where executableSegments.contains(section.segmentName)+ && va >= section.address && va < section.address + section.size+ {+ return key+ }+ return nil+ }++}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd.swiftindex 41e98354..0e6be07c 100644--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd.swift+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd.swift@@ -293,311 +293,6 @@ public enum CustomFirmwareMobileactivationd {stride(from: anchor.fileOffset, to: anchor.fileOffset + patched.count, by: 4).map(\.self)}- // MARK: - Anchoring-- /// Resolve the IMP of ``method``, by symbol and by ObjC metadata.- ///- /// Both routes are independent: one reads `LC_SYMTAB`, the other walks- /// `__objc_methname` -> `__objc_selrefs` -> relative method list. When both- /// answer they must give the same address.- public static func locateIMP(in data: Data) throws -> Anchor {- let data = data.startIndex == 0 ? data : Data(data)- let segments = MachOParser.parseSegments(from: data)- guard !segments.isEmpty else {- throw PatcherError.invalidFormat("not a 64-bit Mach-O, or it carries no LC_SEGMENT_64")- }-- let bySymbol = symbolVirtualAddress(in: data)- let byMetadata = objcMetadataVirtualAddress(in: data, segments: segments)-- let source: AnchorSource- let virtualAddress: UInt64- switch (bySymbol, byMetadata) {- case let (symbol?, metadata?):- guard symbol == metadata else {- throw PatcherError.invalidFormat(- "\(method): symbol table says 0x\(hex(symbol)) but the ObjC method list "- + "says 0x\(hex(metadata)) — refusing to guess which is the IMP",- )- }- source = .symbolTableAndObjCMetadata- virtualAddress = symbol- case let (symbol?, nil):- source = .symbolTable- virtualAddress = symbol- case let (nil, metadata?):- source = .objcMetadata- virtualAddress = metadata- case (nil, nil):- throw PatcherError.patchSiteNotFound(- "\(method): neither LC_SYMTAB nor the ObjC method lists carry it",- )- }-- guard let fileOffset = MachOParser.vaToFileOffset(virtualAddress, segments: segments) else {- throw PatcherError.invalidFormat(- "\(method): VA 0x\(hex(virtualAddress)) maps to no segment",- )- }- guard let section = executableSection(containing: virtualAddress, in: data) else {- throw PatcherError.invalidFormat(- "\(method): VA 0x\(hex(virtualAddress)) is not inside an executable section — "- + "the anchor resolved to data, not code",- )- }-- return Anchor(- virtualAddress: virtualAddress,- fileOffset: fileOffset,- source: source,- section: section,- )- }-- /// The VA of the `LC_SYMTAB` entry whose name is exactly ``method``.- ///- /// Exact, not a substring: `_objc_msgSend$should_hactivate` and- /// `_OBJC_IVAR_$_DeviceType._should_hactivate` both contain the selector and- /// neither is the IMP. N_STAB debug entries are skipped — the same address- /// arrives twice on this binary, once as N_SECT and once as N_FUN — and the- /// symbol must be section-defined with a non-zero value.- static func symbolVirtualAddress(in data: Data) -> UInt64? {- guard let symtab = MachOParser.parseSymtab(from: data) else { return nil }- // <mach-o/nlist.h>: N_STAB masks off the debug entries, N_TYPE selects- // the kind, and N_SECT is the one kind that means "defined in a section".- let nStab: UInt8 = 0xE0- let nTypeMask: UInt8 = 0x0E- let nSect: UInt8 = 0x0E-- for index in 0 ..< symtab.nsyms {- let entry = symtab.symoff + index * 16 // sizeof(nlist_64)- guard entry + 16 <= data.count else { break }-- let typeByte = data[entry + 4]- guard typeByte & nStab == 0, typeByte & nTypeMask == nSect else { continue }-- let strx = Int(data.loadLE(UInt32.self, at: entry))- let value = data.loadLE(UInt64.self, at: entry + 8)- guard value != 0, strx < symtab.strsize else { continue }-- guard let name = cString(in: data, at: symtab.stroff + strx,- limit: symtab.stroff + symtab.strsize) else { continue }- if name == method {- return value- }- }- return nil- }-- /// The VA of the IMP, walked out of the ObjC metadata:- /// `__objc_methname` selector -> `__objc_selrefs` entry -> the relative- /// method-list entry whose `name` field points at that selref -> its `imp`.- static func objcMetadataVirtualAddress(- in data: Data,- segments: [MachOSegmentInfo],- ) -> UInt64? {- let sections = MachOParser.parseSections(from: data)- guard let imageBase = segments.first(where: { $0.name == "__TEXT" })?.vmAddr else {- return nil- }- guard let selectorVA = selectorVirtualAddress(in: data, sections: sections) else {- return nil- }- guard let selrefVA = selectorReferenceVirtualAddress(- to: selectorVA, in: data, sections: sections, imageBase: imageBase,- ) else { return nil }-- return methodImplementation(- forSelectorReference: selrefVA, in: data, sections: sections,- )- }-- /// The selector string's VA — the whole string ``selector``, not a suffix of- /// a longer one.- ///- /// `DeviceType`'s property-attribute string `TB,R,N,V_should_hactivate`- /// names the backing ivar and sits earlier in the very same section, so a- /// plain `memmem` for `should_hactivate\0` — what the Python does — hits its- /// tail first. Requiring the preceding byte to be the previous string's NUL- /// is what separates a whole selector from a suffix of something longer.- static func selectorVirtualAddress(- in data: Data,- sections: [String: MachOSectionInfo],- ) -> UInt64? {- let candidates = ["__TEXT,__objc_methname", "__DATA,__objc_methname"]- guard let section = candidates.compactMap({ sections[$0] }).first else { return nil }-- let start = Int(section.fileOffset)- let end = start + Int(section.size)- guard start >= 0, end <= data.count, start < end else { return nil }-- let needle = Data(selector.utf8) + Data([0])- var cursor = start- while cursor + needle.count <= end {- guard let found = data[cursor ..< end].range(of: needle) else { return nil }- let offset = found.lowerBound- // The first string in the section needs no separator before it.- if offset == start || data[offset - 1] == 0 {- return section.address + UInt64(offset - start)- }- cursor = offset + 1- }- return nil- }-- /// The `__objc_selrefs` slot that points at `selectorVA`.- ///- /// The slots are chained-fixup rebases on this stack, not plain pointers, so- /// the raw word is matched three ways: as-is (an already-bound pointer), as a- /// 36-bit rebase target relative to the image base, and as an absolute 36-bit- /// target. Whichever form the binary uses, the resolved address has to be the- /// selector's.- static func selectorReferenceVirtualAddress(- to selectorVA: UInt64,- in data: Data,- sections: [String: MachOSectionInfo],- imageBase: UInt64,- ) -> UInt64? {- let candidates = [- "__DATA,__objc_selrefs",- "__DATA_CONST,__objc_selrefs",- "__AUTH_CONST,__objc_selrefs",- ]- guard let section = candidates.compactMap({ sections[$0] }).first else { return nil }-- let start = Int(section.fileOffset)- let count = Int(section.size)- guard start >= 0, start + count <= data.count else { return nil }-- // dyld_chained_ptr_64_rebase.target is 36 bits wide.- let targetMask: UInt64 = (1 << 36) - 1-- for slot in stride(from: 0, to: count - 7, by: 8) {- let raw = data.loadLE(UInt64.self, at: start + slot)- let target = raw & targetMask- if raw == selectorVA || target == selectorVA || imageBase &+ target == selectorVA {- return section.address + UInt64(slot)- }- }- return nil- }-- /// The IMP of the relative-method-list entry whose `name` field resolves to- /// `selrefVA`.- ///- /// iOS 16+ stores "small" method lists — three `int32`s per entry, each- /// relative to its own field's address — in `__TEXT,__objc_methlist`. The- /// Python looks in `__objc_const`, which is why its fallback never fires.- /// Both are searched here, so an older layout still resolves.- static func methodImplementation(- forSelectorReference selrefVA: UInt64,- in data: Data,- sections: [String: MachOSectionInfo],- ) -> UInt64? {- let candidates = [- "__TEXT,__objc_methlist",- "__DATA,__objc_const",- "__DATA_CONST,__objc_const",- "__AUTH_CONST,__objc_const",- ]- for name in candidates {- guard let section = sections[name] else { continue }- if let imp = methodImplementation(- forSelectorReference: selrefVA, in: data, section: section,- ) {- return imp- }- }- return nil- }-- /// Walk one section as a run of relative method lists.- ///- /// Each list is `{ uint32 entsizeAndFlags; uint32 count; }` followed by- /// `count` 12-byte entries, and the next list starts at the following 8-byte- /// boundary. A header that is not a 12-byte-entry small list ends the walk:- /// past it the bytes are no longer method lists, and matching an "entry" in- /// them would be matching noise.- static func methodImplementation(- forSelectorReference selrefVA: UInt64,- in data: Data,- section: MachOSectionInfo,- ) -> UInt64? {- let smallMethodListFlag: UInt32 = 0x8000_0000- let entrySizeMask: UInt32 = 0x0000_FFFC- let entrySize = 12-- let base = Int(section.fileOffset)- let size = Int(section.size)- guard base >= 0, base + size <= data.count else { return nil }-- var cursor = 0- while cursor + 8 <= size {- let header = data.loadLE(UInt32.self, at: base + cursor)- let count = Int(data.loadLE(UInt32.self, at: base + cursor + 4))- guard header & smallMethodListFlag != 0,- Int(header & entrySizeMask) == entrySize,- count > 0,- cursor + 8 + count * entrySize <= size- else { return nil }-- for index in 0 ..< count {- let entry = cursor + 8 + index * entrySize- let entryVA = section.address + UInt64(entry)- let nameDelta = Int(data.loadLE(Int32.self, at: base + entry))- guard UInt64(bitPattern: Int64(entryVA) + Int64(nameDelta)) == selrefVA else {- continue- }- // { name, types, imp } — the imp field is 8 bytes in, and its- // delta is relative to the imp field's own address.- let impField = entryVA + 8- let impDelta = Int(data.loadLE(Int32.self, at: base + entry + 8))- return UInt64(bitPattern: Int64(impField) + Int64(impDelta))- }- cursor += 8 + count * entrySize- cursor = (cursor + 7) & ~7- }- return nil- }-- /// `segment,section` of the executable section containing `va`, or nil when- /// the address is not in one.- ///- /// Executability is read off the segment's `initprot`, not off the segment's- /// name, so this keeps working if the IMP ever lives somewhere other than- /// `__TEXT,__text`.- static func executableSection(containing va: UInt64, in data: Data) -> String? {- let vmProtExecute: UInt32 = 0x4- var executableSegments: Set<String> = []-- let ncmds = data.loadLE(UInt32.self, at: 16)- var offset = 32 // sizeof(mach_header_64)- for _ in 0 ..< ncmds {- guard offset + 8 <= data.count else { break }- let cmd = data.loadLE(UInt32.self, at: offset)- let cmdsize = Int(data.loadLE(UInt32.self, at: offset + 4))- guard cmdsize > 0 else { break }- if cmd == 0x19, offset + 64 <= data.count { // LC_SEGMENT_64- let initprot = data.loadLE(UInt32.self, at: offset + 60)- if initprot & vmProtExecute != 0 {- let raw = data[offset + 8 ..< offset + 24]- executableSegments.insert(- String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self),- )- }- }- offset += cmdsize- }-- for (key, section) in MachOParser.parseSections(from: data)- where executableSegments.contains(section.segmentName)- && va >= section.address && va < section.address + section.size- {- return key- }- return nil- }-// MARK: - Body Shape/// Decode the eight bytes the patch replaces.diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogd.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogd.swiftindex 9a3b5f16..cbdd0dc9 100644--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogd.swift+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogd.swift@@ -328,245 +328,6 @@ public enum CustomFirmwareWatchdogd {return Report(outcome: .patched, sites: sites, records: records, rehashedSlots: rehashed)}- // MARK: - Site discovery-- /// Every VM-presence cache site in `data`, pristine or already patched, in- /// address order.- ///- /// Throws rather than returning an empty array when nothing matches: an- /// empty result would be indistinguishable from "this binary does not need- /// the patch", and for watchdogd it always does.- public static func locateSites(in data: Data, log: ((String) -> Void)? = nil) throws -> [Site] {- let data = data.startIndex == 0 ? data : Data(data)- let sections = MachOParser.parseSections(from: data)- guard let text = sections[textSectionKey] else {- throw PatcherError.invalidFormat("no \(textSectionKey) section")- }- guard let literal = findLiteral(in: data, sections: sections) else {- throw PatcherError.patchSiteNotFound("'\(sysctlName)' cstring not present")- }- log?(" [.] cstring at va:0x\(hex(literal.address)) "- + "(foff:0x\(hex(UInt64(literal.fileOffset))), sect=\(literal.section))")-- guard let symbols = CustomFirmwareWatchdogdSymbolTargets(data: data) else {- throw PatcherError.invalidFormat(- "no LC_SYMTAB/LC_DYSYMTAB — \(sysctlFunction) cannot be resolved",- )- }-- let start = Int(text.fileOffset)- let end = start + Int(text.size)- guard start >= 0, end <= data.count else {- throw PatcherError.invalidFormat("\(textSectionKey) falls outside the file")- }- let instructions = ARM64Disassembler().disassemble(data.subdata(in: start ..< end), at: text.address)-- let segments = MachOParser.parseSegments(from: data)- var pages: [UInt32: (page: UInt64, index: Int)] = [:]- var sites: [Site] = []-- for (index, instruction) in instructions.enumerated() {- // Capstone runs with `skipData` on, so a word it cannot decode- // arrives as a data pseudo-instruction rather than ending the- // stream. Register state across such a word means nothing.- guard instruction.id != 0 else {- pages.removeAll()- continue- }-- if instruction.mnemonic == "adrp" {- if let destination = registerNumber(instruction, 0),- let page = immediate(instruction, 1)- {- pages[destination] = (UInt64(bitPattern: page), index)- }- continue- }-- // Layer 2: an ADRP+ADD pair that resolves to the literal. The 64-bit- // form only — a `w` destination is arithmetic, not an address.- guard instruction.mnemonic == "add",- let pointer = registerName(instruction, 0), pointer.hasPrefix("x"),- let base = registerNumber(instruction, 1),- let offset = immediate(instruction, 2),- let page = pages[base],- index - page.index <= pageToOffsetWindow,- page.page &+ UInt64(bitPattern: offset) == literal.address- else { continue }-- guard let site = matchSite(- instructions: instructions,- addIndex: index,- pointerRegister: pointer,- literalVMA: literal.address,- text: text,- segments: segments,- symbols: symbols,- ) else { continue }-- if !sites.contains(where: { $0.gateVMA == site.gateVMA }) {- sites.append(site)- }- }-- guard !sites.isEmpty else {- throw PatcherError.patchSiteNotFound(- "no '\(sysctlName)' cache site: expected an adrp+add for the cstring reaching "- + "\(argumentRegister), a bl \(sysctlFunction), a cbnz w0 gate, a cset wN, ne "- + "and a strb into a \(globalSegmentPrefix) global",- )- }- return sites.sorted { $0.gateVMA < $1.gateVMA }- }-- /// Match the canonical shape forward from the ADD that formed the string- /// pointer. Returns `nil` when any layer of the anchor fails, which is how- /// the three unrelated `sysctlbyname` calls in watchdogd are rejected.- static func matchSite(- instructions: [Instruction],- addIndex: Int,- pointerRegister: String,- literalVMA: UInt64,- text: MachOSectionInfo,- segments: [MachOSegmentInfo],- symbols: CustomFirmwareWatchdogdSymbolTargets,- ) -> Site? {- // Layer 3: the call, and the import it resolves to.- guard let callIndex = firstIndex(- in: instructions, from: addIndex + 1, within: argumentSetupWindow,- where: { $0.mnemonic == "bl" },- ) else { return nil }- let call = instructions[callIndex]- guard let target = ARM64Encoder.decodeBranchTarget(- insn: word(of: call), pc: call.address,- ), symbols.name(forBranchTarget: target) == sysctlFunction else { return nil }-- // Layer 2, concluded: the literal has to be the call's `name` argument,- // not just something this stretch of code also mentions.- guard passesLiteral(- inRegister: pointerRegister, from: addIndex, toCallAt: callIndex, in: instructions,- ) else { return nil }-- // Layer 4a: the gate, which must be the very next instruction — the- // defensive check on the call's return value.- let gateIndex = callIndex + 1- guard gateIndex < instructions.count else { return nil }- let gate = instructions[gateIndex]- let state: Site.State- if gate.mnemonic == "cbnz", registerName(gate, 0) == "w0" {- state = .pristine- } else if gate.mnemonic == "nop" {- state = .patched- } else {- return nil- }-- // Layer 4b: the value the store writes. `cset wN, ne` is the stock- // truthiness of the sysctl's out-parameter; `mov wN, #1` is what this- // patch leaves in its place.- guard let valueIndex = firstIndex(- in: instructions, from: gateIndex + 1, within: gateToValueWindow,- where: { instruction in- switch state {- case .pristine:- instruction.mnemonic == "cset" && instruction.aarch64?.conditionCode == AArch64CC_NE- case .patched:- isMoveOfOne(instruction)- }- },- ) else { return nil }- let value = instructions[valueIndex]- guard let valueRegister = registerName(value, 0),- let valueNumber = wRegisterNumber(valueRegister) else { return nil }-- // Layer 5: the store of that same register into an ADRP-relative- // __DATA address — the cached global.- guard let storeIndex = firstIndex(- in: instructions, from: valueIndex + 1, within: valueToStoreWindow,- where: { $0.mnemonic == "strb" && registerName($0, 0) == valueRegister },- ) else { return nil }- let store = instructions[storeIndex]- guard let memory = memoryOperand(store) else { return nil }- guard let basePage = pageAddress(- ofRegister: UInt32(memory.base.rawValue),- before: storeIndex, notBefore: addIndex, in: instructions,- ) else { return nil }- let cachedByte = basePage &+ UInt64(bitPattern: Int64(memory.disp))- guard let segment = segments.first(where: {- cachedByte >= $0.vmAddr && cachedByte < $0.vmAddr &+ $0.vmSize- }), segment.name.hasPrefix(globalSegmentPrefix) else { return nil }-- return Site(- state: state,- literalVMA: literalVMA,- addVMA: instructions[addIndex].address,- callVMA: call.address,- gateVMA: gate.address,- gateFileOffset: fileOffset(of: gate.address, in: text),- valueVMA: value.address,- valueFileOffset: fileOffset(of: value.address, in: text),- valueRegister: valueRegister,- valueRegisterNumber: valueNumber,- storeVMA: store.address,- cachedByteVMA: cachedByte,- )- }-- /// True when the literal the ADD at `addIndex` formed is in `x0` by the time- /// the call at `callIndex` runs.- ///- /// Two ways that happens, and both occur in Apple's own codegen: the ADD- /// writes `x0` outright, or it writes a scratch register that a later- /// `mov x0, xN` moves into place. Accepting only the first would make the- /// patch miss the site on a build that schedules the argument differently —- /// loudly, but still wrongly.- static func passesLiteral(- inRegister pointer: String,- from addIndex: Int,- toCallAt callIndex: Int,- in instructions: [Instruction],- ) -> Bool {- if pointer == argumentRegister {- return true- }- for index in (addIndex + 1) ..< callIndex {- let instruction = instructions[index]- if instruction.mnemonic == "mov",- registerName(instruction, 0) == argumentRegister,- registerName(instruction, 1) == pointer- {- return true- }- }- return false- }-- /// The literal's VA, file offset and section, matched only at a string- /// boundary so a suffix of a longer literal cannot pass.- static func findLiteral(- in data: Data,- sections: [String: MachOSectionInfo],- ) -> (address: UInt64, fileOffset: Int, section: String)? {- for (key, section) in sections.sorted(by: { $0.key < $1.key })- where literalSectionNames.contains(section.sectionName)- {- let start = Int(section.fileOffset)- let end = start + Int(section.size)- guard start >= 0, end <= data.count, start < end else { continue }- let body = data.subdata(in: start ..< end)-- var searchFrom = body.startIndex- while let found = body.range(of: needle, in: searchFrom ..< body.endIndex) {- let index = found.lowerBound- if index == body.startIndex || body[index - 1] == 0 {- return (section.address &+ UInt64(index), start + index, key)- }- searchFrom = index + 1- }- }- return nil- }-// MARK: - Verification/// Read the patched words back out and confirm they are what was written.@@ -734,153 +495,3 @@ public enum CustomFirmwareWatchdogd {String(value, radix: 16, uppercase: true)}}--// MARK: - Symbol targets--/// Resolves a branch target to the name of the function it calls.-///-/// Two paths, because a call can reach a function either way:-///-/// * through a stub section (`S_SYMBOL_STUBS`, which is what `__auth_stubs`-/// is), whose entries map one-to-one onto a window of the indirect symbol-/// table — the classic Mach-O import lookup, and the one watchdogd's-/// `bl _sysctlbyname` takes;-/// * directly to a defined symbol, for a statically linked build.-///-/// This is deliberately not in `MachOParser`: it needs each section's `flags`,-/// `reserved1` and `reserved2` and the `LC_DYSYMTAB` indirect table, none of-/// which that shared parser exposes. It carries this patcher's name because-/// this patcher is its only caller — the first time a second one needs the same-/// lookup, move it to `Binary/` under a neutral name rather than growing a copy.-struct CustomFirmwareWatchdogdSymbolTargets {- /// A section of branch-island stubs, one per imported symbol.- struct StubSection {- let address: UInt64- let size: UInt64- /// `reserved2` — bytes per stub.- let entrySize: UInt64- /// `reserved1` — index of this section's first indirect symbol.- let firstIndirectIndex: Int- }-- let data: Data- let symbolOffset: Int- let symbolCount: Int- let stringOffset: Int- let stringSize: Int- let indirectOffset: Int- let indirectCount: Int- let stubSections: [StubSection]-- static let machMagic64: UInt32 = 0xFEED_FACF- static let lcSegment64: UInt32 = 0x19- static let lcDysymtab: UInt32 = 0x0B- /// `SECTION_TYPE` of a stub section.- static let sectionTypeSymbolStubs: UInt32 = 0x08- /// Indirect entries that name no import.- static let indirectSymbolLocal: UInt32 = 0x8000_0000- static let indirectSymbolAbs: UInt32 = 0x4000_0000- /// `N_STAB` — a debug entry, never a call target name.- static let symbolIsDebug: UInt8 = 0xE0-- init?(data: Data) {- let data = data.startIndex == 0 ? data : Data(data)- guard data.count > 32, data.loadLE(UInt32.self, at: 0) == Self.machMagic64 else { return nil }- guard let symtab = MachOParser.parseSymtab(from: data) else { return nil }-- var indirectOffset = 0- var indirectCount = 0- var stubs: [StubSection] = []-- let commandCount = data.loadLE(UInt32.self, at: 16)- var offset = 32- for _ in 0 ..< commandCount {- guard offset + 8 <= data.count else { return nil }- let command = data.loadLE(UInt32.self, at: offset)- let commandSize = Int(data.loadLE(UInt32.self, at: offset + 4))- guard commandSize > 0 else { return nil }-- if command == Self.lcDysymtab, offset + 64 <= data.count {- indirectOffset = Int(data.loadLE(UInt32.self, at: offset + 56))- indirectCount = Int(data.loadLE(UInt32.self, at: offset + 60))- } else if command == Self.lcSegment64, offset + 72 <= data.count {- let sectionCount = data.loadLE(UInt32.self, at: offset + 64)- var section = offset + 72- for _ in 0 ..< sectionCount {- guard section + 80 <= data.count else { break }- let flags = data.loadLE(UInt32.self, at: section + 64)- let entrySize = UInt64(data.loadLE(UInt32.self, at: section + 72)) // reserved2- if flags & 0xFF == Self.sectionTypeSymbolStubs, entrySize > 0 {- stubs.append(StubSection(- address: data.loadLE(UInt64.self, at: section + 32),- size: data.loadLE(UInt64.self, at: section + 40),- entrySize: entrySize,- firstIndirectIndex: Int(data.loadLE(UInt32.self, at: section + 68)), // reserved1- ))- }- section += 80- }- }- offset += commandSize- }-- self.data = data- symbolOffset = symtab.symoff- symbolCount = symtab.nsyms- stringOffset = symtab.stroff- stringSize = symtab.strsize- self.indirectOffset = indirectOffset- self.indirectCount = indirectCount- stubSections = stubs- }-- /// Name of the function a `bl`/`b` to `address` ends up in, or `nil`.- func name(forBranchTarget address: UInt64) -> String? {- importName(atStub: address) ?? definedName(at: address)- }-- /// The imported symbol a stub at `address` stands for.- func importName(atStub address: UInt64) -> String? {- guard indirectCount > 0 else { return nil }- for section in stubSections {- guard address >= section.address, address < section.address &+ section.size else { continue }- let index = section.firstIndirectIndex + Int((address - section.address) / section.entrySize)- guard index >= 0, index < indirectCount else { return nil }- let entryOffset = indirectOffset + index * 4- guard entryOffset + 4 <= data.count else { return nil }- let entry = data.loadLE(UInt32.self, at: entryOffset)- guard entry & (Self.indirectSymbolLocal | Self.indirectSymbolAbs) == 0 else { return nil }- return symbolName(at: Int(entry))- }- return nil- }-- /// A defined symbol whose value is exactly `address`.- func definedName(at address: UInt64) -> String? {- guard address != 0 else { return nil }- for index in 0 ..< symbolCount {- let entry = symbolOffset + index * 16- guard entry + 16 <= data.count else { return nil }- guard data[entry + 4] & Self.symbolIsDebug == 0 else { continue }- guard data.loadLE(UInt64.self, at: entry + 8) == address else { continue }- return symbolName(at: index)- }- return nil- }-- func symbolName(at index: Int) -> String? {- guard index >= 0, index < symbolCount else { return nil }- let entry = symbolOffset + index * 16- guard entry + 4 <= data.count else { return nil }- let stringIndex = Int(data.loadLE(UInt32.self, at: entry))- guard stringIndex < stringSize else { return nil }- let start = stringOffset + stringIndex- guard start < data.count else { return nil }- var end = start- let limit = min(data.count, stringOffset + stringSize)- while end < limit, data[end] != 0 {- end += 1- }- return String(data: data.subdata(in: start ..< end), encoding: .utf8)- }-}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swiftnew file mode 100644index 00000000..c5a60528--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swift@@ -0,0 +1,245 @@+// CustomFirmwareWatchdogdDiscovery.swift — Locate watchdogd VM-presence cache sites.++import Capstone+import Foundation++extension CustomFirmwareWatchdogd {+ // MARK: - Site discovery++ /// Every VM-presence cache site in `data`, pristine or already patched, in+ /// address order.+ ///+ /// Throws rather than returning an empty array when nothing matches: an+ /// empty result would be indistinguishable from "this binary does not need+ /// the patch", and for watchdogd it always does.+ public static func locateSites(in data: Data, log: ((String) -> Void)? = nil) throws -> [Site] {+ let data = data.startIndex == 0 ? data : Data(data)+ let sections = MachOParser.parseSections(from: data)+ guard let text = sections[textSectionKey] else {+ throw PatcherError.invalidFormat("no \(textSectionKey) section")+ }+ guard let literal = findLiteral(in: data, sections: sections) else {+ throw PatcherError.patchSiteNotFound("'\(sysctlName)' cstring not present")+ }+ log?(" [.] cstring at va:0x\(hex(literal.address)) "+ + "(foff:0x\(hex(UInt64(literal.fileOffset))), sect=\(literal.section))")++ guard let symbols = CustomFirmwareWatchdogdSymbolTargets(data: data) else {+ throw PatcherError.invalidFormat(+ "no LC_SYMTAB/LC_DYSYMTAB — \(sysctlFunction) cannot be resolved",+ )+ }++ let start = Int(text.fileOffset)+ let end = start + Int(text.size)+ guard start >= 0, end <= data.count else {+ throw PatcherError.invalidFormat("\(textSectionKey) falls outside the file")+ }+ let instructions = ARM64Disassembler().disassemble(data.subdata(in: start ..< end), at: text.address)++ let segments = MachOParser.parseSegments(from: data)+ var pages: [UInt32: (page: UInt64, index: Int)] = [:]+ var sites: [Site] = []++ for (index, instruction) in instructions.enumerated() {+ // Capstone runs with `skipData` on, so a word it cannot decode+ // arrives as a data pseudo-instruction rather than ending the+ // stream. Register state across such a word means nothing.+ guard instruction.id != 0 else {+ pages.removeAll()+ continue+ }++ if instruction.mnemonic == "adrp" {+ if let destination = registerNumber(instruction, 0),+ let page = immediate(instruction, 1)+ {+ pages[destination] = (UInt64(bitPattern: page), index)+ }+ continue+ }++ // Layer 2: an ADRP+ADD pair that resolves to the literal. The 64-bit+ // form only — a `w` destination is arithmetic, not an address.+ guard instruction.mnemonic == "add",+ let pointer = registerName(instruction, 0), pointer.hasPrefix("x"),+ let base = registerNumber(instruction, 1),+ let offset = immediate(instruction, 2),+ let page = pages[base],+ index - page.index <= pageToOffsetWindow,+ page.page &+ UInt64(bitPattern: offset) == literal.address+ else { continue }++ guard let site = matchSite(+ instructions: instructions,+ addIndex: index,+ pointerRegister: pointer,+ literalVMA: literal.address,+ text: text,+ segments: segments,+ symbols: symbols,+ ) else { continue }++ if !sites.contains(where: { $0.gateVMA == site.gateVMA }) {+ sites.append(site)+ }+ }++ guard !sites.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "no '\(sysctlName)' cache site: expected an adrp+add for the cstring reaching "+ + "\(argumentRegister), a bl \(sysctlFunction), a cbnz w0 gate, a cset wN, ne "+ + "and a strb into a \(globalSegmentPrefix) global",+ )+ }+ return sites.sorted { $0.gateVMA < $1.gateVMA }+ }++ /// Match the canonical shape forward from the ADD that formed the string+ /// pointer. Returns `nil` when any layer of the anchor fails, which is how+ /// the three unrelated `sysctlbyname` calls in watchdogd are rejected.+ static func matchSite(+ instructions: [Instruction],+ addIndex: Int,+ pointerRegister: String,+ literalVMA: UInt64,+ text: MachOSectionInfo,+ segments: [MachOSegmentInfo],+ symbols: CustomFirmwareWatchdogdSymbolTargets,+ ) -> Site? {+ // Layer 3: the call, and the import it resolves to.+ guard let callIndex = firstIndex(+ in: instructions, from: addIndex + 1, within: argumentSetupWindow,+ where: { $0.mnemonic == "bl" },+ ) else { return nil }+ let call = instructions[callIndex]+ guard let target = ARM64Encoder.decodeBranchTarget(+ insn: word(of: call), pc: call.address,+ ), symbols.name(forBranchTarget: target) == sysctlFunction else { return nil }++ // Layer 2, concluded: the literal has to be the call's `name` argument,+ // not just something this stretch of code also mentions.+ guard passesLiteral(+ inRegister: pointerRegister, from: addIndex, toCallAt: callIndex, in: instructions,+ ) else { return nil }++ // Layer 4a: the gate, which must be the very next instruction — the+ // defensive check on the call's return value.+ let gateIndex = callIndex + 1+ guard gateIndex < instructions.count else { return nil }+ let gate = instructions[gateIndex]+ let state: Site.State+ if gate.mnemonic == "cbnz", registerName(gate, 0) == "w0" {+ state = .pristine+ } else if gate.mnemonic == "nop" {+ state = .patched+ } else {+ return nil+ }++ // Layer 4b: the value the store writes. `cset wN, ne` is the stock+ // truthiness of the sysctl's out-parameter; `mov wN, #1` is what this+ // patch leaves in its place.+ guard let valueIndex = firstIndex(+ in: instructions, from: gateIndex + 1, within: gateToValueWindow,+ where: { instruction in+ switch state {+ case .pristine:+ instruction.mnemonic == "cset" && instruction.aarch64?.conditionCode == AArch64CC_NE+ case .patched:+ isMoveOfOne(instruction)+ }+ },+ ) else { return nil }+ let value = instructions[valueIndex]+ guard let valueRegister = registerName(value, 0),+ let valueNumber = wRegisterNumber(valueRegister) else { return nil }++ // Layer 5: the store of that same register into an ADRP-relative+ // __DATA address — the cached global.+ guard let storeIndex = firstIndex(+ in: instructions, from: valueIndex + 1, within: valueToStoreWindow,+ where: { $0.mnemonic == "strb" && registerName($0, 0) == valueRegister },+ ) else { return nil }+ let store = instructions[storeIndex]+ guard let memory = memoryOperand(store) else { return nil }+ guard let basePage = pageAddress(+ ofRegister: UInt32(memory.base.rawValue),+ before: storeIndex, notBefore: addIndex, in: instructions,+ ) else { return nil }+ let cachedByte = basePage &+ UInt64(bitPattern: Int64(memory.disp))+ guard let segment = segments.first(where: {+ cachedByte >= $0.vmAddr && cachedByte < $0.vmAddr &+ $0.vmSize+ }), segment.name.hasPrefix(globalSegmentPrefix) else { return nil }++ return Site(+ state: state,+ literalVMA: literalVMA,+ addVMA: instructions[addIndex].address,+ callVMA: call.address,+ gateVMA: gate.address,+ gateFileOffset: fileOffset(of: gate.address, in: text),+ valueVMA: value.address,+ valueFileOffset: fileOffset(of: value.address, in: text),+ valueRegister: valueRegister,+ valueRegisterNumber: valueNumber,+ storeVMA: store.address,+ cachedByteVMA: cachedByte,+ )+ }++ /// True when the literal the ADD at `addIndex` formed is in `x0` by the time+ /// the call at `callIndex` runs.+ ///+ /// Two ways that happens, and both occur in Apple's own codegen: the ADD+ /// writes `x0` outright, or it writes a scratch register that a later+ /// `mov x0, xN` moves into place. Accepting only the first would make the+ /// patch miss the site on a build that schedules the argument differently —+ /// loudly, but still wrongly.+ static func passesLiteral(+ inRegister pointer: String,+ from addIndex: Int,+ toCallAt callIndex: Int,+ in instructions: [Instruction],+ ) -> Bool {+ if pointer == argumentRegister {+ return true+ }+ for index in (addIndex + 1) ..< callIndex {+ let instruction = instructions[index]+ if instruction.mnemonic == "mov",+ registerName(instruction, 0) == argumentRegister,+ registerName(instruction, 1) == pointer+ {+ return true+ }+ }+ return false+ }++ /// The literal's VA, file offset and section, matched only at a string+ /// boundary so a suffix of a longer literal cannot pass.+ static func findLiteral(+ in data: Data,+ sections: [String: MachOSectionInfo],+ ) -> (address: UInt64, fileOffset: Int, section: String)? {+ for (key, section) in sections.sorted(by: { $0.key < $1.key })+ where literalSectionNames.contains(section.sectionName)+ {+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard start >= 0, end <= data.count, start < end else { continue }+ let body = data.subdata(in: start ..< end)++ var searchFrom = body.startIndex+ while let found = body.range(of: needle, in: searchFrom ..< body.endIndex) {+ let index = found.lowerBound+ if index == body.startIndex || body[index - 1] == 0 {+ return (section.address &+ UInt64(index), start + index, key)+ }+ searchFrom = index + 1+ }+ }+ return nil+ }+}diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdSymbolTargets.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdSymbolTargets.swiftnew file mode 100644index 00000000..90f786ed--- /dev/null+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdSymbolTargets.swift@@ -0,0 +1,153 @@+// CustomFirmwareWatchdogdSymbolTargets.swift — Resolve watchdogd branch targets.++import Foundation++// MARK: - Symbol targets++/// Resolves a branch target to the name of the function it calls.+///+/// Two paths, because a call can reach a function either way:+///+/// * through a stub section (`S_SYMBOL_STUBS`, which is what `__auth_stubs`+/// is), whose entries map one-to-one onto a window of the indirect symbol+/// table — the classic Mach-O import lookup, and the one watchdogd's+/// `bl _sysctlbyname` takes;+/// * directly to a defined symbol, for a statically linked build.+///+/// This is deliberately not in `MachOParser`: it needs each section's `flags`,+/// `reserved1` and `reserved2` and the `LC_DYSYMTAB` indirect table, none of+/// which that shared parser exposes. It carries this patcher's name because+/// this patcher is its only caller — the first time a second one needs the same+/// lookup, move it to `Binary/` under a neutral name rather than growing a copy.+struct CustomFirmwareWatchdogdSymbolTargets {+ /// A section of branch-island stubs, one per imported symbol.+ struct StubSection {+ let address: UInt64+ let size: UInt64+ /// `reserved2` — bytes per stub.+ let entrySize: UInt64+ /// `reserved1` — index of this section's first indirect symbol.+ let firstIndirectIndex: Int+ }++ let data: Data+ let symbolOffset: Int+ let symbolCount: Int+ let stringOffset: Int+ let stringSize: Int+ let indirectOffset: Int+ let indirectCount: Int+ let stubSections: [StubSection]++ static let machMagic64: UInt32 = 0xFEED_FACF+ static let lcSegment64: UInt32 = 0x19+ static let lcDysymtab: UInt32 = 0x0B+ /// `SECTION_TYPE` of a stub section.+ static let sectionTypeSymbolStubs: UInt32 = 0x08+ /// Indirect entries that name no import.+ static let indirectSymbolLocal: UInt32 = 0x8000_0000+ static let indirectSymbolAbs: UInt32 = 0x4000_0000+ /// `N_STAB` — a debug entry, never a call target name.+ static let symbolIsDebug: UInt8 = 0xE0++ init?(data: Data) {+ let data = data.startIndex == 0 ? data : Data(data)+ guard data.count > 32, data.loadLE(UInt32.self, at: 0) == Self.machMagic64 else { return nil }+ guard let symtab = MachOParser.parseSymtab(from: data) else { return nil }++ var indirectOffset = 0+ var indirectCount = 0+ var stubs: [StubSection] = []++ let commandCount = data.loadLE(UInt32.self, at: 16)+ var offset = 32+ for _ in 0 ..< commandCount {+ guard offset + 8 <= data.count else { return nil }+ let command = data.loadLE(UInt32.self, at: offset)+ let commandSize = Int(data.loadLE(UInt32.self, at: offset + 4))+ guard commandSize > 0 else { return nil }++ if command == Self.lcDysymtab, offset + 64 <= data.count {+ indirectOffset = Int(data.loadLE(UInt32.self, at: offset + 56))+ indirectCount = Int(data.loadLE(UInt32.self, at: offset + 60))+ } else if command == Self.lcSegment64, offset + 72 <= data.count {+ let sectionCount = data.loadLE(UInt32.self, at: offset + 64)+ var section = offset + 72+ for _ in 0 ..< sectionCount {+ guard section + 80 <= data.count else { break }+ let flags = data.loadLE(UInt32.self, at: section + 64)+ let entrySize = UInt64(data.loadLE(UInt32.self, at: section + 72)) // reserved2+ if flags & 0xFF == Self.sectionTypeSymbolStubs, entrySize > 0 {+ stubs.append(StubSection(+ address: data.loadLE(UInt64.self, at: section + 32),+ size: data.loadLE(UInt64.self, at: section + 40),+ entrySize: entrySize,+ firstIndirectIndex: Int(data.loadLE(UInt32.self, at: section + 68)), // reserved1+ ))+ }+ section += 80+ }+ }+ offset += commandSize+ }++ self.data = data+ symbolOffset = symtab.symoff+ symbolCount = symtab.nsyms+ stringOffset = symtab.stroff+ stringSize = symtab.strsize+ self.indirectOffset = indirectOffset+ self.indirectCount = indirectCount+ stubSections = stubs+ }++ /// Name of the function a `bl`/`b` to `address` ends up in, or `nil`.+ func name(forBranchTarget address: UInt64) -> String? {+ importName(atStub: address) ?? definedName(at: address)+ }++ /// The imported symbol a stub at `address` stands for.+ func importName(atStub address: UInt64) -> String? {+ guard indirectCount > 0 else { return nil }+ for section in stubSections {+ guard address >= section.address, address < section.address &+ section.size else { continue }+ let index = section.firstIndirectIndex + Int((address - section.address) / section.entrySize)+ guard index >= 0, index < indirectCount else { return nil }+ let entryOffset = indirectOffset + index * 4+ guard entryOffset + 4 <= data.count else { return nil }+ let entry = data.loadLE(UInt32.self, at: entryOffset)+ guard entry & (Self.indirectSymbolLocal | Self.indirectSymbolAbs) == 0 else { return nil }+ return symbolName(at: Int(entry))+ }+ return nil+ }++ /// A defined symbol whose value is exactly `address`.+ func definedName(at address: UInt64) -> String? {+ guard address != 0 else { return nil }+ for index in 0 ..< symbolCount {+ let entry = symbolOffset + index * 16+ guard entry + 16 <= data.count else { return nil }+ guard data[entry + 4] & Self.symbolIsDebug == 0 else { continue }+ guard data.loadLE(UInt64.self, at: entry + 8) == address else { continue }+ return symbolName(at: index)+ }+ return nil+ }++ func symbolName(at index: Int) -> String? {+ guard index >= 0, index < symbolCount else { return nil }+ let entry = symbolOffset + index * 16+ guard entry + 4 <= data.count else { return nil }+ let stringIndex = Int(data.loadLE(UInt32.self, at: entry))+ guard stringIndex < stringSize else { return nil }+ let start = stringOffset + stringIndex+ guard start < data.count else { return nil }+ var end = start+ let limit = min(data.count, stringOffset + stringSize)+ while end < limit, data[end] != 0 {+ end += 1+ }+ return String(data: data.subdata(in: start ..< end), encoding: .utf8)+ }+}diff --git a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher+MachOStringSites.swift b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher+MachOStringSites.swiftnew file mode 100644index 00000000..53197418--- /dev/null+++ b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher+MachOStringSites.swift@@ -0,0 +1,137 @@+import Foundation++extension DyldSharedCacheHVVMMPatcher {+ /// One occurrence of the pristine cstring in a standalone Mach-O.+ public struct MachOStringSite: Sendable, Equatable {+ /// Address the literal is mapped at.+ public let stringVMA: UInt64+ /// Offset of the literal in the file.+ public let fileOffset: Int+ /// `"segment,section"` it was found in.+ public let section: String+ }++ /// Every pristine `"kern.hv_vmm_present\0"` in `data`'s string sections.+ ///+ /// Hits are anchored at a cstring boundary — the start of the section, or+ /// just after a NUL — so the tail of some longer literal that happens to end+ /// in these bytes is not returned.+ ///+ /// - Throws: ``PatcherError/invalidFormat(_:)`` when `data` is not a 64-bit+ /// little-endian Mach-O. A fat binary has to be sliced first.+ public static func findStringSites(inMachO data: Data) throws -> [MachOStringSite] {+ let image = data.startIndex == 0 ? data : Data(data)+ var sites: [MachOStringSite] = []+ for (name, section) in try machOSections(of: image)+ where cstringSectionNames.contains(section.sectionName)+ {+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard start >= 0, end <= image.count, start <= end else { continue }+ let buffer = image[start ..< end]++ var searchFrom = buffer.startIndex+ while searchFrom < buffer.endIndex,+ let found = buffer.range(of: needle, in: searchFrom ..< buffer.endIndex)+ {+ let position = found.lowerBound - buffer.startIndex+ if position == 0 || buffer[buffer.startIndex + position - 1] == 0 {+ sites.append(+ MachOStringSite(+ stringVMA: section.address &+ UInt64(position),+ fileOffset: start + position,+ section: name,+ ),+ )+ }+ searchFrom = found.lowerBound + 1+ }+ }+ return sites+ }++ /// True when `data` holds the mangled form anywhere.+ ///+ /// Only for saying something useful in the log: ``findStringSites(inMachO:)``+ /// already returns nothing for an already-patched binary, so the patch flow+ /// is idempotent with or without this.+ public static func isAlreadyMangled(_ data: Data) -> Bool {+ data.range(of: mangledNeedle) != nil+ }++ // MARK: - Minimal Mach-O section table++ /// One `section_64`, reduced to what the string scan needs.+ struct MachOSection {+ let segmentName: String+ let sectionName: String+ let address: UInt64+ let size: UInt64+ let fileOffset: UInt32+ }++ /// `LC_SEGMENT_64` sections of a thin 64-bit Mach-O, as+ /// `("segment,section", section)` pairs.+ ///+ /// Later sections with the same `"segment,section"` name replace earlier+ /// ones while keeping the earlier one's position, which is what the+ /// reference's dict does and is the only reason the two agree on the order+ /// sites come back in.+ static func machOSections(of data: Data) throws -> [(String, MachOSection)] {+ guard data.count >= 32 else {+ throw PatcherError.invalidFormat("truncated Mach-O header (\(data.count) bytes)")+ }+ let magic = data.loadLE(UInt32.self, at: 0)+ guard magic == 0xFEED_FACF else {+ throw PatcherError.invalidFormat(+ "not a 64-bit Mach-O (magic=0x\(String(magic, radix: 16, uppercase: true)))",+ )+ }++ let commandCount = Int(data.loadLE(UInt32.self, at: 16))+ var ordered: [String] = []+ var byName: [String: MachOSection] = [:]+ var offset = 32+ for _ in 0 ..< commandCount {+ guard offset + 8 <= data.count else { break }+ let command = data.loadLE(UInt32.self, at: offset)+ let commandSize = Int(data.loadLE(UInt32.self, at: offset + 4))+ guard commandSize >= 8, offset + commandSize <= data.count else { break }++ if command == 0x19 { // LC_SEGMENT_64+ let segmentName = fixedWidthName(data, at: offset + 8)+ let sectionCount = Int(data.loadLE(UInt32.self, at: offset + 64))+ var sectionOffset = offset + 72+ for _ in 0 ..< sectionCount {+ guard sectionOffset + 80 <= data.count else { break }+ let sectionName = fixedWidthName(data, at: sectionOffset)+ let key = "\(segmentName),\(sectionName)"+ if byName[key] == nil {+ ordered.append(key)+ }+ byName[key] = MachOSection(+ segmentName: segmentName,+ sectionName: sectionName,+ address: data.loadLE(UInt64.self, at: sectionOffset + 32),+ size: data.loadLE(UInt64.self, at: sectionOffset + 40),+ fileOffset: data.loadLE(UInt32.self, at: sectionOffset + 48),+ )+ sectionOffset += 80+ }+ }+ offset += commandSize+ }+ return ordered.compactMap { key in byName[key].map { (key, $0) } }+ }++ /// A 16-byte NUL-padded Mach-O name field.+ private static func fixedWidthName(_ data: Data, at offset: Int) -> String {+ let start = data.startIndex + offset+ let end = min(start + 16, data.endIndex)+ guard start < end else { return "" }+ let field = data[start ..< end]+ let terminated = field.prefix { $0 != 0 }+ return String(decoding: terminated, as: UTF8.self)+ }++}diff --git a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher.swift b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher.swiftindex b47859f7..b65561c1 100644--- a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher.swift+++ b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHVVMMPatcher.swift@@ -500,64 +500,6 @@ public enum DyldSharedCacheHVVMMPatcher {// `research/0_binary_patch_comparison.md` still names six files it applies// to.- /// One occurrence of the pristine cstring in a standalone Mach-O.- public struct MachOStringSite: Sendable, Equatable {- /// Address the literal is mapped at.- public let stringVMA: UInt64- /// Offset of the literal in the file.- public let fileOffset: Int- /// `"segment,section"` it was found in.- public let section: String- }-- /// Every pristine `"kern.hv_vmm_present\0"` in `data`'s string sections.- ///- /// Hits are anchored at a cstring boundary — the start of the section, or- /// just after a NUL — so the tail of some longer literal that happens to end- /// in these bytes is not returned.- ///- /// - Throws: ``PatcherError/invalidFormat(_:)`` when `data` is not a 64-bit- /// little-endian Mach-O. A fat binary has to be sliced first.- public static func findStringSites(inMachO data: Data) throws -> [MachOStringSite] {- let image = data.startIndex == 0 ? data : Data(data)- var sites: [MachOStringSite] = []- for (name, section) in try machOSections(of: image)- where cstringSectionNames.contains(section.sectionName)- {- let start = Int(section.fileOffset)- let end = start + Int(section.size)- guard start >= 0, end <= image.count, start <= end else { continue }- let buffer = image[start ..< end]-- var searchFrom = buffer.startIndex- while searchFrom < buffer.endIndex,- let found = buffer.range(of: needle, in: searchFrom ..< buffer.endIndex)- {- let position = found.lowerBound - buffer.startIndex- if position == 0 || buffer[buffer.startIndex + position - 1] == 0 {- sites.append(- MachOStringSite(- stringVMA: section.address &+ UInt64(position),- fileOffset: start + position,- section: name,- ),- )- }- searchFrom = found.lowerBound + 1- }- }- return sites- }-- /// True when `data` holds the mangled form anywhere.- ///- /// Only for saying something useful in the log: ``findStringSites(inMachO:)``- /// already returns nothing for an already-patched binary, so the patch flow- /// is idempotent with or without this.- public static func isAlreadyMangled(_ data: Data) -> Bool {- data.range(of: mangledNeedle) != nil- }-/// Mangle every cstring site in the Mach-O at `url`.////// - Returns: how many sites were mangled. Idempotent: a second run finds@@ -631,81 +573,6 @@ public enum DyldSharedCacheHVVMMPatcher {return patched}- // MARK: - Minimal Mach-O section table-- /// One `section_64`, reduced to what the string scan needs.- struct MachOSection {- let segmentName: String- let sectionName: String- let address: UInt64- let size: UInt64- let fileOffset: UInt32- }-- /// `LC_SEGMENT_64` sections of a thin 64-bit Mach-O, as- /// `("segment,section", section)` pairs.- ///- /// Later sections with the same `"segment,section"` name replace earlier- /// ones while keeping the earlier one's position, which is what the- /// reference's dict does and is the only reason the two agree on the order- /// sites come back in.- static func machOSections(of data: Data) throws -> [(String, MachOSection)] {- guard data.count >= 32 else {- throw PatcherError.invalidFormat("truncated Mach-O header (\(data.count) bytes)")- }- let magic = data.loadLE(UInt32.self, at: 0)- guard magic == 0xFEED_FACF else {- throw PatcherError.invalidFormat(- "not a 64-bit Mach-O (magic=0x\(String(magic, radix: 16, uppercase: true)))",- )- }-- let commandCount = Int(data.loadLE(UInt32.self, at: 16))- var ordered: [String] = []- var byName: [String: MachOSection] = [:]- var offset = 32- for _ in 0 ..< commandCount {- guard offset + 8 <= data.count else { break }- let command = data.loadLE(UInt32.self, at: offset)- let commandSize = Int(data.loadLE(UInt32.self, at: offset + 4))- guard commandSize >= 8, offset + commandSize <= data.count else { break }-- if command == 0x19 { // LC_SEGMENT_64- let segmentName = fixedWidthName(data, at: offset + 8)- let sectionCount = Int(data.loadLE(UInt32.self, at: offset + 64))- var sectionOffset = offset + 72- for _ in 0 ..< sectionCount {- guard sectionOffset + 80 <= data.count else { break }- let sectionName = fixedWidthName(data, at: sectionOffset)- let key = "\(segmentName),\(sectionName)"- if byName[key] == nil {- ordered.append(key)- }- byName[key] = MachOSection(- segmentName: segmentName,- sectionName: sectionName,- address: data.loadLE(UInt64.self, at: sectionOffset + 32),- size: data.loadLE(UInt64.self, at: sectionOffset + 40),- fileOffset: data.loadLE(UInt32.self, at: sectionOffset + 48),- )- sectionOffset += 80- }- }- offset += commandSize- }- return ordered.compactMap { key in byName[key].map { (key, $0) } }- }-- /// A 16-byte NUL-padded Mach-O name field.- private static func fixedWidthName(_ data: Data, at offset: Int) -> String {- let start = data.startIndex + offset- let end = min(start + 16, data.endIndex)- guard start < end else { return "" }- let field = data[start ..< end]- let terminated = field.prefix { $0 != 0 }- return String(decoding: terminated, as: UTF8.self)- }-// MARK: - Formattingprivate static func hex(_ value: UInt64) -> String {