Run a virtual iPhone on an Apple Silicon Mac.
Swift
chore: swift format 6.2
Lakrba00db391dfb
diff --git a/Package.swift b/Package.swiftindex e9e2e4db..69138641 100644--- a/Package.swift+++ b/Package.swift@@ -53,7 +53,7 @@ let package = Package("VPhoneArchive","VPhoneCore",],- path: "sources/FirmwarePatcher"+ path: "sources/FirmwarePatcher",),.target(name: "VPhoneCore",@@ -63,7 +63,7 @@ let package = Package(path: "sources/VPhoneCore",linkerSettings: [.linkedFramework("Virtualization"),- ]+ ],),// Archive reading and writing: the one place that knows how ownership,// permissions and path safety differ between unpacking onto a mounted@@ -76,7 +76,7 @@ let package = Package(.product(name: "LibArchive", package: "libarchive.xcframework"),"VPhoneCore",],- path: "sources/VPhoneArchive"+ path: "sources/VPhoneArchive",),// Ad-hoc and PKCS#12 Mach-O code signing, byte for byte what ldid// writes. It replaces ldid, which is the only program this project@@ -89,7 +89,7 @@ let package = Package(path: "sources/VPhoneSign",linkerSettings: [.linkedFramework("Security"),- ]+ ],),// libirecovery 1.3.1, vendored. It talks to iBoot/iBSS over USB, which// is the half of a restore that `idevicerestore` does not get from@@ -129,7 +129,7 @@ let package = Package(linkerSettings: [.linkedFramework("IOKit"),.linkedFramework("CoreFoundation"),- ]+ ],),// idevicerestore, vendored. This is the restore backend itself — the// thing scripts/pymobiledevice3_bridge.py has been standing in for,@@ -176,7 +176,7 @@ let package = Package(// check_aux.sh's system whitelist; nothing else is linked..linkedLibrary("curl"),.linkedLibrary("z"),- ]+ ],),// The Swift face of the two C targets above, and what actually// replaces scripts/pymobiledevice3_bridge.py: probe for a DFU/recovery@@ -197,7 +197,7 @@ let package = Package(path: "sources/VPhoneRestore",linkerSettings: [.linkedLibrary("z"),- ]+ ],),// Everything that touches a running guest: the machine, its window and// menus, the vsock channel and the host device bridges. It is a library@@ -218,7 +218,7 @@ let package = Package(.linkedFramework("SwiftUI"),.linkedFramework("CoreLocation"),.linkedFramework("AVFoundation"),- ]+ ],),// The only binary signed with sources/vphone.entitlements..executableTarget(@@ -228,7 +228,7 @@ let package = Package("VPhoneCore","VPhoneVMKit",],- path: "sources/vphone-vm"+ path: "sources/vphone-vm",),// The user-facing entry point. Note it depends on neither VPhoneVMKit// nor any of the five frameworks above: it never builds a machine, it@@ -251,7 +251,7 @@ let package = Package("VPhoneCore","VPhoneRestore",],- path: "sources/vphone-cli"+ path: "sources/vphone-cli",),.executableTarget(name: "vphone-archive",@@ -260,7 +260,7 @@ let package = Package("VPhoneArchive","VPhoneCore",],- path: "sources/vphone-archive"+ path: "sources/vphone-archive",),// The SUDO_ASKPASS program, and the probe behind `VPhoneSudo.route()`.// No ArgumentParser and no VPhoneCore: it is two verbs, it runs while@@ -269,7 +269,7 @@ let package = Package(// put AppKit under vphone-cli..executableTarget(name: "vphone-ask-for-permission",- path: "sources/vphone-ask-for-permission"+ path: "sources/vphone-ask-for-permission",),// `vphone-amfi-allow` is NOT here, and cannot be: SwiftPM emits arm64// and it has to be arm64e to read amfid's ObjC runtime. `scripts/build.sh`@@ -284,17 +284,17 @@ let package = Package(.testTarget(name: "FirmwarePatcherTests",dependencies: ["FirmwarePatcher"],- path: "tests/FirmwarePatcherTests"+ path: "tests/FirmwarePatcherTests",),.testTarget(name: "VPhoneCoreTests",dependencies: ["VPhoneCore"],- path: "tests/VPhoneCoreTests"+ path: "tests/VPhoneCoreTests",),.testTarget(name: "VPhoneArchiveTests",dependencies: ["VPhoneArchive"],- path: "tests/VPhoneArchiveTests"+ path: "tests/VPhoneArchiveTests",),.testTarget(name: "VPhoneSignTests",@@ -305,7 +305,7 @@ let package = Package(// `#filePath`, so they need to be on disk and not in a bundle,// and left in place SwiftPM would try to compile the .c and refuse// the target for mixing languages.- exclude: ["Fixtures"]+ exclude: ["Fixtures"],),// Everything here runs without a device attached: argument parsing,// the restore-tree rules, the .shsh naming and the C struct the@@ -314,7 +314,7 @@ let package = Package(.testTarget(name: "VPhoneRestoreTests",dependencies: ["VPhoneRestore"],- path: "tests/VPhoneRestoreTests"+ path: "tests/VPhoneRestoreTests",),- ]+ ],)diff --git a/research/VPhoneVirtualMachineRefactored.swift b/research/VPhoneVirtualMachineRefactored.swiftindex 28a6941d..f66263d4 100644--- a/research/VPhoneVirtualMachineRefactored.swift+++ b/research/VPhoneVirtualMachineRefactored.swift@@ -36,7 +36,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {width: 1290,height: 2796,pixelsPerInch: 460,- scale: 3.0+ scale: 3.0,)}@@ -60,7 +60,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {let platform = try configurePlatform(machineIDURL: options.machineIDURL,nvramURL: options.nvramURL,- hardwareModel: hardwareModel+ hardwareModel: hardwareModel,)if let machineIdentifier = platform.machineIdentifier {@@ -74,7 +74,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {let config = buildConfiguration(options: options,platform: platform,- bootloader: bootloader+ bootloader: bootloader,)try config.validate()@@ -98,7 +98,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {private func configurePlatform(machineIDURL: URL,nvramURL: URL,- hardwareModel: VZMacHardwareModel+ hardwareModel: VZMacHardwareModel,) throws -> VZMacPlatformConfiguration {let platform = VZMacPlatformConfiguration()platform.hardwareModel = hardwareModel@@ -109,7 +109,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {let auxiliaryStorage = try VZMacAuxiliaryStorage(creatingStorageAt: nvramURL,hardwareModel: hardwareModel,- options: .allowOverwrite+ options: .allowOverwrite,)platform.auxiliaryStorage = auxiliaryStorage@@ -158,7 +158,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {private func buildConfiguration(options: Configuration,platform: VZMacPlatformConfiguration,- bootloader: VZMacOSBootLoader+ bootloader: VZMacOSBootLoader,) -> VZVirtualMachineConfiguration {let config = VZVirtualMachineConfiguration()config.bootLoader = bootloader@@ -185,7 +185,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {let displayConfiguration = VZMacGraphicsDisplayConfiguration(widthInPixels: screen.width,heightInPixels: screen.height,- pixelsPerInch: screen.pixelsPerInch+ pixelsPerInch: screen.pixelsPerInch,)graphicsConfiguration.displays = [displayConfiguration]config.graphicsDevices = [graphicsConfiguration]@@ -230,7 +230,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {serialPort.attachment = VZFileHandleSerialPortAttachment(fileHandleForReading: inputPipe.fileHandleForReading,- fileHandleForWriting: outputPipe.fileHandleForWriting+ fileHandleForWriting: outputPipe.fileHandleForWriting,)forwardStandardInput(to: inputPipe.fileHandleForWriting)@@ -276,7 +276,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {guard let batteryObject = batteryConfiguration.asObject else { return }Dynamic(config)._setPowerSourceDevices([batteryObject])- self.batterySource = syntheticBatterySource.asObject as AnyObject?+ batterySource = syntheticBatterySource.asObject as AnyObject?print("[vphone] Synthetic battery configured (100%, charging)")}@@ -403,7 +403,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {nonisolated func virtualMachine(_: VZVirtualMachine,networkDevice _: VZNetworkDevice,- attachmentWasDisconnectedWithError error: Error+ attachmentWasDisconnectedWithError error: Error,) {print("[vphone] Network error: \(error)")}diff --git a/sources/FirmwarePatcher/ARM64/ARM64Encoder.swift b/sources/FirmwarePatcher/ARM64/ARM64Encoder.swiftindex f296934c..abe95aa3 100644--- a/sources/FirmwarePatcher/ARM64/ARM64Encoder.swift+++ b/sources/FirmwarePatcher/ARM64/ARM64Encoder.swift@@ -85,7 +85,7 @@ public enum ARM64Encoder {register: UInt32,bit: UInt32,from pc: Int,- to target: Int+ to target: Int,) -> Data? {guard register < 32, bit < 64 else { return nil }let delta = target - pc@@ -173,7 +173,7 @@ public enum ARM64Encoder {/// `[11:10] = 01 (o2:o1, selects CSINC)`, `[9:5] = Rn`, `[4:0] = Rd`public static func encodeCsetW(rd: UInt32, condition: ARM64Condition) -> Data? {guard rd < 32 else { return nil }- var insn: UInt32 = 0b0_0_0_1101_0100 << 21+ var insn: UInt32 = 0b000_1101_0100 << 21insn |= 31 << 16 // Rm = WZRinsn |= condition.inverted.rawValue << 12insn |= 0b01 << 10 // CSINCdiff --git a/sources/FirmwarePatcher/ARM64/ARM64Inst.swift b/sources/FirmwarePatcher/ARM64/ARM64Inst.swiftindex d573fdfb..c72db367 100644--- a/sources/FirmwarePatcher/ARM64/ARM64Inst.swift+++ b/sources/FirmwarePatcher/ARM64/ARM64Inst.swift@@ -17,52 +17,95 @@ public enum ARM64Inst {// MARK: - Register / immediate field accessors/// Rd / Rt — destination (or transfer) register, bits [4:0].- public static func rd(_ i: UInt32) -> UInt32 { i & 0x1F }+ public static func rd(_ i: UInt32) -> UInt32 {+ i & 0x1F+ }+/// Rn — first source / base register, bits [9:5].- public static func rn(_ i: UInt32) -> UInt32 { (i >> 5) & 0x1F }+ public static func rn(_ i: UInt32) -> UInt32 {+ (i >> 5) & 0x1F+ }+/// Rm — second source register, bits [20:16].- public static func rm(_ i: UInt32) -> UInt32 { (i >> 16) & 0x1F }+ public static func rm(_ i: UInt32) -> UInt32 {+ (i >> 16) & 0x1F+ }+/// MOVZ/MOVN/MOVK 16-bit immediate, bits [20:5].- public static func movImm16(_ i: UInt32) -> UInt32 { (i >> 5) & 0xFFFF }+ public static func movImm16(_ i: UInt32) -> UInt32 {+ (i >> 5) & 0xFFFF+ }+/// Unsigned 12-bit immediate of an ADD/SUB (immediate), bits [21:10].- public static func addSubImm12(_ i: UInt32) -> UInt32 { (i >> 10) & 0xFFF }+ public static func addSubImm12(_ i: UInt32) -> UInt32 {+ (i >> 10) & 0xFFF+ }// MARK: - Opcode predicates (mask/value verified against the ISA)/// ADRP (any Rd): op=1, [28:24]=10000.- public static func isADRP(_ i: UInt32) -> Bool { (i & 0x9F00_0000) == 0x9000_0000 }+ public static func isADRP(_ i: UInt32) -> Bool {+ (i & 0x9F00_0000) == 0x9000_0000+ }/// LDR Xt, [Xn, #imm] — 64-bit unsigned-offset load, [31:22]=1111100101.- public static func isLDRImm64(_ i: UInt32) -> Bool { (i & 0xFFC0_0000) == 0xF940_0000 }+ public static func isLDRImm64(_ i: UInt32) -> Bool {+ (i & 0xFFC0_0000) == 0xF940_0000+ }/// CMP Xn, Xm ≡ SUBS XZR, Xn, Xm (64-bit, shift=0, imm6=0); Rn/Rm left free.- public static func isCMPReg64(_ i: UInt32) -> Bool { (i & 0xFFE0_FC1F) == 0xEB00_001F }+ public static func isCMPReg64(_ i: UInt32) -> Bool {+ (i & 0xFFE0_FC1F) == 0xEB00_001F+ }/// SUB Wd, Wn, #imm — 32-bit SUB (immediate), shift=0; [31:22]=0101000100.- public static func isSUBImm32(_ i: UInt32) -> Bool { (i & 0xFFC0_0000) == 0x5100_0000 }+ public static func isSUBImm32(_ i: UInt32) -> Bool {+ (i & 0xFFC0_0000) == 0x5100_0000+ }/// MOVZ Wd, #imm16 (32-bit, no shift): [31:21]=01010010100.- public static func isMOVZW(_ i: UInt32) -> Bool { (i & 0xFFE0_0000) == 0x5280_0000 }+ public static func isMOVZW(_ i: UInt32) -> Bool {+ (i & 0xFFE0_0000) == 0x5280_0000+ }/// AND Wd, Wn, Wm — 32-bit shifted-register AND (imm6=0; shift type left free,/// harmless at shift amount 0): [31:24]=00001010, N=0.- public static func isANDRegW(_ i: UInt32) -> Bool { (i & 0xFF20_FC00) == 0x0A00_0000 }+ public static func isANDRegW(_ i: UInt32) -> Bool {+ (i & 0xFF20_FC00) == 0x0A00_0000+ }/// LSR Wd, Wn, #7 ≡ UBFM Wd, Wn, #7, #31 (immr=7, imms=0x1F).- public static func isLSRImm7W(_ i: UInt32) -> Bool { (i & 0xFFFF_FC00) == 0x5307_7C00 }+ public static func isLSRImm7W(_ i: UInt32) -> Bool {+ (i & 0xFFFF_FC00) == 0x5307_7C00+ }/// BL — branch with link, [31:26]=100101.- public static func isBL(_ i: UInt32) -> Bool { i >> 26 == 0b100101 }+ public static func isBL(_ i: UInt32) -> Bool {+ i >> 26 == 0b100101+ }/// B.EQ — conditional branch, [31:24]=0x54, bit4=0, cond=0000.- public static func isBEQ(_ i: UInt32) -> Bool { (i & 0xFF00_001F) == 0x5400_0000 }+ public static func isBEQ(_ i: UInt32) -> Bool {+ (i & 0xFF00_001F) == 0x5400_0000+ }/// CBZ Wn (sf=0): top byte 0x34.- public static func isCBZW(_ i: UInt32) -> Bool { (i & 0xFF00_0000) == 0x3400_0000 }+ public static func isCBZW(_ i: UInt32) -> Bool {+ (i & 0xFF00_0000) == 0x3400_0000+ }+/// CBNZ Wn (sf=0): top byte 0x35.- public static func isCBNZW(_ i: UInt32) -> Bool { (i & 0xFF00_0000) == 0x3500_0000 }+ public static func isCBNZW(_ i: UInt32) -> Bool {+ (i & 0xFF00_0000) == 0x3500_0000+ }+/// CBZ or CBNZ Wn.- public static func isCBZorCBNZW(_ i: UInt32) -> Bool { isCBZW(i) || isCBNZW(i) }+ public static func isCBZorCBNZW(_ i: UInt32) -> Bool {+ isCBZW(i) || isCBNZW(i)+ }+/// CBZ Xn (sf=1): top byte 0xB4.- public static func isCBZX(_ i: UInt32) -> Bool { (i & 0xFF00_0000) == 0xB400_0000 }+ public static func isCBZX(_ i: UInt32) -> Bool {+ (i & 0xFF00_0000) == 0xB400_0000+ }}diff --git a/sources/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift b/sources/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swiftindex fd86f04e..c39a0b97 100644--- a/sources/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift+++ b/sources/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift@@ -142,7 +142,7 @@ public final class AVPBooterPatcher: Patcher {patchedBytes: patchedBytes,beforeDisasm: beforeStr,afterDisasm: afterStr,- description: "DGST validation bypass: force x0=0 return value"+ description: "DGST validation bypass: force x0=0 return value",)patches.append(record)@@ -151,7 +151,7 @@ public final class AVPBooterPatcher: Patcher {format: " 0x%06X: %@ → %@ [avpbooter.dgst_bypass]",fileOff,beforeStr,- afterStr+ afterStr,))}}diff --git a/sources/FirmwarePatcher/Binary/IM4PHandler.swift b/sources/FirmwarePatcher/Binary/IM4PHandler.swiftindex ec1f5d29..ebdae416 100644--- a/sources/FirmwarePatcher/Binary/IM4PHandler.swift+++ b/sources/FirmwarePatcher/Binary/IM4PHandler.swift@@ -42,7 +42,7 @@ public enum IM4PHandler {public static func save(patchedData: Data,originalIM4P: IM4P?,- to url: URL+ to url: URL,) throws {if let original = originalIM4P {// Rebuild the IM4P container with the patched payload. Do not force@@ -52,7 +52,7 @@ public enum IM4PHandler {let newIM4P = try IM4P(fourcc: original.fourcc,description: original.description,- payload: patchedData+ payload: patchedData,)let output: Data = if paypPreservingFourCCs.contains(original.fourcc) {try appendPAYPIfPresent(from: original.data, to: newIM4P.data)diff --git a/sources/FirmwarePatcher/Binary/MachOParser.swift b/sources/FirmwarePatcher/Binary/MachOParser.swiftindex 13b01c70..49410d52 100644--- a/sources/FirmwarePatcher/Binary/MachOParser.swift+++ b/sources/FirmwarePatcher/Binary/MachOParser.swift@@ -44,7 +44,7 @@ public enum MachOParser {/// and the caller sees an empty/partial result it can reject normally.static func forEachLoadCommand(in data: Data,- _ body: (_ cmd: UInt32, _ offset: Int, _ cmdsize: Int) -> Void+ _ body: (_ cmd: UInt32, _ offset: Int, _ cmdsize: Int) -> Void,) {guard data.count > 32 else { return }let ncmds = data.loadLE(UInt32.self, at: 16)@@ -85,7 +85,7 @@ public enum MachOParser {vmAddr: vmAddr,vmSize: vmSize,fileOffset: fileOff,- fileSize: fileSize+ fileSize: fileSize,))}return segments@@ -125,7 +125,7 @@ public enum MachOParser {sectionName: sectName,address: addr,size: size,- fileOffset: fileOff+ fileOffset: fileOff,)sectOff += section64Size}@@ -180,7 +180,9 @@ public enum MachOParser {// Read null-terminated stringvar strEnd = strStartwhile strEnd < data.count, strEnd < symtab.stroff + symtab.strsize {- if data[strEnd] == 0 { break }+ if data[strEnd] == 0 {+ break+ }strEnd += 1}diff --git a/sources/FirmwarePatcher/CFW/CFWBuildVersion.swift b/sources/FirmwarePatcher/CFW/CFWBuildVersion.swiftindex 3e8ccc52..34aa174b 100644--- a/sources/FirmwarePatcher/CFW/CFWBuildVersion.swift+++ b/sources/FirmwarePatcher/CFW/CFWBuildVersion.swift@@ -38,7 +38,9 @@ public enum CFWBuildVersion {/// True only when bytes landed on disk — mirrors the Python's/// `patch_plist()` return value.public var didWrite: Bool {- if case .rewritten = self { return true }+ if case .rewritten = self {+ return true+ }return false}}@@ -56,7 +58,7 @@ public enum CFWBuildVersion {at url: URL,to target: String,dryRun: Bool = false,- verbose: Bool = true+ verbose: Bool = true,) throws -> Outcome {let data = try readFile(at: url)let format = detectFormat(data)@@ -64,14 +66,14 @@ public enum CFWBuildVersion {guard let parsed = try? PropertyListSerialization.propertyList(from: data,options: [],- format: nil+ format: nil,) else {throw PatcherError.invalidFormat("cannot parse as plist: \(url.path)")}guard var plist = parsed as? [String: Any] else {throw PatcherError.invalidFormat(- "top-level plist is \(type(of: parsed)), expected dict: \(url.path)"+ "top-level plist is \(type(of: parsed)), expected dict: \(url.path)",)}@@ -80,27 +82,33 @@ public enum CFWBuildVersion {}guard let currentString = current as? String else {throw PatcherError.invalidFormat(- "'\(key)' is \(type(of: current)), expected str: \(url.path)"+ "'\(key)' is \(type(of: current)), expected str: \(url.path)",)}if currentString == target {- if verbose { print(" [.] \(url.path): \(key) already = '\(target)'") }+ if verbose {+ print(" [.] \(url.path): \(key) already = '\(target)'")+ }return .alreadyTarget(target)}- if verbose { print(" [+] \(url.path): \(key) '\(currentString)' -> '\(target)'") }+ if verbose {+ print(" [+] \(url.path): \(key) '\(currentString)' -> '\(target)'")+ }plist[key] = targetif dryRun {- if verbose { print(" [.] dry-run — not writing back") }+ if verbose {+ print(" [.] dry-run — not writing back")+ }return .dryRun(from: currentString, to: target)}let output = try PropertyListSerialization.data(fromPropertyList: plist,format: format,- options: 0+ options: 0,)try output.write(to: url)return .rewritten(from: currentString, to: target)diff --git a/sources/FirmwarePatcher/CFW/CFWDaemons.swift b/sources/FirmwarePatcher/CFW/CFWDaemons.swiftindex c630fc77..5cea931e 100644--- a/sources/FirmwarePatcher/CFW/CFWDaemons.swift+++ b/sources/FirmwarePatcher/CFW/CFWDaemons.swift@@ -86,7 +86,7 @@ public enum CFWDaemons {guard let dict = try PropertyListSerialization.propertyList(from: data,options: [],- format: nil+ format: nil,) as? PlistDict else {throw DaemonError.invalidPlist(url.path)}@@ -105,7 +105,7 @@ public enum CFWDaemons {let data = try PropertyListSerialization.data(fromPropertyList: plist,format: .xml,- options: 0+ options: 0,)try data.write(to: url)}diff --git a/sources/FirmwarePatcher/CFW/CFWDaemonsDropbear.swift b/sources/FirmwarePatcher/CFW/CFWDaemonsDropbear.swiftindex 56c48c15..fa398914 100644--- a/sources/FirmwarePatcher/CFW/CFWDaemonsDropbear.swift+++ b/sources/FirmwarePatcher/CFW/CFWDaemonsDropbear.swift@@ -6,7 +6,7 @@import Foundation-extension CFWDaemons {+public extension CFWDaemons {// MARK: - Host keys/// The host keys dropbear is pointed at instead of generating its own.@@ -14,7 +14,7 @@ extension CFWDaemons {/// `/var` is on the writable Data volume; `/etc/dropbear`, where `-R` would/// put them, is on a read-only root during a normal VM boot. `cfw_install`/// seeds these two files.- public static let dropbearKeyArguments: [String] = [+ static let dropbearKeyArguments: [String] = ["-r","/var/dropbear/dropbear_rsa_host_key","-r",@@ -33,7 +33,7 @@ extension CFWDaemons {/// Elements are compared as strings but carried through as read, so a plist/// holding a non-string in `ProgramArguments` round-trips unchanged rather/// than failing.- public static func patchedDropbearArguments(_ arguments: [Any]) -> [Any] {+ static func patchedDropbearArguments(_ arguments: [Any]) -> [Any] {guard !arguments.isEmpty else { return arguments }var cleaned: [Any] = []@@ -53,7 +53,7 @@ extension CFWDaemons {}/// Apply `patchedDropbearArguments` to a loaded daemon plist in place.- public static func patchDropbearDaemon(_ daemon: inout PlistDict) {+ static func patchDropbearDaemon(_ daemon: inout PlistDict) {guard let arguments = daemon["ProgramArguments"] as? [Any], !arguments.isEmpty else {return}@@ -61,7 +61,7 @@ extension CFWDaemons {}/// Rewrite a dropbear daemon plist on disk. Implements `cfw.py patch-dropbear-plist`.- public static func patchDropbearPlist(at url: URL) throws {+ static func patchDropbearPlist(at url: URL) throws {var daemon = try loadPlist(url)patchDropbearDaemon(&daemon)try savePlist(daemon, to: url)diff --git a/sources/FirmwarePatcher/CFW/CFWDaemonsLaunchd.swift b/sources/FirmwarePatcher/CFW/CFWDaemonsLaunchd.swiftindex 2156de91..8d926ec6 100644--- a/sources/FirmwarePatcher/CFW/CFWDaemonsLaunchd.swift+++ b/sources/FirmwarePatcher/CFW/CFWDaemonsLaunchd.swift@@ -10,11 +10,11 @@import Foundation-extension CFWDaemons {+public extension CFWDaemons {// MARK: - Daemon/// One LaunchDaemon to merge, already loaded and already rewritten.- public struct Daemon {+ struct Daemon {/// Label as installed, without `.plist` — e.g. `dropbear`, `com.vphone.jb-setup`.public let name: Stringpublic let contents: PlistDict@@ -35,7 +35,7 @@ extension CFWDaemons {/// A fixed list rather than a directory listing, so what gets injected does/// not depend on what else a variant happens to leave in the staging/// directory, and so the order stays the order the log lines come out in.- public static let defaultDaemonNames: [String] = [+ static let defaultDaemonNames: [String] = ["bash","dropbear","trollvnc",@@ -50,7 +50,7 @@ extension CFWDaemons {/// A daemon that is not there is not an error — a variant that does not ship/// `rpcserver_ios` still installs — so absence is a result, not a throw. The/// scan is returned in order because the caller logs it line by line.- public enum StagedDaemon {+ enum StagedDaemon {case present(Daemon)case absent(source: String)}@@ -59,7 +59,7 @@ extension CFWDaemons {////// The dropbear rewrite lives here rather than in the directory loader so it/// holds however the daemon reaches the merge.- public static func loadDaemon(name: String, from url: URL) throws -> Daemon {+ static func loadDaemon(name: String, from url: URL) throws -> Daemon {var contents = try loadPlist(url)if name == "dropbear" {patchDropbearDaemon(&contents)@@ -68,16 +68,16 @@ extension CFWDaemons {}/// Scan a staging directory for the named daemons, in the order given.- public static func loadDaemons(+ static func loadDaemons(inDirectory directory: URL,- names: [String] = defaultDaemonNames+ names: [String] = defaultDaemonNames,) throws -> [StagedDaemon] {try names.map { name inlet source = directory.appendingPathComponent("\(name).plist")guard FileManager.default.fileExists(atPath: source.path) else {return .absent(source: source.path)}- return .present(try loadDaemon(name: name, from: source))+ return try .present(loadDaemon(name: name, from: source))}}@@ -92,7 +92,7 @@ extension CFWDaemons {////// - Returns: the names injected, in the order given.@discardableResult- public static func inject(_ daemons: [Daemon], into launchdPlist: URL) throws -> [String] {+ static func inject(_ daemons: [Daemon], into launchdPlist: URL) throws -> [String] {var target = try loadPlist(launchdPlist)var launchDaemons = target["LaunchDaemons"] as? PlistDict ?? [:]@@ -109,10 +109,10 @@ extension CFWDaemons {////// - Returns: the scan, in scan order, so the caller can log one line each.@discardableResult- public static func injectDaemons(+ static func injectDaemons(into launchdPlist: URL,fromDirectory directory: URL,- names: [String] = defaultDaemonNames+ names: [String] = defaultDaemonNames,) throws -> [StagedDaemon] {let staged = try loadDaemons(inDirectory: directory, names: names)try inject(staged.present, into: launchdPlist)@@ -124,10 +124,10 @@ extension CFWDaemons {/// `name` is the installed label, which is not the source filename: the jb/// setup daemon ships as `vphone_jb_setup.plist` and installs as/// `com.vphone.jb-setup.plist`.- public static func injectDaemon(+ static func injectDaemon(into launchdPlist: URL,name: String,- from source: URL+ from source: URL,) throws {try inject([loadDaemon(name: name, from: source)], into: launchdPlist)}@@ -137,7 +137,13 @@ extension CFWDaemons {public extension [CFWDaemons.StagedDaemon] {var present: [CFWDaemons.Daemon] {- compactMap { if case let .present(daemon) = $0 { daemon } else { nil } }+ compactMap {+ if case let .present(daemon) = $0 {+ daemon+ } else {+ nil+ }+ }}var injectedNames: [String] {@@ -145,6 +151,12 @@ public extension [CFWDaemons.StagedDaemon] {}var missingSources: [String] {- compactMap { if case let .absent(source) = $0 { source } else { nil } }+ compactMap {+ if case let .absent(source) = $0 {+ source+ } else {+ nil+ }+ }}}diff --git a/sources/FirmwarePatcher/CFW/CFWInjectDylib.swift b/sources/FirmwarePatcher/CFW/CFWInjectDylib.swiftindex bc5e5ab5..1e4387d7 100644--- a/sources/FirmwarePatcher/CFW/CFWInjectDylib.swift+++ b/sources/FirmwarePatcher/CFW/CFWInjectDylib.swift@@ -134,7 +134,7 @@ public enum CFWInjectDylib {into url: URL,weak: Bool = true,policy: CodeSignaturePolicy = .strip,- allowNonEmptyPadding: Bool = false+ allowNonEmptyPadding: Bool = false,) throws -> [CFWDylibInjection] {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -145,7 +145,7 @@ public enum CFWInjectDylib {into: &data,weak: weak,policy: policy,- allowNonEmptyPadding: allowNonEmptyPadding+ allowNonEmptyPadding: allowNonEmptyPadding,)try data.write(to: url)return injections@@ -158,16 +158,18 @@ public enum CFWInjectDylib {into data: inout Data,weak: Bool = true,policy: CodeSignaturePolicy = .strip,- allowNonEmptyPadding: Bool = false+ allowNonEmptyPadding: Bool = false,) throws -> [CFWDylibInjection] {- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }guard data.holds(0, 4) else { throw PatcherError.invalidFormat("file is too small to be a Mach-O") }let options = Options(dylibPath: dylibPath,weak: weak,policy: policy,- allowNonEmptyPadding: allowNonEmptyPadding+ allowNonEmptyPadding: allowNonEmptyPadding,)switch data.loadBEValue(UInt32.self, at: 0) {case fatMagic:@@ -181,9 +183,11 @@ public enum CFWInjectDylib {into: &data,headerOffset: 0,sliceSize: &sliceSize,- options: options+ options: options,)- if sliceSize < data.count { data = data.prefix(sliceSize) }+ if sliceSize < data.count {+ data = data.prefix(sliceSize)+ }return [injection]}}@@ -230,17 +234,17 @@ public enum CFWInjectDylib {// Zero whatever the move left behind, so the gap is not stale code.data.zeroBytes(at: Swift.min(cursor, originalOffset) + originalSize,- count: abs(cursor - originalOffset)+ count: abs(cursor - originalOffset),)data.storeBE(UInt32(cursor), at: entry + 8)}var sliceSize = originalSize- injections.append(try injectSlice(+ try injections.append(injectSlice(into: &data,headerOffset: cursor,sliceSize: &sliceSize,- options: options+ options: options,))if sliceSize < originalSize, index < archCount - 1 {@@ -251,7 +255,9 @@ public enum CFWInjectDylib {data.storeBE(UInt32(sliceSize), at: entry + 12)}- if fileSize < data.count { data = data.prefix(fileSize) }+ if fileSize < data.count {+ data = data.prefix(fileSize)+ }return injections}@@ -261,7 +267,7 @@ public enum CFWInjectDylib {into data: inout Data,headerOffset: Int,sliceSize: inout Int,- options: Options+ options: Options,) throws -> CFWDylibInjection {guard data.holds(headerOffset, machHeader64Size) else {throw PatcherError.invalidFormat("Mach-O header at 0x\(String(headerOffset, radix: 16)) is truncated")@@ -284,7 +290,7 @@ public enum CFWInjectDylib {in: data,headerOffset: headerOffset,commandsOffset: commandsOffset,- ncmds: Int(ncmds)+ ncmds: Int(ncmds),)var removedCodeSignature = false@@ -294,7 +300,7 @@ public enum CFWInjectDylib {headerOffset: headerOffset,sliceSize: &sliceSize,signature: signature,- layout: layout+ layout: layout,)ncmds -= 1sizeofcmds -= signature.commandSize@@ -310,7 +316,7 @@ public enum CFWInjectDylib {guard data.holds(commandOffset, commandSize), commandOffset + commandSize <= headerOffset + sliceSize else {throw PatcherError.invalidFormat(- "no room for a \(commandSize)-byte load command at 0x\(String(commandOffset, radix: 16))"+ "no room for a \(commandSize)-byte load command at 0x\(String(commandOffset, radix: 16))",)}if !options.allowNonEmptyPadding, data[commandOffset ..< commandOffset + commandSize].contains(where: { $0 != 0 }) {@@ -319,7 +325,7 @@ public enum CFWInjectDylib {// the first section, and clobbering them is silent.throw PatcherError.invalidFormat("load-command padding at 0x\(String(commandOffset, radix: 16)) is not empty; "- + "inserting would overwrite \(commandSize) bytes of the first section"+ + "inserting would overwrite \(commandSize) bytes of the first section",)}@@ -350,7 +356,7 @@ public enum CFWInjectDylib {touched: [(headerOffset + 16) ..< (headerOffset + 24),commandOffset ..< commandOffset + commandSize,- ]+ ],)}@@ -363,7 +369,7 @@ public enum CFWInjectDylib {loadCommandSize: commandSize,isWeak: options.weak,removedCodeSignature: removedCodeSignature,- rehashedSlots: rehashed+ rehashedSlots: rehashed,)}@@ -389,9 +395,9 @@ public enum CFWInjectDylib {static func scanLoadCommands(in data: Data,- headerOffset: Int,+ headerOffset _: Int,commandsOffset: Int,- ncmds: Int+ ncmds: Int,) throws -> SliceLayout {var layout = SliceLayout()var offset = commandsOffset@@ -414,7 +420,7 @@ public enum CFWInjectDylib {commandOffset: offset,commandSize: cmdsize,dataOffset: Int(data.loadLEValue(UInt32.self, at: offset + 8)),- dataSize: Int(data.loadLEValue(UInt32.self, at: offset + 12))+ dataSize: Int(data.loadLEValue(UInt32.self, at: offset + 12)),)layout.codeSignatureIsLast = index == ncmds - 1case lcSegment64:@@ -460,7 +466,7 @@ public enum CFWInjectDylib {headerOffset: Int,sliceSize: inout Int,signature: CodeSignatureCommand,- layout: SliceLayout+ layout: SliceLayout,) throws {data.zeroBytes(at: signature.commandOffset, count: signature.commandSize)@@ -506,7 +512,7 @@ public enum CFWInjectDylib {in data: inout Data,headerOffset: Int,sliceSize: Int,- touched: [Range<Int>]+ touched: [Range<Int>],) throws -> [CFWSlotRehash] {var slice = Data(data[headerOffset ..< headerOffset + sliceSize])let offsets = touched.flatMap { range in range.map { $0 - headerOffset } }diff --git a/sources/FirmwarePatcher/CFW/CFWMachLookupExceptions.swift b/sources/FirmwarePatcher/CFW/CFWMachLookupExceptions.swiftindex 872acda9..da270e5d 100644--- a/sources/FirmwarePatcher/CFW/CFWMachLookupExceptions.swift+++ b/sources/FirmwarePatcher/CFW/CFWMachLookupExceptions.swift@@ -73,13 +73,13 @@ public enum CFWMachLookupExceptions {guard let parsed = try? PropertyListSerialization.propertyList(from: data,options: [],- format: nil+ format: nil,) else {throw PatcherError.invalidFormat("cannot parse as plist: \(url.path)")}guard var entitlements = parsed as? [String: Any] else {throw PatcherError.invalidFormat(- "top-level plist is \(type(of: parsed)), expected dict: \(url.path)"+ "top-level plist is \(type(of: parsed)), expected dict: \(url.path)",)}@@ -91,7 +91,7 @@ public enum CFWMachLookupExceptions {let output = try PropertyListSerialization.data(fromPropertyList: entitlements,format: .xml,- options: 0+ options: 0,)try output.write(to: url)@@ -113,13 +113,13 @@ public enum CFWMachLookupExceptions {guard let value else { return [] }guard let array = value as? [Any] else {throw PatcherError.invalidFormat(- "'\(exceptionKey)' is \(type(of: value)), expected array: \(path)"+ "'\(exceptionKey)' is \(type(of: value)), expected array: \(path)",)}return try array.map { element inguard let string = element as? String else {throw PatcherError.invalidFormat(- "'\(exceptionKey)' holds a non-string entry (\(type(of: element))): \(path)"+ "'\(exceptionKey)' holds a non-string entry (\(type(of: element))): \(path)",)}return stringdiff --git a/sources/FirmwarePatcher/CFW/CFWMachOCodeSignature.swift b/sources/FirmwarePatcher/CFW/CFWMachOCodeSignature.swiftindex 87de928b..26d7c250 100644--- a/sources/FirmwarePatcher/CFW/CFWMachOCodeSignature.swift+++ b/sources/FirmwarePatcher/CFW/CFWMachOCodeSignature.swift@@ -24,9 +24,9 @@ import Foundation// MARK: - Byte Reading-// The Mach-O header and load commands are little-endian; everything inside the-// CS_SuperBlob is big-endian. Data.loadLE covers the first half, so this file-// only needs the second.+/// The Mach-O header and load commands are little-endian; everything inside the+/// CS_SuperBlob is big-endian. Data.loadLE covers the first half, so this file+/// only needs the second.private extension Data {func loadBE<T: FixedWidthInteger>(_: T.Type, at offset: Int) -> T {var value: T = .zero@@ -96,8 +96,13 @@ public struct CFWSlotRehash: Sendable, Equatable {public let pageSize: Int/// Bytes actually hashed. Less than `pageSize` for the tail slot.- public var hashedLength: Int { pageEnd - pageStart }- public var isTailSlot: Bool { hashedLength != pageSize }+ public var hashedLength: Int {+ pageEnd - pageStart+ }++ public var isTailSlot: Bool {+ hashedLength != pageSize+ }}extension CFWSlotRehash: CustomStringConvertible {@@ -109,7 +114,7 @@ extension CFWSlotRehash: CustomStringConvertible {tail,hashFileOffset,String(before.hex.prefix(8)),- String(after.hex.prefix(8))+ String(after.hex.prefix(8)),)}}@@ -151,7 +156,7 @@ public enum CFWMachOCodeSignature {guard data.fits(offset, 16) else { return nil }return (Int(data.loadLE(UInt32.self, at: offset + 8)),- Int(data.loadLE(UInt32.self, at: offset + 12))+ Int(data.loadLE(UInt32.self, at: offset + 12)),)}guard cmdsize > 0 else { return nil }@@ -177,7 +182,7 @@ public enum CFWMachOCodeSignature {static func superBlobEntries(in data: Data,- at superBlobOffset: Int+ at superBlobOffset: Int,) -> [(slotType: UInt32, offset: Int, magic: UInt32)]? {guard data.fits(superBlobOffset, 12) else { return nil }let magic = data.loadBE(UInt32.self, at: superBlobOffset)@@ -229,7 +234,7 @@ public enum CFWMachOCodeSignature {pageSize: pageSize,pageSizeLog2: pageSizeLog2,codeSlotCount: codeSlotCount,- codeLimit: codeLimit+ codeLimit: codeLimit,)}@@ -238,7 +243,7 @@ public enum CFWMachOCodeSignature {public static func pageBounds(fileOffset: Int,pageSize: Int,- codeLimit: Int+ codeLimit: Int,) -> (index: Int, start: Int, end: Int)? {guard fileOffset >= 0, fileOffset < codeLimit, pageSize > 0 else { return nil }let index = fileOffset / pageSize@@ -267,12 +272,16 @@ public enum CFWMachOCodeSignature {public static func reattest(_ data: inout Data,modifiedOffsets: some Sequence<Int>,- dryRun: Bool = false+ dryRun: Bool = false,) throws -> [CFWSlotRehash] {let offsets = Array(modifiedOffsets)- if offsets.isEmpty { return [] }+ if offsets.isEmpty {+ return []+ }- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }guard let directories = codeDirectories(in: data) else {throw PatcherError.invalidFormat("no LC_CODE_SIGNATURE / CS_CodeDirectory found")@@ -289,14 +298,14 @@ public enum CFWMachOCodeSignature {guard directory.hashSize == SHA256.byteCount else {throw PatcherError.invalidFormat("SHA-256 CodeDirectory at 0x\(String(directory.offset, radix: 16)) "- + "declares hashSize \(directory.hashSize), expected \(SHA256.byteCount)"+ + "declares hashSize \(directory.hashSize), expected \(SHA256.byteCount)",)}for fileOffset in offsets {guard let bounds = pageBounds(fileOffset: fileOffset,pageSize: directory.pageSize,- codeLimit: directory.codeLimit+ codeLimit: directory.codeLimit,) else { continue }guard bounds.index < directory.codeSlotCount else { continue }work[SlotKey(cdIndex: cdIndex, pageIndex: bounds.index)] = bounds.start ..< bounds.end@@ -313,7 +322,9 @@ public enum CFWMachOCodeSignature {let newHash = Data(SHA256.hash(data: data[range]))let oldHash = data[slotOffset ..< slotOffset + directory.hashSize]- if oldHash == newHash { continue }+ if oldHash == newHash {+ continue+ }if !dryRun {data.replaceSubrange(slotOffset ..< slotOffset + directory.hashSize, with: newHash)@@ -327,7 +338,7 @@ public enum CFWMachOCodeSignature {hashFileOffset: slotOffset,before: Data(oldHash),after: newHash,- pageSize: directory.pageSize+ pageSize: directory.pageSize,))}return records@@ -338,7 +349,7 @@ public enum CFWMachOCodeSignature {public static func reattest(fileAt url: URL,modifiedOffsets: some Sequence<Int>,- dryRun: Bool = false+ dryRun: Bool = false,) throws -> [CFWSlotRehash] {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)diff --git a/sources/FirmwarePatcher/CFW/CFWPostRestoreDeviceTree.swift b/sources/FirmwarePatcher/CFW/CFWPostRestoreDeviceTree.swiftindex 6ac94f55..c34a832a 100644--- a/sources/FirmwarePatcher/CFW/CFWPostRestoreDeviceTree.swift+++ b/sources/FirmwarePatcher/CFW/CFWPostRestoreDeviceTree.swift@@ -41,7 +41,7 @@ public enum CFWPostRestoreDeviceTree {/// The reordered `compatible` body, NUL-delimited, before slot padding.static let targetCompatibleBody = Data(- "D47AP\0VPHONE600AP\0AppleVirtualPlatformARM\0".utf8+ "D47AP\0VPHONE600AP\0AppleVirtualPlatformARM\0".utf8,)// MARK: - Results@@ -70,7 +70,7 @@ public enum CFWPostRestoreDeviceTree {public static func patch(at url: URL,dryRun: Bool = false,- verbose: Bool = true+ verbose: Bool = true,) throws -> Outcome {let data: Datado {@@ -83,7 +83,7 @@ public enum CFWPostRestoreDeviceTree {let im4p = try IM4P(container.im4pBytes)guard im4p.fourcc == "dtre" else {throw PatcherError.invalidFormat(- "expected DT payload (fourcc='dtre'), got fourcc='\(im4p.fourcc)'"+ "expected DT payload (fourcc='dtre'), got fourcc='\(im4p.fourcc)'",)}guard !im4p.isEncrypted else {@@ -104,14 +104,18 @@ public enum CFWPostRestoreDeviceTree {// it: the alternative is parsing compressed bytes as a device tree.guard compression == .none || !compression.isStillCompressed(blob) else {throw PatcherError.invalidFormat(- "IM4P payload is \(compression) but did not decompress — no compression-info element?"+ "IM4P payload is \(compression) but did not decompress — no compression-info element?",)}- if verbose { print(" [.] DT blob: \(blob.count) bytes") }+ if verbose {+ print(" [.] DT blob: \(blob.count) bytes")+ }let (newBlob, changes) = try patchedDeviceTree(blob)guard !changes.isEmpty else {- if verbose { print(" [.] \(url.path): DT already in target state — no change") }+ if verbose {+ print(" [.] \(url.path): DT already in target state — no change")+ }return Outcome(changes: [], wrote: false, outputSize: data.count)}if verbose {@@ -125,7 +129,7 @@ public enum CFWPostRestoreDeviceTree {// uncompressed size will not load.guard newBlob.count == blob.count else {throw PatcherError.patchVerificationFailed(- "DT size changed: \(blob.count) -> \(newBlob.count) bytes (would break IM4P offsets)"+ "DT size changed: \(blob.count) -> \(newBlob.count) bytes (would break IM4P offsets)",)}@@ -133,18 +137,24 @@ public enum CFWPostRestoreDeviceTree {fourcc: im4p.fourcc,description: im4p.description,payload: newBlob,- compression: compression.img4toolName+ compression: compression.img4toolName,)let output = try container.rebuilt(im4pBytes: newIM4P.data)- if verbose { print(" [.] output size: \(output.count) bytes (was \(data.count))") }+ if verbose {+ print(" [.] output size: \(output.count) bytes (was \(data.count))")+ }if dryRun {- if verbose { print(" [.] dry-run — not writing back") }+ if verbose {+ print(" [.] dry-run — not writing back")+ }return Outcome(changes: changes, wrote: false, outputSize: output.count)}try output.write(to: url)- if verbose { print(" [+] wrote \(url.path)") }+ if verbose {+ print(" [+] wrote \(url.path)")+ }return Outcome(changes: changes, wrote: true, outputSize: output.count)}@@ -157,12 +167,12 @@ public enum CFWPostRestoreDeviceTree {let (root, end) = try parseNode(blob, at: 0)guard end == blob.count else {throw PatcherError.invalidFormat(- "DT parse length mismatch: ended at \(end), blob is \(blob.count)"+ "DT parse length mismatch: ended at \(end), blob is \(blob.count)",)}guard nodeName(root) == "device-tree" else {throw PatcherError.invalidFormat(- "expected root node 'device-tree', got '\(nodeName(root))'"+ "expected root node 'device-tree', got '\(nodeName(root))'",)}@@ -174,7 +184,7 @@ public enum CFWPostRestoreDeviceTree {changes.append(Change(property: "model",before: cString(model.value),- after: targetModel+ after: targetModel,))model.value = newModel}@@ -185,7 +195,7 @@ public enum CFWPostRestoreDeviceTree {changes.append(Change(property: "target-type",before: cString(targetType.value),- after: targetTargetType+ after: targetTargetType,))targetType.value = newTargetType}@@ -193,18 +203,18 @@ public enum CFWPostRestoreDeviceTree {let compatible = try property(root, named: "compatible")guard targetCompatibleBody.count <= compatible.length else {throw PatcherError.invalidFormat(- "compatible body \(targetCompatibleBody.count)B > slot \(compatible.length)B"+ "compatible body \(targetCompatibleBody.count)B > slot \(compatible.length)B",)}var newCompatible = targetCompatibleBodynewCompatible.append(- contentsOf: [UInt8](repeating: 0, count: compatible.length - newCompatible.count)+ contentsOf: [UInt8](repeating: 0, count: compatible.length - newCompatible.count),)if compatible.value != newCompatible {changes.append(Change(property: "compatible",before: "[\(cStringList(compatible.value).joined(separator: ", "))]",- after: "[D47AP, VPHONE600AP, AppleVirtualPlatformARM]"+ after: "[D47AP, VPHONE600AP, AppleVirtualPlatformARM]",))compatible.value = newCompatible}@@ -214,6 +224,7 @@ public enum CFWPostRestoreDeviceTree {}// MARK: - Flat device tree format+//// Per node: u32 nProps, u32 nChildren, then each property as// char[32] name, u16 length, u16 flags, u8[length] value, padded to a@@ -225,11 +236,13 @@ public enum CFWPostRestoreDeviceTree {// its own parse/serialize pair is file-private. See `integrationNeeded`// in the migration notes.- private static func align4(_ n: Int) -> Int { (n + 3) & ~3 }+ private static func align4(_ n: Int) -> Int {+ (n + 3) & ~3+ }private static func parseNode(_ blob: Data,- at offset: Int+ at offset: Int,) throws -> (DeviceTreePatcher.DTNode, Int) {guard offset + 8 <= blob.count else {throw PatcherError.invalidFormat("DT truncated at offset 0x\(String(offset, radix: 16))")@@ -242,7 +255,7 @@ public enum CFWPostRestoreDeviceTree {for _ in 0 ..< propertyCount {guard pos + 36 <= blob.count else {throw PatcherError.invalidFormat(- "DT property header truncated at 0x\(String(pos, radix: 16))"+ "DT property header truncated at 0x\(String(pos, radix: 16))",)}let name = cString(slice(blob, pos, 32))@@ -251,7 +264,7 @@ public enum CFWPostRestoreDeviceTree {let valueOffset = pos + 36guard valueOffset + length <= blob.count else {throw PatcherError.invalidFormat(- "DT property value '\(name)' truncated at 0x\(String(valueOffset, radix: 16))"+ "DT property value '\(name)' truncated at 0x\(String(valueOffset, radix: 16))",)}node.properties.append(DeviceTreePatcher.DTProperty(@@ -259,7 +272,7 @@ public enum CFWPostRestoreDeviceTree {length: length,flags: flags,value: slice(blob, valueOffset, length),- valueOffset: valueOffset+ valueOffset: valueOffset,))pos = valueOffset + align4(length)}@@ -278,14 +291,18 @@ public enum CFWPostRestoreDeviceTree {out.append(littleEndian: UInt32(node.children.count))for property in node.properties {var name = Data(property.name.utf8)- if name.count >= 32 { name = Data(name.prefix(31)) }+ if name.count >= 32 {+ name = Data(name.prefix(31))+ }name.append(contentsOf: [UInt8](repeating: 0, count: 32 - name.count))out.append(name)out.append(littleEndian: UInt16(property.length))out.append(littleEndian: property.flags)out.append(property.value)let pad = align4(property.length) - property.length- if pad > 0 { out.append(Data(repeating: 0, count: pad)) }+ if pad > 0 {+ out.append(Data(repeating: 0, count: pad))+ }}for child in node.children {out.append(serializeNode(child))@@ -302,13 +319,13 @@ public enum CFWPostRestoreDeviceTree {private static func property(_ node: DeviceTreePatcher.DTNode,- named name: String+ named name: String,) throws -> DeviceTreePatcher.DTProperty {for property in node.properties where property.name == name {return property}throw PatcherError.patchSiteNotFound(- "property '\(name)' not found in node '\(nodeName(node))'"+ "property '\(name)' not found in node '\(nodeName(node))'",)}@@ -318,7 +335,9 @@ public enum CFWPostRestoreDeviceTree {private static func encodeFixedString(_ text: String, length: Int) -> Data {var raw = Data(text.utf8)raw.append(0)- if raw.count > length { return Data(raw.prefix(length)) }+ if raw.count > length {+ return Data(raw.prefix(length))+ }raw.append(contentsOf: [UInt8](repeating: 0, count: length - raw.count))return raw}@@ -430,7 +449,10 @@ extension CFWPostRestoreDeviceTree {}let payload = DER.value(im4pBytes, children[3])for candidate in [PayloadCompression.lzss, .lzfse]- where candidate.isStillCompressed(payload) { return candidate }+ where candidate.isStillCompressed(payload)+ {+ return candidate+ }return .none}@@ -439,7 +461,9 @@ extension CFWPostRestoreDeviceTree {guard isIMG4 else { return newIM4P }var body = leadingbody.append(newIM4P)- for element in trailing { body.append(element) }+ for element in trailing {+ body.append(element)+ }var out = DER.sequenceHeader(bodyCount: body.count)out.append(body)return out@@ -448,6 +472,7 @@ extension CFWPostRestoreDeviceTree {}// MARK: - Minimal DER reader+//// Enough of DER to walk an Image4 container and splice one element: tags// are single-byte here, lengths are definite. Img4tool's own DER helpers are@@ -457,7 +482,9 @@ private enum DER {static let sequence: UInt8 = 0x30static let ia5String: UInt8 = 0x16- static func contextConstructed(_ number: UInt8) -> UInt8 { 0xA0 | number }+ static func contextConstructed(_ number: UInt8) -> UInt8 {+ 0xA0 | number+ }struct Element {let tag: UInt8@@ -495,7 +522,7 @@ private enum DER {return Element(tag: tag,valueRange: cursor ..< (cursor + length),- range: offset ..< (cursor + length)+ range: offset ..< (cursor + length),)}@@ -550,7 +577,7 @@ private enum DER {// MARK: - Little-endian appendprivate extension Data {- mutating func append<T: FixedWidthInteger>(littleEndian value: T) {+ mutating func append(littleEndian value: some FixedWidthInteger) {Swift.withUnsafeBytes(of: value.littleEndian) { append(contentsOf: $0) }}}diff --git a/sources/FirmwarePatcher/CFW/Patches/CFWCacheloader.swift b/sources/FirmwarePatcher/CFW/Patches/CFWCacheloader.swiftindex e98db25f..a764d241 100644--- a/sources/FirmwarePatcher/CFW/Patches/CFWCacheloader.swift+++ b/sources/FirmwarePatcher/CFW/Patches/CFWCacheloader.swift@@ -127,7 +127,9 @@ public enum CFWCacheLoaderPatcher {public let targetVMA: UInt64?/// True when the site already holds this patch's own output.- public var wasAlreadyNOP: Bool { mnemonic == "nop" }+ public var wasAlreadyNOP: Bool {+ mnemonic == "nop"+ }/// How the gate reads in disassembly.public var text: String {@@ -158,7 +160,9 @@ public enum CFWCacheLoaderPatcher {/// 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 }+ public var sitesWritten: Int {+ record == nil ? 0 : 1+ }}/// Where progress goes when the caller does not say. The Python prints to@@ -185,7 +189,7 @@ public enum CFWCacheLoaderPatcher {fileAt url: URL,dryRun: Bool = false,reattestsCodeSignature: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -195,7 +199,7 @@ public enum CFWCacheLoaderPatcher {&data,dryRun: dryRun,reattestsCodeSignature: reattestsCodeSignature,- log: log+ log: log,)if !dryRun, report.sitesWritten > 0 || !report.reattestedSlots.isEmpty {try data.write(to: url)@@ -212,11 +216,13 @@ public enum CFWCacheLoaderPatcher {_ data: inout Data,dryRun: Bool = false,reattestsCodeSignature: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {// Every offset below is an absolute file offset, so the buffer has to be// zero-based — a slice handed in by a caller is not.- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }let located = try locateGate(in: data)let anchor = located.anchor@@ -249,14 +255,16 @@ public enum CFWCacheLoaderPatcher {var slots: [CFWSlotRehash] = []if reattestsCodeSignature, !dryRun {slots = try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: [gate.fileOffset])- for slot in slots { log?(" re-attested \(slot)") }+ for slot in slots {+ log?(" re-attested \(slot)")+ }}return Report(outcome: .alreadyPatched,anchor: anchor,gate: gate,record: nil,- reattestedSlots: slots+ reattestedSlots: slots,)}@@ -273,7 +281,7 @@ public enum CFWCacheLoaderPatcher {anchor: anchor,gate: gate,record: nil,- reattestedSlots: []+ reattestedSlots: [],)}@@ -285,14 +293,16 @@ public enum CFWCacheLoaderPatcher {let written = Data(data[gate.fileOffset ..< gate.fileOffset + nop.count])guard written == nop else {throw PatcherError.patchVerificationFailed(- "\(component): gate at 0x\(hex(UInt64(gate.fileOffset))) reads \(written.hex) after write"+ "\(component): gate at 0x\(hex(UInt64(gate.fileOffset))) reads \(written.hex) after write",)}var slots: [CFWSlotRehash] = []if reattestsCodeSignature {slots = try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: [gate.fileOffset])- for slot in slots { log?(" re-attested \(slot)") }+ for slot in slots {+ log?(" re-attested \(slot)")+ }}log?(" [+] NOPped at 0x\(hex(UInt64(gate.fileOffset)))")@@ -302,7 +312,7 @@ public enum CFWCacheLoaderPatcher {anchor: anchor,gate: gate,record: record(anchor: anchor, gate: gate, original: original, patched: nop),- reattestedSlots: slots+ reattestedSlots: slots,)}@@ -326,7 +336,9 @@ public enum CFWCacheLoaderPatcher {var firstFound: StringHit?for hit in stringHits(in: data, sections: sections) {- if firstFound == nil { firstFound = hit }+ if firstFound == nil {+ firstFound = hit+ }// The code addresses the string's first byte, so that VA is tried// first; the substring's own VA is the Python's fallback, for a// compiler that split the literal.@@ -345,19 +357,19 @@ public enum CFWCacheLoaderPatcher {stringVMA: hit.stringVMA,matchVMA: hit.matchVMA,referenceFileOffset: reference.fileOffset,- referenceVMA: reference.vma+ referenceVMA: reference.vma,)- return (anchor, try findGate(in: data, text: text, anchor: anchor))+ return try (anchor, findGate(in: data, text: text, anchor: anchor))}guard let found = firstFound else {throw PatcherError.patchSiteNotFound(- "\(component): none of \(anchorTokens) appears in this binary's string sections"+ "\(component): none of \(anchorTokens) appears in this binary's string sections",)}throw PatcherError.patchSiteNotFound("\(component): \"\(found.text)\" is present but nothing in __TEXT,__text "- + "forms its address (ADRP+ADD) — the boot-arg check looks compiled out"+ + "forms its address (ADRP+ADD) — the boot-arg check looks compiled out",)}@@ -410,7 +422,7 @@ public enum CFWCacheLoaderPatcher {sectionName: "\(section.segmentName),\(section.sectionName)",stringFileOffset: stringStart,stringVMA: section.address + UInt64(stringStart - start),- matchVMA: section.address + UInt64(match - start)+ matchVMA: section.address + UInt64(match - start),))break}@@ -426,7 +438,9 @@ public enum CFWCacheLoaderPatcher {matched = falsebreak}- if matched { return offset }+ if matched {+ return offset+ }}return nil}@@ -438,13 +452,17 @@ public enum CFWCacheLoaderPatcher {/// 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 }+ 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 }+ while position < ceiling, data[position] != 0 {+ position += 1+ }return position}@@ -461,13 +479,13 @@ public enum CFWCacheLoaderPatcher {static func findStringReference(in data: Data,text: MachOSectionInfo,- targetVMA: UInt64+ 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).+ // 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() {@@ -513,7 +531,7 @@ public enum CFWCacheLoaderPatcher {static func findGate(in data: Data,text: MachOSectionInfo,- anchor: Anchor+ anchor: Anchor,) throws -> Gate {let disassembler = ARM64Disassembler()let textEnd = Int(text.fileOffset) + Int(text.size)@@ -522,7 +540,7 @@ public enum CFWCacheLoaderPatcher {return disassembler.disassembleOne(in: data,at: offset,- address: text.address + UInt64(offset - Int(text.fileOffset))+ address: text.address + UInt64(offset - Int(text.fileOffset)),)}@@ -554,7 +572,7 @@ public enum CFWCacheLoaderPatcher {operandString: instruction.operandString,callFileOffset: call.map { Int($0.address - text.address) + Int(text.fileOffset) },callVMA: call?.address,- targetVMA: nil+ targetVMA: nil,)}@@ -567,14 +585,14 @@ public enum CFWCacheLoaderPatcher {operandString: instruction.operandString,callFileOffset: call.map { Int($0.address - text.address) + Int(text.fileOffset) },callVMA: call?.address,- targetVMA: branchTarget(of: instruction)+ targetVMA: branchTarget(of: instruction),)}throw PatcherError.patchSiteNotFound("\(component): no conditional branch within \(window) instructions of "+ (call.map { "the call at 0x\(hex($0.address))" }- ?? "the \"\(anchor.text)\" xref at 0x\(hex(anchor.referenceVMA))")+ ?? "the \"\(anchor.text)\" xref at 0x\(hex(anchor.referenceVMA))"),)}@@ -598,14 +616,14 @@ public enum CFWCacheLoaderPatcher {in data: Data,text: MachOSectionInfo,after call: Instruction?,- _ disassembler: ARM64Disassembler+ _ disassembler: ARM64Disassembler,) throws {if let target = branchTarget(of: gate) {let textEnd = text.address + text.sizeguard target > gate.address, target < textEnd else {throw PatcherError.patchSiteNotFound("\(component): branch at 0x\(hex(gate.address)) jumps to 0x\(hex(target)), "- + "which is not forward inside __TEXT,__text — not the unsecure-cache gate"+ + "which is not forward inside __TEXT,__text — not the unsecure-cache gate",)}}@@ -618,7 +636,7 @@ public enum CFWCacheLoaderPatcher {guard register == "x0" || register == "w0" else {throw PatcherError.patchSiteNotFound("\(component): branch at 0x\(hex(gate.address)) tests "- + "\(register ?? "an unknown register"), not the call's result in x0/w0"+ + "\(register ?? "an unknown register"), not the call's result in x0/w0",)}default:@@ -628,7 +646,7 @@ public enum CFWCacheLoaderPatcher {else {throw PatcherError.patchSiteNotFound("\(component): \(gate.mnemonic) at 0x\(hex(gate.address)) is not preceded by a "- + "compare of the call's result — nothing ties it to the boot-arg lookup"+ + "compare of the call's result — nothing ties it to the boot-arg lookup",)}}@@ -641,7 +659,7 @@ public enum CFWCacheLoaderPatcher {and gate: Instruction,in data: Data,text: MachOSectionInfo,- _ disassembler: ARM64Disassembler+ _ disassembler: ARM64Disassembler,) -> Bool {var address = call.address + 4while address < gate.address {@@ -653,7 +671,9 @@ public enum CFWCacheLoaderPatcher {else { continue }for operand in operands where operand.type == AARCH64_OP_REG {let name = disassembler.registerName(UInt32(operand.reg.rawValue))- if name == "x0" || name == "w0" { return true }+ if name == "x0" || name == "w0" {+ return true+ }}}return false@@ -676,7 +696,7 @@ public enum CFWCacheLoaderPatcher {anchor: Anchor,gate: Gate,original: Data,- patched: Data+ patched: Data,) -> PatchRecord {PatchRecord(patchID: patchID,@@ -688,7 +708,7 @@ public enum CFWCacheLoaderPatcher {beforeDisasm: disassemblyText(of: original, at: gate.vma),afterDisasm: disassemblyText(of: patched, at: gate.vma),// Worded as the Python words it, so a captured reference compares.- description: "NOP the cache-validation branch gated on '\(anchor.token)'"+ description: "NOP the cache-validation branch gated on '\(anchor.token)'",)}diff --git a/sources/FirmwarePatcher/CFW/Patches/CFWDiskimagesiod.swift b/sources/FirmwarePatcher/CFW/Patches/CFWDiskimagesiod.swiftindex 78c40605..bf46cfa0 100644--- a/sources/FirmwarePatcher/CFW/Patches/CFWDiskimagesiod.swift+++ b/sources/FirmwarePatcher/CFW/Patches/CFWDiskimagesiod.swift@@ -134,7 +134,9 @@ public enum CFWDiskimagesiod {public let original: Data/// True when the site already holds this patch's own output.- public var isAlreadyPatched: Bool { original == CFWDiskimagesiod.replacement }+ public var isAlreadyPatched: Bool {+ original == CFWDiskimagesiod.replacement+ }}/// What a run did.@@ -160,7 +162,9 @@ public enum CFWDiskimagesiod {public let rehashes: [CFWSlotRehash]/// The parity number: the Python writes exactly one site, and so must this.- public var sitesWritten: Int { record == nil ? 0 : 1 }+ public var sitesWritten: Int {+ record == nil ? 0 : 1+ }}/// Where progress goes when the caller does not say. The Python prints to@@ -191,9 +195,11 @@ public enum CFWDiskimagesiod {_ data: inout Data,reattest: Bool = false,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }let site = try locate(in: data)let patched = replacement@@ -221,9 +227,11 @@ public enum CFWDiskimagesiod {// leave the second page's slot stale.rehashes = try CFWMachOCodeSignature.reattest(&data,- modifiedOffsets: [site.fileOffset, site.fileOffset + patched.count - 1]+ modifiedOffsets: [site.fileOffset, site.fileOffset + patched.count - 1],)- for rehash in rehashes { log?(" [~] \(rehash)") }+ for rehash in rehashes {+ log?(" [~] \(rehash)")+ }if rehashes.isEmpty {log?(" [=] code directory slots already current; no re-attest needed")}@@ -232,7 +240,7 @@ public enum CFWDiskimagesiod {let written = data[site.fileOffset ..< site.fileOffset + patched.count]guard written == patched else {throw PatcherError.patchVerificationFailed(- "\(method): site at 0x\(hex(UInt64(site.fileOffset))) reads \(Data(written).hex) after write"+ "\(method): site at 0x\(hex(UInt64(site.fileOffset))) reads \(Data(written).hex) after write",)}@@ -241,7 +249,7 @@ public enum CFWDiskimagesiod {outcome: site.isAlreadyPatched ? .alreadyPatched : .patched,site: site,record: record,- rehashes: rehashes+ rehashes: rehashes,)}@@ -254,7 +262,7 @@ public enum CFWDiskimagesiod {fileAt url: URL,reattest: Bool = false,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -293,7 +301,7 @@ public enum CFWDiskimagesiod {fileOffset: offset,virtualAddress: va,anchor: .symbolTable,- textRange: textRange+ textRange: textRange,){return site@@ -303,7 +311,7 @@ public enum CFWDiskimagesiod {let (impVA, anchor) = try resolveIMPViaObjCMetadata(in: data, sections: sections)guard let offset = MachOParser.vaToFileOffset(impVA, segments: segments) else {throw PatcherError.invalidFormat(- "\(method): IMP va 0x\(hex(impVA)) is in no mapped segment"+ "\(method): IMP va 0x\(hex(impVA)) is in no mapped segment",)}guard let site = makeSite(@@ -311,11 +319,11 @@ public enum CFWDiskimagesiod {fileOffset: offset,virtualAddress: impVA,anchor: anchor,- textRange: textRange+ textRange: textRange,) else {throw PatcherError.patchSiteNotFound("\(method): IMP at 0x\(hex(impVA)) (foff 0x\(hex(UInt64(offset)))) "- + "is outside __TEXT,__text or does not decode as instructions"+ + "is outside __TEXT,__text or does not decode as instructions",)}return site@@ -331,7 +339,7 @@ public enum CFWDiskimagesiod {fileOffset: Int,virtualAddress: UInt64?,anchor: Anchor,- textRange: Range<Int>?+ textRange: Range<Int>?,) -> Site? {let length = replacement.countguard fileOffset >= 0, fileOffset + length <= data.count else { return nil }@@ -344,16 +352,18 @@ public enum CFWDiskimagesiod {fileOffset: fileOffset,virtualAddress: virtualAddress,anchor: anchor,- original: original+ original: original,)- if site.isAlreadyPatched { return site }+ if site.isAlreadyPatched {+ return site+ }// `skipData` is on in the shared disassembler, so an undecodable word// arrives as a data pseudo-instruction (id 0) instead of ending the// stream — which is what makes this a usable "is this code?" test.let decoded = ARM64Disassembler().disassemble(original,- at: virtualAddress ?? UInt64(fileOffset)+ at: virtualAddress ?? UInt64(fileOffset),)guard decoded.count == length / 4, decoded.allSatisfy({ $0.id != 0 }) else { return nil }return site@@ -364,11 +374,11 @@ public enum CFWDiskimagesiod {/// selector cstring → selref → method-list entry → IMP.static func resolveIMPViaObjCMetadata(in data: Data,- sections: [String: MachOSectionInfo]+ 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"+ "\(component): selector '\(selector)' not present in the image",)}@@ -382,7 +392,7 @@ public enum CFWDiskimagesiod {in: data,selrefs: selrefsSection,selectorVA: selectorVA,- imageBase: imageBase(sections)+ imageBase: imageBase(sections),){targets.insert(selrefVA)@@ -414,7 +424,7 @@ public enum CFWDiskimagesiod {}throw PatcherError.patchSiteNotFound(- "\(method): no ObjC method-list entry names '\(selector)'"+ "\(method): no ObjC method-list entry names '\(selector)'",)}@@ -430,7 +440,7 @@ public enum CFWDiskimagesiod {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"+ + "implementations (\(list)) — no unambiguous target",)}return first@@ -489,7 +499,7 @@ public enum CFWDiskimagesiod {in data: Data,selrefs: MachOSectionInfo,selectorVA: UInt64,- imageBase: UInt64+ imageBase: UInt64,) -> UInt64? {let start = Int(selrefs.fileOffset)let count = Int(selrefs.size)@@ -528,7 +538,7 @@ public enum CFWDiskimagesiod {static func relativeMethodListIMPs(in data: Data,section: MachOSectionInfo,- naming targets: Set<UInt64>+ naming targets: Set<UInt64>,) -> [UInt64] {let base = Int(section.fileOffset)let size = Int(section.size)@@ -553,7 +563,7 @@ public enum CFWDiskimagesiod {in: data,fileOffset: base + entryOffset,virtualAddress: section.address + UInt64(entryOffset),- naming: targets+ naming: targets,) {found.append(impVA)}@@ -570,7 +580,7 @@ public enum CFWDiskimagesiod {static func scanRelativeMethodEntryIMPs(in data: Data,section: MachOSectionInfo,- naming targets: Set<UInt64>+ naming targets: Set<UInt64>,) -> [UInt64] {let base = Int(section.fileOffset)let size = Int(section.size)@@ -583,7 +593,7 @@ public enum CFWDiskimagesiod {in: data,fileOffset: base + offset,virtualAddress: section.address + UInt64(offset),- naming: targets+ naming: targets,) {found.append(impVA)}@@ -598,7 +608,7 @@ public enum CFWDiskimagesiod {in data: Data,fileOffset: Int,virtualAddress: UInt64,- naming targets: Set<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))@@ -623,7 +633,7 @@ public enum CFWDiskimagesiod {patchedBytes: patched,beforeDisasm: disassemblyText(of: site.original, at: site.virtualAddress),afterDisasm: disassemblyText(of: patched, at: site.virtualAddress),- description: "\(method) -> mov x0, #1; ret"+ description: "\(method) -> mov x0, #1; ret",)}@@ -665,7 +675,9 @@ public enum CFWDiskimagesiod {static func section(_ sections: [String: MachOSectionInfo], _ keys: String...) -> MachOSectionInfo? {for key in keys {- if let section = sections[key] { return section }+ if let section = sections[key] {+ return section+ }}return nil}diff --git a/sources/FirmwarePatcher/CFW/Patches/CFWJetsam.swift b/sources/FirmwarePatcher/CFW/Patches/CFWJetsam.swiftindex 9fb29864..bf088da4 100644--- a/sources/FirmwarePatcher/CFW/Patches/CFWJetsam.swift+++ b/sources/FirmwarePatcher/CFW/Patches/CFWJetsam.swift@@ -160,7 +160,7 @@ public enum CFWJetsamPatcher {returnBlockOffset: Int,functionOffset: Int,record: PatchRecord? = nil,- rehashes: [CFWSlotRehash] = []+ rehashes: [CFWSlotRehash] = [],) {self.verdict = verdictself.anchor = anchor@@ -173,7 +173,9 @@ public enum CFWJetsamPatcher {}/// Sites this run put on disk — 1 on a live patch, 0 otherwise.- public var sitesWritten: Int { verdict == .patched ? 1 : 0 }+ public var sitesWritten: Int {+ verdict == .patched ? 1 : 0+ }}// MARK: - Entry points@@ -188,7 +190,7 @@ public enum CFWJetsamPatcher {fileAt url: URL,dryRun: Bool = false,reattest: Bool = false,- log: ((String) -> Void)? = { FileHandle.standardError.write(Data(($0 + "\n").utf8)) }+ log: ((String) -> Void)? = { FileHandle.standardError.write(Data(($0 + "\n").utf8)) },) throws -> Outcome {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -207,15 +209,17 @@ public enum CFWJetsamPatcher {_ data: inout Data,dryRun: Bool = false,reattest: Bool = false,- log: ((String) -> Void)? = nil+ log: ((String) -> Void)? = nil,) throws -> Outcome {- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }let image = try Image(data: data)guard let site = try locate(in: image, log: log) else {throw PatcherError.patchSiteNotFound("launchd jetsam: no anchor string resolved to a conditional branch "- + "into its function's return block"+ + "into its function's return block",)}@@ -229,7 +233,7 @@ public enum CFWJetsamPatcher {log?(String(format: " [=] already patched at 0x%X: b 0x%X (jetsam panic guard bypass)",site.gateOffset,- site.returnBlockOffset+ site.returnBlockOffset,))return Outcome(verdict: .alreadyPatched,@@ -237,7 +241,7 @@ public enum CFWJetsamPatcher {gateOffset: site.gateOffset,gateVMA: gateVMA,returnBlockOffset: site.returnBlockOffset,- functionOffset: site.functionOffset+ functionOffset: site.functionOffset,)}@@ -246,8 +250,8 @@ public enum CFWJetsamPatcher {String(format: "launchd jetsam: b 0x%X is out of range from 0x%X",site.returnBlockOffset,- site.gateOffset- )+ site.gateOffset,+ ),)}@@ -263,8 +267,8 @@ public enum CFWJetsamPatcher {afterDisasm: describe(branch, at: site.gateOffset),description: String(format: "conditional branch -> unconditional b 0x%X (jetsam panic guard bypass)",- site.returnBlockOffset- )+ site.returnBlockOffset,+ ),)log?(String(@@ -272,7 +276,7 @@ public enum CFWJetsamPatcher {dryRun ? "[.] would patch" : "[+] patching",site.gateOffset,record.beforeDisasm,- record.afterDisasm+ record.afterDisasm,))guard !dryRun else {@@ -283,21 +287,23 @@ public enum CFWJetsamPatcher {gateVMA: gateVMA,returnBlockOffset: site.returnBlockOffset,functionOffset: site.functionOffset,- record: record+ record: record,)}data.replaceSubrange(site.gateOffset ..< site.gateOffset + 4, with: branch)guard Data(data[site.gateOffset ..< site.gateOffset + 4]) == branch else {throw PatcherError.patchVerificationFailed(- String(format: "launchd jetsam: post-write verify failed at 0x%X", site.gateOffset)+ String(format: "launchd jetsam: post-write verify failed at 0x%X", site.gateOffset),)}var rehashes: [CFWSlotRehash] = []if reattest {rehashes = try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: [site.gateOffset])- for rehash in rehashes { log?(" [.] re-attest \(rehash)") }+ for rehash in rehashes {+ log?(" [.] re-attest \(rehash)")+ }}log?(String(format: " [+] Patched at 0x%X: jetsam panic guard bypass", site.gateOffset))@@ -309,7 +315,7 @@ public enum CFWJetsamPatcher {returnBlockOffset: site.returnBlockOffset,functionOffset: site.functionOffset,record: record,- rehashes: rehashes+ rehashes: rehashes,)}@@ -350,9 +356,13 @@ public enum CFWJetsamPatcher {.sorted { $0.fileOffset < $1.fileOffset }}- var textEnd: Int { textOffset + textSize }+ var textEnd: Int {+ textOffset + textSize+ }- func isInText(_ offset: Int) -> Bool { offset >= textOffset && offset < textEnd }+ 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.@@ -413,7 +423,7 @@ public enum CFWJetsamPatcher {functionOffset: functionOffset,gateOffset: gate.offset,returnBlockOffset: gate.target,- isAlreadyPatched: gate.isUnconditional+ isAlreadyPatched: gate.isUnconditional,)}return nil@@ -489,7 +499,9 @@ public enum CFWJetsamPatcher {////// 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 }+ static func isAddImm64(_ word: UInt32) -> Bool {+ (word & 0xFFC0_0000) == 0x9100_0000+ }/// First instruction of the function containing `offset`.///@@ -507,7 +519,9 @@ public enum CFWJetsamPatcher {let floor = max(image.textOffset, offset - maxFunctionPrologueScan)var scan = offset - 4while scan >= floor {- if image.data.loadLE(UInt32.self, at: scan) == ARM64.pacibspU32 { return scan }+ if image.data.loadLE(UInt32.self, at: scan) == ARM64.pacibspU32 {+ return scan+ }scan -= 4}return max(image.textOffset, offset - fallbackScanWindow)@@ -534,7 +548,7 @@ public enum CFWJetsamPatcher {static func findReturnGate(from start: Int,to end: Int,- in image: Image+ in image: Image,) -> (offset: Int, target: Int, isUnconditional: Bool)? {var liveGate: (offset: Int, target: Int)?var patchedGate: (offset: Int, target: Int)?@@ -550,11 +564,15 @@ public enum CFWJetsamPatcher {guard isReturnBlock(target, in: image) else { continue }if unconditional {- if patchedGate == nil { patchedGate = (offset, target) }+ if patchedGate == nil {+ patchedGate = (offset, target)+ }} else if liveGate == nil {liveGate = (offset, target)}- if liveGate != nil, patchedGate != nil { break }+ if liveGate != nil, patchedGate != nil {+ break+ }}switch (liveGate, patchedGate) {@@ -609,7 +627,9 @@ public enum CFWJetsamPatcher {/// 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 }+ if insn.groups.contains(UInt8(CS_GRP_CALL.rawValue)) {+ return true+ }return insn.groups.contains(UInt8(CS_GRP_JUMP.rawValue))&& !conditionalBranchMnemonics.contains(insn.mnemonic)}@@ -624,8 +644,12 @@ public enum CFWJetsamPatcher {let probe = offset + step * 4guard 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 }+ if isReturn(insn) {+ return true+ }+ if leavesBlock(insn) {+ return false+ }}return false}diff --git a/sources/FirmwarePatcher/CFW/Patches/CFWMobileactivationd.swift b/sources/FirmwarePatcher/CFW/Patches/CFWMobileactivationd.swiftindex 7ed67b26..ed39768e 100644--- a/sources/FirmwarePatcher/CFW/Patches/CFWMobileactivationd.swift+++ b/sources/FirmwarePatcher/CFW/Patches/CFWMobileactivationd.swift@@ -122,7 +122,9 @@ public enum CFWMobileactivationd {/// 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 }+ public var sitesWritten: Int {+ record == nil ? 0 : 1+ }}// MARK: - Patching@@ -146,7 +148,7 @@ public enum CFWMobileactivationd {fileAt url: URL,resign: Bool = true,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -170,9 +172,11 @@ public enum CFWMobileactivationd {_ data: inout Data,resign: Bool = true,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }let anchor = try locateIMP(in: data)log?(" [.] \(method) @ 0x\(hex(anchor.virtualAddress)) "@@ -182,7 +186,7 @@ public enum CFWMobileactivationd {let patched = try replacementBytes()guard data.count >= anchor.fileOffset + patched.count else {throw PatcherError.invalidFormat(- "\(method): IMP at 0x\(hex(UInt64(anchor.fileOffset))) is past the end of the file"+ "\(method): IMP at 0x\(hex(UInt64(anchor.fileOffset))) is past the end of the file",)}let original = Data(data[anchor.fileOffset ..< anchor.fileOffset + patched.count])@@ -206,14 +210,14 @@ public enum CFWMobileactivationd {outcome: .alreadyPatched,anchor: anchor,record: nil,- slotRehashes: rehashes+ slotRehashes: rehashes,)}guard isPlausibleGetterBody(body) else {throw PatcherError.invalidFormat("\(method): body at 0x\(hex(anchor.virtualAddress)) reads `\(text(of: body))`, "- + "which is not a two-instruction body this patch can replace"+ + "which is not a two-instruction body this patch can replace",)}@@ -224,12 +228,12 @@ public enum CFWMobileactivationd {}data.replaceSubrange(anchor.fileOffset ..< anchor.fileOffset + patched.count, with: patched)- log?(" [+] after: \(text(of: try decodeBody(patched, at: anchor.virtualAddress)))")+ try log?(" [+] after: \(text(of: decodeBody(patched, at: anchor.virtualAddress)))")let written = Data(data[anchor.fileOffset ..< anchor.fileOffset + patched.count])guard written == patched else {throw PatcherError.patchVerificationFailed(- "\(method): site at 0x\(hex(UInt64(anchor.fileOffset))) reads \(written.hex) after write"+ "\(method): site at 0x\(hex(UInt64(anchor.fileOffset))) reads \(written.hex) after write",)}@@ -237,7 +241,7 @@ public enum CFWMobileactivationd {if resign {rehashes = try CFWMachOCodeSignature.reattest(&data,- modifiedOffsets: touchedOffsets(anchor, patched)+ modifiedOffsets: touchedOffsets(anchor, patched),)log?(" [.] re-attested \(rehashes.count) slot(s): "+ rehashes.map(\.description).joined(separator: ", "))@@ -248,7 +252,7 @@ public enum CFWMobileactivationd {}log?(" [+] Patched at 0x\(hex(UInt64(anchor.fileOffset))): mov x0, #1; ret")- return Report(+ return try Report(outcome: .patched,anchor: anchor,record: PatchRecord(@@ -259,10 +263,10 @@ public enum CFWMobileactivationd {originalBytes: original,patchedBytes: patched,beforeDisasm: text(of: body),- afterDisasm: text(of: try decodeBody(patched, at: anchor.virtualAddress)),- description: "\(method) -> mov x0, #1; ret"+ afterDisasm: text(of: decodeBody(patched, at: anchor.virtualAddress)),+ description: "\(method) -> mov x0, #1; ret",),- slotRehashes: rehashes+ slotRehashes: rehashes,)}@@ -286,7 +290,7 @@ public enum CFWMobileactivationd {/// dirties two slots, and hashing only the first would leave the tail slot/// stale — a SIGKILL the first time that page is demand-paged in.static func touchedOffsets(_ anchor: Anchor, _ patched: Data) -> [Int] {- stride(from: anchor.fileOffset, to: anchor.fileOffset + patched.count, by: 4).map { $0 }+ stride(from: anchor.fileOffset, to: anchor.fileOffset + patched.count, by: 4).map(\.self)}// MARK: - Anchoring@@ -313,7 +317,7 @@ public enum CFWMobileactivationd {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"+ + "says 0x\(hex(metadata)) — refusing to guess which is the IMP",)}source = .symbolTableAndObjCMetadata@@ -326,19 +330,19 @@ public enum CFWMobileactivationd {virtualAddress = metadatacase (nil, nil):throw PatcherError.patchSiteNotFound(- "\(method): neither LC_SYMTAB nor the ObjC method lists carry it"+ "\(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"+ "\(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"+ + "the anchor resolved to data, not code",)}@@ -346,7 +350,7 @@ public enum CFWMobileactivationd {virtualAddress: virtualAddress,fileOffset: fileOffset,source: source,- section: section+ section: section,)}@@ -378,7 +382,9 @@ public enum CFWMobileactivationd {guard let name = cString(in: data, at: symtab.stroff + strx,limit: symtab.stroff + symtab.strsize) else { continue }- if name == method { return value }+ if name == method {+ return value+ }}return nil}@@ -388,7 +394,7 @@ public enum CFWMobileactivationd {/// method-list entry whose `name` field points at that selref -> its `imp`.static func objcMetadataVirtualAddress(in data: Data,- segments: [MachOSegmentInfo]+ segments: [MachOSegmentInfo],) -> UInt64? {let sections = MachOParser.parseSections(from: data)guard let imageBase = segments.first(where: { $0.name == "__TEXT" })?.vmAddr else {@@ -398,11 +404,11 @@ public enum CFWMobileactivationd {return nil}guard let selrefVA = selectorReferenceVirtualAddress(- to: selectorVA, in: data, sections: sections, imageBase: imageBase+ to: selectorVA, in: data, sections: sections, imageBase: imageBase,) else { return nil }return methodImplementation(- forSelectorReference: selrefVA, in: data, sections: sections+ forSelectorReference: selrefVA, in: data, sections: sections,)}@@ -416,7 +422,7 @@ public enum CFWMobileactivationd {/// is what separates a whole selector from a suffix of something longer.static func selectorVirtualAddress(in data: Data,- sections: [String: MachOSectionInfo]+ sections: [String: MachOSectionInfo],) -> UInt64? {let candidates = ["__TEXT,__objc_methname", "__DATA,__objc_methname"]guard let section = candidates.compactMap({ sections[$0] }).first else { return nil }@@ -450,7 +456,7 @@ public enum CFWMobileactivationd {to selectorVA: UInt64,in data: Data,sections: [String: MachOSectionInfo],- imageBase: UInt64+ imageBase: UInt64,) -> UInt64? {let candidates = ["__DATA,__objc_selrefs",@@ -486,7 +492,7 @@ public enum CFWMobileactivationd {static func methodImplementation(forSelectorReference selrefVA: UInt64,in data: Data,- sections: [String: MachOSectionInfo]+ sections: [String: MachOSectionInfo],) -> UInt64? {let candidates = ["__TEXT,__objc_methlist",@@ -497,8 +503,10 @@ public enum CFWMobileactivationd {for name in candidates {guard let section = sections[name] else { continue }if let imp = methodImplementation(- forSelectorReference: selrefVA, in: data, section: section- ) { return imp }+ forSelectorReference: selrefVA, in: data, section: section,+ ) {+ return imp+ }}return nil}@@ -513,7 +521,7 @@ public enum CFWMobileactivationd {static func methodImplementation(forSelectorReference selrefVA: UInt64,in data: Data,- section: MachOSectionInfo+ section: MachOSectionInfo,) -> UInt64? {let smallMethodListFlag: UInt32 = 0x8000_0000let entrySizeMask: UInt32 = 0x0000_FFFC@@ -574,7 +582,7 @@ public enum CFWMobileactivationd {if initprot & vmProtExecute != 0 {let raw = data[offset + 8 ..< offset + 24]executableSegments.insert(- String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)+ String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self),)}}@@ -598,7 +606,7 @@ public enum CFWMobileactivationd {guard decoded.count == 2, decoded.allSatisfy({ $0.id != 0 }) else {throw PatcherError.invalidFormat("\(method): the eight bytes at 0x\(hex(va)) (\(bytes.hex)) are not two "- + "decodable instructions"+ + "decodable instructions",)}return decoded@@ -615,10 +623,12 @@ public enum CFWMobileactivationd {static func isPlausibleGetterBody(_ body: [Instruction]) -> Bool {guard body.count == 2 else { return false }// A getter: `ldr…/mov… ; ret`.- if body[1].mnemonic == "ret" || body[1].mnemonic.hasPrefix("reta") { return true }+ if body[1].mnemonic == "ret" || body[1].mnemonic.hasPrefix("reta") {+ return true+ }// A real function: a recognisable prologue in the first word, so the// eight bytes are the head of a function and an early return is safe.- let prologue: Set<String> = ["pacibsp", "paciasp", "stp", "sub"]+ let prologue: Set = ["pacibsp", "paciasp", "stp", "sub"]return prologue.contains(body[0].mnemonic)}@@ -635,7 +645,9 @@ public enum CFWMobileactivationd {guard offset >= 0, offset < min(limit, data.count) else { return nil }var end = offsetlet stop = min(limit, data.count)- while end < stop, data[end] != 0 { end += 1 }+ while end < stop, data[end] != 0 {+ end += 1+ }return String(data: data[offset ..< end], encoding: .ascii)}diff --git a/sources/FirmwarePatcher/CFW/Patches/CFWSeputil.swift b/sources/FirmwarePatcher/CFW/Patches/CFWSeputil.swiftindex 34a1d4f7..543d54c6 100644--- a/sources/FirmwarePatcher/CFW/Patches/CFWSeputil.swift+++ b/sources/FirmwarePatcher/CFW/Patches/CFWSeputil.swift@@ -147,7 +147,7 @@ public enum CFWSeputil {site: Site,references: [UInt64],record: PatchRecord? = nil,- rehashes: [CFWSlotRehash] = []+ rehashes: [CFWSlotRehash] = [],) {self.verdict = verdictself.site = site@@ -158,7 +158,9 @@ public enum CFWSeputil {/// Sites this run put on disk — 1 on a live patch, 0 otherwise. Mirrors/// what `patch_seputil()` reports.- public var sitesWritten: Int { verdict == .patched ? 1 : 0 }+ public var sitesWritten: Int {+ verdict == .patched ? 1 : 0+ }}// MARK: - Entry points@@ -175,7 +177,7 @@ public enum CFWSeputil {fileAt url: URL,dryRun: Bool = false,reattest: Bool = true,- log: ((String) -> Void)? = stderrLog+ log: ((String) -> Void)? = stderrLog,) throws -> Outcome {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -195,15 +197,17 @@ public enum CFWSeputil {_ data: inout Data,dryRun: Bool = false,reattest: Bool = true,- log: ((String) -> Void)? = stderrLog+ log: ((String) -> Void)? = stderrLog,) throws -> Outcome {- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }let (cstring, text) = try sections(in: data)let site = try findSite(in: data, cstring: cstring)log?(" [.] literal \"\(site.literal)\" @ 0x\(hex(site.literalVMA)) "- + "(file 0x\(hex(site.literalOffset)))"+ + "(file 0x\(hex(site.literalOffset)))",)// The literal has to be one the code actually formats with. Without@@ -215,7 +219,7 @@ public enum CFWSeputil {throw PatcherError.patchSiteNotFound("seputil: \"\(site.literal)\" @ 0x\(hex(site.literalVMA)) has no adrp+add "+ "reference in \(textSection.segment),\(textSection.section); "- + "it is not the literal the gigalocker path is built from"+ + "it is not the literal the gigalocker path is built from",)}log?(" [.] referenced from \(references.map { "0x" + hex($0) }.joined(separator: ", "))")@@ -223,7 +227,7 @@ public enum CFWSeputil {guard site.isPristine else {log?(" [=] field at 0x\(hex(site.fieldOffset)) already reads "- + "\"\(uuidReplacement)\"; nothing to patch/re-attest"+ + "\"\(uuidReplacement)\"; nothing to patch/re-attest",)return Outcome(verdict: .alreadyPatched, site: site, references: references)}@@ -239,14 +243,14 @@ public enum CFWSeputil {verdict: .wouldPatch,site: site,references: references,- record: record+ record: record,)}data.replaceSubrange(range, with: replacement)log?(" [+] 0x\(hex(site.fieldOffset)): \(original.hex) -> \(replacement.hex) "- + "(\"\(site.literal)\" -> \"\(patchedLiteral(of: site))\")"+ + "(\"\(site.literal)\" -> \"\(patchedLiteral(of: site))\")",)var rehashes: [CFWSlotRehash] = []@@ -254,11 +258,13 @@ public enum CFWSeputil {for directory in CFWMachOCodeSignature.unsupportedCodeDirectories(in: data) {log?(" [-] CodeDirectory @ 0x\(hex(directory.offset)) is hashType "- + "\(directory.hashType), not SHA-256 — left untouched"+ + "\(directory.hashType), not SHA-256 — left untouched",)}rehashes = try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: site.modifiedOffsets)- for rehash in rehashes { log?(" [+] \(rehash)") }+ for rehash in rehashes {+ log?(" [+] \(rehash)")+ }}// Re-read the site the same way it was found, rather than trusting the@@ -266,7 +272,7 @@ public enum CFWSeputil {let after = try findSite(in: data, cstring: cstring)guard after.fieldOffset == site.fieldOffset, !after.isPristine else {throw PatcherError.patchVerificationFailed(- "seputil: post-write read back \"\(after.literal)\" at 0x\(hex(after.fieldOffset))"+ "seputil: post-write read back \"\(after.literal)\" at 0x\(hex(after.fieldOffset))",)}log?(" [+] seputil gigalocker name pinned to \"\(uuidReplacement)\(gigalockerSuffix)\"")@@ -276,7 +282,7 @@ public enum CFWSeputil {site: site,references: references,record: record,- rehashes: rehashes+ rehashes: rehashes,)}@@ -288,12 +294,12 @@ public enum CFWSeputil {guard let cstring = all["\(cstringSection.segment),\(cstringSection.section)"] else {throw PatcherError.invalidFormat("seputil: no \(cstringSection.segment),\(cstringSection.section) section "- + "(not a 64-bit Mach-O, or not the binary we were handed)"+ + "(not a 64-bit Mach-O, or not the binary we were handed)",)}guard let text = all["\(textSection.segment),\(textSection.section)"] else {throw PatcherError.invalidFormat(- "seputil: no \(textSection.segment),\(textSection.section) section"+ "seputil: no \(textSection.segment),\(textSection.section) section",)}return (cstring, text)@@ -314,7 +320,7 @@ public enum CFWSeputil {guard start >= 0, end <= data.count, start <= end else {throw PatcherError.invalidFormat("seputil: \(cstringSection.section) runs to 0x\(hex(end)), past the end of a "- + "0x\(hex(data.count))-byte file"+ + "0x\(hex(data.count))-byte file",)}@@ -322,7 +328,9 @@ public enum CFWSeputil {var cursor = startwhile cursor < end {var terminator = cursor- while terminator < end, data[terminator] != 0 { terminator += 1 }+ while terminator < end, data[terminator] != 0 {+ terminator += 1+ }guard terminator < end else { break } // unterminated tail, not a literallet literal = Array(data[cursor ..< terminator])if let field = fileField(of: literal), let pristine = pristineness(of: literal[field]) {@@ -332,7 +340,7 @@ public enum CFWSeputil {literal: String(decoding: literal, as: UTF8.self),fieldOffset: cursor + field.lowerBound,fieldVMA: cstring.address + UInt64(cursor - start + field.lowerBound),- isPristine: pristine+ isPristine: pristine,))}cursor = terminator + 1@@ -341,14 +349,14 @@ public enum CFWSeputil {guard let site = sites.first else {throw PatcherError.patchSiteNotFound("seputil: no \"<dir>/\(uuidConversion)\(gigalockerSuffix)\" literal in "- + "\(cstringSection.segment),\(cstringSection.section)"+ + "\(cstringSection.segment),\(cstringSection.section)",)}guard sites.count == 1 else {throw PatcherError.patchSiteNotFound("seputil: \(sites.count) gigalocker path literals "+ "(\(sites.map { "\"\($0.literal)\" @ 0x" + hex($0.literalOffset) }.joined(separator: ", "))); "- + "refusing to guess which one builds the path"+ + "refusing to guess which one builds the path",)}return site@@ -375,8 +383,12 @@ public enum CFWSeputil {/// `true` for a field that still reads `%s`, `false` for one already/// reading `AA`, `nil` for anything else — which is not this patch's site.static func pristineness(of field: ArraySlice<UInt8>) -> Bool? {- if field.elementsEqual(uuidConversion.utf8) { return true }- if field.elementsEqual(uuidReplacement.utf8) { return false }+ if field.elementsEqual(uuidConversion.utf8) {+ return true+ }+ if field.elementsEqual(uuidReplacement.utf8) {+ return false+ }return nil}@@ -468,7 +480,7 @@ public enum CFWSeputil {originalBytes: original,patchedBytes: replacement,description: "gigalocker path format '/\(uuidConversion)\(gigalockerSuffix)' "- + "-> '/\(uuidReplacement)\(gigalockerSuffix)'"+ + "-> '/\(uuidReplacement)\(gigalockerSuffix)'",)}diff --git a/sources/FirmwarePatcher/CFW/Patches/CFWWatchdogd.swift b/sources/FirmwarePatcher/CFW/Patches/CFWWatchdogd.swiftindex aa091723..c2175bfe 100644--- a/sources/FirmwarePatcher/CFW/Patches/CFWWatchdogd.swift+++ b/sources/FirmwarePatcher/CFW/Patches/CFWWatchdogd.swift@@ -127,6 +127,7 @@ public enum CFWWatchdogd {static let argumentRegister = "x0"// MARK: - Scan windows+//// Instruction counts, not byte counts. Same values as the Python, which// measured them against the shipped binary.@@ -201,7 +202,9 @@ public enum CFWWatchdogd {/// Sites whose bytes this run changed. The parity number against the/// Python, whose `patch_watchdogd()` returns exactly this.- public var sitesWritten: Int { records.count / 2 }+ public var sitesWritten: Int {+ records.count / 2+ }}/// Where progress goes when the caller does not say. The Python prints to@@ -223,7 +226,7 @@ public enum CFWWatchdogd {public static func patch(at url: URL,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -242,9 +245,11 @@ public enum CFWWatchdogd {public static func patch(_ data: inout Data,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {- if data.startIndex != 0 { data = Data(data) }+ if data.startIndex != 0 {+ data = Data(data)+ }let sites = try locateSites(in: data, log: log)let pending = sites.filter { $0.state == .pristine }@@ -262,7 +267,7 @@ public enum CFWWatchdogd {for site in pending {guard let value = ARM64Encoder.encodeMovzW(rd: site.valueRegisterNumber, imm16: 1) else {throw PatcherError.patchVerificationFailed(- "could not encode `mov \(site.valueRegister), #1`"+ "could not encode `mov \(site.valueRegister), #1`",)}let gate = ARM64.nop@@ -278,7 +283,7 @@ public enum CFWWatchdogd {patched: gate,id: "\(component).hv_vmm_cache.cbnz@0x\(hex(site.gateVMA))",description: "NOP the cbnz w0 that skips the cached hv_vmm_present store",- disassembler: disassembler+ disassembler: disassembler,))records.append(record(in: data,@@ -288,7 +293,7 @@ public enum CFWWatchdogd {id: "\(component).hv_vmm_cache.cset@0x\(hex(site.valueVMA))",description: "cset \(site.valueRegister) -> mov \(site.valueRegister), #1 "+ "(cached 'am I a VM?' byte forced to 1)",- disassembler: disassembler+ disassembler: disassembler,))if !dryRun {@@ -314,7 +319,9 @@ public enum CFWWatchdogd {}let rehashed = try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: modifiedOffsets)- for slot in rehashed { log?(" [+] re-attest: \(slot)") }+ for slot in rehashed {+ log?(" [+] re-attest: \(slot)")+ }log?(" [+] re-attest updated \(rehashed.count) slot(s)")try verify(sites: pending, in: data)@@ -343,7 +350,7 @@ public enum CFWWatchdogd {guard let symbols = CFWWatchdogdSymbolTargets(data: data) else {throw PatcherError.invalidFormat(- "no LC_SYMTAB/LC_DYSYMTAB — \(sysctlFunction) cannot be resolved"+ "no LC_SYMTAB/LC_DYSYMTAB — \(sysctlFunction) cannot be resolved",)}@@ -394,17 +401,19 @@ public enum CFWWatchdogd {literalVMA: literal.address,text: text,segments: segments,- symbols: symbols+ symbols: symbols,) else { continue }- if !sites.contains(where: { $0.gateVMA == site.gateVMA }) { sites.append(site) }+ 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"+ + "and a strb into a \(globalSegmentPrefix) global",)}return sites.sorted { $0.gateVMA < $1.gateVMA }@@ -420,22 +429,22 @@ public enum CFWWatchdogd {literalVMA: UInt64,text: MachOSectionInfo,segments: [MachOSegmentInfo],- symbols: CFWWatchdogdSymbolTargets+ symbols: CFWWatchdogdSymbolTargets,) -> 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" }+ where: { $0.mnemonic == "bl" },) else { return nil }let call = instructions[callIndex]guard let target = ARM64Encoder.decodeBranchTarget(- insn: word(of: call), pc: call.address+ 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+ inRegister: pointerRegister, from: addIndex, toCallAt: callIndex, in: instructions,) else { return nil }// Layer 4a: the gate, which must be the very next instruction — the@@ -464,7 +473,7 @@ public enum CFWWatchdogd {case .patched:isMoveOfOne(instruction)}- }+ },) else { return nil }let value = instructions[valueIndex]guard let valueRegister = registerName(value, 0),@@ -474,13 +483,13 @@ public enum CFWWatchdogd {// __DATA address — the cached global.guard let storeIndex = firstIndex(in: instructions, from: valueIndex + 1, within: valueToStoreWindow,- where: { $0.mnemonic == "strb" && registerName($0, 0) == valueRegister }+ 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+ before: storeIndex, notBefore: addIndex, in: instructions,) else { return nil }let cachedByte = basePage &+ UInt64(bitPattern: Int64(memory.disp))guard let segment = segments.first(where: {@@ -499,7 +508,7 @@ public enum CFWWatchdogd {valueRegister: valueRegister,valueRegisterNumber: valueNumber,storeVMA: store.address,- cachedByteVMA: cachedByte+ cachedByteVMA: cachedByte,)}@@ -515,9 +524,11 @@ public enum CFWWatchdogd {inRegister pointer: String,from addIndex: Int,toCallAt callIndex: Int,- in instructions: [Instruction]+ in instructions: [Instruction],) -> Bool {- if pointer == argumentRegister { return true }+ if pointer == argumentRegister {+ return true+ }for index in (addIndex + 1) ..< callIndex {let instruction = instructions[index]if instruction.mnemonic == "mov",@@ -534,7 +545,7 @@ public enum CFWWatchdogd {/// boundary so a suffix of a longer literal cannot pass.static func findLiteral(in data: Data,- sections: [String: MachOSectionInfo]+ 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)@@ -564,13 +575,13 @@ public enum CFWWatchdogd {let gate = data.subdata(in: site.gateFileOffset ..< site.gateFileOffset + 4)guard gate == ARM64.nop else {throw PatcherError.patchVerificationFailed(- "gate at 0x\(hex(site.gateVMA)) reads \(gate.hex) after write"+ "gate at 0x\(hex(site.gateVMA)) reads \(gate.hex) after write",)}let value = data.subdata(in: site.valueFileOffset ..< site.valueFileOffset + 4)guard value == ARM64Encoder.encodeMovzW(rd: site.valueRegisterNumber, imm16: 1) else {throw PatcherError.patchVerificationFailed(- "value at 0x\(hex(site.valueVMA)) reads \(value.hex) after write"+ "value at 0x\(hex(site.valueVMA)) reads \(value.hex) after write",)}}@@ -585,7 +596,7 @@ public enum CFWWatchdogd {patched: Data,id: String,description: String,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> PatchRecord {let original = data.subdata(in: fileOffset ..< fileOffset + patched.count)return PatchRecord(@@ -597,7 +608,7 @@ public enum CFWWatchdogd {patchedBytes: patched,beforeDisasm: text(of: original, at: virtualAddress, disassembler),afterDisasm: text(of: patched, at: virtualAddress, disassembler),- description: description+ description: description,)}@@ -618,14 +629,16 @@ public enum CFWWatchdogd {in instructions: [Instruction],from: Int,within: Int,- where predicate: (Instruction) -> Bool+ where predicate: (Instruction) -> Bool,) -> Int? {guard from >= 0 else { return nil }let end = min(instructions.count, from + within)var index = fromwhile index < end {guard instructions[index].id != 0 else { return nil }- if predicate(instructions[index]) { return index }+ if predicate(instructions[index]) {+ return index+ }index += 1}return nil@@ -637,7 +650,7 @@ public enum CFWWatchdogd {ofRegister register: UInt32,before: Int,notBefore: Int,- in instructions: [Instruction]+ in instructions: [Instruction],) -> UInt64? {var index = before - 1while index >= notBefore {@@ -665,7 +678,9 @@ public enum CFWWatchdogd {/// The instruction's raw little-endian word, for the branch decoder.static func word(of instruction: Instruction) -> UInt32 {var value: UInt32 = 0- for byte in instruction.bytes.prefix(4).reversed() { value = (value << 8) | UInt32(byte) }+ for byte in instruction.bytes.prefix(4).reversed() {+ value = (value << 8) | UInt32(byte)+ }return value}@@ -800,7 +815,7 @@ struct CFWWatchdogdSymbolTargets {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+ firstIndirectIndex: Int(data.loadLE(UInt32.self, at: section + 68)), // reserved1))}section += 80@@ -863,7 +878,9 @@ struct CFWWatchdogdSymbolTargets {guard start < data.count else { return nil }var end = startlet limit = min(data.count, stringOffset + stringSize)- while end < limit, data[end] != 0 { end += 1 }+ while end < limit, data[end] != 0 {+ end += 1+ }return String(data: data.subdata(in: start ..< end), encoding: .utf8)}}diff --git a/sources/FirmwarePatcher/Core/PatchRecord.swift b/sources/FirmwarePatcher/Core/PatchRecord.swiftindex 1c30b932..d87e9c74 100644--- a/sources/FirmwarePatcher/Core/PatchRecord.swift+++ b/sources/FirmwarePatcher/Core/PatchRecord.swift@@ -40,7 +40,7 @@ public struct PatchRecord: Codable, Equatable, Sendable {patchedBytes: Data,beforeDisasm: String = "",afterDisasm: String = "",- description: String+ description: String,) {self.patchID = patchIDself.component = component@@ -63,7 +63,7 @@ extension PatchRecord: CustomStringConvertible {addr,beforeDisasm.isEmpty ? originalBytes.hex : beforeDisasm,afterDisasm.isEmpty ? patchedBytes.hex : afterDisasm,- patchID+ patchID,)}}diff --git a/sources/FirmwarePatcher/DSC/DSCChunkSet.swift b/sources/FirmwarePatcher/DSC/DSCChunkSet.swiftindex 944c017d..1a2716b4 100644--- a/sources/FirmwarePatcher/DSC/DSCChunkSet.swift+++ b/sources/FirmwarePatcher/DSC/DSCChunkSet.swift@@ -61,9 +61,14 @@ public struct DSCWriteSpan: Sendable, Hashable {}/// Last address the span covers.- public var lastVMA: UInt64 { vma &+ UInt64(length - 1) }+ public var lastVMA: UInt64 {+ vma &+ UInt64(length - 1)+ }+/// One past the last address the span covers.- public var endVMA: UInt64 { vma &+ UInt64(length) }+ public var endVMA: UInt64 {+ vma &+ UInt64(length)+ }}/// Random-access byte view over a chunked dyld shared cache.@@ -82,9 +87,13 @@ public final class DSCChunkSet {public let chunkURL: URL/// One past the last address the mapping covers.- public var endAddress: UInt64 { address &+ size }+ public var endAddress: UInt64 {+ address &+ size+ }- public var isExecutable: Bool { initProt & DSCChunkSet.vmProtExecute != 0 }+ public var isExecutable: Bool {+ initProt & DSCChunkSet.vmProtExecute != 0+ }}public static let vmProtExecute: UInt32 = 4@@ -171,7 +180,11 @@ public final class DSCChunkSet {var high = mappings.countwhile low < high {let mid = (low + high) / 2- if mappings[mid].address <= vma { low = mid + 1 } else { high = mid }+ if mappings[mid].address <= vma {+ low = mid + 1+ } else {+ high = mid+ }}guard low > 0 else { return nil }return vma < mappings[low - 1].endAddress ? low - 1 : nil@@ -323,7 +336,9 @@ public final class DSCChunkSet {/// both of them `nil`.public func localSymbolTable() throws -> DSCLocalSymbolTable {try stateLock.withLock {- if let loadedLocalSymbols { return loadedLocalSymbols }+ if let loadedLocalSymbols {+ return loadedLocalSymbols+ }guard FileManager.default.fileExists(atPath: localSymbolsURL.path) else {throw DSCError.localSymbolsMissing(path: localSymbolsURL.path)}@@ -364,7 +379,7 @@ public final class DSCChunkSet {var results: [UInt64] = []for mapping in mappings where mapping.isExecutable {let buffer = try Self.window(- over: mapping, at: mapping.fileOffset, length: Int(mapping.size)+ over: mapping, at: mapping.fileOffset, length: Int(mapping.size),)var searchFrom = buffer.startIndexwhile searchFrom < buffer.endIndex,@@ -389,7 +404,7 @@ public final class DSCChunkSet {/// `__text`, so the search never has to leave the containing mapping.public func findMachOHeaderBefore(_ vma: UInt64,- maxWalk: Int = 64 * 1024 * 1024+ maxWalk: Int = 64 * 1024 * 1024,) throws -> UInt64? {guard let mapping = mapping(forVMA: vma) else { return nil }let localOffset = Int(vma &- mapping.address)@@ -399,19 +414,21 @@ public final class DSCChunkSet {let buffer = try Self.window(over: mapping,at: mapping.fileOffset &+ UInt64(scanStart),- length: scanLength + 4+ length: scanLength + 4,)var searchEnd = buffer.endIndexwhile searchEnd > buffer.startIndex,let found = buffer.range(of: Self.machOMagic64LE,options: .backwards,- in: buffer.startIndex ..< searchEnd+ in: buffer.startIndex ..< searchEnd,){let position = found.lowerBound - buffer.startIndexlet candidate = mapping.address &+ UInt64(scanStart + position)- if candidate & 0xFFF == 0 { return candidate }+ if candidate & 0xFFF == 0 {+ return candidate+ }searchEnd = found.lowerBound}return nil@@ -441,12 +458,16 @@ public final class DSCChunkSet {guard nameStart < head.count, nameStart < offset + commandSize else { return nil }let limit = min(head.count, offset + commandSize)var end = nameStart- while end < limit, head[head.startIndex + end] != 0 { end += 1 }+ while end < limit, head[head.startIndex + end] != 0 {+ end += 1+ }let bytes = head[(head.startIndex + nameStart) ..< (head.startIndex + end)]return String(decoding: bytes, as: UTF8.self)}offset += commandSize- if offset > Int(commandsSize) + 32 { return nil }+ if offset > Int(commandsSize) + 32 {+ return nil+ }}return nil}@@ -460,15 +481,19 @@ public final class DSCChunkSet {.filter { $0.hasPrefix(prefix) }.filter { !$0.hasSuffix(".symbols") && !$0.hasSuffix(".map") }- // Base file first, then numerically by sub-cache index. Files whose- // suffix is not a bare number (`.75.dylddata`, `.atlas`) sort after,- // by name — they still carry mappings and must not be dropped.+ /// Base file first, then numerically by sub-cache index. Files whose+ /// suffix is not a bare number (`.75.dylddata`, `.atlas`) sort after,+ /// by name — they still carry mappings and must not be dropped.func sortKey(_ name: String) -> (Int, Int, String) {- if name == prefix { return (0, -1, name) }+ if name == prefix {+ return (0, -1, name)+ }let suffix = name.dropFirst(prefix.count)guard suffix.hasPrefix(".") else { return (1, 0, name) }let rest = suffix.dropFirst()- if let index = Int(rest), !rest.isEmpty { return (0, index, name) }+ if let index = Int(rest), !rest.isEmpty {+ return (0, index, name)+ }return (1, 0, name)}return names@@ -495,7 +520,7 @@ public final class DSCChunkSet {guard let raw = try? read(url: url,offset: UInt64(mappingOffset),- length: Int(mappingCount) * 32+ length: Int(mappingCount) * 32,), raw.count == Int(mappingCount) * 32 else { return [] }return (0 ..< Int(mappingCount)).map { index in@@ -506,7 +531,7 @@ public final class DSCChunkSet {fileOffset: raw.loadLE(UInt64.self, at: base + 16),maxProt: raw.loadLE(UInt32.self, at: base + 24),initProt: raw.loadLE(UInt32.self, at: base + 28),- chunkURL: url+ chunkURL: url,)}}diff --git a/sources/FirmwarePatcher/DSC/DSCCodeSignature.swift b/sources/FirmwarePatcher/DSC/DSCCodeSignature.swiftindex c0728aa4..a2f7d792 100644--- a/sources/FirmwarePatcher/DSC/DSCCodeSignature.swift+++ b/sources/FirmwarePatcher/DSC/DSCCodeSignature.swift@@ -126,7 +126,9 @@ public struct DSCReattestationSkip: Sendable {}public let reason: Reason- public var description: String { reason.description }+ public var description: String {+ reason.description+ }}/// What one re-attestation run did.@@ -144,11 +146,15 @@ public struct DSCReattestation: Sendable {public let skipped: [DSCReattestationSkip]/// Pages the run actually reached — rewritten plus already-correct.- public var pagesAttested: Int { updated.count + alreadyAttested.count }+ public var pagesAttested: Int {+ updated.count + alreadyAttested.count+ }/// True when every page the caller's spans touched now carries a slot hash/// that matches its contents. False the moment anything was skipped.- public var isFullyAttested: Bool { skipped.isEmpty }+ public var isFullyAttested: Bool {+ skipped.isEmpty+ }public var summary: String {"\(updated.count) slot(s) rewritten, \(alreadyAttested.count) already correct, "@@ -188,7 +194,7 @@ public enum DSCCodeSignature {let indexData = try DSCChunkSet.read(url: url,offset: signatureOffset + 12,- length: Int(blobCount) * 8+ length: Int(blobCount) * 8,)guard indexData.count == Int(blobCount) * 8 else { return nil }@@ -230,7 +236,7 @@ public enum DSCCodeSignature {hashSize: hashSize,codeSlotCount: codeSlotCount,codeLimit: codeLimit,- pageSize: pageSize+ pageSize: pageSize,)}@@ -266,7 +272,7 @@ public enum DSCCodeSignature {in chunks: DSCChunkSet,modifiedSpans: some Sequence<DSCWriteSpan>,dryRun: Bool = false,- log: ((String) -> Void)? = stderrLog+ log: ((String) -> Void)? = stderrLog,) throws -> DSCReattestation {var pagesByChunk: [URL: Set<Int>] = [:]var directories: [URL: DSCChunkCodeDirectory?] = [:]@@ -310,7 +316,7 @@ public enum DSCCodeSignature {skip(.pageBeyondCodeSlots(chunk: chunkURL.lastPathComponent,page: pageIndex,- codeSlotCount: directory.codeSlotCount+ codeSlotCount: directory.codeSlotCount,))continue}@@ -318,7 +324,7 @@ public enum DSCCodeSignature {skip(.pageBeyondCodeLimit(chunk: chunkURL.lastPathComponent,page: pageIndex,- codeLimit: directory.codeLimit+ codeLimit: directory.codeLimit,))continue}@@ -329,7 +335,7 @@ public enum DSCCodeSignature {guard !pagesByChunk.isEmpty else {log?(" [.] re-attest: no eligible pages "- + "(\(skipped.count) skipped)"+ + "(\(skipped.count) skipped)",)return DSCReattestation(updated: [], alreadyAttested: [], skipped: skipped)}@@ -354,7 +360,7 @@ public enum DSCCodeSignature {chunk: chunkURL.lastPathComponent,page: pageIndex,got: pageData.count,- wanted: directory.pageSize+ wanted: directory.pageSize,))continue}@@ -365,11 +371,11 @@ public enum DSCCodeSignature {guard oldHash != newHash else {alreadyAttested.append(- DSCPageReference(chunkURL: chunkURL, pageIndex: pageIndex)+ DSCPageReference(chunkURL: chunkURL, pageIndex: pageIndex),)log?(" [.] re-attest: page \(pageIndex) of "- + "\(chunkURL.lastPathComponent) slot already matches (no-op)"+ + "\(chunkURL.lastPathComponent) slot already matches (no-op)",)continue}@@ -381,7 +387,7 @@ public enum DSCCodeSignature {log?(" [+] re-attest: \(dryRun ? "would write" : "wrote") slot "+ "\(pageIndex) of \(chunkURL.lastPathComponent) "- + "(\(Data(oldHash.prefix(4)).hex).. -> \(Data(newHash.prefix(4)).hex)..)"+ + "(\(Data(oldHash.prefix(4)).hex).. -> \(Data(newHash.prefix(4)).hex)..)",)records.append(DSCSlotReattestation(@@ -390,8 +396,8 @@ public enum DSCCodeSignature {chunkOffset: pageOffset,slotOffset: slotOffset,hashBefore: oldHash,- hashAfter: newHash- )+ hashAfter: newHash,+ ),)}}@@ -399,12 +405,12 @@ public enum DSCCodeSignature {log?(" [+] re-attest: \(dryRun ? "would update" : "updated") \(records.count) "+ "slot hash(es) across \(pagesByChunk.count) chunk(s), "- + "\(alreadyAttested.count) already correct, \(skipped.count) skipped"+ + "\(alreadyAttested.count) already correct, \(skipped.count) skipped",)return DSCReattestation(updated: records,alreadyAttested: alreadyAttested,- skipped: skipped+ skipped: skipped,)}@@ -417,13 +423,13 @@ public enum DSCCodeSignature {public static func reattestRecordedWrites(in chunks: DSCChunkSet,dryRun: Bool = false,- log: ((String) -> Void)? = stderrLog+ log: ((String) -> Void)? = stderrLog,) throws -> DSCReattestation {try reattest(in: chunks,modifiedSpans: chunks.recordedWrites,dryRun: dryRun,- log: log+ log: log,)}@@ -436,17 +442,17 @@ public enum DSCCodeSignature {public static func pageHashes(chunkURL: URL,pageIndex: Int,- directory: DSCChunkCodeDirectory+ directory: DSCChunkCodeDirectory,) throws -> (computed: Data, stored: Data) {let page = try DSCChunkSet.read(url: chunkURL,offset: UInt64(pageIndex * directory.pageSize),- length: directory.pageSize+ length: directory.pageSize,)let stored = try DSCChunkSet.read(url: chunkURL,offset: UInt64(directory.slotOffset(forPage: pageIndex)),- length: directory.hashSize+ length: directory.hashSize,)return (Data(SHA256.hash(data: page)), stored)}diff --git a/sources/FirmwarePatcher/DSC/DSCLocalSymbolTable.swift b/sources/FirmwarePatcher/DSC/DSCLocalSymbolTable.swiftindex 24141057..d4ac60bc 100644--- a/sources/FirmwarePatcher/DSC/DSCLocalSymbolTable.swift+++ b/sources/FirmwarePatcher/DSC/DSCLocalSymbolTable.swift@@ -110,7 +110,7 @@ public struct DSCLocalSymbolTable: Sendable {return ImageEntry(dylibOffset: file.at(UInt64.self, base),nlistStartIndex: Int(file.at(UInt32.self, base + 8)),- nlistCount: Int(file.at(UInt32.self, base + 12))+ nlistCount: Int(file.at(UInt32.self, base + 12)),)}}@@ -123,7 +123,9 @@ public struct DSCLocalSymbolTable: Sendable {let start = file.startIndex + stringBase + stringIndexlet limit = file.startIndex + stringBase + stringSizevar end = start- while end < limit, file[end] != 0 { end += 1 }+ while end < limit, file[end] != 0 {+ end += 1+ }guard end > start else { return "" }return String(decoding: file[start ..< end], as: UTF8.self)}@@ -143,7 +145,7 @@ public struct DSCLocalSymbolTable: Sendable {for index in 0 ..< nlistCount {let base = nlistBase + index * 16let stringIndex = Int(- bytes.loadUnaligned(fromByteOffset: base, as: UInt32.self).littleEndian+ bytes.loadUnaligned(fromByteOffset: base, as: UInt32.self).littleEndian,)guard matches(wanted, in: bytes, atStringIndex: stringIndex) else { continue }return bytes@@ -169,7 +171,9 @@ public struct DSCLocalSymbolTable: Sendable {let value = file.at(UInt64.self, base + 8)guard value != 0, let name = name(atStringIndex: stringIndex), !name.isEmptyelse { continue }- if result[name] == nil { result[name] = value }+ if result[name] == nil {+ result[name] = value+ }}return result}@@ -183,7 +187,7 @@ public struct DSCLocalSymbolTable: Sendable {private func matches(_ wanted: [UInt8],in bytes: UnsafeRawBufferPointer,- atStringIndex stringIndex: Int+ atStringIndex stringIndex: Int,) -> Bool {guard stringIndex >= 0, stringIndex + wanted.count < stringSize else { return false }let base = stringBase + stringIndexdiff --git a/sources/FirmwarePatcher/DSC/DSCSymbolResolver.swift b/sources/FirmwarePatcher/DSC/DSCSymbolResolver.swiftindex dfe116b4..e63cb4e8 100644--- a/sources/FirmwarePatcher/DSC/DSCSymbolResolver.swift+++ b/sources/FirmwarePatcher/DSC/DSCSymbolResolver.swift@@ -66,7 +66,9 @@ public final class DSCSymbolResolver {if let infos = cache.imageInfos {for info in infos {guard let path = info.path(in: cache) else { continue }- if addresses[path] == nil { addresses[path] = info.address }+ if addresses[path] == nil {+ addresses[path] = info.address+ }}}imageAddresses = addresses@@ -84,7 +86,9 @@ public final class DSCSymbolResolver {try self.init(mainCacheURL: chunks.mainCacheURL)}- public var hasLocalSymbols: Bool { localSymbols != nil }+ public var hasLocalSymbols: Bool {+ localSymbols != nil+ }/// Fail now if the local symbol table is not there.///@@ -100,7 +104,9 @@ public final class DSCSymbolResolver {}/// Every image path in the cache, sorted.- public var imagePaths: [String] { imageAddresses.keys.sorted() }+ public var imagePaths: [String] {+ imageAddresses.keys.sorted()+ }/// The mach header address of `imagePath`.public func headerAddress(ofImage imagePath: String) throws -> UInt64 {@@ -118,7 +124,9 @@ public final class DSCSymbolResolver {/// tables reports the exported address — the one a caller of the public/// entry point would branch to.public func symbols(inImage imagePath: String) throws -> [String: Resolution] {- if let cached = symbolCacheByImage[imagePath] { return cached }+ if let cached = symbolCacheByImage[imagePath] {+ return cached+ }let headerAddress = try headerAddress(ofImage: imagePath)var result: [String: Resolution] = [:]@@ -131,7 +139,7 @@ public final class DSCSymbolResolver {result[exported.name] = Resolution(name: exported.name,address: address,- source: .exportTrie+ source: .exportTrie,)}}@@ -144,7 +152,7 @@ public final class DSCSymbolResolver {result[name] = Resolution(name: name,address: address,- source: .localSymbols+ source: .localSymbols,)}}@@ -174,7 +182,7 @@ public final class DSCSymbolResolver {/// has lost five ObjC methods to a rename wants to see all five.public func addresses(of symbols: [String],- inImage imagePath: String+ inImage imagePath: String,) throws -> [String: UInt64] {let table = try self.symbols(inImage: imagePath)var result: [String: UInt64] = [:]@@ -190,7 +198,7 @@ public final class DSCSymbolResolver {try requireLocalSymbols()throw DSCError.symbolNotFound(symbol: missing.joined(separator: ", "),- image: imagePath+ image: imagePath,)}return result@@ -203,7 +211,7 @@ public final class DSCSymbolResolver {/// them and pairs each with its `_kern_` sibling.public func symbols(inImage imagePath: String,- withPrefix prefix: String+ withPrefix prefix: String,) throws -> [String: UInt64] {try symbols(inImage: imagePath).filter { $0.key.hasPrefix(prefix) }diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swiftindex b36d1f08..d697fc05 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swift@@ -168,7 +168,9 @@ public enum DSCCameraPatcher {public let reattestation: DSCReattestation?public let dryRun: Bool- public var siteCount: Int { sites.count }+ public var siteCount: Int {+ sites.count+ }/// True when every site was written and every page they dirtied now/// carries a matching slot hash. A dry run is never complete.@@ -201,7 +203,7 @@ public enum DSCCameraPatcher {symbolCacheURL: URL? = nil,dryRun: Bool = false,force: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Result {try apply(families: Family.allCases,@@ -209,7 +211,7 @@ public enum DSCCameraPatcher {symbolCacheURL: symbolCacheURL,dryRun: dryRun,force: force,- log: log+ log: log,)}@@ -222,7 +224,7 @@ public enum DSCCameraPatcher {symbolCacheURL: URL? = nil,dryRun: Bool = false,force: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Result {try apply(families: [.avfAuthorization],@@ -230,7 +232,7 @@ public enum DSCCameraPatcher {symbolCacheURL: symbolCacheURL,dryRun: dryRun,force: force,- log: log+ log: log,)}@@ -242,11 +244,11 @@ public enum DSCCameraPatcher {symbolCacheURL: URL?,dryRun: Bool,force: Bool,- log: ((String) -> Void)?+ log: ((String) -> Void)?,) throws -> Result {let chunks = try DSCChunkSet(directory: chunksDirectory)let resolver = try DSCSymbolResolver(- mainCacheURL: symbolCacheURL ?? chunks.mainCacheURL+ mainCacheURL: symbolCacheURL ?? chunks.mainCacheURL,)// Every symbol here is an ObjC class method, and those live only in the// stripped local-symbol table. Without it the six lookups would each@@ -283,7 +285,7 @@ public enum DSCCameraPatcher {log?(" resolving \(family.symbols.count) symbol(s) in \(family.imagePath)")let addresses = try resolver.addresses(of: family.symbols,- inImage: family.imagePath+ inImage: family.imagePath,)// Sorted by symbol, as the Python's `sorted(vmas.items())` is. Only@@ -304,7 +306,7 @@ public enum DSCCameraPatcher {returning: family.returnValue,disassembler: disassembler,force: force,- log: log+ log: log,)sites.append(@@ -315,8 +317,8 @@ public enum DSCCameraPatcher {vma: vma,originalBytes: original,patchedBytes: replacement,- wasAlreadyPatched: alreadyPatched- )+ wasAlreadyPatched: alreadyPatched,+ ),)}}@@ -336,7 +338,7 @@ public enum DSCCameraPatcher {// which addresses were touched, so nothing can under-attest.let reattestation = try DSCCodeSignature.reattestRecordedWrites(in: chunks,- log: log+ log: log,)log?(" re-attested \(reattestation.pagesAttested) page(s)")@@ -348,7 +350,7 @@ public enum DSCCameraPatcher {guard written == site.patchedBytes else {throw PatcherError.patchVerificationFailed("post-write verify failed at 0x\(String(site.vma, radix: 16, uppercase: true)): "- + "read back \(written.hex), expected \(site.patchedBytes.hex)"+ + "read back \(written.hex), expected \(site.patchedBytes.hex)",)}}@@ -394,11 +396,13 @@ public enum DSCCameraPatcher {returning value: UInt16,disassembler: ARM64Disassembler,force: Bool,- log: ((String) -> Void)?+ log: ((String) -> Void)?,) throws -> Bool {let decoded = disassembler.disassemble(bytes, at: vma, count: 2)- if decoded.first?.mnemonic == "pacibsp" { return false }+ if decoded.first?.mnemonic == "pacibsp" {+ return false+ }if isReturnConstantShape(decoded, returning: value, disassembler: disassembler) {log?(" [=] already `mov w0, #\(value); ret` — re-install, rewriting inertly")@@ -411,7 +415,7 @@ public enum DSCCameraPatcher {?? "<undecodable>"throw PatcherError.patchVerificationFailed("\(symbol) @ 0x\(String(vma, radix: 16, uppercase: true)): prologue is not "- + "pacibsp (got \(head), bytes \(bytes.prefix(4).hex)); pass force to override"+ + "pacibsp (got \(head), bytes \(bytes.prefix(4).hex)); pass force to override",)}log?(" [!] prologue is not pacibsp — forced")@@ -428,7 +432,7 @@ public enum DSCCameraPatcher {static func isReturnConstantShape(_ decoded: [Instruction],returning value: UInt16,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> Bool {guard decoded.count == 2,decoded[1].mnemonic == "ret",@@ -451,7 +455,9 @@ public enum DSCCameraPatcher {var pendingSeparator = falsefor character in symbol {if character.isASCII, character.isLetter || character.isNumber {- if pendingSeparator, !slug.isEmpty { slug.append("_") }+ if pendingSeparator, !slug.isEmpty {+ slug.append("_")+ }pendingSeparator = falseslug.append(character)} else {diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swiftindex cf01c90e..594b25ce 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swift@@ -77,6 +77,7 @@ import Foundation/// shared cache and over standalone Mach-Os.public enum DSCHVVMMPatcher {// MARK: - The cstring and its mangle+//// Port of the five constants `cfw_patch_hv_vmm.py` exports. They are derived// from the sysctl name rather than written out as bytes, so "byte 5" is the@@ -121,6 +122,7 @@ public enum DSCHVVMMPatcher {]// MARK: - Blacklist+//// A dylib named here keeps `"kern.hv_vmm_present\0"`. With the kernel rename// in place that name is ENOENT, the dylib's defensive check takes the skip@@ -216,7 +218,7 @@ public enum DSCHVVMMPatcher {refused: 0,reattestOnly: 0,blacklistDrift: 0,- reattestation: nil+ reattestation: nil,)}@@ -231,14 +233,14 @@ public enum DSCHVVMMPatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Result {let chunks = try DSCChunkSet(directory: chunksDirectory)log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "+ "\(chunks.mappings.count) mapping(s), "+ "vm 0x\(hex(chunks.addressRange.lowerBound))"- + "..0x\(hex(chunks.addressRange.upperBound))"+ + "..0x\(hex(chunks.addressRange.upperBound))",)return try patch(in: chunks, dryRun: dryRun, log: log)}@@ -257,7 +259,7 @@ public enum DSCHVVMMPatcher {public static func patch(in chunks: DSCChunkSet,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Result {log?(" [.] locating cstring \"kern.hv_vmm_present\\0\"…")let pristineSites = try chunks.findStringVMAs(needle).sorted()@@ -270,17 +272,17 @@ public enum DSCHVVMMPatcher {guard !pristineSites.isEmpty || !alreadyMangledSites.isEmpty else {log?(" [-] cstring not present in any executable mapping; nothing to "- + "do (either patched already or absent)"+ + "do (either patched already or absent)",)return .empty}log?(" [.] \(pristineSites.count) pristine + \(alreadyMangledSites.count) "- + "already-mangled cstring occurrence(s) found"+ + "already-mangled cstring occurrence(s) found",)log?(" [.] resolving containing dylib for each occurrence (blacklist has "- + "\(dontPatchSet.count) entries — these stay unpatched)…"+ + "\(dontPatchSet.count) entries — these stay unpatched)…",)var mangledCountByInstallName: [String: Int] = [:]@@ -312,7 +314,7 @@ public enum DSCHVVMMPatcher {if dontPatchSet.contains(installName) {log?(" [.] SKIP (blacklisted — stays unpatched, will hit "- + "ENOENT): \(installName) string@0x\(hex(vma))"+ + "ENOENT): \(installName) string@0x\(hex(vma))",)skippedInBlacklist += 1note(label, in: &mangledCountByInstallName)@@ -334,7 +336,7 @@ public enum DSCHVVMMPatcher {// below picks the page up through `alreadyMangledSites`.log?(" [.] already mangled at byte \(mangleOffset): \(label) "- + "string@0x\(hex(vma))"+ + "string@0x\(hex(vma))",)note(label, in: &mangledCountByInstallName)continue@@ -342,7 +344,7 @@ public enum DSCHVVMMPatcher {guard current == needle else {log?(" [-] unexpected bytes at 0x\(hex(vma)) (\(current.hex)); "- + "refusing (\(label))"+ + "refusing (\(label))",)refused += 1continue@@ -359,7 +361,7 @@ public enum DSCHVVMMPatcher {+ "string@0x\(hex(vma)) byte \(mangleOffset) "+ "(\(Character(UnicodeScalar(originalByte))) -> "+ "\(Character(UnicodeScalar(mangledByte)))) now queries "- + "kern.Xv_vmm_present, will see 1 (in a VM)"+ + "kern.Xv_vmm_present, will see 1 (in a VM)",)mangledCountByInstallName[label, default: 0] += 1mangled += 1@@ -388,7 +390,7 @@ public enum DSCHVVMMPatcher {" [!] drift: \(installName) is in the blacklist but "+ "already mangled at string@0x\(hex(vma)) — slot will be "+ "re-attested to current bytes; consider whether you "- + "actually want this dylib re-patched"+ + "actually want this dylib re-patched",)reattestOnlySpans.append(span)blacklistDrift += 1@@ -400,13 +402,13 @@ public enum DSCHVVMMPatcher {if reattestOnly > 0 {log?(" [.] also queueing \(reattestOnly) already-mangled cstring "- + "page(s) for re-attestation"+ + "page(s) for re-attestation",)}if blacklistDrift > 0 {log?(" [.] \(blacklistDrift) blacklisted dylib(s) found mangled on "- + "disk — see drift warnings above"+ + "disk — see drift warnings above",)}@@ -425,20 +427,20 @@ public enum DSCHVVMMPatcher {if !spans.isEmpty {log?(" [.] \(dryRun ? "dry-run: would re-attest" : "re-attesting") "- + "\(spans.count) modified page span(s)…"+ + "\(spans.count) modified page span(s)…",)reattestation = try DSCCodeSignature.reattest(in: chunks,modifiedSpans: spans,dryRun: dryRun,- log: log+ log: log,)}log?(" [+] DSC patch complete: \(mangled) cstring(s) mangled, "+ "\(skippedInBlacklist) in-blacklist (left unpatched), "- + "\(skippedUnclassified) unclassified, \(refused) refused/error"+ + "\(skippedUnclassified) unclassified, \(refused) refused/error",)return Result(pristineSiteCount: pristineSites.count,@@ -450,7 +452,7 @@ public enum DSCHVVMMPatcher {refused: refused,reattestOnly: reattestOnly,blacklistDrift: blacklistDrift,- reattestation: reattestation+ reattestation: reattestation,)}@@ -479,10 +481,13 @@ public enum DSCHVVMMPatcher {/// alone" from "never seen", and the reference's `results.get(label, 0)`/// spelling of it is easy to mistake for a no-op.private static func note(_ label: String, in counts: inout [String: Int]) {- if counts[label] == nil { counts[label] = 0 }+ if counts[label] == nil {+ counts[label] = 0+ }}// MARK: - Standalone Mach-O+//// The other half of `cfw_patch_hv_vmm.py`: the same mangle applied to a// Mach-O on disk rather than to a dylib inside the cache. No caller in this@@ -534,8 +539,8 @@ public enum DSCHVVMMPatcher {MachOStringSite(stringVMA: section.address &+ UInt64(position),fileOffset: start + position,- section: name- )+ section: name,+ ),)}searchFrom = found.lowerBound + 1@@ -561,7 +566,7 @@ public enum DSCHVVMMPatcher {public static func patchStandaloneMachO(at url: URL,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Int {guard FileManager.default.fileExists(atPath: url.path) else {throw PatcherError.fileNotFound(url.path)@@ -572,12 +577,12 @@ public enum DSCHVVMMPatcher {if isAlreadyMangled(data) {log?(" [.] \(url.path): already mangled (no original "- + "'kern.hv_vmm_present' cstring present)"+ + "'kern.hv_vmm_present' cstring present)",)} else {log?(" [.] \(url.path): 'kern.hv_vmm_present' cstring not "- + "present — nothing to do"+ + "present — nothing to do",)}return 0@@ -593,14 +598,14 @@ public enum DSCHVVMMPatcher {log?(" [.] string@0x\(hex(site.stringVMA)) already mangled "+ "(byte \(mangleOffset) is already "- + "'\(Character(UnicodeScalar(mangledByte)))')"+ + "'\(Character(UnicodeScalar(mangledByte)))')",)continue}guard original == needle else {log?(" [-] string@0x\(hex(site.stringVMA)) bytes look unexpected "- + "(\(Data(original).hex)); skipping"+ + "(\(Data(original).hex)); skipping",)continue}@@ -609,7 +614,7 @@ public enum DSCHVVMMPatcher {+ "byte \(mangleOffset) "+ "'\(Character(UnicodeScalar(originalByte)))' -> "+ "'\(Character(UnicodeScalar(mangledByte)))' "- + "('kern.hv_vmm_present' -> 'kern.Xv_vmm_present')"+ + "('kern.hv_vmm_present' -> 'kern.Xv_vmm_present')",)data[data.startIndex + site.fileOffset + mangleOffset] = mangledBytepatched += 1@@ -651,7 +656,7 @@ public enum DSCHVVMMPatcher {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)))"+ "not a 64-bit Mach-O (magic=0x\(String(magic, radix: 16, uppercase: true)))",)}@@ -673,13 +678,15 @@ public enum DSCHVVMMPatcher {guard sectionOffset + 80 <= data.count else { break }let sectionName = fixedWidthName(data, at: sectionOffset)let key = "\(segmentName),\(sectionName)"- if byName[key] == nil { ordered.append(key) }+ 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)+ fileOffset: data.loadLE(UInt32.self, at: sectionOffset + 48),)sectionOffset += 80}diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swiftindex 30536f4e..c1e6c2d8 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swift@@ -133,13 +133,23 @@ public enum DSCIOMFBForceKernPatcher {/// The re-attestation pass, or `nil` when nothing was written.public let reattestation: DSCReattestation?- public var forced: [Site] { sites.filter { $0.disposition == .forced } }- public var alreadyForced: [Site] { sites.filter { $0.disposition == .alreadyForced } }- public var notTrampolines: [Site] { sites.filter { $0.disposition == .notATrampoline } }+ public var forced: [Site] {+ sites.filter { $0.disposition == .forced }+ }++ public var alreadyForced: [Site] {+ sites.filter { $0.disposition == .alreadyForced }+ }++ public var notTrampolines: [Site] {+ sites.filter { $0.disposition == .notATrampoline }+ }/// How many 4-byte sites this run put on disk. The reference returns/// exactly this number.- public var writtenSiteCount: Int { forced.count }+ public var writtenSiteCount: Int {+ forced.count+ }/// Suffixes now on the kern path, whether this run did it or a previous/// one did.@@ -158,7 +168,7 @@ public enum DSCIOMFBForceKernPatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Outcome {let chunks = try DSCChunkSet(directory: chunksDirectory)let resolver = try DSCSymbolResolver(chunks: chunks)@@ -176,7 +186,7 @@ public enum DSCIOMFBForceKernPatcher {chunks: DSCChunkSet,resolver: DSCSymbolResolver,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Outcome {log?(" [.] \(chunks.chunkURLs.count) chunk(s), \(chunks.mappings.count) mapping(s)")@@ -192,7 +202,7 @@ public enum DSCIOMFBForceKernPatcher {// check below has to be able to refuse while the cache is still clean.var sites: [Site] = []for entry in entries {- sites.append(try classify(entry, chunks: chunks, disassembler: disassembler))+ try sites.append(classify(entry, chunks: chunks, disassembler: disassembler))}let covered = Set(sites.filter { $0.disposition != .notATrampoline }.map(\.entry.suffix))@@ -202,7 +212,7 @@ public enum DSCIOMFBForceKernPatcher {let already = sites.filter { $0.disposition == .alreadyForced }.map(\.entry.suffix).sorted()throw PatcherError.patchSiteNotFound("force-kern did not cover required entrypoints \(missing) "- + "(forcible: \(forcible); already forced: \(already))"+ + "(forcible: \(forcible); already forced: \(already))",)}@@ -216,7 +226,7 @@ public enum DSCIOMFBForceKernPatcher {log?(" [+] \(site.entry.publicName) @ 0x\(hex(site.entry.publicAddress)): "+ "'\(site.originalDisassembly)' -> 'b \(site.entry.kernName)' "- + "(0x\(hex(site.entry.kernAddress)))"+ + "(0x\(hex(site.entry.kernAddress)))",)}}@@ -229,14 +239,14 @@ public enum DSCIOMFBForceKernPatcher {var records: [PatchRecord] = []for site in toWrite {- records.append(try force(site, chunks: chunks))+ try records.append(force(site, chunks: chunks))}var reattestation: DSCReattestation?if records.isEmpty {log?(" [=] all \(sites.count { $0.disposition == .alreadyForced }) entrypoint(s) "- + "already forced; nothing to patch/re-attest"+ + "already forced; nothing to patch/re-attest",)} else {log?(" [.] re-attesting the pages \(records.count) write(s) dirtied...")@@ -244,7 +254,7 @@ public enum DSCIOMFBForceKernPatcher {guard result.isFullyAttested else {throw PatcherError.patchVerificationFailed("re-attestation skipped \(result.skipped.count) page(s): "- + result.skipped.map(\.description).joined(separator: "; ")+ + result.skipped.map(\.description).joined(separator: "; "),)}reattestation = result@@ -255,7 +265,7 @@ public enum DSCIOMFBForceKernPatcher {let alreadyCount = sites.count { $0.disposition == .alreadyForced }log?(" [+] IOMFB force-kern complete: \(forcedCount) newly forced, "- + "\(alreadyCount) already -> _kern_*"+ + "\(alreadyCount) already -> _kern_*",)return Outcome(sites: sites, records: records, reattestation: reattestation)}@@ -269,7 +279,7 @@ public enum DSCIOMFBForceKernPatcher {/// and which of them kept a kern implementation, is a property of the cache/// being patched and changes between OS versions.public static func discoverEntryPoints(- resolver: DSCSymbolResolver+ resolver: DSCSymbolResolver,) throws -> [EntryPoint] {let all = try resolver.symbols(inImage: imagePath)let publicEntries = try resolver.symbols(inImage: imagePath, withPrefix: publicPrefix)@@ -285,8 +295,8 @@ public enum DSCIOMFBForceKernPatcher {publicName: publicName,publicAddress: publicAddress,kernName: kernName,- kernAddress: kern.address- )+ kernAddress: kern.address,+ ),)}entries.sort { ($0.suffix, $0.publicName) < ($1.suffix, $1.publicName) }@@ -298,12 +308,12 @@ public enum DSCIOMFBForceKernPatcher {private static func classify(_ entry: EntryPoint,chunks: DSCChunkSet,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) throws -> Site {- let instructions = disassembler.disassemble(- try chunks.bytesAtVMA(entry.publicAddress, length: 4 * 4),+ let instructions = try disassembler.disassemble(+ chunks.bytesAtVMA(entry.publicAddress, length: 4 * 4),at: entry.publicAddress,- count: 4+ count: 4,)let first = instructions.firstlet text = first.map { "\($0.mnemonic) \($0.operandString)" } ?? "<undecodable>"@@ -367,11 +377,11 @@ public enum DSCIOMFBForceKernPatcher {let entry = site.entryguard let branch = ARM64Encoder.encodeB(from: Int(entry.publicAddress),- to: Int(entry.kernAddress)+ to: Int(entry.kernAddress),), branch.count == 4 else {throw PatcherError.patchVerificationFailed("cannot encode b 0x\(hex(entry.publicAddress)) -> 0x\(hex(entry.kernAddress)) "- + "for \(entry.publicName)"+ + "for \(entry.publicName)",)}@@ -390,7 +400,7 @@ public enum DSCIOMFBForceKernPatcher {beforeDisasm: site.originalDisassembly,afterDisasm: "b #0x\(hex(entry.kernAddress).lowercased())",description: "\(entry.publicName) trampoline -> b \(entry.kernName) "- + "(0x\(hex(entry.kernAddress)))"+ + "(0x\(hex(entry.kernAddress)))",)}@@ -399,7 +409,7 @@ public enum DSCIOMFBForceKernPatcher {private static func verify(_ sites: [Site],chunks: DSCChunkSet,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) throws {for site in sites {let address = site.entry.publicAddress@@ -410,7 +420,7 @@ public enum DSCIOMFBForceKernPatcher {UInt64(bitPattern: target) == site.entry.kernAddresselse {throw PatcherError.patchVerificationFailed(- "post-write verify failed at 0x\(hex(address)) for \(site.entry.publicName)"+ "post-write verify failed at 0x\(hex(address)) for \(site.entry.publicName)",)}}diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swiftindex d20c1d1c..3e4ba917 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swift@@ -74,7 +74,9 @@ public struct DSCIOMFBSwapEndPatch: Sendable {public let reattestation: DSCReattestation?/// The Python's return value: one site *considered*, patched or not.- public var sitesConsidered: Int { 1 }+ public var sitesConsidered: Int {+ 1+ }}public enum DSCIOMFBSwapEndPatcher {@@ -123,7 +125,7 @@ public enum DSCIOMFBSwapEndPatcher {chunksDirectory: URL,targetSize: UInt32 = defaultTargetSize,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> DSCIOMFBSwapEndPatch {// Before opening a 6.7 GB cache and its 1.2 GB symbol table: a target// size that cannot be encoded is an argument error, and it should read@@ -137,7 +139,7 @@ public enum DSCIOMFBSwapEndPatcher {resolver: resolver,targetSize: targetSize,dryRun: dryRun,- log: log+ log: log,)}@@ -153,7 +155,7 @@ public enum DSCIOMFBSwapEndPatcher {resolver: DSCSymbolResolver,targetSize: UInt32 = defaultTargetSize,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> DSCIOMFBSwapEndPatch {let replacement = try replacement(forTargetSize: targetSize)@@ -167,14 +169,14 @@ public enum DSCIOMFBSwapEndPatcher {in: chunks,at: functionVMA,maximumInstructions: maximumInstructions,- disassembler: disassembler+ disassembler: disassembler,)guard let site = findSizeInstruction(in: instructions, disassembler: disassembler),let current = movRegisterImmediate(site.instruction, disassembler: disassembler)else {throw PatcherError.patchSiteNotFound("\(symbolName) SwapEnd size site (mov w1, #\(selector) -> "- + "mov \(sizeRegister), #imm -> mov x4, #0 -> mov x5, #0 -> bl) not found"+ + "mov \(sizeRegister), #imm -> mov x4, #0 -> mov x5, #0 -> bl) not found",)}@@ -185,13 +187,13 @@ public enum DSCIOMFBSwapEndPatcher {if wasAlreadyCorrect {log?(" [=] already 0x\(hex(targetSize)) at 0x\(hex(siteVMA)); "- + "re-attesting page only"+ + "re-attesting page only",)} else {log?(" [\(dryRun ? "~" : "+")] \(dryRun ? "would patch" : "patched") "+ "\(imagePath) \(symbolName) size 0x\(hex(originalSize)) -> "- + "0x\(hex(targetSize)) at 0x\(hex(siteVMA))"+ + "0x\(hex(targetSize)) at 0x\(hex(siteVMA))",)}@@ -210,7 +212,7 @@ public enum DSCIOMFBSwapEndPatcher {guard readBack == replacement else {throw PatcherError.patchVerificationFailed("\(symbolName) size site at 0x\(hex(siteVMA)) reads back "- + "\(readBack.hex), expected \(replacement.hex)"+ + "\(readBack.hex), expected \(replacement.hex)",)}}@@ -223,7 +225,7 @@ public enum DSCIOMFBSwapEndPatcher {targetSize: targetSize,wasAlreadyCorrect: wasAlreadyCorrect,sitesWritten: (dryRun || wasAlreadyCorrect) ? 0 : 1,- reattestation: reattestation+ reattestation: reattestation,)}@@ -237,14 +239,14 @@ public enum DSCIOMFBSwapEndPatcher {static func replacement(forTargetSize targetSize: UInt32) throws -> Data {guard let immediate = UInt16(exactly: targetSize) else {throw PatcherError.invalidFormat(- "SwapEnd target size 0x\(hex(targetSize)) does not fit a MOVZ immediate"+ "SwapEnd target size 0x\(hex(targetSize)) does not fit a MOVZ immediate",)}guard let encoded = ARM64Encoder.encodeMovzW(rd: 3, imm16: immediate),encoded.count == 4else {throw PatcherError.invalidFormat(- "could not encode mov \(sizeRegister), #0x\(hex(targetSize))"+ "could not encode mov \(sizeRegister), #0x\(hex(targetSize))",)}return encoded@@ -269,7 +271,7 @@ public enum DSCIOMFBSwapEndPatcher {/// operand string.static func findSizeInstruction(in instructions: [Instruction],- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> SizeSite? {// selector, size, the zeroed argument registers, then the call.let shapeLength = 3 + zeroedRegisters.count@@ -278,20 +280,20 @@ public enum DSCIOMFBSwapEndPatcher {for index in 0 ... (instructions.count - shapeLength) {guard let selectorMove = movRegisterImmediate(instructions[index],- disassembler: disassembler+ disassembler: disassembler,), selectorMove.register == "w1", selectorMove.immediate == selectorelse { continue }guard let sizeMove = movRegisterImmediate(instructions[index + 1],- disassembler: disassembler+ disassembler: disassembler,), sizeMove.register == sizeRegisterelse { continue }let zeroed = zeroedRegisters.enumerated().allSatisfy { offset, name inguard let move = movRegisterImmediate(instructions[index + 2 + offset],- disassembler: disassembler+ disassembler: disassembler,) else { return false }return move.register == name && move.immediate == 0}@@ -311,7 +313,7 @@ public enum DSCIOMFBSwapEndPatcher {/// a change in how Capstone renders an operand cannot move the site.static func movRegisterImmediate(_ instruction: Instruction,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> (register: String, immediate: Int64)? {guard instruction.mnemonic == "mov" else { return nil }guard let operands = instruction.aarch64?.operands, operands.count == 2,@@ -332,17 +334,19 @@ public enum DSCIOMFBSwapEndPatcher {in chunks: DSCChunkSet,at vma: UInt64,maximumInstructions: Int,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) throws -> [Instruction] {let code = try chunks.readAtVMA(vma,length: maximumInstructions * 4,- allowShort: true+ allowShort: true,)var result: [Instruction] = []for instruction in disassembler.disassemble(code, at: vma, count: maximumInstructions) {result.append(instruction)- if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" { break }+ if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" {+ break+ }}return result}diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swiftindex 15a162cf..797b1ac2 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swift@@ -84,7 +84,9 @@ public enum DSCLSDEmbeddedRegPatcher {public let resultRegister: String/// True when the site already holds this patch's own output.- public var wasAlreadyNOP: Bool { mnemonic == "nop" }+ public var wasAlreadyNOP: Bool {+ mnemonic == "nop"+ }/// How the gate reads in disassembly.public var text: String {@@ -117,11 +119,15 @@ public enum DSCLSDEmbeddedRegPatcher {/// 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 }+ public var sitesWritten: Int {+ record == nil ? 0 : 1+ }/// Whether the gate method exists in this cache at all. Mirrors the/// Python's return value, which is 0 when absent and 1 otherwise.- public var methodIsPresent: Bool { outcome != .methodAbsent }+ public var methodIsPresent: Bool {+ outcome != .methodAbsent+ }}/// Where progress goes when the caller does not say. The Python prints to@@ -147,7 +153,7 @@ public enum DSCLSDEmbeddedRegPatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,- log: ((String) -> Void)? = stdoutLog+ log: ((String) -> Void)? = stdoutLog,) throws -> Report {let chunks = try DSCChunkSet(directory: chunksDirectory)log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "@@ -197,7 +203,7 @@ public enum DSCLSDEmbeddedRegPatcher {let written = try chunks.bytesAtVMA(gate.vma, length: nop.count)guard written == nop else {throw PatcherError.patchVerificationFailed(- "\(method): gate at 0x\(hex(gate.vma)) reads \(written.hex) after write"+ "\(method): gate at 0x\(hex(gate.vma)) reads \(written.hex) after write",)}@@ -206,10 +212,10 @@ public enum DSCLSDEmbeddedRegPatcher {guard !alreadyNOP else {return Report(outcome: .alreadyPatched, gate: gate, record: nil)}- return Report(+ return try Report(outcome: .patched,gate: gate,- record: try record(for: gate, in: chunks, original: original, patched: nop)+ record: record(for: gate, in: chunks, original: original, patched: nop),)}@@ -220,14 +226,14 @@ public enum DSCLSDEmbeddedRegPatcher {/// Returns `nil` when the method is absent, which is the pre-iOS-27 no-op/// case rather than an error.public static func locateGate(- in chunks: DSCChunkSet+ in chunks: DSCChunkSet,) throws -> (functionVMA: UInt64, gate: Gate)? {guard let functionVMA = try chunks.resolveLocalSymbol(method) else { return nil }let instructions = try disassembleFunction(in: chunks, at: functionVMA)guard let gate = findGate(in: instructions) else {throw PatcherError.patchSiteNotFound(- "\(method): entitled-result gate (cbz/cbnz w0 -> mov w<reg>,#1) not found"+ "\(method): entitled-result gate (cbz/cbnz w0 -> mov w<reg>,#1) not found",)}return (functionVMA, gate)@@ -241,12 +247,12 @@ public enum DSCLSDEmbeddedRegPatcher {/// mapping must not turn into an unmapped-span error.static func disassembleFunction(in chunks: DSCChunkSet,- at vma: UInt64+ at vma: UInt64,) throws -> [Instruction] {let buffer = try chunks.readAtVMA(vma,length: maxInstructions * 4,- allowShort: true+ allowShort: true,)let decoded = ARM64Disassembler().disassemble(buffer, at: vma)var result: [Instruction] = []@@ -259,7 +265,9 @@ public enum DSCLSDEmbeddedRegPatcher {// be matching noise.guard instruction.id != 0 else { break }result.append(instruction)- if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" { break }+ if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" {+ break+ }}return result}@@ -293,7 +301,7 @@ public enum DSCLSDEmbeddedRegPatcher {vma: candidate.address,mnemonic: candidate.mnemonic,operandString: candidate.operandString,- resultRegister: next.register+ resultRegister: next.register,)}return nil@@ -306,7 +314,7 @@ public enum DSCLSDEmbeddedRegPatcher {/// source — rather than on operand text.static func movRegisterImmediate(_ instruction: Instruction,- _ disassembler: ARM64Disassembler+ _ disassembler: ARM64Disassembler,) -> (register: String, immediate: Int64)? {guard instruction.mnemonic == "mov",let operands = instruction.aarch64?.operands,@@ -327,7 +335,7 @@ public enum DSCLSDEmbeddedRegPatcher {for gate: Gate,in chunks: DSCChunkSet,original: Data,- patched: Data+ patched: Data,) throws -> PatchRecord {let span = DSCWriteSpan(vma: gate.vma, length: patched.count)let (chunkURL, range) = try chunks.fileRange(of: span)@@ -341,7 +349,7 @@ public enum DSCLSDEmbeddedRegPatcher {beforeDisasm: disassemblyText(of: original, at: gate.vma),afterDisasm: disassemblyText(of: patched, at: gate.vma),description: "NOP `\(gate.text)` in \(method) so the fall-through "- + "sets \(gate.resultRegister)=1 (entitled)"+ + "sets \(gate.resultRegister)=1 (entitled)",)}diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swiftindex 33133f49..3b667e14 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swift@@ -102,7 +102,7 @@ public enum DSCLockdownModePatcher {functionVMA: UInt64? = nil,gateVMA: UInt64? = nil,record: PatchRecord? = nil,- reattestation: DSCReattestation? = nil+ reattestation: DSCReattestation? = nil,) {self.verdict = verdictself.symbolName = symbolName@@ -113,12 +113,16 @@ public enum DSCLockdownModePatcher {}/// Sites this run put on disk — 1 on a live patch, 0 otherwise.- public var sitesWritten: Int { verdict == .patched ? 1 : 0 }+ public var sitesWritten: Int {+ verdict == .patched ? 1 : 0+ }/// Sites this run found, patched or already patched. This is the number/// `patch_lockdown_mode` returns: 0 when the symbol is absent, 1/// otherwise.- public var sitesFound: Int { verdict == .symbolAbsent ? 0 : 1 }+ public var sitesFound: Int {+ verdict == .symbolAbsent ? 0 : 1+ }}// MARK: - Entry points@@ -128,7 +132,7 @@ public enum DSCLockdownModePatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Outcome {try patch(in: DSCChunkSet(directory: chunksDirectory), dryRun: dryRun, log: log)}@@ -144,17 +148,17 @@ public enum DSCLockdownModePatcher {public static func patch(in chunks: DSCChunkSet,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Outcome {log?(" [.] \(chunks.directory.path) "- + "(\(chunks.chunkURLs.count) chunk(s), \(chunks.mappings.count) mapping(s))"+ + "(\(chunks.chunkURLs.count) chunk(s), \(chunks.mappings.count) mapping(s))",)guard let block = try resolveBlockInvoke(in: chunks) else {log?(" [=] os_lockdown_mode_enabled not present "- + "(pre-iOS-27 userland); nothing to patch"+ + "(pre-iOS-27 userland); nothing to patch",)return Outcome(verdict: .symbolAbsent)}@@ -164,7 +168,7 @@ public enum DSCLockdownModePatcher {guard let gate = findErrorGate(instructions) else {throw PatcherError.patchSiteNotFound("lockdown_mode: `cmn wR,#1; b.eq <crash>` sysctl-error gate not found "- + "(nor an already-NOPed one)"+ + "(nor an already-NOPed one)",)}log?(" [.] gate @ 0x\(hex(gate.address)): \(gate.mnemonic) \(gate.operandString)")@@ -174,20 +178,20 @@ public enum DSCLockdownModePatcher {guard current != nop else {log?(" [=] already patched at 0x\(hex(gate.address)); "- + "nothing to patch/re-attest"+ + "nothing to patch/re-attest",)return Outcome(verdict: .alreadyPatched,symbolName: block.name,functionVMA: block.vma,- gateVMA: gate.address+ gateVMA: gate.address,)}let record = try record(for: gate, original: current, replacement: nop, in: chunks)log?(" [+] \(dryRun ? "would write" : "wrote") nop at 0x\(hex(gate.address)) "- + "(\(current.hex) -> \(nop.hex))"+ + "(\(current.hex) -> \(nop.hex))",)guard !dryRun else {return Outcome(@@ -195,7 +199,7 @@ public enum DSCLockdownModePatcher {symbolName: block.name,functionVMA: block.vma,gateVMA: gate.address,- record: record+ record: record,)}@@ -203,7 +207,7 @@ public enum DSCLockdownModePatcher {let reattestation = try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: log)guard try chunks.bytesAtVMA(gate.address, length: nop.count) == nop else {throw PatcherError.patchVerificationFailed(- "lockdown_mode: post-write verify failed at 0x\(hex(gate.address))"+ "lockdown_mode: post-write verify failed at 0x\(hex(gate.address))",)}log?(" [+] lockdown-mode crash patch complete")@@ -214,7 +218,7 @@ public enum DSCLockdownModePatcher {functionVMA: block.vma,gateVMA: gate.address,record: record,- reattestation: reattestation+ reattestation: reattestation,)}@@ -262,7 +266,9 @@ public enum DSCLockdownModePatcher {for insn in disassembler.disassemble(window, at: vma, count: maxInstructions) {guard insn.id != 0 else { break }decoded.append(insn)- if insn.mnemonic == "ret" || insn.mnemonic == "retab" { break }+ if insn.mnemonic == "ret" || insn.mnemonic == "retab" {+ break+ }}return decoded}@@ -281,11 +287,15 @@ public enum DSCLockdownModePatcher {var sawCall = falsefor index in 0 ..< (instructions.count - 1) {let insn = instructions[index]- if insn.mnemonic == "bl" { sawCall = true }+ if insn.mnemonic == "bl" {+ sawCall = true+ }guard sawCall else { continue }guard insn.mnemonic == "cmn", immediate(of: insn, at: 1) == 1 else { continue }let gate = instructions[index + 1]- if gate.mnemonic == "b.eq" || gate.mnemonic == "nop" { return gate }+ if gate.mnemonic == "b.eq" || gate.mnemonic == "nop" {+ return gate+ }}return nil}@@ -308,7 +318,7 @@ public enum DSCLockdownModePatcher {for gate: Instruction,original: Data,replacement: Data,- in chunks: DSCChunkSet+ in chunks: DSCChunkSet,) throws -> PatchRecord {let span = DSCWriteSpan(vma: gate.address, length: replacement.count)let (chunkURL, range) = try chunks.fileRange(of: span)@@ -322,7 +332,7 @@ public enum DSCLockdownModePatcher {beforeDisasm: "\(gate.mnemonic) \(gate.operandString)",afterDisasm: "nop",description: "NOP `\(gate.mnemonic) \(gate.operandString)` so a missing "- + "security.mac.lockdown_mode_state_public sysctl reads 0 instead of aborting"+ + "security.mac.lockdown_mode_state_public sysctl reads 0 instead of aborting",)}diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swiftindex 99954293..deb4aac5 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swift@@ -153,9 +153,14 @@ public enum DSCMaxSlidePatcher {public let writtenSpan: DSCWriteSpan?/// Sites patched — the Python function's return value, which is 0 or 1.- public var siteCount: Int { record == nil ? 0 : 1 }+ public var siteCount: Int {+ record == nil ? 0 : 1+ }+/// Whether bytes actually reached the chunk file.- public var didWrite: Bool { writtenSpan != nil }+ public var didWrite: Bool {+ writtenSpan != nil+ }}// MARK: - Patching@@ -185,7 +190,7 @@ public enum DSCMaxSlidePatcher {kernelRegionSize: UInt64 = kernelSharedRegionSize,dryRun: Bool = false,force: Bool = false,- verbose: Bool = true+ verbose: Bool = true,) throws -> Result {let mainChunkName = "dyld_shared_cache_\(architecture)"let mainChunk = chunksDirectory.appendingPathComponent(mainChunkName)@@ -204,7 +209,7 @@ public enum DSCMaxSlidePatcher {if verbose {print(" [.] \(mainChunkName): start=\(hex(header.sharedRegionStart)) "- + "size=\(hex(header.sharedRegionSize)) maxSlide=\(hex(header.maxSlide))"+ + "size=\(hex(header.sharedRegionSize)) maxSlide=\(hex(header.maxSlide))",)}@@ -216,7 +221,7 @@ public enum DSCMaxSlidePatcher {guard !overflowed else {throw PatcherError.invalidFormat("\(mainChunk.path): sharedRegionSize \(hex(header.sharedRegionSize)) + maxSlide "- + "\(hex(header.maxSlide)) overflows 64 bits; header is not a dyld_cache_header"+ + "\(hex(header.maxSlide)) overflows 64 bits; header is not a dyld_cache_header",)}@@ -225,7 +230,7 @@ public enum DSCMaxSlidePatcher {if verbose {print(" [=] fits: span+maxSlide \(hex(combined)) <= "- + "region \(hex(kernelRegionSize)); no change"+ + "region \(hex(kernelRegionSize)); no change",)}return Result(@@ -234,18 +239,20 @@ public enum DSCMaxSlidePatcher {sharedRegionSize: header.sharedRegionSize,maxSlide: header.maxSlide,record: nil,- writtenSpan: nil+ writtenSpan: nil,)}guard header.maxSlide != 0 else {- if verbose { print(" [=] maxSlide already 0; no change") }+ if verbose {+ print(" [=] maxSlide already 0; no change")+ }return Result(outcome: .alreadyZero,sharedRegionStart: header.sharedRegionStart,sharedRegionSize: header.sharedRegionSize,maxSlide: header.maxSlide,record: nil,- writtenSpan: nil+ writtenSpan: nil,)}@@ -256,7 +263,7 @@ public enum DSCMaxSlidePatcher {if verbose {print(" [+] \(reason); \(dryRun ? "would set" : "set") "- + "maxSlide \(hex(header.maxSlide)) -> 0x0"+ + "maxSlide \(hex(header.maxSlide)) -> 0x0",)}@@ -270,7 +277,7 @@ public enum DSCMaxSlidePatcher {virtualAddress: fieldVMA,originalBytes: originalBytes,patchedBytes: patchedBytes,- description: "dyld_cache_header maxSlide \(hex(header.maxSlide)) -> 0 (\(reason))"+ description: "dyld_cache_header maxSlide \(hex(header.maxSlide)) -> 0 (\(reason))",)guard !dryRun else {@@ -278,14 +285,16 @@ public enum DSCMaxSlidePatcher {// did complete, it just wrote nothing. Every log line in this// function is kept identical to the Python's, so a `--dry-run` of// one can be diffed against a `--dry-run` of the other.- if verbose { print(" [+] DSC maxSlide patch complete") }+ if verbose {+ print(" [+] DSC maxSlide patch complete")+ }return Result(outcome: outcome,sharedRegionStart: header.sharedRegionStart,sharedRegionSize: header.sharedRegionSize,maxSlide: header.maxSlide,record: record,- writtenSpan: nil+ writtenSpan: nil,)}@@ -298,7 +307,7 @@ public enum DSCMaxSlidePatcher {let readBack = try chunks.bytesAtVMA(fieldVMA, length: 8).loadLE(UInt64.self, at: 0)guard readBack == 0 else {throw PatcherError.patchVerificationFailed(- "maxSlide write verify failed: \(hex(readBack))"+ "maxSlide write verify failed: \(hex(readBack))",)}@@ -307,14 +316,16 @@ public enum DSCMaxSlidePatcher {// cs_validate'd code page, and leaving the slot alone is the behaviour// that was validated on device.- if verbose { print(" [+] DSC maxSlide patch complete") }+ if verbose {+ print(" [+] DSC maxSlide patch complete")+ }return Result(outcome: outcome,sharedRegionStart: header.sharedRegionStart,sharedRegionSize: header.sharedRegionSize,maxSlide: header.maxSlide,record: record,- writtenSpan: span+ writtenSpan: span,)}@@ -338,7 +349,7 @@ public enum DSCMaxSlidePatcher {$0.chunkURL == main && $0.fileOffset == 0}) else {throw PatcherError.invalidFormat(- "\(main.path): no mapping covers the cache header at file offset 0"+ "\(main.path): no mapping covers the cache header at file offset 0",)}return mapping.address@@ -361,14 +372,14 @@ public enum DSCMaxSlidePatcher {static func readHeader(from chunks: DSCChunkSet,at headerVMA: UInt64,- chunkName: String+ chunkName: String,) throws -> Header {let header = try chunks.bytesAtVMA(headerVMA, length: 0x100)guard header.prefix(magicPrefix.count) == magicPrefix else {let magic = header.subdata(in: HeaderField.magic ..< (HeaderField.magic + 16))throw PatcherError.invalidFormat(- "\(chunkName): not a dyld shared cache (magic=\(magic.hex))"+ "\(chunkName): not a dyld shared cache (magic=\(magic.hex))",)}@@ -378,14 +389,14 @@ public enum DSCMaxSlidePatcher {throw PatcherError.invalidFormat("\(chunkName): dyld_cache_header ends at \(hex(UInt64(mappingOffset))), before "+ "maxSlide at \(hex(UInt64(HeaderField.maxSlide))); this cache version has no "- + "maxSlide field"+ + "maxSlide field",)}let parsed = Header(sharedRegionStart: header.loadLE(UInt64.self, at: HeaderField.sharedRegionStart),sharedRegionSize: header.loadLE(UInt64.self, at: HeaderField.sharedRegionSize),- maxSlide: header.loadLE(UInt64.self, at: HeaderField.maxSlide)+ maxSlide: header.loadLE(UInt64.self, at: HeaderField.maxSlide),)let mapped = chunks.addressRange@@ -393,7 +404,7 @@ public enum DSCMaxSlidePatcher {throw PatcherError.invalidFormat("\(chunkName): sharedRegionStart \(hex(parsed.sharedRegionStart)) is not the "+ "cache's lowest mapped address \(hex(mapped.lowerBound)); the header layout "- + "is not the one these offsets describe"+ + "is not the one these offsets describe",)}let span = mapped.upperBound &- mapped.lowerBound@@ -401,7 +412,7 @@ public enum DSCMaxSlidePatcher {throw PatcherError.invalidFormat("\(chunkName): sharedRegionSize \(hex(parsed.sharedRegionSize)) is smaller than "+ "the \(hex(span)) the cache actually maps; the header layout is not the one "- + "these offsets describe"+ + "these offsets describe",)}return parseddiff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swiftindex 16d49793..cf1d1935 100644--- a/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swift+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swift@@ -99,7 +99,9 @@ public enum DSCXPCLWCRPatcher {/// Sites written — the number the Python prints, and the number the/// parity test compares.- public var siteCount: Int { records.count }+ public var siteCount: Int {+ records.count+ }}// MARK: - Entry point@@ -114,7 +116,7 @@ public enum DSCXPCLWCRPatcher {public static func apply(directory: URL,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Outcome {let chunks = try DSCChunkSet(directory: directory)return try apply(chunks: chunks, dryRun: dryRun, log: log)@@ -131,7 +133,7 @@ public enum DSCXPCLWCRPatcher {public static func apply(chunks: DSCChunkSet,dryRun: Bool = false,- log: ((String) -> Void)? = DSCCodeSignature.stderrLog+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog,) throws -> Outcome {log?(" [.] \(chunks.directory.path) — \(chunks.chunkURLs.count) chunk(s), "+ "\(chunks.mappings.count) mapping(s)")@@ -154,7 +156,7 @@ public enum DSCXPCLWCRPatcher {status: .symbolAbsent,functionVMA: nil,resolvedName: nil,- records: []+ records: [],)}log?(" [.] \(resolvedName) @ 0x\(hex(functionVMA))")@@ -163,7 +165,7 @@ public enum DSCXPCLWCRPatcher {let instructions = try disassembleFunction(in: chunks,at: functionVMA,- disassembler: disassembler+ disassembler: disassembler,)guard let site = findConsistencyCheck(in: instructions, disassembler: disassembler) else {@@ -175,12 +177,12 @@ public enum DSCXPCLWCRPatcher {status: .alreadyPatched,functionVMA: functionVMA,resolvedName: resolvedName,- records: []+ records: [],)}throw PatcherError.patchSiteNotFound("\(symbol): LWCR consistency idiom (cset wC,ne; eor wE,w0,wC; tbz wE,#0) "- + "not found at 0x\(hex(functionVMA))"+ + "not found at 0x\(hex(functionVMA))",)}@@ -218,7 +220,7 @@ public enum DSCXPCLWCRPatcher {original: current,chunkName: location?.chunkURL.lastPathComponent ?? chunks.directory.lastPathComponent,fileOffset: location?.fileOffset ?? 0,- disassembler: disassembler+ disassembler: disassembler,))}@@ -229,7 +231,7 @@ public enum DSCXPCLWCRPatcher {let readBack = try chunks.bytesAtVMA(edit.address, length: edit.bytes.count)guard readBack == edit.bytes else {throw PatcherError.patchVerificationFailed(- "post-write verify failed at 0x\(hex(edit.address))"+ "post-write verify failed at 0x\(hex(edit.address))",)}}@@ -243,7 +245,7 @@ public enum DSCXPCLWCRPatcher {status: records.isEmpty ? .alreadyPatched : .patched,functionVMA: functionVMA,resolvedName: resolvedName,- records: records+ records: records,)}@@ -268,7 +270,7 @@ public enum DSCXPCLWCRPatcher {/// dataflow between the three is what makes the match unambiguous.static func findConsistencyCheck(in instructions: [Instruction],- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> ConsistencyCheck? {guard instructions.count >= 2 else { return nil }for index in 0 ..< (instructions.count - 1) {@@ -295,7 +297,9 @@ public enum DSCXPCLWCRPatcher {if candidate.mnemonic == "cset", register(candidate, 0, disassembler) == source {// The condition is read off Capstone's decode, not the// printed operand text.- if candidate.aarch64?.conditionCode == AArch64CC_NE { cset = candidate }+ if candidate.aarch64?.conditionCode == AArch64CC_NE {+ cset = candidate+ }break}back -= 1@@ -320,7 +324,7 @@ public enum DSCXPCLWCRPatcher {/// already-patched cache the idiom is gone by construction.static func findPatchedShape(in instructions: [Instruction],- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> Instruction? {guard instructions.count >= 3 else { return nil }for index in 0 ..< (instructions.count - 2) {@@ -362,13 +366,15 @@ public enum DSCXPCLWCRPatcher {static func disassembleFunction(in chunks: DSCChunkSet,at vma: UInt64,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) throws -> [Instruction] {let window = try chunks.readAtVMA(vma, length: maxInstructions * 4, allowShort: true)var result: [Instruction] = []for insn in disassembler.disassemble(window, at: vma) {result.append(insn)- if insn.mnemonic == "ret" || insn.mnemonic == "retab" { break }+ if insn.mnemonic == "ret" || insn.mnemonic == "retab" {+ break+ }}return result}@@ -379,7 +385,7 @@ public enum DSCXPCLWCRPatcher {static func register(_ insn: Instruction,_ index: Int,- _ disassembler: ARM64Disassembler+ _ disassembler: ARM64Disassembler,) -> String? {guard let operands = insn.aarch64?.operands, index < operands.count else { return nil }let operand = operands[index]@@ -408,7 +414,7 @@ public enum DSCXPCLWCRPatcher {original: Data,chunkName: String,fileOffset: Int,- disassembler: ARM64Disassembler+ disassembler: ARM64Disassembler,) -> PatchRecord {PatchRecord(patchID: "\(recordGroup).\(edit.label.split(separator: " ").first ?? "")"@@ -421,7 +427,7 @@ public enum DSCXPCLWCRPatcher {beforeDisasm: disassembler.disassembleOne(original, at: edit.address).map(text) ?? "",afterDisasm: disassembler.disassembleOne(edit.bytes, at: edit.address).map(text) ?? "",description: "\(symbol): `\(edit.label)` — derive matched from error_code "- + "and drop the abort"+ + "and drop the abort",)}diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swiftindex 77bc6d79..716e2622 100644--- a/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swift+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swift@@ -46,8 +46,8 @@ extension DeviceTreePatcher {parentPath: ["device-tree", "product"],nodeName: "camera",properties: [- .init(name: "aggregate-cam-photo-zoom", length: 4, flags: 0, value: .integer(0x7d0)),- .init(name: "aggregate-cam-video-zoom", length: 4, flags: 0, value: .integer(0x4b0)),+ .init(name: "aggregate-cam-photo-zoom", length: 4, flags: 0, value: .integer(0x7D0)),+ .init(name: "aggregate-cam-video-zoom", length: 4, flags: 0, value: .integer(0x4B0)),.init(name: "aggregate-camera", length: 4, flags: 0, value: .integer(1)),.init(name: "auto-focus", length: 4, flags: 0, value: .integer(1)),.init(name: "auto-low-light-video", length: 4, flags: 0, value: .integer(1)),@@ -110,7 +110,7 @@ extension DeviceTreePatcher {.init(name: "video-stills", length: 4, flags: 0, value: .integer(1)),],patchID: "devicetree.product.camera_node",- description: "Add /product/camera node with full iPhone17,3 D47AP property set (62 props)"+ description: "Add /product/camera node with full iPhone17,3 D47AP property set (62 props)",),// ── /product/facetime (Tier C — front-camera video-call config) ──@@ -128,28 +128,28 @@ extension DeviceTreePatcher {.init(name: "bitrate-lte", length: 4, flags: 0, value: .integer(228)),.init(name: "bitrate-wifi", length: 4, flags: 0, value: .integer(2000)),.init(name: "decoding", length: 48, flags: 0, value: .bytes(Data([- 0x40, 0x01, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x00,- 0x40, 0x01, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00,- 0xe0, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x70, 0x01,- 0xe0, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x70, 0x01,- 0x80, 0x02, 0x00, 0x00, 0x1e, 0x00, 0xe0, 0x01,- 0x00, 0x04, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x03,+ 0x40, 0x01, 0x00, 0x00, 0x0F, 0x00, 0xF0, 0x00,+ 0x40, 0x01, 0x00, 0x00, 0x1E, 0x00, 0xF0, 0x00,+ 0xE0, 0x01, 0x00, 0x00, 0x0F, 0x00, 0x70, 0x01,+ 0xE0, 0x01, 0x00, 0x00, 0x1E, 0x00, 0x70, 0x01,+ 0x80, 0x02, 0x00, 0x00, 0x1E, 0x00, 0xE0, 0x01,+ 0x00, 0x04, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x03,]))),.init(name: "encoding", length: 56, flags: 0, value: .bytes(Data([- 0x40, 0x01, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x00,- 0x40, 0x01, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00,- 0xe0, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x70, 0x01,- 0xe0, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x70, 0x01,- 0x80, 0x02, 0x00, 0x00, 0x1e, 0x00, 0xe0, 0x01,- 0x00, 0x04, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x03,- 0x00, 0x05, 0x00, 0x00, 0x1e, 0x00, 0xd0, 0x02,+ 0x40, 0x01, 0x00, 0x00, 0x0F, 0x00, 0xF0, 0x00,+ 0x40, 0x01, 0x00, 0x00, 0x1E, 0x00, 0xF0, 0x00,+ 0xE0, 0x01, 0x00, 0x00, 0x0F, 0x00, 0x70, 0x01,+ 0xE0, 0x01, 0x00, 0x00, 0x1E, 0x00, 0x70, 0x01,+ 0x80, 0x02, 0x00, 0x00, 0x1E, 0x00, 0xE0, 0x01,+ 0x00, 0x04, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x03,+ 0x00, 0x05, 0x00, 0x00, 0x1E, 0x00, 0xD0, 0x02,]))),- .init(name: "pref-decoding", length: 8, flags: 0, value: .integer(0x0300_001e_0000_0400)),+ .init(name: "pref-decoding", length: 8, flags: 0, value: .integer(0x0300_001E_0000_0400)),.init(name: "tnr-mode-back", length: 4, flags: 0, value: .integer(10)),.init(name: "tnr-mode-front", length: 4, flags: 0, value: .integer(10)),],patchID: "devicetree.product.facetime_node",- description: "Add /product/facetime node with full iPhone17,3 D47AP property set (9 props)"+ description: "Add /product/facetime node with full iPhone17,3 D47AP property set (9 props)",),// ── /product/audio (Tier C — audio + spatial-capture flags) ──@@ -170,16 +170,16 @@ extension DeviceTreePatcher {nodeName: "audio",properties: [.init(name: "acoustic-id", length: 4, flags: 0, value: .integer(8018)),- .init(name: "actuator-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_0eef_0000_01f4)),- .init(name: "actuator-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_1db0_0000_06d6)),+ .init(name: "actuator-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_0EEF_0000_01F4)),+ .init(name: "actuator-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_1DB0_0000_06D6)),.init(name: "enabledChannels", length: 4, flags: 0, value: .integer(15)),.init(name: "historyChannels", length: 4, flags: 0, value: .integer(15)),.init(name: "mic-trim-gains-0", length: 12, flags: 0, value: .string("syscfg/MiGH")),.init(name: "mic-trim-gains-2", length: 12, flags: 0, value: .string("syscfg/MiGB")),.init(name: "mic-trim-gains-key-cnt", length: 4, flags: 0, value: .integer(2)),- .init(name: "speaker-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),- .init(name: "speaker-cpms-bgd_1s", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),- .init(name: "speaker-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),+ .init(name: "speaker-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04B0)),+ .init(name: "speaker-cpms-bgd_1s", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04B0)),+ .init(name: "speaker-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04B0)),.init(name: "speaker-thiele-small-0", length: 12, flags: 0, value: .string("syscfg/SpPH")),.init(name: "speaker-thiele-small-key-cnt", length: 4, flags: 0, value: .integer(1)),.init(name: "speaker-trim-gains-0", length: 12, flags: 0, value: .string("syscfg/SpGH")),@@ -196,23 +196,23 @@ extension DeviceTreePatcher {.init(name: "supports-spatial-audio-capture", length: 4, flags: 0, value: .integer(1)),.init(name: "supports-spatial-facetime", length: 4, flags: 0, value: .integer(1)),.init(name: "use-case-client-format", length: 96, flags: 0, value: .bytes(Data([- 0x61, 0x64, 0x6e, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x61, 0x64, 0x6E, 0x73, 0x80, 0xBB, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x69, 0x72, 0x69, 0x73, 0x80, 0x3e, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x69, 0x72, 0x69, 0x73, 0x80, 0x3E, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x73, 0x74, 0x70, 0x6c, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x73, 0x74, 0x70, 0x6C, 0x80, 0x3E, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,]))),.init(name: "use-case-dsp-in-format", length: 160, flags: 0, value: .bytes(Data([- 0x64, 0x6b, 0x74, 0x6d, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x64, 0x6B, 0x74, 0x6D, 0x80, 0xBB, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x61, 0x64, 0x6e, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x61, 0x64, 0x6E, 0x73, 0x80, 0xBB, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x64, 0x76, 0x70, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x64, 0x76, 0x70, 0x73, 0x80, 0xBB, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x69, 0x72, 0x69, 0x73, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x69, 0x72, 0x69, 0x73, 0x80, 0x3E, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x73, 0x74, 0x70, 0x6c, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x73, 0x74, 0x70, 0x6C, 0x80, 0x3E, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,]))),.init(name: "use-case-struct-version", length: 4, flags: 0, value: .integer(1)),@@ -220,7 +220,7 @@ extension DeviceTreePatcher {.init(name: "wireless-splitter", length: 4, flags: 0, value: .integer(1)),],patchID: "devicetree.product.audio_node",- description: "Add /product/audio node with full iPhone17,3 D47AP property set (31 props)"+ description: "Add /product/audio node with full iPhone17,3 D47AP property set (31 props)",),// ── /product/iopm (Tier C — always-on technology) ────────────@@ -240,7 +240,7 @@ extension DeviceTreePatcher {.init(name: "aot-mode", length: 4, flags: 0, value: .integer(13)),],patchID: "devicetree.product.iopm_node",- description: "Add /product/iopm node with aot-mode=13 + aot-linger-time-ms=0 (2 props)"+ description: "Add /product/iopm node with aot-mode=13 + aot-linger-time-ms=0 (2 props)",),// ── ISP / SMC camera-flag stubs (Tier F — /arm-io subtree) ──@@ -283,7 +283,7 @@ extension DeviceTreePatcher {nodeName: "smc",properties: [],patchID: "devicetree.arm_io.smc_stub",- description: "Add /arm-io/smc empty stub (parent for smc-ext-charger chain)"+ description: "Add /arm-io/smc empty stub (parent for smc-ext-charger chain)",),// /arm-io/smc/iop-smc-nub — empty stub (parent for smc-ext-charger).@@ -292,7 +292,7 @@ extension DeviceTreePatcher {nodeName: "iop-smc-nub",properties: [],patchID: "devicetree.arm_io.smc.iop_smc_nub_stub",- description: "Add /arm-io/smc/iop-smc-nub empty stub (parent for smc-ext-charger)"+ description: "Add /arm-io/smc/iop-smc-nub empty stub (parent for smc-ext-charger)",),// /arm-io/smc/iop-smc-nub/smc-ext-charger — carries camera-driver.@@ -303,7 +303,7 @@ extension DeviceTreePatcher {.init(name: "camera-driver", length: 14, flags: 0, value: .string("AppleH16CamIn")),],patchID: "devicetree.arm_io.smc.smc_ext_charger_camera_driver",- description: "Add /arm-io/smc/iop-smc-nub/smc-ext-charger with camera-driver='AppleH16CamIn'"+ description: "Add /arm-io/smc/iop-smc-nub/smc-ext-charger with camera-driver='AppleH16CamIn'",),// /arm-io/isp — minimal stub carrying camera-front + camera-rear.@@ -315,7 +315,7 @@ extension DeviceTreePatcher {.init(name: "camera-rear", length: 4, flags: 0, value: .integer(1)),],patchID: "devicetree.arm_io.isp_camera_flags",- description: "Add /arm-io/isp stub with camera-front=1 + camera-rear=1"+ description: "Add /arm-io/isp stub with camera-front=1 + camera-rear=1",),// /arm-io/ispRtb — minimal stub carrying camera-front + camera-rear.@@ -327,7 +327,7 @@ extension DeviceTreePatcher {.init(name: "camera-rear", length: 4, flags: 0, value: .integer(1)),],patchID: "devicetree.arm_io.ispRtb_camera_flags",- description: "Add /arm-io/ispRtb stub with camera-front=1 + camera-rear=1"+ description: "Add /arm-io/ispRtb stub with camera-front=1 + camera-rear=1",),]}diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swiftindex c8601eaa..51e3bd67 100644--- a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift@@ -144,7 +144,7 @@ public final class DeviceTreePatcher: Patcher {length: length,flags: flags,value: value,- valueOffset: valueOffset+ valueOffset: valueOffset,))}@@ -162,7 +162,7 @@ public final class DeviceTreePatcher: Patcher {let (root, end) = try parseNode(blob, offset: 0)guard end == blob.count else {throw PatcherError.invalidFormat(- "DeviceTree: unexpected trailing bytes (\(blob.count - end) extra)"+ "DeviceTree: unexpected trailing bytes (\(blob.count - end) extra)",)}return root@@ -329,7 +329,7 @@ public final class DeviceTreePatcher: Patcher {virtualAddress: nil,originalBytes: originalBytes,patchedBytes: newValue,- description: patch.description+ description: patch.description,)patches.append(record)@@ -339,7 +339,7 @@ public final class DeviceTreePatcher: Patcher {prop.valueOffset,originalBytes.hex,newValue.hex,- patch.patchID+ patch.patchID,))}}@@ -380,7 +380,7 @@ public final class DeviceTreePatcher: Patcher {length: nameValue.count,flags: 0,value: nameValue,- valueOffset: 0+ valueOffset: 0,))for spec in patch.properties {@@ -397,7 +397,7 @@ public final class DeviceTreePatcher: Patcher {length: spec.length,flags: spec.flags,value: value,- valueOffset: 0+ valueOffset: 0,))}@@ -415,7 +415,7 @@ public final class DeviceTreePatcher: Patcher {virtualAddress: nil,originalBytes: Data(),patchedBytes: serialized,- description: patch.description+ description: patch.description,))if verbose {diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swiftindex 6ec18aa9..5b8d33ae 100644--- a/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swift+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swift@@ -52,7 +52,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("vphone-1337"),patchID: "devicetree.serial_number",- description: "Set serial number to vphone-1337"+ description: "Set serial number to vphone-1337",),PropertyPatch(nodePath: ["device-tree", "buttons"],@@ -61,7 +61,7 @@ extension DeviceTreePatcher {flags: 0,value: .integer(2),patchID: "devicetree.home_button_type",- description: "Set home button type to 2"+ description: "Set home button type to 2",),PropertyPatch(nodePath: ["device-tree", "product"],@@ -70,7 +70,7 @@ extension DeviceTreePatcher {flags: 0,value: .integer(2556),patchID: "devicetree.artwork_device_subtype",- description: "Set artwork device subtype to 2556"+ description: "Set artwork device subtype to 2556",),PropertyPatch(nodePath: ["device-tree", "product"],@@ -79,7 +79,7 @@ extension DeviceTreePatcher {flags: 0,value: .integer(144),patchID: "devicetree.island_notch_location",- description: "Set island notch location to 144"+ description: "Set island notch location to 144",),]@@ -119,7 +119,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("D47AP"),patchID: "devicetree.target_sub_type",- description: "Set target-sub-type to D47AP (was VPHONE600AP)"+ description: "Set target-sub-type to D47AP (was VPHONE600AP)",),// #3 — root `compatible` surgical mangle. Keep VPHONE600AP as first@@ -136,7 +136,7 @@ extension DeviceTreePatcher {flags: 0,value: .bytes(compatibleRewrite),patchID: "devicetree.compatible_secondary",- description: "Surgical rewrite of compatible[1]: iPhone99,11 -> iPhone17,3"+ description: "Surgical rewrite of compatible[1]: iPhone99,11 -> iPhone17,3",),// #10 — device-tree/product/fdr-product-type "iPhone99,11" -> "iPhone17,3".@@ -149,7 +149,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("iPhone17,3"),patchID: "devicetree.product.fdr_product_type",- description: "Set product/fdr-product-type to iPhone17,3 (was iPhone99,11)"+ description: "Set product/fdr-product-type to iPhone17,3 (was iPhone99,11)",),// #11 — device-tree/product/sub-product-type "iPhone99,11" -> "iPhone17,3".@@ -162,7 +162,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("iPhone17,3"),patchID: "devicetree.product.sub_product_type",- description: "Set product/sub-product-type to iPhone17,3 (was iPhone99,11)"+ description: "Set product/sub-product-type to iPhone17,3 (was iPhone99,11)",),// #12 — device-tree/product/unique-model "VPHONE600AP" -> "D47AP".@@ -175,7 +175,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("D47AP"),patchID: "devicetree.product.unique_model",- description: "Set product/unique-model to D47AP (was VPHONE600AP)"+ description: "Set product/unique-model to D47AP (was VPHONE600AP)",),// ── Identity rewrite (Tier 1c) ────────────────────────────────@@ -195,7 +195,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("t8140-io"),patchID: "devicetree.arm_io.device_type",- description: "Set arm-io/device_type to t8140-io (was vresearch1-io)"+ description: "Set arm-io/device_type to t8140-io (was vresearch1-io)",),// #7 — device-tree/arm-io/soc-generation "VResearch1" -> "H17".@@ -209,7 +209,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("H17"),patchID: "devicetree.arm_io.soc_generation",- description: "Set arm-io/soc-generation to H17 (was VResearch1)"+ description: "Set arm-io/soc-generation to H17 (was VResearch1)",),// #13 — rename node device-tree/product/vphone600-gestalt-variants@@ -230,7 +230,7 @@ extension DeviceTreePatcher {flags: 0,value: .string("d47-gestalt-variants"),patchID: "devicetree.product.gestalt_variants_rename",- description: "Rename node vphone600-gestalt-variants -> d47-gestalt-variants"+ description: "Rename node vphone600-gestalt-variants -> d47-gestalt-variants",),// ── Camera physical-offset rewrites (Tier B) ──────────────────@@ -248,12 +248,12 @@ extension DeviceTreePatcher {length: 20,flags: 0,value: .bytes(Data([- 0x61, 0x00, 0x01, 0x00, 0x92, 0x1c, 0x00, 0x00,- 0xd8, 0x13, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,+ 0x61, 0x00, 0x01, 0x00, 0x92, 0x1C, 0x00, 0x00,+ 0xD8, 0x13, 0x00, 0x00, 0xE8, 0x03, 0x00, 0x00,0x00, 0x00, 0x00, 0x00,])),patchID: "devicetree.product.front_cam_offset",- description: "Set product/front-cam-offset-from-center to d47ap geometry (was syscfg/fcof)"+ description: "Set product/front-cam-offset-from-center to d47ap geometry (was syscfg/fcof)",),PropertyPatch(nodePath: ["device-tree", "product"],@@ -261,12 +261,12 @@ extension DeviceTreePatcher {length: 20,flags: 0,value: .bytes(Data([- 0xed, 0xa5, 0x00, 0x00, 0xb2, 0x56, 0x00, 0x00,- 0x59, 0x08, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,+ 0xED, 0xA5, 0x00, 0x00, 0xB2, 0x56, 0x00, 0x00,+ 0x59, 0x08, 0x00, 0x00, 0xE8, 0x03, 0x00, 0x00,0x00, 0x00, 0x00, 0x00,])),patchID: "devicetree.product.rear_cam_offset",- description: "Set product/rear-cam-offset-from-center to d47ap geometry (was syscfg/rcof)"+ description: "Set product/rear-cam-offset-from-center to d47ap geometry (was syscfg/rcof)",),]}diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swiftindex cf3486a4..f0fded1c 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift@@ -14,8 +14,8 @@// CryptexFilesystemPatcherAEA.swift, CryptexFilesystemPatcherDiskImage.swift and// CryptexFilesystemPatcherProcess.swift.-import Foundationimport CryptoKit+import Foundationimport Img4toolimport VPhoneArchiveimport VPhoneCore@@ -39,7 +39,7 @@ public final class CryptexFilesystemPatcher: Patcher {buildManiest: Data,restoreDir: URL,verbose: Bool = true,- noBinpack: Bool = false+ noBinpack: Bool = false,) {self.buildManiest = buildManiestself.restoreDir = restoreDir@@ -56,7 +56,7 @@ public final class CryptexFilesystemPatcher: Patcher {// MARK: - Patcherpublic func findAll() throws -> [PatchRecord] {- return [PatchRecord(+ [PatchRecord(patchID: "filesystem.cryptex.merge",component: "",fileOffset: 0,@@ -83,7 +83,7 @@ public final class CryptexFilesystemPatcher: Patcher {let (digestDbPath, rootHashPath) = try createDigestAndHash(filesystem: unencryptedImage,mtree: mtreePath,- remap: didEdit+ remap: didEdit,)let metadataPath = try compressCanonicalMetadata(mtree: mtreePath, digestDb: digestDbPath)let rootHashContainer = try wrapRootHash(rootHashPath)@@ -93,7 +93,7 @@ public final class CryptexFilesystemPatcher: Patcher {filesystem: aeaImage,trustcache: trustcachePath,metadata: metadataPath,- rootHash: rootHashContainer+ rootHash: rootHashContainer,)rebuiltData = try serializePayload(updatedManifest)@@ -105,12 +105,12 @@ public final class CryptexFilesystemPatcher: Patcher {rebuiltData!}- // mergeFilesystems merges the main OS filesystem with the Cryptexes filesystems.- // It returns the path of the merged image (plain and encrypted)+ /// mergeFilesystems merges the main OS filesystem with the Cryptexes filesystems.+ /// It returns the path of the merged image (plain and encrypted)func mergeFilesystems() throws -> (URL, URL) {let osPath = try componentPath("OS")- let osDmgPath = try decryptAeaFile(self.restoreDir.appending(path: osPath))- let newDmgPath = self.restoreDir.appending(path: "new-filesystem.dmg")+ let osDmgPath = try decryptAeaFile(restoreDir.appending(path: osPath))+ let newDmgPath = restoreDir.appending(path: "new-filesystem.dmg")print("- Converting OS image…")let tmpDir = try createTmpDir()@@ -144,10 +144,10 @@ public final class CryptexFilesystemPatcher: Patcher {print("- Finalizing merged image…")try shrinkImage(dmg: targetImagePath)try convertToUDRWImage(input: targetImagePath, output: newDmgPath)- let metadata = try getAeaMetadata(self.restoreDir.appending(path: osPath))- let key = try getAeaKey(self.restoreDir.appending(path: osPath), metadata: metadata)+ let metadata = try getAeaMetadata(restoreDir.appending(path: osPath))+ let key = try getAeaKey(restoreDir.appending(path: osPath), metadata: metadata)let finalFile = newDmgPath.appendingPathExtension("aea")- let finalDestination = self.restoreDir.appending(path: finalFile.lastPathComponent)+ let finalDestination = restoreDir.appending(path: finalFile.lastPathComponent)if FileManager.default.fileExists(atPath: finalDestination.path) {try FileManager.default.removeItem(at: finalDestination)}@@ -157,30 +157,30 @@ public final class CryptexFilesystemPatcher: Patcher {}func copyCryptex(targetMount: String, appOS: Bool = false, systemOS: Bool = false) throws {- guard (appOS || systemOS) && !(appOS && systemOS) else {+ guard appOS || systemOS, !(appOS && systemOS) else {throw FirmwarePatcher.PatcherError.patchVerificationFailed("Can patch only one at a time")}let osPath = if appOS {- self.restoreDir.appending(path: try componentPath("Cryptex1,AppOS"))+ try restoreDir.appending(path: componentPath("Cryptex1,AppOS"))} else {- try decryptAeaFile(self.restoreDir.appending(path: try componentPath("Cryptex1,SystemOS")))+ try decryptAeaFile(restoreDir.appending(path: componentPath("Cryptex1,SystemOS")))}let (osDevice, osMount) = try attachImage(path: osPath, readonly: true)defer { try? detachImage(deviceNode: osDevice) }- let destination = URL.init(filePath: targetMount)+ let destination = URL(filePath: targetMount).appending(path: appOS ? "/System/Cryptexes/App" : "/System/Cryptexes/OS")try FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)- try copyImageContents(source: URL.init(filePath: osMount), destination: destination)+ try copyImageContents(source: URL(filePath: osMount), destination: destination)}func createTmpDir() throws -> URL {let tmpDir = FileManager.default.temporaryDirectory- .appending(path: "vphone-\(UUID.init().uuidString)")+ .appending(path: "vphone-\(UUID().uuidString)")try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true)- self.tmpDirectories.append(tmpDir)+ tmpDirectories.append(tmpDir)return tmpDir}}diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swiftindex a91c25f1..9df66823 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift@@ -18,7 +18,7 @@ extension Data {return nil}- let chars = hex.map { $0 }+ let chars = hex.map(\.self)let bytes = stride(from: 0, to: chars.count, by: 2).map { String(chars[$0]) + String(chars[$0 + 1]) }.compactMap { UInt8($0, radix: 16) }@@ -34,7 +34,8 @@ extension CryptexFilesystemPatcher {let key = String(key.dropFirst(4))if let unwrapped = Data(fromHexString: key),let encoded = String(data: unwrapped, encoding: .utf8),- let data = Data(fromHexString: encoded) {+ let data = Data(fromHexString: encoded)+ {return "base64:\(data.base64EncodedString())"}return keydiff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swiftindex c32313a6..5cd2f31e 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift@@ -17,7 +17,7 @@ extension CryptexFilesystemPatcher {let keys: [URLResourceKey] = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]guard let enumerator = FileManager.default.enumerator(at: sourceRoot, includingPropertiesForKeys: keys) else {throw FirmwareManifest.ManifestError.fileNotFound(- "Unable to read \(sourceRoot.path). Check that the image is still mounted, then try again."+ "Unable to read \(sourceRoot.path). Check that the image is still mounted, then try again.",)}for case let fileURL as URL in enumerator {@@ -36,7 +36,7 @@ extension CryptexFilesystemPatcher {fileURL.path,destinationPath.path,nil,- copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA)+ copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA),)if result < 0 {print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")@@ -47,14 +47,15 @@ extension CryptexFilesystemPatcher {let vals = try destinationPath.resourceValues(forKeys: Set(keys))if values.isDirectory != vals.isDirectory ||values.isRegularFile != vals.isRegularFile ||- values.isSymbolicLink != vals.isSymbolicLink {+ values.isSymbolicLink != vals.isSymbolicLink+ {try FileManager.default.removeItem(at: destinationPath)// try FileManager.default.copyItem(at: fileURL, to: destinationPath)let result = copyfile(fileURL.path,destinationPath.path,nil,- copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA)+ copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA),)if result < 0 {print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")@@ -67,7 +68,7 @@ extension CryptexFilesystemPatcher {_ = try runProcess("/usr/sbin/diskutil", ["image", "create", "from","--format", "RAW", input.path,- output.path+ output.path,])// Resize to max. Asking diskutil how big it may get returns a plist, and@@ -76,11 +77,11 @@ extension CryptexFilesystemPatcher {// can read directly — and a pipeline whose stdout is also where diskutil's// own warnings land, so a noisy run produced a "size" that was a sentence.let sizes = try runProcess("/usr/sbin/diskutil", [- "image", "resize", "--plist", output.path+ "image", "resize", "--plist", output.path,])let maxsize = try Self.maxResizeSize(fromDiskutilPlist: sizes)_ = try runProcess("/usr/sbin/diskutil", [- "image", "resize", "--size", maxsize, output.path+ "image", "resize", "--size", maxsize, output.path,])}@@ -94,7 +95,7 @@ extension CryptexFilesystemPatcher {let body = output.range(of: "<?xml").map { String(output[$0.lowerBound...]) } ?? outputguard let data = body.data(using: .utf8),let root = try? PropertyListSerialization.propertyList(- from: data, options: [], format: nil+ from: data, options: [], format: nil,) as? [String: Any]else {throw ProcessError.failed(0, "diskutil did not return a plist:\n\(output)")@@ -115,7 +116,7 @@ extension CryptexFilesystemPatcher {"convert",input.path,"-format", "UDRW",- "-o", output.path+ "-o", output.path,])}@@ -124,7 +125,7 @@ extension CryptexFilesystemPatcher {"image","resize","--size", "min",- dmg.path+ dmg.path,])}@@ -132,20 +133,24 @@ extension CryptexFilesystemPatcher {_ = try runProcess("/usr/sbin/diskutil", ["unmount", mount])}- // attachImage returns the device and mount point+ /// attachImage returns the device and mount pointfunc attachImage(path: URL, readonly: Bool = false, forceRW: Bool = false) throws -> (String, String) {let process = Process()process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")- process.arguments = if readonly {[- "attach",- "-readonly",- "-plist",- path.path,- ]} else {[- "attach",- "-plist",- path.path,- ]}+ process.arguments = if readonly {+ [+ "attach",+ "-readonly",+ "-plist",+ path.path,+ ]+ } else {+ [+ "attach",+ "-plist",+ path.path,+ ]+ }let pipe = Pipe()process.standardOutput = pipe@@ -167,7 +172,8 @@ extension CryptexFilesystemPatcher {for entry in entries {guard let entry = entry as? PlistDict,let volumeKind = entry["volume-kind"] as? String,- volumeKind == "apfs" || volumeKind == "hfs" else {+ volumeKind == "apfs" || volumeKind == "hfs"+ else {continue}let device = entry["dev-entry"] as? String ?? ""diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swiftindex 5313ac98..2df91b65 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swift@@ -39,7 +39,7 @@ extension CryptexFilesystemPatcher {/// Follows symlinks, which is what chmod(1) does without `-h`.func setMode(_ mode: Int, at url: URL) throws {try FileManager.default.setAttributes(- [.posixPermissions: mode], ofItemAtPath: url.path+ [.posixPermissions: mode], ofItemAtPath: url.path,)}@@ -77,7 +77,7 @@ extension CryptexFilesystemPatcher {try FileManager.default.removeItem(at: link)}try FileManager.default.createSymbolicLink(- atPath: link.path, withDestinationPath: destination+ atPath: link.path, withDestinationPath: destination,)}@@ -94,7 +94,8 @@ extension CryptexFilesystemPatcher {func deleteAppleDoubleFiles(under directory: URL) throws -> Int {var removed = 0for entry in entriesBelow(directory)- where entry.url.lastPathComponent.hasPrefix("._") {+ where entry.url.lastPathComponent.hasPrefix("._")+ {// unlink(2), not FileManager.removeItem: Foundation reads a `._name`// as the partner file's metadata rather than as a file of its own,// which is the same confusion that hides these from its directory@@ -132,7 +133,9 @@ extension CryptexFilesystemPatcher {String(cString: $0)}}- if name == "." || name == ".." { continue }+ if name == "." || name == ".." {+ continue+ }let child = directory.appendingPathComponent(name)var isDirectory = entry.pointee.d_type == UInt8(DT_DIR)@@ -141,7 +144,9 @@ extension CryptexFilesystemPatcher {isDirectory = lstat(child.path, &info) == 0&& info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR)}- if isDirectory { entries.append(contentsOf: entriesBelow(child)) }+ if isDirectory {+ entries.append(contentsOf: entriesBelow(child))+ }entries.append((child, isDirectory))}return entriesdiff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swiftindex d102b823..d0b323e5 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift@@ -16,17 +16,17 @@ extension CryptexFilesystemPatcher {/// identity for these binaries.func guestSigningOptions(identifier: String? = nil,- entitlements: URL? = nil+ entitlements: URL? = nil,) throws -> VPhoneSignOptions {- return VPhoneSignOptions(+ try VPhoneSignOptions(identifier: identifier,- entitlements: try entitlements.map { try Data(contentsOf: $0, options: .mappedIfSafe) },- mergesExisting: true+ entitlements: entitlements.map { try Data(contentsOf: $0, options: .mappedIfSafe) },+ mergesExisting: true,)}func patchLaunchdCacheLoader(targetMount: String) throws {- let target = URL.init(filePath: targetMount)+ let target = URL(filePath: targetMount)let launchdCacheLoaderPath = target.appending(path: "/usr/libexec/launchd_cache_loader")// Patched in place with no `.bak` to restore from, so this is the call// site that needs the port's idempotence. No re-attestation: the sign@@ -36,14 +36,14 @@ extension CryptexFilesystemPatcher {try VPhoneSigner.sign(fileAt: launchdCacheLoaderPath,- options: try guestSigningOptions(- identifier: "com.apple.launchd_cache_loader"- )+ options: guestSigningOptions(+ identifier: "com.apple.launchd_cache_loader",+ ),)}func injectLaunchDaemons(targetMount: String) throws {- let target = URL.init(filePath: targetMount)+ let target = URL(filePath: targetMount)let scriptDir = resources.scriptsDirlet tmpDir = try createTmpDir()@@ -55,7 +55,7 @@ extension CryptexFilesystemPatcher {let vphonedLaunchdPlist = vphonedSrc.appending(path: "vphoned.plist")try FileManager.default.copyItem(at: vphonedLaunchdPlist,- to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist")+ to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist"),)try CFWDaemons.injectDaemon(into: launchdPath, name: "vphoned", from: vphonedLaunchdPlist)print(" [+] Injected vphoned")@@ -64,7 +64,7 @@ extension CryptexFilesystemPatcher {}func addVphoned(targetMount: String) throws {- let target = URL.init(filePath: targetMount)+ let target = URL(filePath: targetMount)let scriptDir = resources.scriptsDirlet vphonedSrc = scriptDir.appendingPathComponent("vphoned")// vphonedSrc (bundled source) is read-only inside a packaged .app, so the@@ -80,9 +80,9 @@ extension CryptexFilesystemPatcher {try FileManager.default.copyItem(at: vphonedBin, to: targetBin)try VPhoneSigner.sign(fileAt: targetBin,- options: try guestSigningOptions(- entitlements: vphonedSrc.appendingPathComponent("entitlements.plist")- )+ options: guestSigningOptions(+ entitlements: vphonedSrc.appendingPathComponent("entitlements.plist"),+ ),)try setMode(0o755, at: targetBin)}@@ -100,12 +100,12 @@ extension CryptexFilesystemPatcher {}func addGpuDriver(targetMount: String) throws {- let target = URL.init(filePath: targetMount)+ let target = URL(filePath: targetMount)let bundle = target.appending(path: "/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")let staged = VPhonePCCGPUDriver.stagedBundle(in: restoreDir)guard FileManager.default.fileExists(atPath: staged.path) else {throw FirmwarePatcher.PatcherError.patchVerificationFailed(- "PCC GPU driver is missing: \(staged.path). Re-run fw prepare with the PCC IPSW."+ "PCC GPU driver is missing: \(staged.path). Re-run fw prepare with the PCC IPSW.",)}if FileManager.default.fileExists(atPath: bundle.path) {@@ -125,14 +125,14 @@ extension CryptexFilesystemPatcher {}for path in [bundle.appending(path: "/_CodeSignature/CodeResources"),- bundle.appending(path: "/Info.plist")+ bundle.appending(path: "/Info.plist"),] {try setMode(0o644, at: path)}}func patchMobileActivation(targetMount: String) throws {- let target = URL.init(filePath: targetMount)+ let target = URL(filePath: targetMount)let mobileActivationdPath = target.appending(path: "/usr/libexec/mobileactivationd")// `resign: false` because the sign below replaces the signature, and// re-attesting would refuse an unsigned input the Python accepted.@@ -141,19 +141,19 @@ extension CryptexFilesystemPatcher {try VPhoneSigner.sign(fileAt: mobileActivationdPath,- options: try guestSigningOptions()+ options: guestSigningOptions(),)}func addDyldSymlinks(targetMount: String) throws {- let target = URL.init(filePath: targetMount)+ let target = URL(filePath: targetMount)try createSymlink(at: target.appending(path: "/System/Library/Caches/com.apple.dyld"),- to: "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"+ to: "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",)try createSymlink(at: target.appending(path: "/System/DriverKit/System/Library/dyld"),- to: "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld"+ to: "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",)}}diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swiftindex 163e7637..62d13bc6 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swift@@ -8,10 +8,10 @@ import Foundationextension CryptexFilesystemPatcher {func serializePayload(_ buildManifest: PlistDict) throws -> Data {- return try PropertyListSerialization.data(+ try PropertyListSerialization.data(fromPropertyList: buildManifest,format: .xml,- options: 0+ options: 0,)}@@ -19,12 +19,13 @@ extension CryptexFilesystemPatcher {filesystem: URL,trustcache: URL,metadata: URL,- rootHash: URL+ rootHash: URL,) throws -> PlistDict {var root = try parsePlist(data: buildManiest)guard var buildIdentities = root["BuildIdentities"] as? [Any],buildIdentities.count > 0,- var buildIdentity = buildIdentities.first! as? PlistDict else {+ var buildIdentity = buildIdentities.first! as? PlistDict+ else {throw FirmwareManifest.ManifestError.missingKey("Component in BuildManifest")}var identityManifest = try getChildPlistDict(parent: buildIdentity, key: "Manifest")@@ -33,40 +34,40 @@ extension CryptexFilesystemPatcher {identityManifest = try updateManifestComponentPath(identityManifest: identityManifest,component: "OS",- at: filesystem+ at: filesystem,)- let newTrustcachePath = self.restoreDir.appending(path: "Firmware").appending(path: trustcache.lastPathComponent)- if trustcache != newTrustcachePath && FileManager.default.fileExists(atPath: newTrustcachePath.path) {+ let newTrustcachePath = restoreDir.appending(path: "Firmware").appending(path: trustcache.lastPathComponent)+ if trustcache != newTrustcachePath, FileManager.default.fileExists(atPath: newTrustcachePath.path) {try FileManager.default.removeItem(at: newTrustcachePath)}try FileManager.default.moveItem(at: trustcache, to: newTrustcachePath)identityManifest = try updateManifestComponentPath(identityManifest: identityManifest,component: "StaticTrustCache",- at: newTrustcachePath+ at: newTrustcachePath,)- let newMetadataPath = self.restoreDir.appending(path: "Firmware").appending(path: metadata.lastPathComponent)- if metadata != newMetadataPath && FileManager.default.fileExists(atPath: newMetadataPath.path) {+ let newMetadataPath = restoreDir.appending(path: "Firmware").appending(path: metadata.lastPathComponent)+ if metadata != newMetadataPath, FileManager.default.fileExists(atPath: newMetadataPath.path) {try FileManager.default.removeItem(at: newMetadataPath)}try FileManager.default.moveItem(at: metadata, to: newMetadataPath)identityManifest = try updateManifestComponentPath(identityManifest: identityManifest,component: "Ap,SystemVolumeCanonicalMetadata",- at: newMetadataPath+ at: newMetadataPath,)- let newRootHashPath = self.restoreDir.appending(path: "Firmware").appending(path: rootHash.lastPathComponent)- if rootHash != newRootHashPath && FileManager.default.fileExists(atPath: newRootHashPath.path) {+ let newRootHashPath = restoreDir.appending(path: "Firmware").appending(path: rootHash.lastPathComponent)+ if rootHash != newRootHashPath, FileManager.default.fileExists(atPath: newRootHashPath.path) {try FileManager.default.removeItem(at: newRootHashPath)}try FileManager.default.moveItem(at: rootHash, to: newRootHashPath)identityManifest = try updateManifestComponentPath(identityManifest: identityManifest,component: "SystemVolume",- at: newRootHashPath+ at: newRootHashPath,)buildIdentity["Manifest"] = identityManifest@@ -77,7 +78,7 @@ extension CryptexFilesystemPatcher {func updateManifestComponentPath(identityManifest: PlistDict, component: String, at: URL) throws -> PlistDict {var identityManifest = identityManifest- let pathSuffix = relativePath(from: at, base: self.restoreDir.appendingPathComponent("", isDirectory: true))+ let pathSuffix = relativePath(from: at, base: restoreDir.appendingPathComponent("", isDirectory: true))var comp = try getChildPlistDict(parent: identityManifest, key: component)var info = try getChildPlistDict(parent: comp, key: "Info")info["Path"] = pathSuffix@@ -105,7 +106,7 @@ extension CryptexFilesystemPatcher {}func componentPath(_ component: String) throws -> String {- let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")+ let path = restoreDir.appending(path: "iPhone-BuildManifest.plist")let manifest = try getBuildIdentityManifest(path: path)return try getComponentPath(component: component, buildManifest: manifest)}@@ -120,7 +121,7 @@ extension CryptexFilesystemPatcher {}func getBuildIdentityManifest(path: URL) throws -> PlistDict {- let data = try Data.init(contentsOf: path)+ let data = try Data(contentsOf: path)return try getBuildIdentityManifest(data: data)}@@ -128,7 +129,8 @@ extension CryptexFilesystemPatcher {let buildManifest = try parsePlist(data: data)guard let buildIdentities = buildManifest["BuildIdentities"] as? [Any],buildIdentities.count > 0,- let buildIdentity = buildIdentities.first! as? PlistDict else {+ let buildIdentity = buildIdentities.first! as? PlistDict+ else {throw FirmwareManifest.ManifestError.missingKey("Component in BuildManifest")}return try getChildPlistDict(parent: buildIdentity, key: "Manifest")@@ -138,7 +140,7 @@ extension CryptexFilesystemPatcher {guard let buildManifest = try PropertyListSerialization.propertyList(from: data,options: [],- format: nil+ format: nil,) as? PlistDict else {throw FirmwareManifest.ManifestError.invalidPlist("")}diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swiftindex ad03b801..56c7b460 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift@@ -21,7 +21,7 @@ extension CryptexFilesystemPatcher {func runProcess(_ launchPath: String,_ arguments: [String],- output: URL? = nil+ output: URL? = nil,) throws -> String {let process = Process()process.executableURL = URL(fileURLWithPath: launchPath)@@ -29,7 +29,7 @@ extension CryptexFilesystemPatcher {let outPipe = Pipe()if let output {- let outFile = try FileHandle.init(forWritingTo: output)+ let outFile = try FileHandle(forWritingTo: output)process.standardOutput = outFileprocess.standardError = outFile} else {diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swiftindex db58f4cc..071de3d2 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift@@ -8,19 +8,19 @@ import Foundationimport Img4toolextension CryptexFilesystemPatcher {- // `ipsw img4 im4p create --type T --version V` three times over. Img4tool is- // already a dependency of this module and builds the same DER: the IM4P- // SEQUENCE is the string "IM4P", the four-character type, the description- // — which is what ipsw's `--version` set — and the payload OCTET STRING.- // Dropping the subprocess takes the last Homebrew program out of the- // firmware pipeline.+ /// `ipsw img4 im4p create --type T --version V` three times over. Img4tool is+ /// already a dependency of this module and builds the same DER: the IM4P+ /// SEQUENCE is the string "IM4P", the four-character type, the description+ /// — which is what ipsw's `--version` set — and the payload OCTET STRING.+ /// Dropping the subprocess takes the last Homebrew program out of the+ /// firmware pipeline.private func wrap(_ payload: URL, fourcc: String, description: String, named: String) throws -> URL {let im4pPath = try createTmpDir().appending(path: named)// Mapped: the mtree .aar this wraps is the whole system volume's// metadata and runs to hundreds of megabytes.let im4p = try IM4P(fourcc: fourcc, description: description,- payload: Data(contentsOf: payload, options: .mappedIfSafe)+ payload: Data(contentsOf: payload, options: .mappedIfSafe),)try im4p.data.write(to: im4pPath)return im4pPath@@ -45,7 +45,7 @@ extension CryptexFilesystemPatcher {_ = try runProcess("/usr/bin/aa", ["archive","-d", tmpDir.path,- "-o", archivePath.path+ "-o", archivePath.path,])return try wrap(archivePath, fourcc: "msys", description: "0", named: "metadata.mtree")@@ -57,7 +57,7 @@ extension CryptexFilesystemPatcher {// wherever fw_prepare.sh's download_apfs_sealvolume() wrote the file; unset// (dev Makefile flow) falls back to the historical repo-relative `.tools/`.let sealDir = ProcessInfo.processInfo.environment["VPHONE_SEAL_DIR"].map { URL(fileURLWithPath: $0) }- ?? self.vphoneCliDirectory.appending(path: ".tools")+ ?? vphoneCliDirectory.appending(path: ".tools")let path = sealDir.appendingPathComponent("apfs_sealvolume_\(iosVersion)")guard FileManager.default.fileExists(atPath: path.path) else {throw FirmwareManifest.ManifestError.fileNotFound(path.path)@@ -83,17 +83,17 @@ extension CryptexFilesystemPatcher {// Therefore, we parse the modification time of /private/var.let modificationTime = try parsePrivateVarTime(mtree: mtree)let remapContent = """- <?xml version="1.0" encoding="UTF-8"?>- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">- <plist version="1.0">- <dict>- \(remap ? """- <key>MODIFICATION</key>- <integer>\(modificationTime)</integer>- """ : "")- </dict>- </plist>- """+ <?xml version="1.0" encoding="UTF-8"?>+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+ <plist version="1.0">+ <dict>+ \(remap ? """+ <key>MODIFICATION</key>+ <integer>\(modificationTime)</integer>+ """ : "")+ </dict>+ </plist>+ """print("Modification time: \(remap ? modificationTime : "none")")FileManager.default.createFile(atPath: mtreeRemapPath.path, contents: remapContent.data(using: .utf8))@@ -104,14 +104,15 @@ extension CryptexFilesystemPatcher {"-R", mtreeRemapPath.path,"-U", digestDbPath.path, // Save digest records"-M", rootHashPath.path, // Save root hash- device+ device,], output: sealLogPath)return (digestDbPath, rootHashPath)}func parsePrivateVarTime(mtree: URL) throws -> String {guard let mtreeData = FileManager.default.contents(atPath: mtree.path),- let text = String(data: mtreeData, encoding: .utf8) else {+ let text = String(data: mtreeData, encoding: .utf8)+ else {throw FirmwareManifest.ManifestError.fileNotFound(mtree.path)}let lines = text.split(whereSeparator: \.isNewline).map(String.init)@@ -133,7 +134,8 @@ extension CryptexFilesystemPatcher {// Extract time=...guard let match = line.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#,- options: .regularExpression) else {+ options: .regularExpression)+ else {throw FirmwareManifest.ManifestError.fileNotFound("modification time for /private/var in \(mtree.path)")}@@ -184,8 +186,8 @@ extension CryptexFilesystemPatcher {defer { try? detachImage(deviceNode: device) }let oldTrustcache = try componentPath("StaticTrustCache")- let oldTrustcachePath = self.restoreDir.appending(path: oldTrustcache)- let newTrustcachePath = self.restoreDir.appending(path: "Firmware/new.trustcache")+ let oldTrustcachePath = restoreDir.appending(path: oldTrustcache)+ let newTrustcachePath = restoreDir.appending(path: "Firmware/new.trustcache")let tmpDir = try createTmpDir()let tcContainer = tmpDir.appending(path: "new.trustcache")@@ -193,7 +195,7 @@ extension CryptexFilesystemPatcher {"generate-trust-cache", "--type", "static","--base-trust-cache", oldTrustcachePath.path,"--output-file", tcContainer.path,- mount+ mount,])if FileManager.default.fileExists(atPath: newTrustcachePath.path) {diff --git a/sources/FirmwarePatcher/IBoot/IBootJBPatcher.swift b/sources/FirmwarePatcher/IBoot/IBootJBPatcher.swiftindex 646d0a35..1a0d686f 100644--- a/sources/FirmwarePatcher/IBoot/IBootJBPatcher.swift+++ b/sources/FirmwarePatcher/IBoot/IBootJBPatcher.swift@@ -27,7 +27,9 @@ public final class IBootJBPatcher: IBootPatcher {let stringOffsets = buffer.findAll(needle)if stringOffsets.isEmpty {- if verbose { print(" [-] iBSS JB: no refs to 'boot-nonce'") }+ if verbose {+ print(" [-] iBSS JB: no refs to 'boot-nonce'")+ }return false}@@ -43,7 +45,9 @@ public final class IBootJBPatcher: IBootPatcher {}if addOffsets.isEmpty {- if verbose { print(" [-] iBSS JB: no ADRP+ADD refs to 'boot-nonce'") }+ if verbose {+ print(" [-] iBSS JB: no ADRP+ADD refs to 'boot-nonce'")+ }return false}@@ -120,7 +124,7 @@ public final class IBootJBPatcher: IBootPatcher {patchedBytes: patchBytes,beforeDisasm: beforeStr,afterDisasm: afterStr,- description: "JB: skip generate_nonce"+ description: "JB: skip generate_nonce",)patches.append(record)@@ -129,14 +133,16 @@ public final class IBootJBPatcher: IBootPatcher {format: " 0x%06X: %@ → %@ [ibss_jb.skip_generate_nonce]",scan,beforeStr,- afterStr+ afterStr,))}return true}}- if verbose { print(" [-] iBSS JB: generate_nonce branch pattern not found") }+ if verbose {+ print(" [-] iBSS JB: generate_nonce branch pattern not found")+ }return false}diff --git a/sources/FirmwarePatcher/IBoot/IBootPatcher.swift b/sources/FirmwarePatcher/IBoot/IBootPatcher.swiftindex f458046d..4d19ac7d 100644--- a/sources/FirmwarePatcher/IBoot/IBootPatcher.swift+++ b/sources/FirmwarePatcher/IBoot/IBootPatcher.swift@@ -120,7 +120,7 @@ public class IBootPatcher: Patcher {patchedBytes: patchBytes,beforeDisasm: beforeStr,afterDisasm: afterStr,- description: description+ description: description,)patches.append(record)@@ -142,7 +142,7 @@ public class IBootPatcher: Patcher {patchedBytes: data,beforeDisasm: "",afterDisasm: repr(txt),- description: description+ description: description,)patches.append(record)diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swiftindex 5d44fa3f..76fc0c9f 100644--- a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swift+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swift@@ -22,17 +22,23 @@ extension IBootPatcher {guard let newArgsData = newArgs.data(using: .ascii) else { return }guard let fmtOff = findBootArgsFmt() else {- if verbose { print(" [-] boot-args: format string not found") }+ if verbose {+ print(" [-] boot-args: format string not found")+ }return}guard let (adrpOff, addOff) = findBootArgsAdrp(fmtOff: fmtOff) else {- if verbose { print(" [-] boot-args: ADRP+ADD x2 not found") }+ if verbose {+ print(" [-] boot-args: ADRP+ADD x2 not found")+ }return}guard let newOff = findStringSlot(length: newArgsData.count) else {- if verbose { print(" [-] boot-args: no NUL slot") }+ if verbose {+ print(" [-] boot-args: no NUL slot")+ }return}@@ -41,7 +47,9 @@ extension IBootPatcher {// Re-encode ADRP x2 → new pageguard let newAdrp = ARM64Encoder.encodeADRP(rd: 2, pc: UInt64(adrpOff), target: UInt64(newOff)) else {- if verbose { print(" [-] boot-args: ADRP encoding out of range") }+ if verbose {+ print(" [-] boot-args: ADRP encoding out of range")+ }return}emit(adrpOff, newAdrp, id: "\(component).boot_args_adrp", description: "boot-args: adrp x2 → new string page")@@ -49,7 +57,9 @@ extension IBootPatcher {// Re-encode ADD x2, x2, #offsetlet imm12 = UInt32(newOff & 0xFFF)guard let newAdd = ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: imm12) else {- if verbose { print(" [-] boot-args: ADD encoding out of range") }+ if verbose {+ print(" [-] boot-args: ADD encoding out of range")+ }return}emit(addOff, newAdd, id: "\(component).boot_args_add", description: "boot-args: add x2 → new string offset")@@ -76,7 +86,9 @@ extension IBootPatcher {while off < searchEnd {guard let range = raw.range(of: pctS, in: off ..< min(searchEnd, raw.count)) else { return nil }let found = raw.distance(from: raw.startIndex, to: range.lowerBound)- if found >= off + raw.count { return nil }+ if found >= off + raw.count {+ return nil+ }// Must have NUL before and NUL after (isolated "%s\0")if found > 0, raw[found - 1] == 0, found + 2 < raw.count, raw[found + 2] == 0 {diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swiftindex 6c0aa989..b5f96c12 100644--- a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swift+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swift@@ -30,7 +30,7 @@ extension IBootPatcher {/// Refuses to patch on ambiguity (multiple matches).func patchBootxPrecondition() {let hashGetters = enumerateHashGetters()- let bitGetters = enumerateBitGetters()+ let bitGetters = enumerateBitGetters()guard !hashGetters.isEmpty, !bitGetters.isEmpty else {if verbose {@@ -41,7 +41,9 @@ extension IBootPatcher {let panicBlocks = enumeratePanicBlocks(hashGetters: hashGetters)if panicBlocks.isEmpty {- if verbose { print(" [-] bootx precondition: no panic-shaped call blocks") }+ if verbose {+ print(" [-] bootx precondition: no panic-shaped call blocks")+ }return}@@ -79,13 +81,17 @@ extension IBootPatcher {if gates.isEmpty {// 26.4+ construct; genuinely absent on previous iBoot versions.- if verbose { print(" [.] bootx precondition: construct not present (pre-26.4 iBoot) — skipping") }+ if verbose {+ print(" [.] bootx precondition: construct not present (pre-26.4 iBoot) — skipping")+ }return}if gates.count > 1 {if verbose {print(" [-] bootx precondition: ambiguous (\(gates.count) candidates)")- for g in gates.sorted() { print(String(format: " 0x%X", g)) }+ for g in gates.sorted() {+ print(String(format: " 0x%X", g))+ }}return}@@ -94,7 +100,7 @@ extension IBootPatcher {gate,ARM64.nop,id: "\(component).bootx_precondition",- description: "bootx precondition: NOP gate TBZ"+ description: "bootx precondition: NOP gate TBZ",)}@@ -111,7 +117,7 @@ extension IBootPatcher {guard insns[i + 1].mnemonic == "movk" else { continue }guard insns[i + 2].mnemonic == "movk" else { continue }guard insns[i + 3].mnemonic == "movk" else { continue }- guard insns[i + 4].mnemonic == "ret" else { continue }+ guard insns[i + 4].mnemonic == "ret" else { continue }// All four MOV/MOVK destinations must be the same register.var regs = Set<UInt32>()var ok = true@@ -166,7 +172,7 @@ extension IBootPatcher {for i in 0 ..< (insns.count - 2) {guardinsns[i].mnemonic == "bl",- (insns[i + 1].mnemonic == "mov" || insns[i + 1].mnemonic == "movz"),+ insns[i + 1].mnemonic == "mov" || insns[i + 1].mnemonic == "movz",insns[i + 2].mnemonic == "bl"else { continue }guarddiff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swiftindex 864dd050..6c5ce5e2 100644--- a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swift+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swift@@ -51,7 +51,9 @@ extension IBootPatcher {}if candidates.isEmpty {- if verbose { print(" [-] image4 callback: pattern not found") }+ if verbose {+ print(" [-] image4 callback: pattern not found")+ }return}@@ -67,7 +69,7 @@ extension IBootPatcher {off + 4,ARM64.movX0_0,id: "\(component).image4_callback_mov",- description: "image4 callback: mov x0,x22 → mov x0,#0"+ description: "image4 callback: mov x0,x22 → mov x0,#0",)}}diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swiftindex 752f9368..d3fb6f50 100644--- a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swift+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swift@@ -38,7 +38,7 @@ extension IBootPatcher {step + 4,ARM64.nop,id: "\(component).panic_bypass",- description: "panic bypass: NOP cbnz w0"+ description: "panic bypass: NOP cbnz w0",)return}@@ -48,6 +48,8 @@ extension IBootPatcher {}}- if verbose { print(" [-] panic bypass: pattern not found") }+ if verbose {+ print(" [-] panic bypass: pattern not found")+ }}}diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swiftindex c21a05a3..f32ec4d3 100644--- a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swift+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swift@@ -41,11 +41,15 @@ extension IBootPatcher {let cbzOff = errOff - 4guard let insn = disasm.disassembleOne(in: buffer.original, at: cbzOff) else {- if verbose { print(" [-] \(description): no instruction at 0x\(String(format: "%X", cbzOff))") }+ if verbose {+ print(" [-] \(description): no instruction at 0x\(String(format: "%X", cbzOff))")+ }return}guard insn.mnemonic == "cbz" || insn.mnemonic == "cbnz" else {- if verbose { print(" [-] \(description): expected cbz/cbnz at 0x\(String(format: "%X", cbzOff)), got \(insn.mnemonic)") }+ if verbose {+ print(" [-] \(description): expected cbz/cbnz at 0x\(String(format: "%X", cbzOff)), got \(insn.mnemonic)")+ }return}@@ -54,7 +58,9 @@ extension IBootPatcher {let target = Int(detail.operands[1].imm)guard let bInsn = ARM64Encoder.encodeB(from: cbzOff, to: target) else {- if verbose { print(" [-] \(description): B encoding out of range") }+ if verbose {+ print(" [-] \(description): B encoding out of range")+ }return}@@ -72,12 +78,16 @@ extension IBootPatcher {let bhsOff = Int(insn.address) + 4guard let next = disasm.disassembleOne(in: buffer.original, at: bhsOff),next.mnemonic == "b.hs" else { continue }- if !bhsSites.contains(bhsOff) { bhsSites.append(bhsOff) }+ if !bhsSites.contains(bhsOff) {+ bhsSites.append(bhsOff)+ }}}guard bhsSites.count == 1 else {- if verbose { print(" [-] rootfs b.hs: expected 1 'cmp x8,#0x400 ; b.hs' pair, found \(bhsSites.count)") }+ if verbose {+ print(" [-] rootfs b.hs: expected 1 'cmp x8,#0x400 ; b.hs' pair, found \(bhsSites.count)")+ }return}@@ -85,7 +95,7 @@ extension IBootPatcher {bhsSites[0],ARM64.nop,id: "\(component).rootfs_bhs_0x400",- description: "rootfs: NOP b.hs size check (0x400)"+ description: "rootfs: NOP b.hs size check (0x400)",)}@@ -97,7 +107,9 @@ extension IBootPatcher {let locs = buffer.findAll(pattern)guard locs.count == 1 else {- if verbose { print(" [-] rootfs null check: expected 1 'mov w8, #0x110', found \(locs.count)") }+ if verbose {+ print(" [-] rootfs null check: expected 1 'mov w8, #0x110', found \(locs.count)")+ }return}@@ -123,13 +135,15 @@ extension IBootPatcher {scan + 4,ARM64.nop,id: "\(component).rootfs_null_check_0x78",- description: "rootfs: NOP cbz x8 null check (#0x78)"+ description: "rootfs: NOP cbz x8 null check (#0x78)",)return}scan -= 4}- if verbose { print(" [-] rootfs null check: ldr+cbz #0x78 pattern not found") }+ if verbose {+ print(" [-] rootfs null check: ldr+cbz #0x78 pattern not found")+ }}}diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swiftindex 787a4e68..77e59c3a 100644--- a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swift+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swift@@ -45,10 +45,14 @@ extension IBootPatcher {searchStart = range.upperBound}if labelCount >= 2 {- if verbose { print(" [*] serial labels: already present, skipping") }+ if verbose {+ print(" [*] serial labels: already present, skipping")+ }return}- if verbose { print(" [-] serial labels: <2 banner runs found") }+ if verbose {+ print(" [-] serial labels: <2 banner runs found")+ }return}diff --git a/sources/FirmwarePatcher/Kernel/EXPPatches/KernelEXPPatchHvVmmRename.swift b/sources/FirmwarePatcher/Kernel/EXPPatches/KernelEXPPatchHvVmmRename.swiftindex 457d072f..fcffd9e6 100644--- a/sources/FirmwarePatcher/Kernel/EXPPatches/KernelEXPPatchHvVmmRename.swift+++ b/sources/FirmwarePatcher/Kernel/EXPPatches/KernelEXPPatchHvVmmRename.swift@@ -148,7 +148,7 @@ extension KernelEXPPatcher {patchID: "kernelcache_exp.hv_vmm_oid_rename",virtualAddress: va,description: "Part A: rename OID name 'h' -> 'X' "- + "('hv_vmm_present' -> 'Xv_vmm_present')")+ + "('hv_vmm_present' -> 'Xv_vmm_present')")return true}@@ -176,16 +176,16 @@ extension KernelEXPPatcher {// 21 bytes total (leading NUL + 19 cstring bytes + trailing NUL).// Mangle offset within the needle: 1 (skip leading NUL) + 5 = 6.let cstrOriginalNeedle = Data([- 0x00, // \0- 0x6B, 0x65, 0x72, 0x6E, 0x2E, // "kern."- 0x68, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "hv_vmm_"- 0x70, 0x72, 0x65, 0x73, 0x65, 0x6E, 0x74, // "present"- 0x00, // \0+ 0x00, // \0+ 0x6B, 0x65, 0x72, 0x6E, 0x2E, // "kern."+ 0x68, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "hv_vmm_"+ 0x70, 0x72, 0x65, 0x73, 0x65, 0x6E, 0x74, // "present"+ 0x00, // \0])let cstrPatchedNeedle = Data([0x00,- 0x6B, 0x65, 0x72, 0x6E, 0x2E, // "kern."- 0x58, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "Xv_vmm_"+ 0x6B, 0x65, 0x72, 0x6E, 0x2E, // "kern."+ 0x58, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "Xv_vmm_"0x70, 0x72, 0x65, 0x73, 0x65, 0x6E, 0x74,0x00,])@@ -194,14 +194,14 @@ extension KernelEXPPatcher {// 20 bytes total (19 name bytes + trailing \x0f). No leading byte// in the needle. Mangle offset within the needle: 5.let tlvOriginalNeedle = Data([- 0x6B, 0x65, 0x72, 0x6E, 0x2E, // "kern."- 0x68, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "hv_vmm_"- 0x70, 0x72, 0x65, 0x73, 0x65, 0x6E, 0x74, // "present"- 0x0F, // sandbox EOT+ 0x6B, 0x65, 0x72, 0x6E, 0x2E, // "kern."+ 0x68, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "hv_vmm_"+ 0x70, 0x72, 0x65, 0x73, 0x65, 0x6E, 0x74, // "present"+ 0x0F, // sandbox EOT])let tlvPatchedNeedle = Data([0x6B, 0x65, 0x72, 0x6E, 0x2E,- 0x58, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "Xv_vmm_"+ 0x58, 0x76, 0x5F, 0x76, 0x6D, 0x6D, 0x5F, // "Xv_vmm_"0x70, 0x72, 0x65, 0x73, 0x65, 0x6E, 0x74,0x0F,])@@ -246,9 +246,9 @@ extension KernelEXPPatcher {patchID: "kernelcache_exp.hv_vmm_internal_caller_mangle",virtualAddress: va,description: "Part B (\(site.label)): byte-5 mangle "- + "'h' -> 'X' at foff 0x"- + String(format: "%X", mangleOffset)- + " ('kern.hv_vmm_present' -> 'kern.Xv_vmm_present')")+ + "'h' -> 'X' at foff 0x"+ + String(format: "%X", mangleOffset)+ + " ('kern.hv_vmm_present' -> 'kern.Xv_vmm_present')")totalWritten += 1}}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiExecve.swift b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiExecve.swiftindex 152c3de9..e71cea9b 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiExecve.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiExecve.swift@@ -69,7 +69,9 @@ extension KernelJBPatcher {// Function end = next PACIBSP (capped at 0x800 bytes).var funcEnd = findFuncEnd(funcStart, maxSize: 0x800)- if let (_, ke) = kernTextRange { funcEnd = min(funcEnd, ke) }+ if let (_, ke) = kernTextRange {+ funcEnd = min(funcEnd, ke)+ }// Scan backward from funcEnd for MOV W0, #1 followed by LDP X29, X30, [SP, #imm].var targetOff = -1@@ -97,7 +99,7 @@ extension KernelJBPatcher {targetOff,ARM64.movW0_0,patchID: "jb.amfi_execve.kill_return",- description: "mov w0,#0 [AMFI kill return → allow]"+ description: "mov w0,#0 [AMFI kill return → allow]",)log(" [+] Patched kill return at 0x\(String(format: "%X", targetOff)) (func 0x\(String(format: "%X", funcStart)))")diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiTrustcache.swift b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiTrustcache.swiftindex 74023851..024c05b3 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiTrustcache.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchAmfiTrustcache.swift@@ -135,28 +135,28 @@ extension KernelJBPatcher {ARM64.movX0_1,patchID: "amfi_trustcache_1",virtualAddress: va0,- description: "mov x0,#1 [AMFIIsCDHashInTrustCache]"+ description: "mov x0,#1 [AMFIIsCDHashInTrustCache]",)emit(funcStart + 4,ARM64.cbzX2_8,patchID: "amfi_trustcache_2",virtualAddress: va1,- description: "cbz x2,+8 [AMFIIsCDHashInTrustCache]"+ description: "cbz x2,+8 [AMFIIsCDHashInTrustCache]",)emit(funcStart + 8,ARM64.strX0X2,patchID: "amfi_trustcache_3",virtualAddress: va2,- description: "str x0,[x2] [AMFIIsCDHashInTrustCache]"+ description: "str x0,[x2] [AMFIIsCDHashInTrustCache]",)emit(funcStart + 12,ARM64.ret,patchID: "amfi_trustcache_4",virtualAddress: va3,- description: "ret [AMFIIsCDHashInTrustCache]"+ description: "ret [AMFIIsCDHashInTrustCache]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchCredLabel.swift b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchCredLabel.swiftindex b86902d3..72ed9938 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchCredLabel.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchCredLabel.swift@@ -107,7 +107,7 @@ extension KernelJBPatcher {dCaveOff + i,Data(chunk),patchID: "jb.cred_label_update_execve.deny_cave",- description: "deny_trampoline+\(i) [_cred_label_update_execve C21-v3]"+ description: "deny_trampoline+\(i) [_cred_label_update_execve C21-v3]",)}@@ -120,7 +120,7 @@ extension KernelJBPatcher {dOff,branchToCave,patchID: "jb.cred_label_update_execve.deny_redirect",- description: "b deny cave [_cred_label_update_execve C21-v3 exit @ 0x\(String(format: "%X", dOff))]"+ description: "b deny cave [_cred_label_update_execve C21-v3 exit @ 0x\(String(format: "%X", dOff))]",)}@@ -160,7 +160,7 @@ extension KernelJBPatcher {successCaveOff + i,Data(chunk),patchID: "jb.cred_label_update_execve.success_cave",- description: "success_trampoline+\(i) [_cred_label_update_execve C21-v3]"+ description: "success_trampoline+\(i) [_cred_label_update_execve C21-v3]",)}@@ -174,7 +174,7 @@ extension KernelJBPatcher {exitOff,branchToCave,patchID: "jb.cred_label_update_execve.success_redirect",- description: "b success cave [_cred_label_update_execve C21-v3 exit @ 0x\(String(format: "%X", exitOff))]"+ description: "b success cave [_cred_label_update_execve C21-v3 exit @ 0x\(String(format: "%X", exitOff))]",)}}@@ -275,7 +275,9 @@ extension KernelJBPatcher {break}}- if hasMov { exits.append(off) }+ if hasMov {+ exits.append(off)+ }}return exits}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchHookCredLabel.swift b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchHookCredLabel.swiftindex e0928a01..e8b14e22 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchHookCredLabel.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchHookCredLabel.swift@@ -23,12 +23,12 @@ extension KernelJBPatcher {private static let hookCredLabelIndex = 18private static let c23CaveWords = 46 // Must match Python _C23_CAVE_WORDS- // Stable prologue prefix of vfs_context_current (4 words, version-independent).- // The function reads current_thread() from tpidr_el1, then loads the- // uthread/uu_context pointer via `ldr x1, [x0, #uthread_off]`. Only that final- // immediate drifts across versions (0x3E0 on 26.1, 0x3E8 on macOS 26.5.1,- // 0x3F0 on iOS 26.5), so we match the 4 fixed words exactly and require the- // 5th to be *any* `ldr x1, [x0, #imm]` — never pinning the version-specific offset.+ /// Stable prologue prefix of vfs_context_current (4 words, version-independent).+ /// The function reads current_thread() from tpidr_el1, then loads the+ /// uthread/uu_context pointer via `ldr x1, [x0, #uthread_off]`. Only that final+ /// immediate drifts across versions (0x3E0 on 26.1, 0x3E8 on macOS 26.5.1,+ /// 0x3F0 on iOS 26.5), so we match the 4 fixed words exactly and require the+ /// 5th to be *any* `ldr x1, [x0, #imm]` — never pinning the version-specific offset.private static let vfsContextCurrentPrefix: [UInt32] = [ARM64.pacibspU32, // pacibspARM64.stpFP_LR_pre, // stp x29, x30, [sp, #-0x10]!@@ -74,7 +74,7 @@ extension KernelJBPatcher {caveOff: caveOff,vfsContextCurrentOff: vfsCtxOff,vnodeGetattrOff: vnodeGetattrOff,- wrapperOff: wrapperOff+ wrapperOff: wrapperOff,) else {log(" [-] failed to encode faithful C23 branch/call relocations")return false@@ -90,14 +90,14 @@ extension KernelJBPatcher {entryOff,newEntry,patchID: "jb.hook_cred_label.ops_retarget",- description: "retarget ops[\(Self.hookCredLabelIndex)] to faithful C23 cave [_hook_cred_label_update_execve]"+ description: "retarget ops[\(Self.hookCredLabelIndex)] to faithful C23 cave [_hook_cred_label_update_execve]",)emit(caveOff,caveBytes,patchID: "jb.hook_cred_label.c23_cave",- description: "faithful upstream C23 cave (vnode getattr -> uid/gid/P_SUGID fixup -> wrapper)"+ description: "faithful upstream C23 cave (vnode getattr -> uid/gid/P_SUGID fixup -> wrapper)",)_ = opsTable@@ -138,11 +138,15 @@ extension KernelJBPatcher {while i <= dEnd - 40 {defer { i += 8 }let val = buffer.readU64(at: i)- if val == 0 || (val & (1 << 63)) != 0 { continue }+ if val == 0 || (val & (1 << 63)) != 0 {+ continue+ }guard (val & 0x7FF_FFFF_FFFF) == UInt64(sandboxOff) else { continue }let val2 = buffer.readU64(at: i + 8)- if (val2 & (1 << 63)) != 0 { continue }+ if (val2 & (1 << 63)) != 0 {+ continue+ }guard (val2 & 0x7FF_FFFF_FFFF) == UInt64(seatbeltOff) else { continue }let valOps = buffer.readU64(at: i + 32)@@ -203,7 +207,9 @@ extension KernelJBPatcher {/// uthread offset is version-specific and deliberately left unpinned).private func findVfsContextCurrentByShape() -> Int {let cacheKey = "c23_vfs_context_current"- if let cached = jbScanCache[cacheKey] { return cached }+ if let cached = jbScanCache[cacheKey] {+ return cached+ }// Symbol fast-path (version-independent; this research kernel is stripped here, but free + future-proof).if let sym = resolveSymbol("_vfs_context_current"),@@ -337,7 +343,7 @@ extension KernelJBPatcher {caveOff: Int,vfsContextCurrentOff: Int,vnodeGetattrOff: Int,- wrapperOff: Int+ wrapperOff: Int,) -> Data? {var code: [Data] = []diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchLoadDylinker.swift b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchLoadDylinker.swiftindex 2726a0c1..c050e913 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchLoadDylinker.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchLoadDylinker.swift@@ -42,7 +42,7 @@ extension KernelJBPatcher {bBytes,patchID: "jb.load_dylinker.policy_bypass",virtualAddress: fileOffsetToVA(blOff),- description: "b #0x\(String(format: "%X", allowTarget - blOff)) [_load_dylinker policy bypass]"+ description: "b #0x\(String(format: "%X", allowTarget - blOff)) [_load_dylinker policy bypass]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchPostValidation.swift b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchPostValidation.swiftindex 9bd6c264..971396ac 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchPostValidation.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/CodeSigning/KernelJBPatchPostValidation.swift@@ -113,7 +113,7 @@ extension KernelJBPatcher {ARM64.cmpW0W0,patchID: "jb.post_validation.cmp_w0_w0",virtualAddress: fileOffsetToVA(patchOff),- description: "cmp w0,w0 [postValidation additional]"+ description: "cmp w0,w0 [postValidation additional]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchIomfbSwap.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchIomfbSwap.swiftindex c94f1cff..66cd9ed6 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchIomfbSwap.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchIomfbSwap.swift@@ -29,8 +29,8 @@import Foundationextension KernelJBPatcher {- private static let swapEndExpectedSize: UInt32 = 0x588 // 26.4 kernel's native SwapEnd struct size- private static let swapEndIOS27Size: UInt32 = 0x6e0 // iOS 27's native IOMFBSwapRec size+ private static let swapEndExpectedSize: UInt32 = 0x588 // 26.4 kernel's native SwapEnd struct size+ private static let swapEndIOS27Size: UInt32 = 0x6E0 // iOS 27's native IOMFBSwapRec sizeprivate static let kIOUCVariableStructureSize: UInt32 = 0xFFFF_FFFF/// The swap_submit handler has a SECOND, internal exact-size gate beyond the@@ -78,7 +78,7 @@ extension KernelJBPatcher {word = (word & ~(UInt32(0xFFF) << 10)) | (Self.swapEndIOS27Size << 10)var le = word.littleEndianvar newBytes = Data(count: 4)- withUnsafeBytes(of: &le) { newBytes.replaceSubrange(0..<4, with: $0) }+ withUnsafeBytes(of: &le) { newBytes.replaceSubrange(0 ..< 4, with: $0) }let va = fileOffsetToVA(cmpOff)emit(@@ -86,7 +86,7 @@ extension KernelJBPatcher {newBytes,patchID: "iomfb_swapend_handler_size",virtualAddress: va,- description: "swap_submit cmp w2,#0x588 -> #0x6e0 [accept iOS 27 native SwapEnd struct]"+ description: "swap_submit cmp w2,#0x588 -> #0x6e0 [accept iOS 27 native SwapEnd struct]",)return true}@@ -129,7 +129,7 @@ extension KernelJBPatcher {let sizeFieldOff = entryOff + 12var newBytes = Data(count: 4)var v = Self.kIOUCVariableStructureSize.littleEndian- withUnsafeBytes(of: &v) { newBytes.replaceSubrange(0..<4, with: $0) }+ withUnsafeBytes(of: &v) { newBytes.replaceSubrange(0 ..< 4, with: $0) }let va = fileOffsetToVA(sizeFieldOff)emit(@@ -137,7 +137,7 @@ extension KernelJBPatcher {newBytes,patchID: "iomfb_swapend_variable_size",virtualAddress: va,- description: "SwapEnd checkStructureInputSize 0x588 -> variable [accept iOS 27 native IOMFBSwapRec]"+ description: "SwapEnd checkStructureInputSize 0x588 -> variable [accept iOS 27 native IOMFBSwapRec]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchNvram.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchNvram.swiftindex dc0fd4ce..59603f5c 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchNvram.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Drivers/KernelJBPatchNvram.swift@@ -61,7 +61,7 @@ extension KernelJBPatcher {ARM64.nop,patchID: "kernelcache_jb.nvram_verify_permission",virtualAddress: va,- description: "NOP [verifyPermission NVRAM]"+ description: "NOP [verifyPermission NVRAM]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchThreadSetState.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchThreadSetState.swiftindex 7d722e3a..ee654abb 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchThreadSetState.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchThreadSetState.swift@@ -62,7 +62,7 @@ extension KernelJBPatcher {let rd = wRegisterNumber(orig),let bytes = ARM64Encoder.encodeMovzW(rd: rd, imm16: Self.tssFlagsCleared),let check = disasm.disassembleOne(bytes, at: UInt64(setterOff)),- (check.mnemonic == "mov" || check.mnemonic == "movz"),+ check.mnemonic == "mov" || check.mnemonic == "movz",let ops = check.aarch64?.operands, ops.count == 2,ops[1].type == AARCH64_OP_IMM, ops[1].imm == Int64(Self.tssFlagsCleared)else {@@ -74,7 +74,7 @@ extension KernelJBPatcher {bytes,patchID: "kernelcache_frida.thread_set_state_entitlement_flag",virtualAddress: fileOffsetToVA(setterOff),- description: "clear TSSF_CHECK_ENTITLEMENT (0x201 -> 0x1) [thread_set_state user setter, --frida]"+ description: "clear TSSF_CHECK_ENTITLEMENT (0x201 -> 0x1) [thread_set_state user setter, --frida]",)}return truediff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchVmMapDelete.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchVmMapDelete.swiftindex 7b25a88a..bea567d7 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchVmMapDelete.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Frida/KernelJBPatchVmMapDelete.swift@@ -44,13 +44,13 @@ extension KernelJBPatcher {for gate in gates.sorted(by: { $0.offset < $1.offset }) {guard let bytes = ARM64Encoder.encodeTestBitBranch(nonzero: gate.nonzero, register: gate.register, bit: 13,- from: gate.offset, to: gate.target+ from: gate.offset, to: gate.target,),- let decoded = disasm.disassembleOne(bytes, at: UInt64(gate.offset)),- decoded.mnemonic == (gate.nonzero ? "tbnz" : "tbz"),- let ops = decoded.aarch64?.operands, ops.count == 3,- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 13,- ops[2].type == AARCH64_OP_IMM, Int(ops[2].imm) == gate.target+ let decoded = disasm.disassembleOne(bytes, at: UInt64(gate.offset)),+ decoded.mnemonic == (gate.nonzero ? "tbnz" : "tbz"),+ let ops = decoded.aarch64?.operands, ops.count == 3,+ ops[1].type == AARCH64_OP_IMM, ops[1].imm == 13,+ ops[2].type == AARCH64_OP_IMM, Int(ops[2].imm) == gate.targetelse {log(" [-] failed to assemble/verify max-X gate at 0x\(String(format: "%X", gate.offset))")return false@@ -64,7 +64,7 @@ extension KernelJBPatcher {bytes,patchID: "kernelcache_frida.vm_map_delete_immutable_code",virtualAddress: fileOffsetToVA(gate.offset),- description: "\(gate.nonzero ? "tbnz" : "tbz") entry max_protection.X [vm_map_delete immutable-code \(gate.shape), --frida]"+ description: "\(gate.nonzero ? "tbnz" : "tbz") entry max_protection.X [vm_map_delete immutable-code \(gate.shape), --frida]",)}return true@@ -124,7 +124,7 @@ extension KernelJBPatcher {register: flagsReg,nonzero: false,target: exec,- shape: "shape-A"+ shape: "shape-A",)}@@ -143,7 +143,7 @@ extension KernelJBPatcher {register: flagsReg,nonzero: true,target: exec,- shape: "shape-B"+ shape: "shape-B",)}@@ -189,8 +189,9 @@ extension KernelJBPatcher {guard insns[i].mnemonic == "ldrb", let devReg = destRegister(insns[i]) else { continue }for j in (i + 1) ..< min(insns.count, i + 4) {let m = insns[j].mnemonic- if (m == "tbz" || m == "tbnz"),- bitBranch(insns[j], mnemonic: m, register: devReg, bit: 0) != nil {+ if m == "tbz" || m == "tbnz",+ bitBranch(insns[j], mnemonic: m, register: devReg, bit: 0) != nil+ {return true}}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchPortToMap.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchPortToMap.swiftindex 42c50eb5..3f001e20 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchPortToMap.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchPortToMap.swift@@ -55,7 +55,7 @@ extension KernelJBPatcher {bBytes,patchID: "jb.port_to_map.skip_panic",virtualAddress: fileOffsetToVA(back + 4),- description: "b 0x\(String(format: "%X", branchTarget)) [_convert_port_to_map skip panic]"+ description: "b 0x\(String(format: "%X", branchTarget)) [_convert_port_to_map skip panic]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchSharedRegion.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchSharedRegion.swiftindex 06fffd9a..1477088a 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchSharedRegion.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchSharedRegion.swift@@ -56,7 +56,7 @@ extension KernelJBPatcher {ARM64.cmpX0X0,patchID: "kernelcache_jb.shared_region_map",virtualAddress: va,- description: "cmp x0,x0 [_shared_region_map_and_slide_setup]"+ description: "cmp x0,x0 [_shared_region_map_and_slide_setup]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmFault.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmFault.swiftindex 8354a874..6e270ee6 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmFault.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmFault.swift@@ -52,7 +52,7 @@ extension KernelJBPatcher {ARM64.nop,patchID: "kernelcache_jb.vm_fault_enter_prepare",virtualAddress: va,- description: "NOP [_vm_fault_enter_prepare]"+ description: "NOP [_vm_fault_enter_prepare]",)return true} else if candidateSites.count > 1 {diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swiftindex 6404b0d7..bb2a4d73 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swift@@ -102,7 +102,7 @@ extension KernelJBPatcher {patchID: "kernelcache_jb.vm_map_protect",virtualAddress: fileOffsetToVA(brOff),description: "b #0x\(String(format: "%X", delta)) "- + "[_vm_map_protect skip W^X downgrade, shape \(shape)]"+ + "[_vm_map_protect skip W^X downgrade, shape \(shape)]",)return true}@@ -124,7 +124,7 @@ extension KernelJBPatcher {}private func scanRange(- _ start: Int, _ end: Int, _ entryFlagBit: Int64, _ hits: inout [(Int, Int)]+ _ start: Int, _ end: Int, _ entryFlagBit: Int64, _ hits: inout [(Int, Int)],) {var off = startwhile off + 0x18 < end {@@ -182,7 +182,7 @@ extension KernelJBPatcher {// explicit shape tested, so this stays anchored on that flag and cannot// drift onto an unrelated fused compare.guard findEntryFlagMask(- before: off, limit: start, reg: flagsReg, bit: entryFlagBit+ before: off, limit: start, reg: flagsReg, bit: entryFlagBit,) != nil else { continue }// And the block it guards must be the downgrade.@@ -319,7 +319,9 @@ extension KernelJBPatcher {while p + 4 <= end {let insn = buffer.readU32(at: p)if ARM64Inst.isMOVZW(insn), ARM64Inst.rd(insn) == maskReg, ARM64Inst.movImm16(insn) == 5 {- if movOff >= 0 { movOff = -2; break } // ambiguous writer+ if movOff >= 0 {+ movOff = -2; break+ } // ambiguous writermovOff = p}p += 4diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchKcall10.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchKcall10.swiftindex 02e80766..1ee74762 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchKcall10.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchKcall10.swift@@ -45,7 +45,7 @@ extension KernelJBPatcher {let (mungerTarget, _, matchCount) = findMunge32ForNarg(sysEntOff: sysEntOff,narg: Self.kcall10_narg,- argBytes: Self.kcall10_arg_bytes+ argBytes: Self.kcall10_arg_bytes,)guard mungerTarget >= 0 else {log(" [-] no unique reusable 8-arg munge32 helper found")@@ -83,7 +83,7 @@ extension KernelJBPatcher {caveOff,caveBytes,patchID: "jb.kcall10.cave",- description: "kcall10 ABI-correct cave (target + 7 args -> uint64 x0)"+ description: "kcall10 ABI-correct cave (target + 7 args -> uint64 x0)",)emit(@@ -93,10 +93,10 @@ extension KernelJBPatcher {nextVal: callNext,diversity: Self.sysent_pac_diversity,key: 0,- addrDiv: 0+ addrDiv: 0,),patchID: "jb.kcall10.sy_call",- description: "sysent[439].sy_call = cave 0x\(String(format: "%X", caveOff)) (auth rebase, div=0xBCAD, next=\(callNext)) [kcall10]"+ description: "sysent[439].sy_call = cave 0x\(String(format: "%X", caveOff)) (auth rebase, div=0xBCAD, next=\(callNext)) [kcall10]",)emit(@@ -106,10 +106,10 @@ extension KernelJBPatcher {nextVal: mungeNext,diversity: mungeDiv,key: mungeKey,- addrDiv: mungeAddrDiv+ addrDiv: mungeAddrDiv,),patchID: "jb.kcall10.sy_munge",- description: "sysent[439].sy_arg_munge32 = 8-arg helper 0x\(String(format: "%X", mungerTarget)) [kcall10]"+ description: "sysent[439].sy_arg_munge32 = 8-arg helper 0x\(String(format: "%X", mungerTarget)) [kcall10]",)// sy_return_type (u32) + sy_narg (u16) + sy_arg_bytes (u16)@@ -123,7 +123,7 @@ extension KernelJBPatcher {entry439 + 16,metadata,patchID: "jb.kcall10.sysent_meta",- description: "sysent[439].sy_return_type=7,sy_narg=8,sy_arg_bytes=0x20 [kcall10]"+ description: "sysent[439].sy_return_type=7,sy_narg=8,sy_arg_bytes=0x20 [kcall10]",)return true@@ -144,8 +144,12 @@ extension KernelJBPatcher {for seg in segments where execSegNames.contains(seg.name) && seg.fileSize > 0 {execRanges.append((Int(seg.fileOffset), Int(seg.fileOffset + seg.fileSize)))}- if execRanges.isEmpty { execRanges = codeRanges.map { ($0.start, $0.end) } }- func inExec(_ fo: Int) -> Bool { fo > 0 && execRanges.contains { fo >= $0.0 && fo < $0.1 } }+ if execRanges.isEmpty {+ execRanges = codeRanges.map { ($0.start, $0.end) }+ }+ func inExec(_ fo: Int) -> Bool {+ fo > 0 && execRanges.contains { fo >= $0.0 && fo < $0.1 }+ }func validEntry(_ o: Int) -> Bool {guard o + Self.sysent_entry_size <= buffer.count else { return false }@@ -170,7 +174,9 @@ extension KernelJBPatcher {n += 1off += Self.sysent_entry_size}- if n > bestLen { bestLen = n; bestBase = runStart }+ if n > bestLen {+ bestLen = n; bestBase = runStart+ }} else {off += 8 // entries are 8-byte aligned}@@ -193,7 +199,7 @@ extension KernelJBPatcher {private func findMunge32ForNarg(sysEntOff: Int,narg: UInt16,- argBytes: UInt16+ argBytes: UInt16,) -> (Int, Int, Int) {var candidates: [Int: [Int]] = [:]for idx in 0 ..< Self.sysent_max_entries {@@ -301,7 +307,7 @@ extension KernelJBPatcher {nextVal: UInt32,diversity: UInt32,key: UInt32,- addrDiv: UInt32+ addrDiv: UInt32,) -> Data {let val: UInt64 =(UInt64(targetFoff) & 0x3FFF_FFFF) |diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchProcPidinfo.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchProcPidinfo.swiftindex 7ea626ad..a7450452 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchProcPidinfo.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchProcPidinfo.swift@@ -75,14 +75,14 @@ extension KernelJBPatcher {ARM64.nop,patchID: "jb.proc_pidinfo.nop_guard_a",virtualAddress: fileOffsetToVA(guardA),- description: "NOP [_proc_pidinfo pid-0 guard A]"+ description: "NOP [_proc_pidinfo pid-0 guard A]",)emit(guardB,ARM64.nop,patchID: "jb.proc_pidinfo.nop_guard_b",virtualAddress: fileOffsetToVA(guardB),- description: "NOP [_proc_pidinfo pid-0 guard B]"+ description: "NOP [_proc_pidinfo pid-0 guard B]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSpawnPersona.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSpawnPersona.swiftindex 384e8f03..e85bd238 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSpawnPersona.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSpawnPersona.swift@@ -42,14 +42,14 @@ extension KernelJBPatcher {ARM64.nop,patchID: "kernelcache_jb.spawn_validate_persona.cbz1",virtualAddress: va1,- description: "NOP [_spawn_validate_persona pid-slot guard]"+ description: "NOP [_spawn_validate_persona pid-slot guard]",)emit(secondCbz,ARM64.nop,patchID: "kernelcache_jb.spawn_validate_persona.cbz2",virtualAddress: va2,- description: "NOP [_spawn_validate_persona persona-slot guard]"+ description: "NOP [_spawn_validate_persona persona-slot guard]",)return true}@@ -70,7 +70,9 @@ extension KernelJBPatcher {}}- if matches.count == 1 { return matches[0] }+ if matches.count == 1 {+ return matches[0]+ }if !matches.isEmpty {let list = matches.map { String(format: "0x%X/0x%X", $0.0, $0.1) }.joined(separator: ", ")log(" [-] ambiguous persona helper candidates: \(list)")diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSyscallmask.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSyscallmask.swiftindex c1b2b449..cf8a9eac 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSyscallmask.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchSyscallmask.swift@@ -65,7 +65,7 @@ extension KernelJBPatcher {guard let (caveBytes, codeOff) = buildSyscallmaskCave(caveOff: caveOff,zallocOff: mutatorOff,- setterOff: setterOff+ setterOff: setterOff,) else {log(" [-] failed to encode C22 cave branches")return false@@ -83,21 +83,21 @@ extension KernelJBPatcher {callOff,ARM64.encodeU32(movX17X0),patchID: "jb.syscallmask.save_selector",- description: "mov x17,x0 [syscallmask C22 save RO selector]"+ description: "mov x17,x0 [syscallmask C22 save RO selector]",)emit(branchOff,branchToCave,patchID: "jb.syscallmask.tail_redirect",- description: "b cave [syscallmask C22 mutate mask then setter]"+ description: "b cave [syscallmask C22 mutate mask then setter]",)emit(caveOff,caveBytes,patchID: "jb.syscallmask.c22_cave",- description: "syscallmask C22 cave (ff blob 0x\(String(format: "%X", Self.syscallmaskFFBlobSize)) + structural mutator + setter tail)"+ description: "syscallmask C22 cave (ff blob 0x\(String(format: "%X", Self.syscallmaskFFBlobSize)) + structural mutator + setter tail)",)return true@@ -110,7 +110,9 @@ extension KernelJBPatcher {private func findSyscallmaskApplyFunc() -> Int? {// Try symbol lookup firstfor name in ["_syscallmask_apply_to_proc", "_proc_apply_syscall_masks"] {- if let off = resolveSymbol(name) { return off }+ if let off = resolveSymbol(name) {+ return off+ }}// Find manager via error strings@@ -160,7 +162,9 @@ extension KernelJBPatcher {let whiches = Set(calls.compactMap { callOff inextractW1ImmNearCall(funcOff: managerOff, callOff: callOff)})- if whiches.isSuperset(of: [0, 1, 2]) { return target }+ if whiches.isSuperset(of: [0, 1, 2]) {+ return target+ }}return nil}@@ -175,9 +179,13 @@ extension KernelJBPatcher {if insn.mnemonic == "mov", op.hasPrefix("w1,#") {let imm = String(op.dropFirst(4))if imm.hasPrefix("0x") || imm.hasPrefix("0X") {- if let v = Int(imm.dropFirst(2), radix: 16) { return v }+ if let v = Int(imm.dropFirst(2), radix: 16) {+ return v+ }} else {- if let v = Int(imm) { return v }+ if let v = Int(imm) {+ return v+ }}}off -= 4@@ -284,7 +292,7 @@ extension KernelJBPatcher {private func buildSyscallmaskCave(caveOff: Int,zallocOff: Int,- setterOff: Int+ setterOff: Int,) -> (Data, Int)? {let blobSize = Self.syscallmaskFFBlobSizelet codeOff = caveOff + blobSizediff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskConversion.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskConversion.swiftindex 4fda5e25..863b1bdc 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskConversion.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskConversion.swift@@ -48,7 +48,7 @@ extension KernelJBPatcher {ARM64.cmpXzrXzr,patchID: "task_conversion_eval",virtualAddress: va,- description: "cmp xzr,xzr [_task_conversion_eval_internal]"+ description: "cmp xzr,xzr [_task_conversion_eval_internal]",)return true}@@ -56,8 +56,8 @@ extension KernelJBPatcher {// MARK: - Private scannerprivate func collectTaskConversionCandidates(start: Int, end: Int) -> [Int] {- // True iff `cmp` compares register `reg` against the kernel_task register `k`- // (in either operand position — the order drifts across versions).+ /// True iff `cmp` compares register `reg` against the kernel_task register `k`+ /// (in either operand position — the order drifts across versions).func comparesRegAgainst(_ cmp: UInt32, reg: UInt32, k: UInt32) -> Bool {(ARM64Inst.rn(cmp) == reg && ARM64Inst.rm(cmp) == k) ||(ARM64Inst.rn(cmp) == k && ARM64Inst.rm(cmp) == reg)diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskForPid.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskForPid.swiftindex 98412615..9431aa40 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskForPid.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchTaskForPid.swift@@ -58,7 +58,7 @@ extension KernelJBPatcher {ARM64.nop,patchID: "kernelcache_jb.task_for_pid",virtualAddress: va,- description: "NOP [_task_for_pid pid==0 gate]"+ description: "NOP [_task_for_pid pid==0 gate]",)return true}@@ -107,8 +107,12 @@ extension KernelJBPatcher {while prevOff < off {let prevInsns = disasm.disassemble(in: buffer.data, at: prevOff, count: 1)guard let prev = prevInsns.first else { prevOff += 4; continue }- if pidLoad == nil, isWLdrFromXImm(prev, imm: 8) { pidLoad = prev }- if taskptrLoad == nil, isXLdrFromXImm(prev, imm: 0x10) { taskptrLoad = prev }+ if pidLoad == nil, isWLdrFromXImm(prev, imm: 8) {+ pidLoad = prev+ }+ if taskptrLoad == nil, isXLdrFromXImm(prev, imm: 0x10) {+ taskptrLoad = prev+ }prevOff += 4}guard let pid = pidLoad, taskptrLoad != nil else { return nil }diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchThidCrash.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchThidCrash.swiftindex d4c55a3b..82e69a40 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchThidCrash.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Process/KernelJBPatchThidCrash.swift@@ -52,7 +52,7 @@ extension KernelJBPatcher {Data([0, 0, 0, 0]),patchID: "kernelcache_jb.thid_should_crash",virtualAddress: va,- description: "zero [_thid_should_crash]"+ description: "zero [_thid_should_crash]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchContainerUpcall.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchContainerUpcall.swiftindex 0f81d4eb..6e690734 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchContainerUpcall.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchContainerUpcall.swift@@ -94,7 +94,7 @@ extension KernelJBPatcher {bBytes,patchID: "container_manager_upcall_force_success",virtualAddress: va,- description: "cbz w0 -> b [force container-manager exec upcall success; skip autobox/temporary-sandbox]"+ description: "cbz w0 -> b [force container-manager exec upcall success; skip autobox/temporary-sandbox]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchExecPolicyKill.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchExecPolicyKill.swiftindex fb21162c..f35f5965 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchExecPolicyKill.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchExecPolicyKill.swift@@ -94,7 +94,7 @@ extension KernelJBPatcher {bBytes,patchID: "exec_security_policy_kill",virtualAddress: va,- description: "cbz -> b [exec ip_mac_return SECURITY_POLICY kill bypass]"+ description: "cbz -> b [exec ip_mac_return SECURITY_POLICY kill bypass]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchFpfsScopedOpen.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchFpfsScopedOpen.swiftindex c9c7641b..ab09ea70 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchFpfsScopedOpen.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchFpfsScopedOpen.swift@@ -38,24 +38,26 @@ extension KernelJBPatcher {entryOff,newEntry,patchID: "jb.fpfs_scoped_open.ops_retarget",- description: "ops[267] -> FileProvider-scoped vnode_check_open trampoline"+ description: "ops[267] -> FileProvider-scoped vnode_check_open trampoline",)emit(caveOff,caveBytes,patchID: "jb.fpfs_scoped_open.cave",- description: "trampoline: FileProvider daemons -> real check, else allow"+ description: "trampoline: FileProvider daemons -> real check, else allow",)return true}- // vphone600 struct offsets recovered via the kernel gdb stub; cave bytes verified by- // capstone round-trip. p_comm[0:8] little-endian: "Resolver" = ResolverService,- // "fileprov" = fileproviderd.+ /// vphone600 struct offsets recovered via the kernel gdb stub; cave bytes verified by+ /// capstone round-trip. p_comm[0:8] little-endian: "Resolver" = ResolverService,+ /// "fileprov" = fileproviderd.private func buildScopedOpenCave(caveOff: Int, realHookOff: Int) -> Data? {func movkX10(_ hw: [UInt16]) -> [UInt32] {var out: [UInt32] = [0xD280_0000 | (UInt32(hw[0]) << 5) | 10] // movz x10, #hw0- for i in 1 ..< 4 { out.append(0xF280_0000 | (UInt32(i) << 21) | (UInt32(hw[i]) << 5) | 10) } // movk lsl #16*i+ for i in 1 ..< 4 {+ out.append(0xF280_0000 | (UInt32(i) << 21) | (UInt32(hw[i]) << 5) | 10)+ } // movk lsl #16*ireturn out}var w: [UInt32] = [@@ -65,10 +67,10 @@ extension KernelJBPatcher {0x9115_B108, // add x8, x8, #0x56C ; &p_comm0xF940_0109, // ldr x9, [x8] ; p_comm[0:8]]- w += movkX10([0x6552, 0x6f73, 0x766c, 0x7265]) // x10 = "Resolver"+ w += movkX10([0x6552, 0x6F73, 0x766C, 0x7265]) // x10 = "Resolver"w.append(0xEB0A_013F) // cmp x9, x10let beqA = w.count; w.append(0)- w += movkX10([0x6966, 0x656c, 0x7270, 0x766f]) // x10 = "fileprov"+ w += movkX10([0x6966, 0x656C, 0x7270, 0x766F]) // x10 = "fileprov"w.append(0xEB0A_013F) // cmp x9, x10let beqB = w.count; w.append(0)w.append(0xD280_0000) // mov x0, #0@@ -86,7 +88,9 @@ extension KernelJBPatcher {guard w.count == 20 else { log(" [-] cave length drifted: \(w.count)"); return nil }var data = Data(capacity: 80)- for x in w { withUnsafeBytes(of: x.littleEndian) { data.append(contentsOf: $0) } }+ for x in w {+ withUnsafeBytes(of: x.littleEndian) { data.append(contentsOf: $0) }+ }return data}@@ -110,7 +114,9 @@ extension KernelJBPatcher {let v1 = buffer.readU64(at: i + 8)guard (v1 & (1 << 63)) == 0, (v1 & 0x7FF_FFFF_FFFF) == UInt64(seatbeltOff) else { continue }let vOps = buffer.readU64(at: i + 32)- if (vOps & (1 << 63)) == 0 { return Int(vOps & 0x7FF_FFFF_FFFF) }+ if (vOps & (1 << 63)) == 0 {+ return Int(vOps & 0x7FF_FFFF_FFFF)+ }}}return nildiff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucMacf.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucMacf.swiftindex 6a3005e0..e07c09e4 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucMacf.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucMacf.swift@@ -80,7 +80,7 @@ extension KernelJBPatcher {patchBytes,patchID: "iouc_macf_gate",virtualAddress: va,- description: "b #0x\(String(format: "%X", delta)) [IOUC MACF deny → allow]"+ description: "b #0x\(String(format: "%X", delta)) [IOUC MACF deny → allow]",)return true}@@ -138,7 +138,9 @@ extension KernelJBPatcher {{sawIndirectCall = true}- if sawSlotLoad, sawIndirectCall { return true }+ if sawSlotLoad, sawIndirectCall {+ return true+ }off += 4}return falsediff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucSandbox.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucSandbox.swiftindex 6a52ebaf..80e9e5fe 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucSandbox.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchIoucSandbox.swift@@ -84,7 +84,7 @@ extension KernelJBPatcher {patchBytes,patchID: "iouc_sandbox_gate",virtualAddress: va,- description: "b #\(delta >= 0 ? "" : "-")0x\(String(format: "%X", abs(delta))) [IOUC sandbox deny → allow]"+ description: "b #\(delta >= 0 ? "" : "-")0x\(String(format: "%X", abs(delta))) [IOUC sandbox deny → allow]",)return true}@@ -95,7 +95,9 @@ extension KernelJBPatcher {}/// CBNZ Wt, <label> (32-bit): high byte 0x35.- private func isCbnzW(_ insn: UInt32) -> Bool { ((insn >> 24) & 0xFF) == 0x35 }+ private func isCbnzW(_ insn: UInt32) -> Bool {+ ((insn >> 24) & 0xFF) == 0x35+ }/// Decode CBZ/CBNZ target (imm19, sign-extended, scaled by 4).private func cbTarget(_ insn: UInt32, at pc: Int) -> Int? {diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchMacMount.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchMacMount.swiftindex f8635134..52f2a8e7 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchMacMount.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchMacMount.swift@@ -70,14 +70,14 @@ extension KernelJBPatcher {ARM64.nop,patchID: "kernelcache_jb.mac_mount.flag_gate",virtualAddress: va1,- description: "NOP [___mac_mount upstream flag gate]"+ description: "NOP [___mac_mount upstream flag gate]",)emit(movOff,clearBytes,patchID: "kernelcache_jb.mac_mount.state_clear",virtualAddress: va2,- description: "mov x,xzr [___mac_mount upstream state clear]"+ description: "mov x,xzr [___mac_mount upstream state clear]",)return true}@@ -88,7 +88,9 @@ extension KernelJBPatcher {// Require the wrapper to actually call mount_common.var callsMountCommon = falsefor off in stride(from: start, to: end, by: 4) {- if decodeBL(at: off) == mountCommon { callsMountCommon = true; break }+ if decodeBL(at: off) == mountCommon {+ callsMountCommon = true; break+ }}guard callsMountCommon else { return nil }diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchProcSecurity.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchProcSecurity.swiftindex f6550e87..a23c4849 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchProcSecurity.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchProcSecurity.swift@@ -28,14 +28,14 @@ extension KernelJBPatcher {ARM64.movX0_0,patchID: "jb.proc_security_policy.mov_x0_0",virtualAddress: fileOffsetToVA(policy),- description: "mov x0,#0 [_proc_security_policy]"+ description: "mov x0,#0 [_proc_security_policy]",)emit(policy + 4,ARM64.ret,patchID: "jb.proc_security_policy.ret",virtualAddress: fileOffsetToVA(policy + 4),- description: "ret [_proc_security_policy]"+ description: "ret [_proc_security_policy]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchSandboxExtended.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchSandboxExtended.swiftindex 6750510f..8f5620a4 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchSandboxExtended.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Sandbox/KernelJBPatchSandboxExtended.swift@@ -110,7 +110,7 @@ extension KernelJBPatcher {newBytes,patchID: "sandbox_ext_\(idx)",virtualAddress: nil,- description: "ops[\(idx)] -> allow stub [_hook_\(hookName)]"+ description: "ops[\(idx)] -> allow stub [_hook_\(hookName)]",)patched += 1}@@ -163,12 +163,16 @@ extension KernelJBPatcher {defer { i += 8 }let val = buffer.readU64(at: i)// Must not be zero or a tagged (high-bit set) pointer at position [0].- if val == 0 || (val & (1 << 63)) != 0 { continue }+ if val == 0 || (val & (1 << 63)) != 0 {+ continue+ }// Low 43 bits must point to sandboxOff (auth-rebase chained ptr format).guard (val & 0x7FF_FFFF_FFFF) == UInt64(sandboxOff) else { continue }let val2 = buffer.readU64(at: i + 8)- if (val2 & (1 << 63)) != 0 { continue }+ if (val2 & (1 << 63)) != 0 {+ continue+ }guard (val2 & 0x7FF_FFFF_FFFF) == UInt64(seatbeltOff) else { continue }// Offset +32: tagged ptr to mac_policy_ops.diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchBsdInitAuth.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchBsdInitAuth.swiftindex 2dbeef11..2667b0fc 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchBsdInitAuth.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchBsdInitAuth.swift@@ -83,7 +83,7 @@ extension KernelJBPatcher {ARM64.nop,patchID: "jb.bsd_init_auth.nop_cbnz",virtualAddress: fileOffsetToVA(branchOff),- description: "NOP cbnz (rootvp auth) [_bsd_init]"+ description: "NOP cbnz (rootvp auth) [_bsd_init]",)return true}@@ -148,7 +148,9 @@ extension KernelJBPatcher {guard hasImagebootCallNear(off, imagebootNeeded: imagebootNeeded) else { return nil }// Check if already patched (NOP)- if insn.mnemonic == "nop" { return "patched" }+ if insn.mnemonic == "nop" {+ return "patched"+ }// Must be CBNZ on w0 or x0guard insn.mnemonic == "cbnz" else { return nil }@@ -181,7 +183,9 @@ extension KernelJBPatcher {// If we know _imageboot_needed, require an exact match;// otherwise any BL counts (stripped kernel).if let ib = imagebootNeeded {- if target == ib { return true }+ if target == ib {+ return true+ }} else {return true}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDiskImages2.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDiskImages2.swiftindex e4b74c38..2edf9189 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDiskImages2.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDiskImages2.swift@@ -57,7 +57,7 @@ extension KernelJBPatcher {return nopAbiVersionGate(funcSig: "static IOReturn DIDeviceCreatorUserClient::CreateDevice(OSObject *, void *, IOExternalMethodArguments *)",patchID: "di2_createdevice_abi",- desc: "nop [DI2 CreateDevice controller-ABI cmp#9/b.ne gate]"+ desc: "nop [DI2 CreateDevice controller-ABI cmp#9/b.ne gate]",)}@@ -69,7 +69,7 @@ extension KernelJBPatcher {return nopAbiVersionGate(funcSig: "static IOReturn DIDeviceIOUserClient::Connect(OSObject *, void *, IOExternalMethodArguments *)",patchID: "di2_connect_abi",- desc: "nop [DI2 Connect daemon-ABI cmp#9/b.ne gate]"+ desc: "nop [DI2 Connect daemon-ABI cmp#9/b.ne gate]",)}@@ -95,7 +95,7 @@ extension KernelJBPatcher {guard let cmp = disasAt(off), cmp.mnemonic == "cmp",let ops = cmp.aarch64?.operands, ops.count == 2,ops[0].type == AARCH64_OP_REG,- (disasm.firstRegisterName(cmp)?.hasPrefix("w") ?? false),+ disasm.firstRegisterName(cmp)?.hasPrefix("w") ?? false,ops[1].type == AARCH64_OP_IMM, ops[1].imm == 9else { continue }guard let nxt = disasAt(off + 4), nxt.mnemonic == "b.ne" else { continue }@@ -145,12 +145,12 @@ extension KernelJBPatcher {ok = applyFieldLoadMov800(at: f1,patchID: "di2_notif_boundcheck_d8",- desc: "mov wD,#0x800 [DI2 RegisterNotificationPort bound-check field1 @+0xd8]"+ desc: "mov wD,#0x800 [DI2 RegisterNotificationPort bound-check field1 @+0xd8]",) && okok = applyFieldLoadMov800(at: f2,patchID: "di2_notif_boundcheck_e8",- desc: "mov wD,#0x800 [DI2 RegisterNotificationPort bound-check field2 @+0xe8]"+ desc: "mov wD,#0x800 [DI2 RegisterNotificationPort bound-check field2 @+0xe8]",) && okreturn ok}@@ -159,7 +159,7 @@ extension KernelJBPatcher {/// count * 8), unique within the function. Function pinned by its C++ signature.private func findDI2AllocPortsSizeSite() -> Int? {guard let sigOff = buffer.findString(- "static IOReturn DIDeviceIOUserClient::AllocPortsArray(OSObject *, void *, IOExternalMethodArguments *)"+ "static IOReturn DIDeviceIOUserClient::AllocPortsArray(OSObject *, void *, IOExternalMethodArguments *)",) else { return nil }let refs = findStringRefs(sigOff)guard let ref = refs.first, let funcStart = findFunctionStart(ref.adrpOff) else { return nil }@@ -196,7 +196,7 @@ extension KernelJBPatcher {funcEnd: Int,mnemonic: String,disp: Int64,- requireWDest: Bool+ requireWDest: Bool,) -> Int? {var hits: [Int] = []var off = funcStart@@ -207,7 +207,9 @@ extension KernelJBPatcher {ops[0].type == AARCH64_OP_REG,ops[1].type == AARCH64_OP_MEM, ops[1].mem.disp == dispelse { continue }- if requireWDest, !(disasm.firstRegisterName(ins)?.hasPrefix("w") ?? false) { continue }+ if requireWDest, !(disasm.firstRegisterName(ins)?.hasPrefix("w") ?? false) {+ continue+ }hits.append(off)}return hits.count == 1 ? hits[0] : nil@@ -224,7 +226,7 @@ extension KernelJBPatcher {bytes,patchID: "di2_allocports_size",virtualAddress: fileOffsetToVA(lslOff),- description: "mov x1,#0x4000 [DI2 AllocPortsArray widen notif-ports alloc to 0x800 entries]"+ description: "mov x1,#0x4000 [DI2 AllocPortsArray widen notif-ports alloc to 0x800 entries]",)return true}@@ -242,13 +244,17 @@ extension KernelJBPatcher {// MARK: - Register-name → index helpersprivate func wRegIndex(_ name: String) -> UInt32? {- if name == "wzr" { return 31 }+ if name == "wzr" {+ return 31+ }guard name.hasPrefix("w"), let n = UInt32(name.dropFirst()), n < 31 else { return nil }return n}private func xRegIndex(_ name: String) -> UInt32? {- if name == "xzr" { return 31 }+ if name == "xzr" {+ return 31+ }guard name.hasPrefix("x"), let n = UInt32(name.dropFirst()), n < 31 else { return nil }return n}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDounmount.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDounmount.swiftindex 5ed17857..b45eaa28 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDounmount.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchDounmount.swift@@ -31,7 +31,7 @@ extension KernelJBPatcher {ARM64.nop,patchID: "jb.dounmount.nop_cleanup_bl",virtualAddress: fileOffsetToVA(patchOff),- description: "NOP [_dounmount upstream cleanup call]"+ description: "NOP [_dounmount upstream cleanup call]",)return true}@@ -73,7 +73,9 @@ extension KernelJBPatcher {hits.append(Int(i4.address))}- if hits.count == 1 { return hits[0] }+ if hits.count == 1 {+ return hits[0]+ }return nil}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchSecureRoot.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchSecureRoot.swiftindex 244a0dcc..2a9c045d 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchSecureRoot.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Storage/KernelJBPatchSecureRoot.swift@@ -56,7 +56,7 @@ extension KernelJBPatcher {patchBytes,patchID: "jb.io_secure_bsd_root.zero_return",virtualAddress: fileOffsetToVA(off),- description: "mov \(destReg), #0 [_IOSecureBSDRoot SecureRootName allow]"+ description: "mov \(destReg), #0 [_IOSecureBSDRoot SecureRootName allow]",)return true}@@ -150,9 +150,10 @@ extension KernelJBPatcher {guard disasm.writesRegister(ins, named: regName) else { continue }let ops = ins.operandString.replacingOccurrences(of: " ", with: "").lowercased()// movk Wn, #0xe000, lsl #16 → "wN,#0xe000,lsl#16"- if ops.contains("#0xe000,lsl#16") { return true }+ if ops.contains("#0xe000,lsl#16") {+ return true+ }}return false}-}diff --git a/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift b/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swiftindex 07102bcc..7494e914 100644--- a/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift+++ b/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift@@ -104,9 +104,9 @@ public final class KernelJBPatcher: KernelJBPatcherBase, Patcher {if applyIOS27 {patchExecSecurityPolicyKill()patchContainerManagerUpcall()- patchIomfbSwapEndVariableSize() // dispatch checkStructureInputSize → variable- patchIomfbSwapEndHandlerSize() // handler cmp w2,#0x588 → 0x6e0- patchFpfsScopedVnodeOpen() // ops[267] → FileProvider-scoped trampoline (fpfs respring fix)+ patchIomfbSwapEndVariableSize() // dispatch checkStructureInputSize → variable+ patchIomfbSwapEndHandlerSize() // handler cmp w2,#0x588 → 0x6e0+ patchFpfsScopedVnodeOpen() // ops[267] → FileProvider-scoped trampoline (fpfs respring fix)}return patchesdiff --git a/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift b/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swiftindex 013a5dbd..e8f65b18 100644--- a/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift+++ b/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift@@ -65,7 +65,9 @@ public class KernelJBPatcherBase: KernelPatcherBase {tempOff += Int(cmdsize)}- if verbose { print("[*] Symbol table: \(symbols.count) symbols resolved") }+ if verbose {+ print("[*] Symbol table: \(symbols.count) symbols resolved")+ }}/// Parse LC_SYMTAB from a fileset entry Mach-O whose header starts at `mhOff`.@@ -110,14 +112,18 @@ public class KernelJBPatcherBase: KernelPatcherBase {guard nameOff < size else { continue }var nameEnd = nameOffwhile nameEnd < size, nameEnd - nameOff < 512 {- if raw[nameEnd] == 0 { break }+ if raw[nameEnd] == 0 {+ break+ }nameEnd += 1}guard nameEnd > nameOff else { continue }guard let name = String(data: raw[nameOff ..< nameEnd], encoding: .ascii) else { continue }// foff = n_value - base_valet foff = Int(Int64(bitPattern: nValue) - Int64(bitPattern: baseVA))- if foff >= 0, foff < size { symbols[name] = foff }+ if foff >= 0, foff < size {+ symbols[name] = foff+ }}}@@ -186,7 +192,9 @@ public class KernelJBPatcherBase: KernelPatcherBase {var off = funcStart + 4while off + 4 <= limit {let insn = raw.loadLE(UInt32.self, at: off)- if insn == ARM64.pacibspU32 { return off }+ if insn == ARM64.pacibspU32 {+ return off+ }off += 4}return limit@@ -218,7 +226,9 @@ public class KernelJBPatcherBase: KernelPatcherBase {/// loads `0x3EA` into `w1` immediately ahead of a `BL` (the priv-check call) —/// no offsets, no preassembled bytes, no version-pinned switch literal.func findProcSecurityPolicy() -> Int? {- if let cached = procSecurityPolicyOff { return cached >= 0 ? cached : nil }+ if let cached = procSecurityPolicyOff {+ return cached >= 0 ? cached : nil+ }let raw = buffer.originalvar funcs = Set<Int>()@@ -235,7 +245,9 @@ public class KernelJBPatcherBase: KernelPatcherBase {let blA = off + 4 <= limit ? raw.loadLE(UInt32.self, at: off + 4) : 0let blB = off + 8 <= limit ? raw.loadLE(UInt32.self, at: off + 8) : 0guard ARM64Inst.isBL(blA) || ARM64Inst.isBL(blB) else { continue }- if let fn = findFunctionStart(off) { funcs.insert(fn) }+ if let fn = findFunctionStart(off) {+ funcs.insert(fn)+ }}}diff --git a/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift b/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swiftindex 54b0607b..24497b11 100644--- a/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift+++ b/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift@@ -79,7 +79,7 @@ open class KernelPatcherBase {_ patchBytes: Data,patchID: String,virtualAddress: UInt64? = nil,- description: String+ description: String,) {let originalBytes = buffer.readBytes(at: offset, count: patchBytes.count)@@ -99,7 +99,7 @@ open class KernelPatcherBase {patchedBytes: patchBytes,beforeDisasm: beforeStr,afterDisasm: afterStr,- description: description+ description: description,)patches.append(record)@@ -273,7 +273,9 @@ open class KernelPatcherBase {let immhi = (adrpInsn >> 5) & 0x7FFFFlet immlo = (adrpInsn >> 29) & 0x3var imm = Int((immhi << 2) | immlo)- if imm & (1 << 20) != 0 { imm -= 1 << 21 }+ if imm & (1 << 20) != 0 {+ imm -= 1 << 21+ }let pageDelta = imm << 12let pcPage = (back - 4) & ~0xFFFlet strFoff = pcPage + pageDelta + addImm@@ -292,11 +294,15 @@ open class KernelPatcherBase {}back -= 4}- if confirmed >= 3 { break }+ if confirmed >= 3 {+ break+ }}if confirmed >= 3 {panicOffset = targetOff- if verbose { print(String(format: " [*] _panic at foff 0x%X (%d callers)", targetOff, callers.count)) }+ if verbose {+ print(String(format: " [*] _panic at foff 0x%X (%d callers)", targetOff, callers.count))+ }return}}@@ -308,7 +314,9 @@ open class KernelPatcherBase {panicOffset = first.key}if let p = panicOffset {- if verbose { print(String(format: " [*] _panic (fallback) at foff 0x%X", p)) }+ if verbose {+ print(String(format: " [*] _panic (fallback) at foff 0x%X", p))+ }}}@@ -424,9 +432,13 @@ open class KernelPatcherBase {else { continue }var execAddr: UInt64 = 0- if let n = execAddrAny as? UInt64 { execAddr = n }- else if let n = execAddrAny as? Int { execAddr = UInt64(bitPattern: Int64(n)) }- else if let n = execAddrAny as? NSNumber { execAddr = n.uint64Value }+ if let n = execAddrAny as? UInt64 {+ execAddr = n+ } else if let n = execAddrAny as? Int {+ execAddr = UInt64(bitPattern: Int64(n))+ } else if let n = execAddrAny as? NSNumber {+ execAddr = n.uint64Value+ }execAddr &= 0xFFFF_FFFF_FFFF_FFFFguard execAddr > baseVA else { continue }let kextFoff = Int(execAddr - baseVA)diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swiftindex 438ec003..f0c4dfb6 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift@@ -73,7 +73,7 @@ extension KernelPatcher {ARM64.movW0_0,patchID: "apfs_graft",virtualAddress: va,- description: "mov w0,#0 [_apfs_graft]"+ description: "mov w0,#0 [_apfs_graft]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swiftindex c9f4d918..6070bc4f 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift@@ -115,7 +115,7 @@ extension KernelPatcher {ARM64.cmpX0X0,patchID: "kernel.apfs_vfsop_mount.cmp_x0_x0",virtualAddress: va,- description: "cmp x0,x0 (was \(insn.mnemonic) \(insn.operandString)) [_apfs_vfsop_mount]"+ description: "cmp x0,x0 (was \(insn.mnemonic) \(insn.operandString)) [_apfs_vfsop_mount]",)return true}@@ -188,7 +188,7 @@ extension KernelPatcher {ARM64.movW0_0,patchID: "kernel.apfs_mount_upgrade_checks.mov_w0_0",virtualAddress: va,- description: "mov w0,#0 [_apfs_mount_upgrade_checks]"+ description: "mov w0,#0 [_apfs_mount_upgrade_checks]",)return true}@@ -261,7 +261,7 @@ extension KernelPatcher {ARM64.movW0_0,patchID: "kernel.handle_fsioc_graft.mov_w0_0",virtualAddress: va,- description: "mov w0,#0 [_handle_fsioc_graft]"+ description: "mov w0,#0 [_handle_fsioc_graft]",)return true}@@ -356,7 +356,7 @@ extension KernelPatcher {ARM64.nop,patchID: "kernel.handle_get_dev_by_role.gate_\(String(format: "%X", cand.off))",virtualAddress: va,- description: "NOP [handle_get_dev_by_role entitlement gate -> 0x\(String(format: "%X", cand.target))]"+ description: "NOP [handle_get_dev_by_role entitlement gate -> 0x\(String(format: "%X", cand.target))]",)}return true@@ -373,7 +373,9 @@ extension KernelPatcher {var refs = Set<Int>()for needle in needles {guard let strOff = buffer.findString(needle) else { continue }- for ref in findStringRefs(strOff, in: range) { refs.insert(ref.adrpOff) }+ for ref in findStringRefs(strOff, in: range) {+ refs.insert(ref.adrpOff)+ }}return refs}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swiftindex ab3247a0..b726d26e 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift@@ -123,7 +123,7 @@ extension KernelPatcher {ARM64.nop,patchID: "kernel.bsd_init_rootvp",virtualAddress: va,- description: "NOP \(insn.mnemonic) (rootvp auth) [_bsd_init]"+ description: "NOP \(insn.mnemonic) (rootvp auth) [_bsd_init]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swiftindex 94a92c3b..5ba40a7c 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift@@ -63,14 +63,14 @@ extension KernelPatcher {ARM64.movX0_1,patchID: "kernel.debugger.mov_x0_1",virtualAddress: va,- description: "mov x0,#1 [_PE_i_can_has_debugger]"+ description: "mov x0,#1 [_PE_i_can_has_debugger]",)emit(offset + 4,ARM64.ret,patchID: "kernel.debugger.ret",virtualAddress: va.map { $0 + 4 },- description: "ret [_PE_i_can_has_debugger]"+ description: "ret [_PE_i_can_has_debugger]",)}@@ -101,7 +101,9 @@ extension KernelPatcher {// [31:30]=10, [29:27]=111, [26]=0, [25]=0, [24]=1 → 0xB9400000 mask 0xFFC00000guard insn & 0xFFC0_0000 == 0xB940_0000 else { continue }let rn = (insn >> 5) & 0x1F- if rn == 8 { return true }+ if rn == 8 {+ return true+ }}return false}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swiftindex 4ca7393f..40724555 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift@@ -17,7 +17,7 @@ extension KernelPatcher {// Anchor: entitlement string referenced from within the function.guard let strOff = buffer.findString(- "com.apple.developer.swift-playgrounds-app.development-build"+ "com.apple.developer.swift-playgrounds-app.development-build",) else {log(" [-] swift-playgrounds entitlement string not found")return false@@ -67,14 +67,14 @@ extension KernelPatcher {ARM64.movW0_1,patchID: "dyld_policy_1",virtualAddress: va1,- description: "mov w0,#1 (was BL) [_check_dyld_policy_internal @1]"+ description: "mov w0,#1 (was BL) [_check_dyld_policy_internal @1]",)emit(bl2.blOff,ARM64.movW0_1,patchID: "dyld_policy_2",virtualAddress: va2,- description: "mov w0,#1 (was BL) [_check_dyld_policy_internal @2]"+ description: "mov w0,#1 (was BL) [_check_dyld_policy_internal @2]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swiftindex fd772420..c5e03f96 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift@@ -67,7 +67,7 @@ extension KernelPatcher {guard ioff + 4 <= buffer.count else { break }let iraw = buffer.readU32(at: ioff)// TBZ/TBNZ: [30:25] = 01101x- if (iraw & 0x7E000000) == 0x36000000 {+ if (iraw & 0x7E00_0000) == 0x3600_0000 {hasTbCheck = true}// After TBZ, look for BL@@ -93,7 +93,7 @@ extension KernelPatcher {ARM64.ret,patchID: "kernel.thread_guard_violation",virtualAddress: va,- description: "PACIBSP→RET (disable guard violation delivery)"+ description: "PACIBSP→RET (disable guard violation delivery)",)return true}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchLaunchConstraints.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchLaunchConstraints.swiftindex 1dc0b94f..b0c4164f 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchLaunchConstraints.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchLaunchConstraints.swift@@ -54,14 +54,14 @@ extension KernelPatcher {ARM64.movW0_0,patchID: "launch_constraints_mov",virtualAddress: va0,- description: "mov w0,#0 [_proc_check_launch_constraints]"+ description: "mov w0,#0 [_proc_check_launch_constraints]",)emit(funcStart + 4,ARM64.ret,patchID: "launch_constraints_ret",virtualAddress: va1,- description: "ret [_proc_check_launch_constraints]"+ description: "ret [_proc_check_launch_constraints]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swiftindex b3db4199..6e445a61 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift@@ -51,7 +51,7 @@ extension KernelPatcher {ARM64.nop,patchID: "kernel.post_validation.nop_tbnz",virtualAddress: va,- description: "NOP \(insn.mnemonic) \(insn.operandString) [txm post-validation]"+ description: "NOP \(insn.mnemonic) \(insn.operandString) [txm post-validation]",)return true}@@ -98,7 +98,9 @@ extension KernelPatcher {// Collect BL targets by direct instruction decode across the caller body.var blTargets = Set<Int>()for scan in stride(from: callerStart, to: callerEnd, by: 4) {- if scan > callerStart, buffer.readU32(at: scan) == ARM64.pacibspU32 { break }+ if scan > callerStart, buffer.readU32(at: scan) == ARM64.pacibspU32 {+ break+ }if let target = decodeBL(at: scan) {blTargets.insert(target)}@@ -112,7 +114,9 @@ extension KernelPatcher {for off in stride(from: target, to: calleeEnd - 4, by: 4) {// Stop at next function boundary.- if off > target, buffer.readU32(at: off) == ARM64.pacibspU32 { break }+ if off > target, buffer.readU32(at: off) == ARM64.pacibspU32 {+ break+ }let insns = disasm.disassemble(in: buffer.data, at: off, count: 2)guard insns.count >= 2 else { continue }@@ -151,7 +155,7 @@ extension KernelPatcher {ARM64.cmpW0W0,patchID: "kernel.post_validation.cmp_w0_w0",virtualAddress: fileOffsetToVA(patchOff),- description: "cmp w0,w0 (was cmp w0,#imm) [postValidation]"+ description: "cmp w0,w0 (was cmp w0,#imm) [postValidation]",)return true}diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchSandbox.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchSandbox.swiftindex 2148d6d9..598294cf 100644--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchSandbox.swift+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchSandbox.swift@@ -74,14 +74,14 @@ extension KernelPatcher {ARM64.movX0_0,patchID: "kernel.sandbox.\(hook.name).mov_x0_0",virtualAddress: va,- description: "mov x0,#0 [_hook_\(hook.name)]"+ description: "mov x0,#0 [_hook_\(hook.name)]",)emit(funcOff + 4,ARM64.ret,patchID: "kernel.sandbox.\(hook.name).ret",virtualAddress: va.map { $0 + 4 },- description: "ret [_hook_\(hook.name)]"+ description: "ret [_hook_\(hook.name)]",)log(" [+] ops[\(hook.index)] \(hook.name) at foff 0x\(String(format: "%X", funcOff))")diff --git a/sources/FirmwarePatcher/Manifest/FirmwareManifest.swift b/sources/FirmwarePatcher/Manifest/FirmwareManifest.swiftindex afa68791..43283616 100644--- a/sources/FirmwarePatcher/Manifest/FirmwareManifest.swift+++ b/sources/FirmwarePatcher/Manifest/FirmwareManifest.swift@@ -70,7 +70,7 @@ public enum FirmwareManifest {public static func generate(iPhoneDir: URL,cloudOSDir: URL,- verbose: Bool = true+ verbose: Bool = true,) throws {// Load source plists.let cloudOSBM = try loadPlist(cloudOSDir.appendingPathComponent("BuildManifest.plist"))@@ -104,7 +104,7 @@ public enum FirmwareManifest {res: res,vp: vp,vpr: vpr,- iErase: iErase+ iErase: iErase,)// Assemble BuildManifest.@@ -119,15 +119,19 @@ public enum FirmwareManifest {// Assemble Restore.plist.let restore = try buildRestorePlist(cloudOSRP: cloudOSRP,- iPhoneRP: iPhoneRP+ iPhoneRP: iPhoneRP,)// Write output.try writePlist(buildManifest, to: iPhoneDir.appendingPathComponent("BuildManifest.plist"))- if verbose { print(" wrote BuildManifest.plist") }+ if verbose {+ print(" wrote BuildManifest.plist")+ }try writePlist(restore, to: iPhoneDir.appendingPathComponent("Restore.plist"))- if verbose { print(" wrote Restore.plist") }+ if verbose {+ print(" wrote Restore.plist")+ }}// MARK: - Identity Discovery@@ -151,7 +155,7 @@ public enum FirmwareManifest {/// Find release and research identity indices for the given DeviceClass.static func findCloudOS(_ identities: [PlistDict],- deviceClass: String+ deviceClass: String,) throws -> (release: Int, research: Int) {var release: Int?var research: Int?@@ -159,9 +163,13 @@ public enum FirmwareManifest {let dc = (bi["Info"] as? PlistDict)?["DeviceClass"] as? String ?? ""guard dc == deviceClass else { continue }if isResearch(bi) {- if research == nil { research = i }+ if research == nil {+ research = i+ }} else {- if release == nil { release = i }+ if release == nil {+ release = i+ }}}guard let rel = release else {@@ -193,7 +201,7 @@ public enum FirmwareManifest {static func entry(_ identities: [PlistDict],_ idx: Int,- _ key: String+ _ key: String,) throws -> PlistDict {guard let manifest = identities[idx]["Manifest"] as? PlistDict,let value = manifest[key] as? PlistDict@@ -211,7 +219,7 @@ public enum FirmwareManifest {res: Int,vp: Int,vpr: Int,- iErase: Int+ iErase: Int,) throws -> PlistDict {// Identity base from vresearch101ap PROD.var bi = deepCopyPlistDict(C[prod])@@ -303,7 +311,7 @@ public enum FirmwareManifest {/// Build the merged Restore.plist from cloudOS and iPhone sources.static func buildRestorePlist(cloudOSRP: PlistDict,- iPhoneRP: PlistDict+ iPhoneRP: PlistDict,) throws -> PlistDict {// DeviceMap: iPhone first entry + cloudOS vphone600ap/vresearch101ap entries.guard let iPhoneDeviceMap = iPhoneRP["DeviceMap"] as? [PlistDict],@@ -369,7 +377,7 @@ public enum FirmwareManifest {guard let dict = try PropertyListSerialization.propertyList(from: data,options: [],- format: nil+ format: nil,) as? PlistDict else {throw ManifestError.invalidPlist(path)}@@ -381,7 +389,7 @@ public enum FirmwareManifest {let data = try PropertyListSerialization.data(fromPropertyList: dict,format: .xml,- options: 0+ options: 0,)try data.write(to: url, options: .atomic)}diff --git a/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift b/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swiftindex b38d740e..89c86124 100644--- a/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift+++ b/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift@@ -3,8 +3,8 @@// Update the hash in the firmware manifest according to the actual hash of the corresponding files.//-import Foundationimport CryptoKit+import Foundationimport Img4tool/// Patcher for Manifest payloads.@@ -61,18 +61,18 @@ public final class ManifestHashPatcher: Patcher {public var patchedData: Data {buffer.data}-+private func parsePayload(_ blob: Data) throws -> PlistDict {guard let buildManifest = try PropertyListSerialization.propertyList(from: blob,options: [],- format: nil+ format: nil,) as? PlistDict else {throw FirmwareManifest.ManifestError.invalidPlist("")}return buildManifest}-+func applyPatches(buildManifest: PlistDict) throws -> PlistDict {var buildManifest = buildManifestguard let restoreDir else {@@ -81,7 +81,8 @@ public final class ManifestHashPatcher: Patcher {// We assume that FirmwareManifest has generated the manifest containing a single build identity.guard let buildIdentities = buildManifest["BuildIdentities"] as? [Any],- buildIdentities.count == 1 else {+ buildIdentities.count == 1+ else {throw FirmwareManifest.ManifestError.missingKey("BuildIdentities in BuildManifest")}guard var buildIdentity = buildIdentities.first! as? PlistDict else {@@ -102,31 +103,31 @@ public final class ManifestHashPatcher: Patcher {guard let path = info["Path"] as? String else {throw FirmwareManifest.ManifestError.missingKey("Path in build identity component info")}-+// Mapped, not read. This loop hashes every component the build// identity names, and that list includes `OS` — the filesystem// DMG, which is ten gigabytes. Reading it meant holding all of it// while SHA384 walked it; mapping means the kernel pages it in// ahead of the hash and evicts behind it.let componentData = try Data(- contentsOf: restoreDir.appendingPathComponent(path), options: .mappedIfSafe+ contentsOf: restoreDir.appendingPathComponent(path), options: .mappedIfSafe,)let finalData = try patchIm4pTypeTag(comp, info["Img4PayloadType"] as? String, componentData)let shaHash = SHA384.hash(data: finalData)dict["Digest"] = Data(shaHash)newBuildIdentityManifest[comp] = dict}-+buildIdentity["Manifest"] = newBuildIdentityManifestbuildManifest["BuildIdentities"] = [buildIdentity]return buildManifest}-+private func serializePayload(_ buildManifest: PlistDict) throws -> Data {- return try PropertyListSerialization.data(+ try PropertyListSerialization.data(fromPropertyList: buildManifest,format: .xml,- options: 0+ options: 0,)}}@@ -146,7 +147,7 @@ func patchIm4pTypeTag(_ component: String, _ declaredType: String?, _ data: Data"Ap,RestoreSecureM3Firmware","Ap,RestoreSecurePageTableMonitor","Ap,RestoreTrustedExecutionMonitor",- "Ap,RestorecL4"+ "Ap,RestorecL4",].contains(component) else {return data}diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swiftindex 038d803a..f9e4c35d 100644--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift@@ -95,7 +95,7 @@ public final class FirmwarePipeline {noBinpack: Bool = false,forceExcGuard: Bool = false,enableFrida: Bool = false,- loader: (any FirmwareLoader)? = nil+ loader: (any FirmwareLoader)? = nil,) {self.vmDirectory = vmDirectoryself.variant = variant@@ -143,7 +143,7 @@ public final class FirmwarePipeline {restoreDir: restoreDir,iosBaseIs18: iosBaseIs18,iosBaseIs27: iosBaseIs27,- cloudOSIsFridaCapable: cloudOSIsFridaCapable+ cloudOSIsFridaCapable: cloudOSIsFridaCapable,)log("[*] Patching \(components.count) boot-chain components ...")@@ -164,7 +164,7 @@ public final class FirmwarePipeline {let (currentData, componentRecords) = try patchData(rawData,componentName: component.name,- patcherFactories: component.patcherFactories+ patcherFactories: component.patcherFactories,)try loader.save(currentData, to: fileURL)@@ -183,7 +183,7 @@ public final class FirmwarePipeline {func patchData(_ rawData: Data,componentName: String,- patcherFactories: [(Data, Bool) -> any Patcher]+ patcherFactories: [(Data, Bool) -> any Patcher],) throws -> (Data, [PatchRecord]) {var currentData = rawDatavar componentRecords: [PatchRecord] = []@@ -215,15 +215,33 @@ public final class FirmwarePipeline {/// access where possible and fall back to manual patch application.func extractPatchedData(from patcher: any Patcher, fallback: Data, records: [PatchRecord]) -> Data {// Try known patcher types that expose their buffer.- if let avp = patcher as? AVPBooterPatcher { return avp.buffer.data }- if let iboot = patcher as? IBootPatcher { return iboot.buffer.data }- if let txm = patcher as? TXMPatcher { return txm.buffer.data }- if let kp = patcher as? KernelPatcher { return kp.buffer.data }- if let kjb = patcher as? KernelJBPatcher { return kjb.buffer.data }- if let kexp = patcher as? KernelEXPPatcher { return kexp.buffer.data }- if let dt = patcher as? DeviceTreePatcher { return dt.patchedData }- if let fs = patcher as? CryptexFilesystemPatcher { return fs.patchedData }- if let mh = patcher as? ManifestHashPatcher { return mh.patchedData }+ if let avp = patcher as? AVPBooterPatcher {+ return avp.buffer.data+ }+ if let iboot = patcher as? IBootPatcher {+ return iboot.buffer.data+ }+ if let txm = patcher as? TXMPatcher {+ return txm.buffer.data+ }+ if let kp = patcher as? KernelPatcher {+ return kp.buffer.data+ }+ if let kjb = patcher as? KernelJBPatcher {+ return kjb.buffer.data+ }+ if let kexp = patcher as? KernelEXPPatcher {+ return kexp.buffer.data+ }+ if let dt = patcher as? DeviceTreePatcher {+ return dt.patchedData+ }+ if let fs = patcher as? CryptexFilesystemPatcher {+ return fs.patchedData+ }+ if let mh = patcher as? ManifestHashPatcher {+ return mh.patchedData+ }// Fallback: apply records manually to a copy of the original data.var data = fallbackdiff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex 42df9de3..d085ca6a 100644--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -28,7 +28,7 @@ extension FirmwarePipeline {restoreDir: URL,iosBaseIs18: Bool,iosBaseIs27: Bool,- cloudOSIsFridaCapable: Bool+ cloudOSIsFridaCapable: Bool,) -> [ComponentDescriptor] {var components: [ComponentDescriptor] = []@@ -73,7 +73,7 @@ extension FirmwarePipeline {]}return []- }()+ }(),))// 2. iBSS — JB and EXP variants run the base iBSS patcher, then the nonce-skip extension.@@ -82,7 +82,7 @@ extension FirmwarePipeline {inRestoreDir: true,searchPatterns: ["Firmware/dfu/iBSS.vresearch101.RELEASE.im4p"],patcherFactories: {- return switch variant {+ switch variant {case .less:[]case .regular, .dev:@@ -99,7 +99,7 @@ extension FirmwarePipeline {},]}- }()+ }(),))// 3. iBEC - Not required by the less variant, still added for the serial logs.@@ -111,7 +111,7 @@ extension FirmwarePipeline {let p = IBootPatcher(data: data, mode: .ibec, verbose: verbose)p.extraBootArgs = extraBootArgsreturn p- }]+ }],))// 4. LLB - Not required by the less variant, still added for the serial logs.@@ -123,7 +123,7 @@ extension FirmwarePipeline {let p = IBootPatcher(data: data, mode: .llb, verbose: verbose)p.extraBootArgs = extraBootArgsreturn p- }]+ }],))// 5. TXM — dev/jb/exp variants use TXMDevPatcher (adds entitlements, debugger, dev-mode)@@ -132,7 +132,7 @@ extension FirmwarePipeline {inRestoreDir: true,searchPatterns: ["Firmware/txm.iphoneos.research.im4p"],patcherFactories: {- return switch variant {+ switch variant {case .less:[]case .regular:@@ -144,7 +144,7 @@ extension FirmwarePipeline {TXMDevPatcher(data: data, verbose: verbose)}]}- }()+ }(),))// 6. Kernel — JB variant runs base kernel patches first, then JB extensions.@@ -154,7 +154,7 @@ extension FirmwarePipeline {inRestoreDir: true,searchPatterns: ["kernelcache.research.vphone600"],patcherFactories: {- return switch variant {+ switch variant {case .less:[]case .regular:@@ -193,7 +193,7 @@ extension FirmwarePipeline {},]}- }()+ }(),))// 7. DeviceTree — base property patches for every variant. EXP additionally@@ -208,9 +208,9 @@ extension FirmwarePipeline {DeviceTreePatcher(data: data,verbose: verbose,- includeIdentityPatches: dtIncludeIdentity+ includeIdentityPatches: dtIncludeIdentity,)- }]+ }],))// 8. Filesystem@@ -219,20 +219,20 @@ extension FirmwarePipeline {inRestoreDir: true,searchPatterns: ["BuildManifest.plist"],patcherFactories: {- return switch variant {+ switch variant {case .less:[{ data, verbose inCryptexFilesystemPatcher(buildManiest: data,restoreDir: restoreDir,verbose: verbose,- noBinpack: self.noBinpack+ noBinpack: self.noBinpack,)}]case .regular, .dev, .jb, .exp:[]}- }()+ }(),))// 9. Firmware Manifest - Only required when excluding the img4 signature patches.@@ -241,7 +241,7 @@ extension FirmwarePipeline {inRestoreDir: true,searchPatterns: ["BuildManifest.plist"],patcherFactories: {- return switch variant {+ switch variant {case .less:[{ data, verbose inManifestHashPatcher(data: data, restoreDir: restoreDir, verbose: verbose)@@ -249,7 +249,7 @@ extension FirmwarePipeline {case .regular, .dev, .jb, .exp:[]}- }()+ }(),))return componentsdiff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swiftindex 64e00f0d..155c10bf 100644--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift@@ -21,7 +21,7 @@ extension FirmwarePipeline {let fm = FileManager.defaultlet contents = try fm.contentsOfDirectory(at: vmDirectory,- includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey]+ includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey],).filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }.filter { $0.lastPathComponent.contains("Restore") }diff --git a/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift b/sources/FirmwarePatcher/TXM/TXMDevPatcher.swiftindex a9c631ae..b8e4025f 100644--- a/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift+++ b/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift@@ -297,7 +297,7 @@ public final class TXMDevPatcher: TXMPatcher {body,ARM64.movW0_0xA1,patchID: "txm_dev.selector24_bypass_mov",- description: "selector24 bypass: mov w0, #0xa1 (PASS)"+ description: "selector24 bypass: mov w0, #0xa1 (PASS)",)guard let bInsn = ARM64Encoder.encodeB(from: body + 4, to: epilogueOff) else {@@ -308,7 +308,7 @@ public final class TXMDevPatcher: TXMPatcher {body + 4,bInsn,patchID: "txm_dev.selector24_bypass_b",- description: "selector24 bypass: b epilogue"+ description: "selector24 bypass: b epilogue",)return}@@ -353,7 +353,7 @@ public final class TXMDevPatcher: TXMPatcher {cands[0],ARM64.movX0_1,patchID: "txm_dev.get_task_allow",- description: "get-task-allow: bl -> mov x0,#1"+ description: "get-task-allow: bl -> mov x0,#1",)}@@ -425,7 +425,7 @@ public final class TXMDevPatcher: TXMPatcher {stubOff,branchToShellcode,patchID: "txm_dev.sel42_29_branch",- description: "selector42|29: branch to shellcode"+ description: "selector42|29: branch to shellcode",)// Shellcode body at cave@@ -433,25 +433,25 @@ public final class TXMDevPatcher: TXMPatcher {cave,ARM64.nop,patchID: "txm_dev.sel42_29_shell_nop",- description: "selector42|29 shellcode pad: udf -> nop"+ description: "selector42|29 shellcode pad: udf -> nop",)emit(cave + 4,ARM64.movX0_1,patchID: "txm_dev.sel42_29_shell_mov1",- description: "selector42|29 shellcode: mov x0,#1"+ description: "selector42|29 shellcode: mov x0,#1",)emit(cave + 8,ARM64.strbW0X20_30,patchID: "txm_dev.sel42_29_shell_strb",- description: "selector42|29 shellcode: strb w0,[x20,#0x30]"+ description: "selector42|29 shellcode: strb w0,[x20,#0x30]",)emit(cave + 12,ARM64.movX0X20,patchID: "txm_dev.sel42_29_shell_mov20",- description: "selector42|29 shellcode: mov x0,x20"+ description: "selector42|29 shellcode: mov x0,x20",)// Branch back to stub_off + 4 (skip the redirected first instruction)@@ -463,7 +463,7 @@ public final class TXMDevPatcher: TXMPatcher {cave + 16,branchBack,patchID: "txm_dev.sel42_29_shell_ret",- description: "selector42|29 shellcode: branch back"+ description: "selector42|29 shellcode: branch back",)}@@ -515,7 +515,7 @@ public final class TXMDevPatcher: TXMPatcher {cands[0],ARM64.movW0_1,patchID: "txm_dev.debugger_entitlement",- description: "debugger entitlement: bl -> mov w0,#1"+ description: "debugger entitlement: bl -> mov w0,#1",)}@@ -557,7 +557,7 @@ public final class TXMDevPatcher: TXMPatcher {cands[0],ARM64.nop,patchID: "txm_dev.developer_mode_bypass",- description: "developer mode bypass"+ description: "developer mode bypass",)}}diff --git a/sources/FirmwarePatcher/TXM/TXMPatcher.swift b/sources/FirmwarePatcher/TXM/TXMPatcher.swiftindex ea5b0657..1b598b8e 100644--- a/sources/FirmwarePatcher/TXM/TXMPatcher.swift+++ b/sources/FirmwarePatcher/TXM/TXMPatcher.swift@@ -69,7 +69,7 @@ public class TXMPatcher: Patcher {patchedBytes: patchBytes,beforeDisasm: beforeStr,afterDisasm: afterStr,- description: description+ description: description,)patches.append(record)@@ -110,7 +110,7 @@ extension TXMPatcher {legacyBL,ARM64.movX0_0,patchID: "txm.trustcache_bypass",- description: "trustcache bypass: legacy binary-search call → mov x0, #0"+ description: "trustcache bypass: legacy binary-search call → mov x0, #0",)return}@@ -120,7 +120,7 @@ extension TXMPatcher {selector24BL,ARM64.movX0_0,patchID: "txm.trustcache_bypass",- description: "trustcache bypass: selector24 hash-flags call → mov x0, #0"+ description: "trustcache bypass: selector24 hash-flags call → mov x0, #0",)return}@@ -129,7 +129,7 @@ extension TXMPatcher {print(" [-] TXM: selector24 hash-flags site and legacy binary-search site not found")}throw PatcherError.patchSiteNotFound(- "selector24 hash-flags call / legacy binary-search trustcache site not found"+ "selector24 hash-flags call / legacy binary-search trustcache site not found",)}@@ -204,7 +204,9 @@ extension TXMPatcher {if insn == pacibspU32 {return scan}- if scan == 0 { break }+ if scan == 0 {+ break+ }scan -= 4}return nildiff --git a/sources/VPhoneArchive/VPhoneArchiveExtractor.swift b/sources/VPhoneArchive/VPhoneArchiveExtractor.swiftindex 257641f0..14ab75d5 100644--- a/sources/VPhoneArchive/VPhoneArchiveExtractor.swift+++ b/sources/VPhoneArchive/VPhoneArchiveExtractor.swift@@ -34,7 +34,7 @@ public enum VPhoneArchiveExtractor {options: VPhoneArchiveExtractOptions,progress: ((Progress) -> Void)? = nil,bytesRead: ((Int64) -> Void)? = nil,- isCancelled: (() -> Bool)? = nil+ isCancelled: (() -> Bool)? = nil,) throws -> Int {let reader = archive_read_new()archive_read_support_format_all(reader)@@ -50,7 +50,7 @@ public enum VPhoneArchiveExtractor {guard archive_read_open_filename(reader, archive.path, blockSize) == ARCHIVE_OK else {throw VPhoneArchiveError.cannotOpen(- path: archive.path, reason: archiveErrorString(reader)+ path: archive.path, reason: archiveErrorString(reader),)}@@ -69,14 +69,18 @@ public enum VPhoneArchiveExtractor {var bytes: Int64 = 0while true {- if isCancelled?() == true { throw VPhoneArchiveError.cancelled }+ if isCancelled?() == true {+ throw VPhoneArchiveError.cancelled+ }var entry: OpaquePointer?let status = archive_read_next_header(reader, &entry)- if status == ARCHIVE_EOF { break }+ if status == ARCHIVE_EOF {+ break+ }guard status == ARCHIVE_OK || status == ARCHIVE_WARN, let entry else {throw VPhoneArchiveError.readFailed(- path: archive.path, reason: archiveErrorString(reader)+ path: archive.path, reason: archiveErrorString(reader),)}@@ -96,7 +100,7 @@ public enum VPhoneArchiveExtractor {let targetPath = target.standardized.pathguard targetPath == destinationPath || targetPath.hasPrefix(destinationPath + "/") else {throw VPhoneArchiveError.pathEscapesDestination(- member: memberPath, destination: destinationPath+ member: memberPath, destination: destinationPath,)}archive_entry_set_pathname(entry, targetPath)@@ -116,7 +120,7 @@ public enum VPhoneArchiveExtractor {let resolvedLink = linkTarget.standardized.pathguard resolvedLink.hasPrefix(destinationPath + "/") else {throw VPhoneArchiveError.pathEscapesDestination(- member: linkPath, destination: destinationPath+ member: linkPath, destination: destinationPath,)}archive_entry_set_hardlink(entry, resolvedLink)@@ -131,7 +135,7 @@ public enum VPhoneArchiveExtractor {guard archive_write_header(writer, entry) == ARCHIVE_OK else {throw VPhoneArchiveError.writeFailed(- path: target.path, reason: archiveErrorString(writer)+ path: target.path, reason: archiveErrorString(writer),)}@@ -140,13 +144,13 @@ public enum VPhoneArchiveExtractor {from: reader, to: writer, isCancelled: isCancelled,onBlock: bytesRead.map { report in{ report(archive_filter_bytes(reader, -1)) }- }+ },)}guard archive_write_finish_entry(writer) == ARCHIVE_OK else {throw VPhoneArchiveError.writeFailed(- path: target.path, reason: archiveErrorString(writer)+ path: target.path, reason: archiveErrorString(writer),)}@@ -187,7 +191,7 @@ public enum VPhoneArchiveExtractor {/// its metadata is left alone.private static func shouldSkipExistingDirectory(_ entry: OpaquePointer,- at target: URL+ at target: URL,) -> Bool {// S_IFDIR rather than AE_IFDIR: the AE_* names are C macros that Swift// does not import, and they are defined to the same values as the@@ -207,30 +211,34 @@ public enum VPhoneArchiveExtractor {from reader: OpaquePointer?,to writer: OpaquePointer?,isCancelled: (() -> Bool)?,- onBlock: (() -> Void)? = nil+ onBlock: (() -> Void)? = nil,) throws -> Int64 {var total: Int64 = 0while true {// Cancellation is checked per block, not per entry: a single// multi-gigabyte disk image is one entry, and a check that only// happens between entries would not interrupt it.- if isCancelled?() == true { throw VPhoneArchiveError.cancelled }+ if isCancelled?() == true {+ throw VPhoneArchiveError.cancelled+ }var buffer: UnsafeRawPointer?var size = 0var offset: la_int64_t = 0let status = archive_read_data_block(reader, &buffer, &size, &offset)- if status == ARCHIVE_EOF { return total }+ if status == ARCHIVE_EOF {+ return total+ }guard status == ARCHIVE_OK || status == ARCHIVE_WARN else {throw VPhoneArchiveError.readFailed(- path: "<member data>", reason: archiveErrorString(reader)+ path: "<member data>", reason: archiveErrorString(reader),)}guard archive_write_data_block(writer, buffer, size, offset) >= ARCHIVE_OK else {throw VPhoneArchiveError.writeFailed(- path: "<member data>", reason: archiveErrorString(writer)+ path: "<member data>", reason: archiveErrorString(writer),)}total += Int64(size)diff --git a/sources/VPhoneArchive/VPhoneArchiveOptions.swift b/sources/VPhoneArchive/VPhoneArchiveOptions.swiftindex ffd173d4..96240585 100644--- a/sources/VPhoneArchive/VPhoneArchiveOptions.swift+++ b/sources/VPhoneArchive/VPhoneArchiveOptions.swift@@ -72,7 +72,7 @@ public struct VPhoneArchiveExtractOptions: Sendable {exactPermissions: Bool = false,noOverwriteDir: Bool = false,macMetadata: Bool = false,- extendedMetadata: Bool = false+ extendedMetadata: Bool = false,) {self.ownership = ownershipself.exactPermissions = exactPermissions@@ -96,7 +96,7 @@ public struct VPhoneArchiveExtractOptions: Sendable {exactPermissions: true,noOverwriteDir: true,macMetadata: false,- extendedMetadata: true+ extendedMetadata: true,)/// Unpacking into a host directory we own and can throw away.@@ -116,7 +116,7 @@ public struct VPhoneArchiveExtractOptions: Sendable {exactPermissions: false,noOverwriteDir: false,macMetadata: false,- extendedMetadata: false+ extendedMetadata: false,)/// The libarchive `archive_write_disk` flags for these options.@@ -153,10 +153,18 @@ public struct VPhoneArchiveExtractOptions: Sendable {// archive_write_disk_new(). Setting it unconditionally is how `vm// import` came to write a world-writable, setuid tree out of an// archive from somewhere else. See the two presets above.- if exactPermissions { flags |= ARCHIVE_EXTRACT_PERM }- if ownership == .preserveNumeric { flags |= ARCHIVE_EXTRACT_OWNER }- if extendedMetadata { flags |= ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS }- if macMetadata { flags |= ARCHIVE_EXTRACT_MAC_METADATA }+ if exactPermissions {+ flags |= ARCHIVE_EXTRACT_PERM+ }+ if ownership == .preserveNumeric {+ flags |= ARCHIVE_EXTRACT_OWNER+ }+ if extendedMetadata {+ flags |= ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS+ }+ if macMetadata {+ flags |= ARCHIVE_EXTRACT_MAC_METADATA+ }return Int32(flags)}diff --git a/sources/VPhoneArchive/VPhoneArchivePaths.swift b/sources/VPhoneArchive/VPhoneArchivePaths.swiftindex 034c1587..ddf381af 100644--- a/sources/VPhoneArchive/VPhoneArchivePaths.swift+++ b/sources/VPhoneArchive/VPhoneArchivePaths.swift@@ -18,7 +18,7 @@ enum VPhoneArchivePaths {static func resolved(_ url: URL) throws -> URL {guard let resolved = realpath(url.path, nil) else {throw VPhoneArchiveError.cannotOpen(- path: url.path, reason: String(cString: strerror(errno))+ path: url.path, reason: String(cString: strerror(errno)),)}defer { free(resolved) }@@ -30,8 +30,12 @@ enum VPhoneArchivePaths {/// Empty when it *is* the root, which the caller skips: an archive should/// not carry an entry for the directory it was made from.static func relative(_ absolute: String, under root: String) -> String {- if absolute == root { return "" }- if absolute.hasPrefix(root + "/") { return String(absolute.dropFirst(root.count + 1)) }+ if absolute == root {+ return ""+ }+ if absolute.hasPrefix(root + "/") {+ return String(absolute.dropFirst(root.count + 1))+ }return absolute}}diff --git a/sources/VPhoneArchive/VPhoneArchiveReader.swift b/sources/VPhoneArchive/VPhoneArchiveReader.swiftindex 0e3b47dc..e7041058 100644--- a/sources/VPhoneArchive/VPhoneArchiveReader.swift+++ b/sources/VPhoneArchive/VPhoneArchiveReader.swift@@ -50,20 +50,24 @@ public enum VPhoneArchiveReader {var data = Data()let hint = archive_entry_size(entry)- if hint > 0 { data.reserveCapacity(Int(hint)) }+ if hint > 0 {+ data.reserveCapacity(Int(hint))+ }var buffer = [UInt8](repeating: 0, count: 65536)while true {let read = buffer.withUnsafeMutableBytes {archive_read_data(reader, $0.baseAddress, $0.count)}- if read == 0 { break }+ if read == 0 {+ break+ }guard read > 0 else {throw VPhoneArchiveError.readFailed(- path: archive.path, reason: archiveErrorString(reader)+ path: archive.path, reason: archiveErrorString(reader),)}- data.append(contentsOf: buffer[0..<Int(read)])+ data.append(contentsOf: buffer[0 ..< Int(read)])}return data}@@ -85,7 +89,7 @@ public enum VPhoneArchiveReader {private static func withReader<T>(_ archive: URL,- _ body: (OpaquePointer?) throws -> T+ _ body: (OpaquePointer?) throws -> T,) throws -> T {let reader = archive_read_new()archive_read_support_format_all(reader)@@ -95,7 +99,7 @@ public enum VPhoneArchiveReader {guard archive_read_open_filename(reader, archive.path, blockSize) == ARCHIVE_OK else {throw VPhoneArchiveError.cannotOpen(- path: archive.path, reason: archiveErrorString(reader)+ path: archive.path, reason: archiveErrorString(reader),)}return try body(reader)@@ -103,14 +107,16 @@ public enum VPhoneArchiveReader {private static func nextHeader(_ reader: OpaquePointer?,- archive: URL+ archive: URL,) throws -> OpaquePointer? {var entry: OpaquePointer?let status = archive_read_next_header(reader, &entry)- if status == ARCHIVE_EOF { return nil }+ if status == ARCHIVE_EOF {+ return nil+ }guard status == ARCHIVE_OK || status == ARCHIVE_WARN else {throw VPhoneArchiveError.readFailed(- path: archive.path, reason: archiveErrorString(reader)+ path: archive.path, reason: archiveErrorString(reader),)}return entry@@ -130,7 +136,7 @@ public enum VPhoneArchiveReader {uid: Int(archive_entry_uid(entry)),gid: Int(archive_entry_gid(entry)),modified: mtime,- linkTarget: archive_entry_symlink(entry).map { String(cString: $0) }+ linkTarget: archive_entry_symlink(entry).map { String(cString: $0) },)}}diff --git a/sources/VPhoneArchive/VPhoneArchiveWriter.swift b/sources/VPhoneArchive/VPhoneArchiveWriter.swiftindex 6a5a9cdc..cd943173 100644--- a/sources/VPhoneArchive/VPhoneArchiveWriter.swift+++ b/sources/VPhoneArchive/VPhoneArchiveWriter.swift@@ -38,7 +38,7 @@ public enum VPhoneArchiveWriter {excluding patterns: [String] = [],progress: ((Progress) -> Void)? = nil,bytesPacked: ((Int64) -> Void)? = nil,- isCancelled: (() -> Bool)? = nil+ isCancelled: (() -> Bool)? = nil,) throws -> Int {let writer = archive_write_new()defer { archive_write_free(writer) }@@ -73,7 +73,7 @@ public enum VPhoneArchiveWriter {guard archive_write_open_filename(writer, archive.path) == ARCHIVE_OK else {throw VPhoneArchiveError.cannotOpen(- path: archive.path, reason: archiveErrorString(writer)+ path: archive.path, reason: archiveErrorString(writer),)}defer { archive_write_close(writer) }@@ -107,7 +107,7 @@ public enum VPhoneArchiveWriter {let resolvedRoot = try VPhoneArchivePaths.resolved(root)guard archive_read_disk_open(disk, resolvedRoot.path) == ARCHIVE_OK else {throw VPhoneArchiveError.cannotOpen(- path: resolvedRoot.path, reason: archiveErrorString(disk)+ path: resolvedRoot.path, reason: archiveErrorString(disk),)}@@ -131,16 +131,20 @@ public enum VPhoneArchiveWriter {var bytes: Int64 = 0while true {- if isCancelled?() == true { throw VPhoneArchiveError.cancelled }+ if isCancelled?() == true {+ throw VPhoneArchiveError.cancelled+ }let entry = archive_entry_new()defer { archive_entry_free(entry) }let status = archive_read_next_header2(disk, entry)- if status == ARCHIVE_EOF { break }+ if status == ARCHIVE_EOF {+ break+ }guard status == ARCHIVE_OK || status == ARCHIVE_WARN else {throw VPhoneArchiveError.readFailed(- path: root.path, reason: archiveErrorString(disk)+ path: root.path, reason: archiveErrorString(disk),)}@@ -171,7 +175,7 @@ public enum VPhoneArchiveWriter {guard archive_write_header(writer, resolved) == ARCHIVE_OK else {throw VPhoneArchiveError.writeFailed(- path: stored, reason: archiveErrorString(writer)+ path: stored, reason: archiveErrorString(writer),)}@@ -206,14 +210,14 @@ public enum VPhoneArchiveWriter {guard archive_read_open_filename(reader, input.path, 10240) == ARCHIVE_OK else {throw VPhoneArchiveError.cannotOpen(- path: input.path, reason: archiveErrorString(reader)+ path: input.path, reason: archiveErrorString(reader),)}var entry: OpaquePointer?guard archive_read_next_header(reader, &entry) == ARCHIVE_OK else {throw VPhoneArchiveError.readFailed(- path: input.path, reason: archiveErrorString(reader)+ path: input.path, reason: archiveErrorString(reader),)}@@ -228,13 +232,15 @@ public enum VPhoneArchiveWriter {let read = buffer.withUnsafeMutableBytes {archive_read_data(reader, $0.baseAddress, $0.count)}- if read == 0 { break }+ if read == 0 {+ break+ }guard read > 0 else {throw VPhoneArchiveError.readFailed(- path: input.path, reason: archiveErrorString(reader)+ path: input.path, reason: archiveErrorString(reader),)}- try handle.write(contentsOf: buffer[0..<Int(read)])+ try handle.write(contentsOf: buffer[0 ..< Int(read)])}}@@ -244,11 +250,11 @@ public enum VPhoneArchiveWriter {_ writer: OpaquePointer?,_ filter: String,_ key: String,- _ value: String+ _ value: String,) throws {guard archive_write_set_filter_option(writer, filter, key, value) == ARCHIVE_OK else {throw VPhoneArchiveError.writeFailed(- path: "<filter \(filter)>", reason: archiveErrorString(writer)+ path: "<filter \(filter)>", reason: archiveErrorString(writer),)}}@@ -268,7 +274,7 @@ public enum VPhoneArchiveWriter {at path: String,into writer: OpaquePointer?,isCancelled: (() -> Bool)?,- onBytes: (Int64) -> Void+ onBytes: (Int64) -> Void,) throws {guard let handle = FileHandle(forReadingAtPath: path) else {throw VPhoneArchiveError.cannotOpen(path: path, reason: "cannot read")@@ -276,14 +282,16 @@ public enum VPhoneArchiveWriter {defer { try? handle.close() }while true {- if isCancelled?() == true { throw VPhoneArchiveError.cancelled }+ if isCancelled?() == true {+ throw VPhoneArchiveError.cancelled+ }guard let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty else { break }let sent = chunk.withUnsafeBytes {archive_write_data(writer, $0.baseAddress, $0.count)}guard sent > 0 else {throw VPhoneArchiveError.writeFailed(- path: path, reason: archiveErrorString(writer)+ path: path, reason: archiveErrorString(writer),)}onBytes(Int64(sent))diff --git a/sources/VPhoneArchive/VPhoneBundleTransfer.swift b/sources/VPhoneArchive/VPhoneBundleTransfer.swiftindex 043a15ae..285c1dff 100644--- a/sources/VPhoneArchive/VPhoneBundleTransfer.swift+++ b/sources/VPhoneArchive/VPhoneBundleTransfer.swift@@ -14,7 +14,9 @@ public enum VPhoneBundleTransferError: Error, Equatable, CustomStringConvertible}}- public var errorDescription: String? { description }+ public var errorDescription: String? {+ description+ }}// MARK: - VPhoneBundleTransfer@@ -51,7 +53,9 @@ public enum VPhoneBundleTransfer {/// Extension for auto-named output when `export`'s destination is a/// directory.- public var fileExtension: String { archiveCompression.tarExtension }+ public var fileExtension: String {+ archiveCompression.tarExtension+ }}// MARK: - Export@@ -70,9 +74,9 @@ public enum VPhoneBundleTransfer {includeIPSW: Bool,compression: ExportCompression = .fast,in library: VPhoneLibrary,- progress: ((Int64, Int64) -> Void)? = nil+ progress: ((Int64, Int64) -> Void)? = nil,) throws -> URL {- _ = try library.bundle(named: name) // validate it exists+ _ = try library.bundle(named: name) // validate it existsvar isDir: ObjCBool = falselet outFile = FileManager.default.fileExists(atPath: outFile.path, isDirectory: &isDir)&& isDir.boolValue@@ -81,7 +85,9 @@ public enum VPhoneBundleTransfer {let bundleDir = library.url(forName: name)var excludes = VPhoneBundleOps.exportExcludePatterns- if !includeIPSW { excludes.append("*_Restore*") }+ if !includeIPSW {+ excludes.append("*_Restore*")+ }let total = progress != nil? archivedLogicalSize(bundleDir: bundleDir, includeIPSW: includeIPSW)@@ -101,7 +107,7 @@ public enum VPhoneBundleTransfer {format: .gnutar,compression: compression.archiveCompression,excluding: excludes,- bytesPacked: progress.map { report in { done in report(done, total) } }+ bytesPacked: progress.map { report in { done in report(done, total) } },)return outFile}@@ -120,13 +126,15 @@ public enum VPhoneBundleTransfer {let fm = FileManager.defaultguard let en = fm.enumerator(at: bundleDir, includingPropertiesForKeys: keys)else { return 0 }- let prefix = bundleDir.path.count + 1 // members are relative to the bundle+ let prefix = bundleDir.path.count + 1 // members are relative to the bundlevar total: Int64 = 0var countedInodes = Set<Inode>()for case let url as URL in en {guard url.path.count > prefix else { continue }let rel = String(url.path.dropFirst(prefix))- if !includeIPSW, rel.contains("_Restore") { en.skipDescendants(); continue }+ if !includeIPSW, rel.contains("_Restore") {+ en.skipDescendants(); continue+ }if VPhoneBundleOps.exportExcludePatterns.contains(where: { fnmatch($0, rel, 0) == 0 }) {continue}@@ -170,7 +178,7 @@ public enum VPhoneBundleTransfer {from inFile: URL,name: String?,in library: VPhoneLibrary,- progress: ((Int64, Int64) -> Void)? = nil+ progress: ((Int64, Int64) -> Void)? = nil,) throws -> VPhoneBundle {let fm = FileManager.default// Fail fast when the destination name is already known (explicit rename).@@ -200,7 +208,7 @@ public enum VPhoneBundleTransfer {inFile,into: staging,options: .intoHostDirectory,- bytesRead: progress.map { report in { done in report(done, total) } }+ bytesRead: progress.map { report in { done in report(done, total) } },)// A tar reader stops at the end-of-archive marker, which in a// compressed file can sit short of the last byte, so the read position@@ -210,16 +218,20 @@ public enum VPhoneBundleTransfer {let entries = try fm.contentsOfDirectory(atPath: staging.path)guard entries.count == 1, let archived = entries.first else {throw VPhoneBundleTransferError.badArchive(- "This archive is not a VM export. Choose an archive created by 'vphone-cli vm export'.")+ "This archive is not a VM export. Choose an archive created by 'vphone-cli vm export'.",+ )}let finalName = name ?? archivedtry VPhoneBundleOps.requireValidName(finalName)let dst = library.url(forName: finalName)- if fm.fileExists(atPath: dst.path) { throw VPhoneLibraryError.alreadyExists(name: finalName) }+ if fm.fileExists(atPath: dst.path) {+ throw VPhoneLibraryError.alreadyExists(name: finalName)+ }let extracted = staging.appendingPathComponent(archived)guard fm.fileExists(atPath: extracted.appendingPathComponent("config.plist").path) else {throw VPhoneBundleTransferError.badArchive(- "This archive does not contain a valid VM. Choose an archive created by 'vphone-cli vm export'.")+ "This archive does not contain a valid VM. Choose an archive created by 'vphone-cli vm export'.",+ )}let bundle = try VPhoneBundle.load(at: extracted)try fm.moveItem(at: extracted, to: dst)diff --git a/sources/VPhoneArchive/VPhoneIPSWCache.swift b/sources/VPhoneArchive/VPhoneIPSWCache.swiftindex 06e7093b..5d1f0c8e 100644--- a/sources/VPhoneArchive/VPhoneIPSWCache.swift+++ b/sources/VPhoneArchive/VPhoneIPSWCache.swift@@ -33,12 +33,14 @@ public enum VPhoneIPSWCache {public static func resolve(_ source: String,in cacheDirectory: URL,- session: URLSession = .shared+ session: URLSession = .shared,) async throws -> Archive {guard let url = URL(string: source), let scheme = url.scheme?.lowercased() else {return try inspect(URL(fileURLWithPath: source))}- if scheme == "file" { return try inspect(url) }+ if scheme == "file" {+ return try inspect(url)+ }guard scheme == "http" || scheme == "https" else {throw Error.unsupportedSource(source)}@@ -47,7 +49,9 @@ public enum VPhoneIPSWCache {try fm.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)let cache = cacheDirectory.appendingPathComponent(cacheName(for: url))if fm.fileExists(atPath: cache.path) {- if let valid = try? inspect(cache) { return valid }+ if let valid = try? inspect(cache) {+ return valid+ }try fm.removeItem(at: cache)}@@ -61,7 +65,7 @@ public enum VPhoneIPSWCache {let size = try Int64(fm.attributesOfItem(atPath: downloaded.path)[.size] as? UInt64 ?? 0)if response.expectedContentLength > 0, size != response.expectedContentLength {throw Error.incompleteDownload(- url, expected: response.expectedContentLength, actual: size+ url, expected: response.expectedContentLength, actual: size,)}@@ -79,7 +83,7 @@ public enum VPhoneIPSWCache {}guard let data = try? VPhoneArchiveReader.readMember("BuildManifest.plist", from: file),let plist = try? PropertyListSerialization.propertyList(from: data, format: nil)- as? [String: Any],+ as? [String: Any],let version = plist["ProductVersion"] as? String, !version.isEmpty,let build = plist["ProductBuildVersion"] as? String, !build.isEmptyelse {diff --git a/sources/VPhoneArchive/VPhoneTreeFingerprint.swift b/sources/VPhoneArchive/VPhoneTreeFingerprint.swiftindex e7f3d955..dab70c41 100644--- a/sources/VPhoneArchive/VPhoneTreeFingerprint.swift+++ b/sources/VPhoneArchive/VPhoneTreeFingerprint.swift@@ -62,9 +62,9 @@ public struct VPhoneTreeFingerprint: Codable, Equatable, Sendable {var paths: [String] = []- // An explicit walk rather than FileManager's enumerator, which follows- // its own rules about symlinks and packages. This has to see exactly- // what is on disk, in a stable order.+ /// An explicit walk rather than FileManager's enumerator, which follows+ /// its own rules about symlinks and packages. This has to see exactly+ /// what is on disk, in a stable order.func walk(_ directory: String) throws {let names = try FileManager.default.contentsOfDirectory(atPath: directory)for name in names.sorted() {@@ -72,13 +72,15 @@ public struct VPhoneTreeFingerprint: Codable, Equatable, Sendable {paths.append(full)var info = stat()guard lstat(full, &info) == 0 else { continue }- if (info.st_mode & S_IFMT) == S_IFDIR { try walk(full) }+ if (info.st_mode & S_IFMT) == S_IFDIR {+ try walk(full)+ }}}try walk(rootPath)// Hardlink groups, assigned in path order so the numbering is stable.- var groupOf: [String: Int] = [:] // "dev:ino" -> group+ var groupOf: [String: Int] = [:] // "dev:ino" -> groupvar linkCounts: [String: Int] = [:]for path in paths {var info = stat()@@ -123,7 +125,7 @@ public struct VPhoneTreeFingerprint: Codable, Equatable, Sendable {blocks: Int64(info.st_blocks),contentSHA256: includeContentHashes && fileType == S_IFREG? digest(of: path)- : nil+ : nil,))}@@ -147,13 +149,21 @@ public struct VPhoneTreeFingerprint: Codable, Equatable, Sendable {}for path in Set(mine.keys).intersection(theirs.keys).sorted() {let a = mine[path]!, b = theirs[path]!- if a == b { continue }- if a.type != b.type { found.append("\(path): type \(a.type) vs \(b.type)") }- if a.mode != b.mode { found.append("\(path): mode \(a.mode) vs \(b.mode)") }+ if a == b {+ continue+ }+ if a.type != b.type {+ found.append("\(path): type \(a.type) vs \(b.type)")+ }+ if a.mode != b.mode {+ found.append("\(path): mode \(a.mode) vs \(b.mode)")+ }if a.uid != b.uid || a.gid != b.gid {found.append("\(path): owner \(a.uid):\(a.gid) vs \(b.uid):\(b.gid)")}- if a.size != b.size { found.append("\(path): size \(a.size) vs \(b.size)") }+ if a.size != b.size {+ found.append("\(path): size \(a.size) vs \(b.size)")+ }if a.mtimeNanoseconds != b.mtimeNanoseconds {found.append("\(path): mtime \(a.mtimeNanoseconds) vs \(b.mtimeNanoseconds)")}@@ -166,11 +176,15 @@ public struct VPhoneTreeFingerprint: Codable, Equatable, Sendable {if a.xattrs != b.xattrs {found.append("\(path): xattrs \(a.xattrs.keys.sorted()) vs \(b.xattrs.keys.sorted())")}- if a.acl != b.acl { found.append("\(path): ACL differs") }+ if a.acl != b.acl {+ found.append("\(path): ACL differs")+ }if a.blocks != b.blocks {found.append("\(path): occupancy \(a.blocks) vs \(b.blocks) blocks (sparseness)")}- if a.contentSHA256 != b.contentSHA256 { found.append("\(path): contents differ") }+ if a.contentSHA256 != b.contentSHA256 {+ found.append("\(path): contents differ")+ }}return found}diff --git a/sources/VPhoneCore/VPhoneAEA.swift b/sources/VPhoneCore/VPhoneAEA.swiftindex 1373e36a..2475d5ea 100644--- a/sources/VPhoneCore/VPhoneAEA.swift+++ b/sources/VPhoneCore/VPhoneAEA.swift@@ -124,17 +124,17 @@ public enum VPhoneAEA {}let privateKey = try P256.KeyAgreement.PrivateKey(- pemRepresentation: String(decoding: pem, as: UTF8.self)+ pemRepresentation: String(decoding: pem, as: UTF8.self),)var recipient = try HPKE.Recipient(privateKey: privateKey,ciphersuite: HPKE.Ciphersuite(- kem: .P256_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256+ kem: .P256_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256,),info: Data(),- encapsulatedKey: encapsulated+ encapsulatedKey: encapsulated,)- return "base64:" + (try recipient.open(wrapped)).base64EncodedString()+ return try "base64:" + (recipient.open(wrapped)).base64EncodedString()}// MARK: - Re-encryption metadata@@ -172,7 +172,9 @@ public enum VPhoneAEA {}private extension Data {- var hexString: String { map { String(format: "%02x", $0) }.joined() }+ var hexString: String {+ map { String(format: "%02x", $0) }.joined()+ }}// MARK: - Running one async call from synchronous code@@ -189,12 +191,12 @@ private extension Data {/// caller's actor, or a call made on the main actor would block the queue the/// work is waiting to run on.public func vphoneRunBlocking<T: Sendable>(- _ body: @escaping @Sendable () async throws -> T+ _ body: @escaping @Sendable () async throws -> T,) throws -> T {let semaphore = DispatchSemaphore(value: 0)nonisolated(unsafe) var result: Result<T, Swift.Error>!Task.detached {- do { result = .success(try await body()) } catch { result = .failure(error) }+ do { result = try await .success(body()) } catch { result = .failure(error) }semaphore.signal()}semaphore.wait()diff --git a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift b/sources/VPhoneCore/VPhoneAPFSSnapshot.swiftindex 7f8d2378..ef0d484e 100644--- a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift+++ b/sources/VPhoneCore/VPhoneAPFSSnapshot.swift@@ -43,7 +43,7 @@ public enum VPhoneAPFSSnapshotError: Error, CustomStringConvertible {/// same SHA-256.public enum VPhoneAPFSSnapshot {public static let blockSize = 4096- public static let oldPrefix = Array("com.apple.os.update-".utf8) // 20 bytes+ public static let oldPrefix = Array("com.apple.os.update-".utf8) // 20 bytespublic static let defaultNewPrefix = "orig-fs.disabled.rn-"/// One `com.apple.os.update-*` record, and where it lives.@@ -60,8 +60,13 @@ public enum VPhoneAPFSSnapshot {/// Records grouped by block, in ascending block order.public let blocks: [(blockOffset: Int, offsetsInBlock: [Int])]- public var recordCount: Int { blocks.reduce(0) { $0 + $1.offsetsInBlock.count } }- public var isEmpty: Bool { blocks.isEmpty }+ public var recordCount: Int {+ blocks.reduce(0) { $0 + $1.offsetsInBlock.count }+ }++ public var isEmpty: Bool {+ blocks.isEmpty+ }}// MARK: - Checksum@@ -97,9 +102,9 @@ public enum VPhoneAPFSSnapshot {private static func isHexDigit(_ byte: UInt8) -> Bool {switch byte {- case UInt8(ascii: "0")...UInt8(ascii: "9"),- UInt8(ascii: "a")...UInt8(ascii: "f"),- UInt8(ascii: "A")...UInt8(ascii: "F"):+ case UInt8(ascii: "0") ... UInt8(ascii: "9"),+ UInt8(ascii: "a") ... UInt8(ascii: "f"),+ UInt8(ascii: "A") ... UInt8(ascii: "F"):truedefault:false@@ -145,28 +150,32 @@ public enum VPhoneAPFSSnapshot {let hashStart = i + oldPrefix.countvar allHex = true- for k in 0..<hashLength {- if !isHexDigit(image[hashStart + k]) { allHex = false; break }+ for k in 0 ..< hashLength {+ if !isHexDigit(image[hashStart + k]) {+ allHex = false; break+ }}guard allHex else { i += 1; continue }let blockOffset = (i / blockSize) * blockSizeguard blockOffset + blockSize <= image.count else { i += 1; continue }- let block = UnsafeRawBufferPointer(rebasing: image[blockOffset..<blockOffset + blockSize])+ let block = UnsafeRawBufferPointer(rebasing: image[blockOffset ..< blockOffset + blockSize])guard blockIsValid(block) else { i += 1; continue }if name == nil {- let bytes = (0..<needLength).map { image[i + $0] }+ let bytes = (0 ..< needLength).map { image[i + $0] }name = String(decoding: bytes, as: UTF8.self)}- if byBlock[blockOffset] == nil { order.append(blockOffset) }+ if byBlock[blockOffset] == nil {+ order.append(blockOffset)+ }byBlock[blockOffset, default: []].append(i - blockOffset)i += 1}return Report(snapshotName: name,- blocks: order.sorted().map { ($0, byBlock[$0]!) }+ blocks: order.sorted().map { ($0, byBlock[$0]!) },)}@@ -182,12 +191,12 @@ public enum VPhoneAPFSSnapshot {imageAt url: URL,newPrefix: String = defaultNewPrefix,dryRun: Bool = false,- log: (String) -> Void = { print($0) }+ log: (String) -> Void = { print($0) },) throws -> Report {let newPrefixBytes = Array(newPrefix.utf8)guard newPrefixBytes.count == oldPrefix.count else {throw VPhoneAPFSSnapshotError.prefixLengthMismatch(- given: newPrefixBytes.count, required: oldPrefix.count+ given: newPrefixBytes.count, required: oldPrefix.count,)}@@ -211,11 +220,14 @@ public enum VPhoneAPFSSnapshot {for offset in stride(from: 0, to: length, by: windowSize) {let count = min(windowSize, length - offset)guard let base = mmap(nil, count, PROT_READ, MAP_PRIVATE, fd, off_t(offset)),- base != MAP_FAILED else {+ base != MAP_FAILED+ else {throw VPhoneAPFSSnapshotError.cannotMap(url, errno: errno)}let part = scan(UnsafeRawBufferPointer(start: base, count: count))- if snapshotName == nil { snapshotName = part.snapshotName }+ if snapshotName == nil {+ snapshotName = part.snapshotName+ }blocks.append(contentsOf: part.blocks.map {(blockOffset: offset + $0.blockOffset, offsetsInBlock: $0.offsetsInBlock)})@@ -255,7 +267,9 @@ public enum VPhoneAPFSSnapshot {let sum = checksum(UnsafeRawBufferPointer(raw))var littleEndian = sum.littleEndianwithUnsafeBytes(of: &littleEndian) { bytes in- for (k, byte) in bytes.enumerated() { raw[k] = byte }+ for (k, byte) in bytes.enumerated() {+ raw[k] = byte+ }}}let written = block.withUnsafeBytes {diff --git a/sources/VPhoneCore/VPhoneBootCLI.swift b/sources/VPhoneCore/VPhoneBootCLI.swiftindex ae224cd1..b07ee41f 100644--- a/sources/VPhoneCore/VPhoneBootCLI.swift+++ b/sources/VPhoneCore/VPhoneBootCLI.swift@@ -3,9 +3,9 @@ import Foundation// MARK: - Manifest values the CLI can take as arguments-// Kept here, with the other ArgumentParser conformances, rather than beside-// the type: the manifest is a data model and has no other reason to know that-// a command line exists.+/// Kept here, with the other ArgumentParser conformances, rather than beside+/// the type: the manifest is a data model and has no other reason to know that+/// a command line exists.extension VPhoneVirtualMachineManifest.PlatformFusing: ExpressibleByArgument {}// MARK: - VPhoneBootCLI@@ -41,13 +41,13 @@ public struct VPhoneBootCLI: ParsableCommand {Example:vphone-cli --config ./config.plist- """+ """,)@Option(name: .shortAndLong,help: "Path to VM manifest plist (config.plist). Required.",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)public var config: URL@@ -65,7 +65,7 @@ public struct VPhoneBootCLI: ParsableCommand {@Option(help: "Automatically install the given IPA/TIPA after the guest control channel connects. Unavailable with --dfu.",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)public var installIPA: URL?@@ -84,15 +84,16 @@ public struct VPhoneBootCLI: ParsableCommand {if !dfu,let bundle = try? VPhoneBundle.load(at: config.deletingLastPathComponent()),let existingVariant = VPhoneRestoreInfo.load(fromBundle: bundle)?.variant,- existingVariant != "jb" {+ existingVariant != "jb"+ {throw ValidationError(- "This VM was created as '\(existingVariant)'. Only JB VMs are supported by this build."+ "This VM was created as '\(existingVariant)'. Only JB VMs are supported by this build.",)}if dfu, let packageURL = installPackageURL {throw ValidationError(- "`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)"+ "`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)",)}@@ -104,7 +105,7 @@ public struct VPhoneBootCLI: ParsableCommand {guard VPhoneInstallPackage.isSupportedFile(packageURL) else {throw ValidationError(- "`--install-ipa` only supports .ipa or .tipa packages: \(packageURL.lastPathComponent)"+ "`--install-ipa` only supports .ipa or .tipa packages: \(packageURL.lastPathComponent)",)}}@@ -123,11 +124,21 @@ public struct VPhoneBootCLI: ParsableCommand {/// command, so its arguments start at the first option.public var bootArguments: [String] {var args = ["--config", config.path]- if dfu { args.append("--dfu") }- if headless { args.append("--headless") }- if vphonedBin != ".vphoned.signed" { args += ["--vphoned-bin", vphonedBin] }- if let port = kernelDebugPort { args += ["--kernel-debug-port", String(port)] }- if let ipa = installIPA { args += ["--install-ipa", ipa.path] }+ if dfu {+ args.append("--dfu")+ }+ if headless {+ args.append("--headless")+ }+ if vphonedBin != ".vphoned.signed" {+ args += ["--vphoned-bin", vphonedBin]+ }+ if let port = kernelDebugPort {+ args += ["--kernel-debug-port", String(port)]+ }+ if let ipa = installIPA {+ args += ["--install-ipa", ipa.path]+ }return args}}diff --git a/sources/VPhoneCore/VPhoneBootPatterns.swift b/sources/VPhoneCore/VPhoneBootPatterns.swiftindex e735aa09..066b7164 100644--- a/sources/VPhoneCore/VPhoneBootPatterns.swift+++ b/sources/VPhoneCore/VPhoneBootPatterns.swift@@ -10,8 +10,12 @@ public enum VPhoneBootPatterns {/// Accept 1-16 ASCII hex digits, with an optional 0x prefix.public static func normalizeECID(_ raw: String) -> String? {var value = raw- if value.hasPrefix("0x") { value.removeFirst(2) }- if value.hasPrefix("0X") { value.removeFirst(2) }+ if value.hasPrefix("0x") {+ value.removeFirst(2)+ }+ if value.hasPrefix("0X") {+ value.removeFirst(2)+ }guard !value.isEmpty, value.count <= 16, value.allSatisfy(isASCIIHexDigit) else {return nil}@@ -23,7 +27,7 @@ public enum VPhoneBootPatterns {/// that the shell's `[[ =~ ^[0-9A-Fa-f]{1,16}$ ]]` would reject.private static func isASCIIHexDigit(_ c: Character) -> Bool {guard let ascii = c.asciiValue else { return false }- return (0x30...0x39).contains(ascii) || (0x41...0x46).contains(ascii) || (0x61...0x66).contains(ascii)+ return (0x30 ... 0x39).contains(ascii) || (0x41 ... 0x46).contains(ascii) || (0x61 ... 0x66).contains(ascii)}// `parseHVVmmPresent` lived here: the string form of `sysctl -ndiff --git a/sources/VPhoneCore/VPhoneBundle.swift b/sources/VPhoneCore/VPhoneBundle.swiftindex 8af12ed9..70c06011 100644--- a/sources/VPhoneCore/VPhoneBundle.swift+++ b/sources/VPhoneCore/VPhoneBundle.swift@@ -11,8 +11,13 @@ public struct VPhoneBundle: Sendable {self.manifest = manifest}- public var name: String { url.lastPathComponent }- public var configURL: URL { url.appendingPathComponent("config.plist") }+ public var name: String {+ url.lastPathComponent+ }++ public var configURL: URL {+ url.appendingPathComponent("config.plist")+ }public var diskSizeBytes: Int64 {let disk = url.appendingPathComponent(manifest.diskImage)@@ -22,7 +27,8 @@ public struct VPhoneBundle: Sendable {public static func load(at url: URL) throws -> VPhoneBundle {let manifest = try VPhoneVirtualMachineManifest.load(- from: url.appendingPathComponent("config.plist"))+ from: url.appendingPathComponent("config.plist"),+ )return VPhoneBundle(url: url, manifest: manifest)}}diff --git a/sources/VPhoneCore/VPhoneBundleOps.swift b/sources/VPhoneCore/VPhoneBundleOps.swiftindex 780d7ca6..cf91381c 100644--- a/sources/VPhoneCore/VPhoneBundleOps.swift+++ b/sources/VPhoneCore/VPhoneBundleOps.swift@@ -16,7 +16,7 @@ public enum VPhoneBundleOps {memoryMB: UInt64,diskSizeGB: UInt64,romSource: URL,- sepromSource: URL+ sepromSource: URL,) {self.name = name; self.cpuCount = cpuCount; self.memoryMB = memoryMBself.diskSizeGB = diskSizeGB; self.romSource = romSource; self.sepromSource = sepromSource@@ -29,6 +29,7 @@ public enum VPhoneBundleOps {public static func defaultROMSource() -> URL {frameworkResources.appendingPathComponent("AVPBooter.vresearch1.bin")}+public static func defaultSEPROMSource() -> URL {frameworkResources.appendingPathComponent("AVPSEPBooter.vresearch1.bin")}@@ -77,7 +78,8 @@ public enum VPhoneBundleOps {cpuCount: spec.cpuCount,memorySize: spec.memoryMB * 1024 * 1024,romImages: .init(avpBooter: "AVPBooter.vresearch1.bin",- avpSEPBooter: "AVPSEPBooter.vresearch1.bin"))+ avpSEPBooter: "AVPSEPBooter.vresearch1.bin"),+ )try manifest.write(to: dir.appendingPathComponent("config.plist"))return VPhoneBundle(url: dir, manifest: manifest)@@ -95,7 +97,7 @@ public enum VPhoneBundleOps {cpuCount: UInt?,memoryMB: UInt64?,networkMode: VPhoneVirtualMachineManifest.NetworkConfig.NetworkMode? = nil,- bridgeInterface: String? = nil+ bridgeInterface: String? = nil,) throws -> VPhoneBundle {let bundle = try library.bundle(named: name)let editsNetwork = networkMode != nil || bridgeInterface != nil@@ -103,12 +105,14 @@ public enum VPhoneBundleOps {? try VPhoneNetworking.merge(into: bundle.manifest.networkConfig,mode: networkMode,- bridgeInterface: bridgeInterface)+ bridgeInterface: bridgeInterface,+ ): nillet updated = bundle.manifest.updating(cpuCount: cpuCount,memorySize: memoryMB.map { $0 * 1024 * 1024 },- networkConfig: network)+ networkConfig: network,+ )try updated.write(to: bundle.configURL)return VPhoneBundle(url: bundle.url, manifest: updated)}@@ -118,7 +122,7 @@ public enum VPhoneBundleOps {public static func rename(bundleNamed name: String,to newName: String,- in library: VPhoneLibrary+ in library: VPhoneLibrary,) throws -> VPhoneBundle {try requireValidName(newName)let src = try library.bundle(named: name).url@@ -144,17 +148,19 @@ public enum VPhoneBundleOps {public static func clone(bundleNamed name: String,to newName: String,- in library: VPhoneLibrary+ in library: VPhoneLibrary,) throws -> VPhoneBundle {try requireValidName(newName)let src = try library.bundle(named: name).urllet dst = library.url(forName: newName)let fm = FileManager.default- if fm.fileExists(atPath: dst.path) { throw VPhoneLibraryError.alreadyExists(name: newName) }+ if fm.fileExists(atPath: dst.path) {+ throw VPhoneLibraryError.alreadyExists(name: newName)+ }// APFS CoW clone; fall back to a plain recursive copy off-APFS.if clonefile(src.path, dst.path, 0) != 0 {- try? fm.removeItem(at: dst) // clear any partial clonefile output first+ try? fm.removeItem(at: dst) // clear any partial clonefile output firsttry fm.copyItem(at: src, to: dst)}try resetIdentity(inBundleAt: dst)@@ -165,10 +171,14 @@ public enum VPhoneBundleOps {let fm = FileManager.defaultfor name in ["nvram.bin", "udid-prediction.txt"] {let u = dir.appendingPathComponent(name)- if fm.fileExists(atPath: u.path) { try fm.removeItem(at: u) }+ if fm.fileExists(atPath: u.path) {+ try fm.removeItem(at: u)+ }}let entries = try fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)- for u in entries where u.pathExtension == "shsh" { try fm.removeItem(at: u) }+ for u in entries where u.pathExtension == "shsh" {+ try fm.removeItem(at: u)+ }let configURL = dir.appendingPathComponent("config.plist")let manifest = try VPhoneVirtualMachineManifest.load(from: configURL)try manifest.updating(machineIdentifier: Data()).write(to: configURL)diff --git a/sources/VPhoneCore/VPhoneBundleReport.swift b/sources/VPhoneCore/VPhoneBundleReport.swiftindex 2f83032c..3c5f3de7 100644--- a/sources/VPhoneCore/VPhoneBundleReport.swift+++ b/sources/VPhoneCore/VPhoneBundleReport.swift@@ -10,12 +10,12 @@ public struct VPhoneBundleReport: Codable, Equatable, Sendable {public let udid: String?public init(bundle: VPhoneBundle) {- self.name = bundle.name- self.cpuCount = Int(bundle.manifest.cpuCount)- self.memoryMB = Int(bundle.manifest.memorySize / (1024 * 1024))- self.diskSizeBytes = bundle.diskSizeBytes- self.network = bundle.manifest.networkConfig- self.restoreInfo = VPhoneRestoreInfo.load(fromBundle: bundle)- self.udid = VPhoneRestoreOps.resolveUDID(bundle: bundle)+ name = bundle.name+ cpuCount = Int(bundle.manifest.cpuCount)+ memoryMB = Int(bundle.manifest.memorySize / (1024 * 1024))+ diskSizeBytes = bundle.diskSizeBytes+ network = bundle.manifest.networkConfig+ restoreInfo = VPhoneRestoreInfo.load(fromBundle: bundle)+ udid = VPhoneRestoreOps.resolveUDID(bundle: bundle)}}diff --git a/sources/VPhoneCore/VPhoneFirmwareCatalog.swift b/sources/VPhoneCore/VPhoneFirmwareCatalog.swiftindex 51939f0c..a621f6ba 100644--- a/sources/VPhoneCore/VPhoneFirmwareCatalog.swift+++ b/sources/VPhoneCore/VPhoneFirmwareCatalog.swift@@ -23,7 +23,9 @@ public struct VPhoneFirmwarePairing: Sendable, Equatable {public struct VPhoneCloudOSOption: Sendable, Equatable {public let name: Stringpublic let url: String- public init(name: String, url: String) { self.name = name; self.url = url }+ public init(name: String, url: String) {+ self.name = name; self.url = url+ }}// MARK: - VPhoneFirmwareCatalog@@ -85,8 +87,10 @@ public enum VPhoneFirmwareCatalog {pairings: pairings.map {.init(ios: .init(name: $0.iosName, url: $0.iosURL),- recommendedCloudOS: .init(name: $0.cloudosName, url: $0.cloudosURL))- })+ recommendedCloudOS: .init(name: $0.cloudosName, url: $0.cloudosURL),+ )+ },+ )}}@@ -97,7 +101,9 @@ public struct VPhoneFirmwareCatalogReport: Codable, Equatable, Sendable {public struct Firmware: Codable, Equatable, Sendable {public let name: Stringpublic let url: String- public init(name: String, url: String) { self.name = name; self.url = url }+ public init(name: String, url: String) {+ self.name = name; self.url = url+ }}public struct Entry: Codable, Equatable, Sendable {diff --git a/sources/VPhoneCore/VPhoneFirmwareIndex.swift b/sources/VPhoneCore/VPhoneFirmwareIndex.swiftindex 12558002..9f7db458 100644--- a/sources/VPhoneCore/VPhoneFirmwareIndex.swift+++ b/sources/VPhoneCore/VPhoneFirmwareIndex.swift@@ -136,7 +136,9 @@ public enum VPhoneFirmwareIndex {for i in 0 ..< max(lhs.count, rhs.count) {let l = i < lhs.count ? lhs[i] : 0let r = i < rhs.count ? rhs[i] : 0- if l != r { return l < r ? .orderedAscending : .orderedDescending }+ if l != r {+ return l < r ? .orderedAscending : .orderedDescending+ }}return .orderedSame}@@ -156,7 +158,8 @@ public enum VPhoneFirmwareIndex {if let attributes = try? FileManager.default.attributesOfItem(atPath: cache.path),let modified = attributes[.modificationDate] as? Date,Date().timeIntervalSince(modified) < maxAge,- let cached = try? Data(contentsOf: cache, options: .mappedIfSafe) {+ let cached = try? Data(contentsOf: cache, options: .mappedIfSafe)+ {return cached}@@ -165,13 +168,15 @@ public enum VPhoneFirmwareIndex {// A stale catalogue beats no catalogue: the network is the thing// most likely to be missing, and last week's list still has every// firmware from last week.- if let cached = try? Data(contentsOf: cache, options: .mappedIfSafe) { return cached }+ if let cached = try? Data(contentsOf: cache, options: .mappedIfSafe) {+ return cached+ }throw Error.fetchFailed(catalogueURL, http.statusCode)}let json = try decompressXZ(compressed)try? FileManager.default.createDirectory(- at: cache.deletingLastPathComponent(), withIntermediateDirectories: true+ at: cache.deletingLastPathComponent(), withIntermediateDirectories: true,)try? json.write(to: cache)return json@@ -186,10 +191,10 @@ public enum VPhoneFirmwareIndex {static func decompressXZ(_ input: Data) throws -> Data {var stream = compression_stream(dst_ptr: UnsafeMutablePointer<UInt8>(bitPattern: 1)!, dst_size: 0,- src_ptr: UnsafePointer<UInt8>(bitPattern: 1)!, src_size: 0, state: nil+ src_ptr: UnsafePointer<UInt8>(bitPattern: 1)!, src_size: 0, state: nil,)guard compression_stream_init(&stream, COMPRESSION_STREAM_DECODE, COMPRESSION_LZMA)- == COMPRESSION_STATUS_OK+ == COMPRESSION_STATUS_OKelse { throw Error.decompressionFailed }defer { compression_stream_destroy(&stream) }@@ -207,7 +212,7 @@ public enum VPhoneFirmwareIndex {stream.dst_ptr = chunkstream.dst_size = chunkSizestatus = compression_stream_process(- &stream, Int32(COMPRESSION_STREAM_FINALIZE.rawValue)+ &stream, Int32(COMPRESSION_STREAM_FINALIZE.rawValue),)output.append(chunk, count: chunkSize - stream.dst_size)} while status == COMPRESSION_STATUS_OKdiff --git a/sources/VPhoneCore/VPhoneFirmwareMatrix.swift b/sources/VPhoneCore/VPhoneFirmwareMatrix.swiftindex cb753d34..2e737134 100644--- a/sources/VPhoneCore/VPhoneFirmwareMatrix.swift+++ b/sources/VPhoneCore/VPhoneFirmwareMatrix.swift@@ -49,7 +49,7 @@ public struct VPhoneStatusStyle: Sendable, Equatable {/// The policy above, resolved for one file descriptor.public static func forStream(_ fileDescriptor: Int32,- environment: [String: String] = ProcessInfo.processInfo.environment+ environment: [String: String] = ProcessInfo.processInfo.environment,) -> VPhoneStatusStyle {if let noColor = environment["NO_COLOR"], !noColor.isEmpty {return VPhoneStatusStyle(isColored: false)@@ -163,7 +163,7 @@ public enum VPhoneFirmwareMatrix {? String(device.dropFirst("iPhone".count)): deviceguard let cell = try? NSRegularExpression(- pattern: "`(\\d+,\\d+)_([^_`]+)_([A-Za-z0-9]+)`"+ pattern: "`(\\d+,\\d+)_([^_`]+)_([A-Za-z0-9]+)`",) else { return [] }var tested: Set<VPhoneFirmwareBuildID> = []@@ -173,7 +173,9 @@ public enum VPhoneFirmwareMatrix {inSection = truecontinue}- if inSection, line.hasPrefix("## ") { break }+ if inSection, line.hasPrefix("## ") {+ break+ }guard inSection else { continue }for match in cell.matches(in: line, range: NSRange(line.startIndex..., in: line)) {@@ -208,7 +210,9 @@ public enum VPhoneFirmwareMatrix {let build = group(3, of: match, in: line)else { continue }let release = VPhoneFirmwareRelease(version: version, build: build, url: line)- if seen.insert(release).inserted { found.append(release) }+ if seen.insert(release).inserted {+ found.append(release)+ }}return found}@@ -216,7 +220,7 @@ public enum VPhoneFirmwareMatrix {/// The verdict for one release, given what the compatibility guide records.public static func support(of release: VPhoneFirmwareRelease,- tested: Set<VPhoneFirmwareBuildID>+ tested: Set<VPhoneFirmwareBuildID>,) -> VPhoneFirmwareSupport {tested.contains(VPhoneFirmwareBuildID(version: release.version, build: release.build))? .supported@@ -230,7 +234,7 @@ public enum VPhoneFirmwareMatrix {device: String,readme: String?,downloadURLs: String,- style: VPhoneStatusStyle+ style: VPhoneStatusStyle,) -> VPhoneFirmwareListing {let releases = releases(downloadURLs: downloadURLs, device: device)guard !releases.isEmpty else {@@ -269,7 +273,7 @@ public enum VPhoneFirmwareMatrix {build: String,readme: String?,downloadURLs: String,- style: VPhoneStatusStyle+ style: VPhoneStatusStyle,) -> VPhoneFirmwareSelection {let matches = releases(downloadURLs: downloadURLs, device: device).filter {(version.isEmpty || $0.version == version) && (build.isEmpty || $0.build == build)@@ -330,7 +334,11 @@ public enum VPhoneFirmwareMatrix {/// prefix, so `26.4` < `26.4.1`.static func versionKey(_ version: String) -> [VersionPart] {version.components(separatedBy: ".").map { part in- if let number = Int(part) { .number(number) } else { .text(part) }+ if let number = Int(part) {+ .number(number)+ } else {+ .text(part)+ }}}@@ -342,14 +350,20 @@ public enum VPhoneFirmwareMatrix {/// behaviour to reproduce, so the order here is total and reproducible.static func isNewer(_ lhs: VPhoneFirmwareRelease, than rhs: VPhoneFirmwareRelease) -> Bool {let (l, r) = (versionKey(lhs.version), versionKey(rhs.version))- for (lp, rp) in zip(l, r) where lp != rp { return rp < lp }- if l.count != r.count { return r.count < l.count }+ for (lp, rp) in zip(l, r) where lp != rp {+ return rp < lp+ }+ if l.count != r.count {+ return r.count < l.count+ }return hasHigherBuild(lhs, than: rhs)}/// Build descending, URL descending as the tie-break.static func hasHigherBuild(_ lhs: VPhoneFirmwareRelease, than rhs: VPhoneFirmwareRelease) -> Bool {- if lhs.build != rhs.build { return codePointsAscending(rhs.build, lhs.build) }+ if lhs.build != rhs.build {+ return codePointsAscending(rhs.build, lhs.build)+ }return codePointsAscending(rhs.url, lhs.url)}@@ -379,7 +393,9 @@ public enum VPhoneFirmwareMatrix {case (nil, .some): return truecase (.some, nil): return falsecase let (.some(l), .some(r)):- if l.value != r.value { return l.value < r.value }+ if l.value != r.value {+ return l.value < r.value+ }}}}@@ -389,8 +405,12 @@ public enum VPhoneFirmwareMatrix {static func normalizedLines(of text: String) -> [String] {var normalized = text.replacingOccurrences(of: "\r\n", with: "\n")normalized = normalized.replacingOccurrences(of: "\r", with: "\n")- if normalized.hasSuffix("\n") { normalized.removeLast() }- if normalized.isEmpty { return [] }+ if normalized.hasSuffix("\n") {+ normalized.removeLast()+ }+ if normalized.isEmpty {+ return []+ }return normalized.components(separatedBy: "\n")}@@ -418,14 +438,14 @@ public enum VPhoneFirmwareMatrixCommandLine {downloadURLs: String,environment: [String: String] = ProcessInfo.processInfo.environment,stdout: FileHandle = .standardOutput,- stderr: FileHandle = .standardError+ stderr: FileHandle = .standardError,) -> Int32 {let readme = try? String(contentsOfFile: readmePath, encoding: .utf8)switch VPhoneFirmwareMatrix.listing(device: device,readme: readme,downloadURLs: downloadURLs,- style: .forStream(stdout.fileDescriptor, environment: environment)+ style: .forStream(stdout.fileDescriptor, environment: environment),) {case let .matrix(text):write(text, to: stdout)@@ -446,7 +466,7 @@ public enum VPhoneFirmwareMatrixCommandLine {downloadURLs: String,environment: [String: String] = ProcessInfo.processInfo.environment,stdout: FileHandle = .standardOutput,- stderr: FileHandle = .standardError+ stderr: FileHandle = .standardError,) -> Int32 {let readme = try? String(contentsOfFile: readmePath, encoding: .utf8)let selection = VPhoneFirmwareMatrix.selection(@@ -455,7 +475,7 @@ public enum VPhoneFirmwareMatrixCommandLine {build: build,readme: readme,downloadURLs: downloadURLs,- style: .forStream(stderr.fileDescriptor, environment: environment)+ style: .forStream(stderr.fileDescriptor, environment: environment),)switch selection {case .selected:diff --git a/sources/VPhoneCore/VPhoneFirmwarePicker.swift b/sources/VPhoneCore/VPhoneFirmwarePicker.swiftindex 2523935b..7cbfd425 100644--- a/sources/VPhoneCore/VPhoneFirmwarePicker.swift+++ b/sources/VPhoneCore/VPhoneFirmwarePicker.swift@@ -41,7 +41,7 @@ public enum VPhoneFirmwarePicker {isInteractive: Bool,maxRetries: Int = 5,read: () -> String?,- write: (String) -> Void+ write: (String) -> Void,) throws -> VPhoneFirmwareSources {let iphone = (iphone?.isEmpty == true) ? nil : iphonelet cloudos = (cloudos?.isEmpty == true) ? nil : cloudos@@ -55,7 +55,7 @@ public enum VPhoneFirmwarePicker {let p = try pickPairing(maxRetries: maxRetries, read: read, write: write)return VPhoneFirmwareSources(iphoneSource: p.iosURL, cloudosSource: p.cloudosURL)}- if iphone == nil { // cloudOS supplied, choose the iPhone build+ if iphone == nil { // cloudOS supplied, choose the iPhone buildlet p = try pickIPhone(maxRetries: maxRetries, read: read, write: write)return VPhoneFirmwareSources(iphoneSource: p.iosURL, cloudosSource: cloudos)}@@ -69,17 +69,19 @@ public enum VPhoneFirmwarePicker {static func pickPairing(maxRetries: Int,read: () -> String?,- write: (String) -> Void+ write: (String) -> Void,) throws -> VPhoneFirmwarePairing {let pairings = VPhoneFirmwareCatalog.pairingslet w = pairings.map(\.iosName.count).max() ?? 0let idx = try choose("Select a firmware pairing to download:",pairings.map { $0.iosName.padding(toLength: w, withPad: " ", startingAt: 0)- + " (→ \($0.cloudosName))" },+ + " (→ \($0.cloudosName))"+ },maxRetries: maxRetries,read: read,- write: write)+ write: write,+ )let p = pairings[idx]write("→ \(p.iosName) + \(p.cloudosName)")return p@@ -88,7 +90,7 @@ public enum VPhoneFirmwarePicker {static func pickIPhone(maxRetries: Int,read: () -> String?,- write: (String) -> Void+ write: (String) -> Void,) throws -> VPhoneFirmwarePairing {let pairings = VPhoneFirmwareCatalog.pairingslet idx = try choose(@@ -96,7 +98,8 @@ public enum VPhoneFirmwarePicker {pairings.map(\.iosName),maxRetries: maxRetries,read: read,- write: write)+ write: write,+ )let p = pairings[idx]write("→ \(p.iosName)")return p@@ -105,7 +108,7 @@ public enum VPhoneFirmwarePicker {static func pickCloudOS(maxRetries: Int,read: () -> String?,- write: (String) -> Void+ write: (String) -> Void,) throws -> VPhoneCloudOSOption {let options = VPhoneFirmwareCatalog.cloudOSOptionslet idx = try choose(@@ -113,7 +116,8 @@ public enum VPhoneFirmwarePicker {options.map(\.name),maxRetries: maxRetries,read: read,- write: write)+ write: write,+ )let c = options[idx]write("→ \(c.name)")return c@@ -125,21 +129,25 @@ public enum VPhoneFirmwarePicker {_ labels: [String],maxRetries: Int,read: () -> String?,- write: (String) -> Void+ write: (String) -> Void,) throws -> Int {write(prompt)- let iw = String(labels.count).count // right-align indices so labels start in one column+ let iw = String(labels.count).count // right-align indices so labels start in one columnfor (i, label) in labels.enumerated() {let n = String(i + 1)let padded = String(repeating: " ", count: iw - n.count) + nwrite(" [\(padded)] \(label)")}- for _ in 0..<maxRetries {+ for _ in 0 ..< maxRetries {write("Enter number: ")guard let line = read() else { throw VPhoneFirmwarePickerError.aborted }let choice = line.trimmingCharacters(in: .whitespacesAndNewlines)- if choice.isEmpty { continue }- if let n = Int(choice), n >= 1, n <= labels.count { return n - 1 }+ if choice.isEmpty {+ continue+ }+ if let n = Int(choice), n >= 1, n <= labels.count {+ return n - 1+ }write(" '\(choice)' is not a valid selection.")}throw VPhoneFirmwarePickerError.invalidSelectiondiff --git a/sources/VPhoneCore/VPhoneGuestBinaries.swift b/sources/VPhoneCore/VPhoneGuestBinaries.swiftindex d53f51a5..fed2d05c 100644--- a/sources/VPhoneCore/VPhoneGuestBinaries.swift+++ b/sources/VPhoneCore/VPhoneGuestBinaries.swift@@ -38,7 +38,9 @@ public enum VPhoneGuestBinaries {let searched = directories()for directory in searched {let candidate = directory.appendingPathComponent(name)- if FileManager.default.fileExists(atPath: candidate.path) { return candidate }+ if FileManager.default.fileExists(atPath: candidate.path) {+ return candidate+ }}throw Error.missing(name, searched)}diff --git a/sources/VPhoneCore/VPhoneGuestLauncher.swift b/sources/VPhoneCore/VPhoneGuestLauncher.swiftindex 1bbc00db..93ee17eb 100644--- a/sources/VPhoneCore/VPhoneGuestLauncher.swift+++ b/sources/VPhoneCore/VPhoneGuestLauncher.swift@@ -99,7 +99,7 @@ public struct VPhoneGuestLaunchPlanner: Sendable {if try Self.amfidRefuses(vm) {throw VPhoneGuestLaunchError.blockedByAMFI(guest: vm,- cdHash: Self.codeDirectoryHash(of: vm)+ cdHash: Self.codeDirectoryHash(of: vm),)}}@@ -125,11 +125,12 @@ public struct VPhoneGuestLaunchPlanner: Sendable {private static func hasRequiredEntitlements(_ vm: URL) throws -> Bool {let result = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/bin/codesign"),- ["-d", "--entitlements", "-", "--xml", vm.path]+ ["-d", "--entitlements", "-", "--xml", vm.path],)guard result.succeeded,let plist = try? PropertyListSerialization.propertyList(- from: Data(result.stdout.utf8), format: nil) as? [String: Any]+ from: Data(result.stdout.utf8), format: nil,+ ) as? [String: Any]else { return false }return plist["com.apple.private.virtualization"] as? Bool == true &&plist["com.apple.private.virtualization.security-research"] as? Bool == true@@ -146,11 +147,15 @@ public struct VPhoneGuestLaunchPlanner: Sendable {/// itself rather than being mistaken for an AMFI refusal.private static func amfidRefuses(_ vm: URL) throws -> Bool {let probe = try VPhoneProcessRunner.runCapturing(vm, ["--help"])- if probe.succeeded { return false }- if probe.exitCode == SIGKILL { return true }+ if probe.succeeded {+ return false+ }+ if probe.exitCode == SIGKILL {+ return true+ }throw VPhoneGuestLaunchError.probeFailed(exitCode: probe.exitCode,- output: (probe.stderr + probe.stdout).trimmingCharacters(in: .whitespacesAndNewlines)+ output: (probe.stderr + probe.stdout).trimmingCharacters(in: .whitespacesAndNewlines),)}diff --git a/sources/VPhoneCore/VPhoneLaunchLayout.swift b/sources/VPhoneCore/VPhoneLaunchLayout.swiftindex 05e45db3..075a2e09 100644--- a/sources/VPhoneCore/VPhoneLaunchLayout.swift+++ b/sources/VPhoneCore/VPhoneLaunchLayout.swift@@ -5,10 +5,17 @@ import Foundationpublic struct VPhoneLaunchLayout: Sendable {public let resources: VPhoneResources- public init(resources: VPhoneResources) { self.resources = resources }- public init(projectRoot: URL) { self.init(resources: VPhoneResources(base: projectRoot)) }+ public init(resources: VPhoneResources) {+ self.resources = resources+ }- public var vphoned: URL { resources.vphoned }+ public init(projectRoot: URL) {+ self.init(resources: VPhoneResources(base: projectRoot))+ }++ public var vphoned: URL {+ resources.vphoned+ }/// Copy the built vphoned into the bundle if present and different.@discardableResult@@ -20,10 +27,13 @@ public struct VPhoneLaunchLayout: Sendable {let dst = bundle.url.appendingPathComponent(".vphoned.signed")if fm.fileExists(atPath: dst.path),let a = try? Data(contentsOf: vphoned, options: .mappedIfSafe),- let b = try? Data(contentsOf: dst, options: .mappedIfSafe), a == b {+ let b = try? Data(contentsOf: dst, options: .mappedIfSafe), a == b+ {return false}- if fm.fileExists(atPath: dst.path) { try fm.removeItem(at: dst) }+ if fm.fileExists(atPath: dst.path) {+ try fm.removeItem(at: dst)+ }try fm.copyItem(at: vphoned, to: dst)return true}diff --git a/sources/VPhoneCore/VPhoneLibrary.swift b/sources/VPhoneCore/VPhoneLibrary.swiftindex 7c67859f..8bc764ef 100644--- a/sources/VPhoneCore/VPhoneLibrary.swift+++ b/sources/VPhoneCore/VPhoneLibrary.swift@@ -15,7 +15,10 @@ extension VPhoneLibraryError: CustomStringConvertible, LocalizedError {"Invalid VM name '\(name)'. Use a name that is not empty, has no '/', and does not start with '.'."}}- public var errorDescription: String? { description }++ public var errorDescription: String? {+ description+ }}public struct VPhoneLibrarySkip: Sendable {@@ -33,7 +36,9 @@ public struct VPhoneLibrarySkip: Sendable {public struct VPhoneLibrary: Sendable {public let root: URL- public init(root: URL) { self.root = root }+ public init(root: URL) {+ self.root = root+ }public static func defaultRoot() -> URL {if let override = ProcessInfo.processInfo.environment["VPHONE_LIBRARY_ROOT"] {@@ -56,13 +61,15 @@ public struct VPhoneLibrary: Sendable {let entries = try fm.contentsOfDirectory(at: root,includingPropertiesForKeys: [.isDirectoryKey],- options: [.skipsHiddenFiles])+ options: [.skipsHiddenFiles],+ )var bundles: [VPhoneBundle] = []var skipped: [VPhoneLibrarySkip] = []for url in entries- where fm.fileExists(atPath: url.appendingPathComponent("config.plist").path) {+ where fm.fileExists(atPath: url.appendingPathComponent("config.plist").path)+ {do {- bundles.append(try VPhoneBundle.load(at: url))+ try bundles.append(VPhoneBundle.load(at: url))} catch {skipped.append(VPhoneLibrarySkip(name: url.lastPathComponent, reason: "\(error)"))}@@ -77,7 +84,8 @@ public struct VPhoneLibrary: Sendable {public func bundle(named name: String) throws -> VPhoneBundle {let url = url(forName: name)guard FileManager.default.fileExists(- atPath: url.appendingPathComponent("config.plist").path) else {+ atPath: url.appendingPathComponent("config.plist").path,+ ) else {throw VPhoneLibraryError.notFound(name: name)}return try VPhoneBundle.load(at: url)diff --git a/sources/VPhoneCore/VPhoneManagedProcess.swift b/sources/VPhoneCore/VPhoneManagedProcess.swiftindex 25838cb2..2a9c9353 100644--- a/sources/VPhoneCore/VPhoneManagedProcess.swift+++ b/sources/VPhoneCore/VPhoneManagedProcess.swift@@ -59,13 +59,17 @@ public final class VPhoneManagedProcess: @unchecked Sendable {_ args: [String],cwd: URL? = nil,env: [String: String]? = nil,- echo: Bool = true+ echo: Bool = true,) {self.echo = echoprocess.executableURL = executableprocess.arguments = args- if let cwd { process.currentDirectoryURL = cwd }- if let env { process.environment = env }+ if let cwd {+ process.currentDirectoryURL = cwd+ }+ if let env {+ process.environment = env+ }}/// Spawn the child with a piped stdin and a combined piped stdout/stderr.@@ -76,8 +80,8 @@ public final class VPhoneManagedProcess: @unchecked Sendable {process.standardOutput = outPipeprocess.standardError = outPipe- let box = self.box- let echo = self.echo+ let box = box+ let echo = echooutPipe.fileHandleForReading.readabilityHandler = { handle inlet chunk = handle.availableDataif chunk.isEmpty {@@ -106,24 +110,30 @@ public final class VPhoneManagedProcess: @unchecked Sendable {let deadline = Date().addingTimeInterval(timeout)while true {- if matches(re, box.snapshotText()) { return .matched }+ if matches(re, box.snapshotText()) {+ return .matched+ }if !process.isRunning {- while !box.hasReachedEOF() && Date() < deadline {+ while !box.hasReachedEOF(), Date() < deadline {Thread.sleep(forTimeInterval: 0.02)}- if matches(re, box.snapshotText()) { return .matched }+ if matches(re, box.snapshotText()) {+ return .matched+ }return .exited(process.terminationStatus)}- if Date() >= deadline { return .timedOut }+ if Date() >= deadline {+ return .timedOut+ }Thread.sleep(forTimeInterval: 0.05)}}private func matches(_ re: NSRegularExpression?, _ text: String) -> Bool {guard let re else { return false }- let range = NSRange(text.startIndex..<text.endIndex, in: text)+ let range = NSRange(text.startIndex ..< text.endIndex, in: text)return re.firstMatch(in: text, options: [], range: range) != nil}@@ -149,7 +159,7 @@ public final class VPhoneManagedProcess: @unchecked Sendable {process.interrupt()let deadline = Date().addingTimeInterval(2)- while process.isRunning && Date() < deadline {+ while process.isRunning, Date() < deadline {Thread.sleep(forTimeInterval: 0.05)}if process.isRunning {diff --git a/sources/VPhoneCore/VPhoneNetworking.swift b/sources/VPhoneCore/VPhoneNetworking.swiftindex 8df0d15e..2fda26e3 100644--- a/sources/VPhoneCore/VPhoneNetworking.swift+++ b/sources/VPhoneCore/VPhoneNetworking.swift@@ -37,7 +37,10 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {"--bridge-interface is only valid with --network bridged."}}- public var errorDescription: String? { description }++ public var errorDescription: String? {+ description+ }}// MARK: - Networking helpers@@ -71,8 +74,12 @@ public enum VPhoneNetworking {// and let vphone-vm — which is entitled — decide at boot, where the// error can name the real problem.guard !available.isEmpty else {- if let requested { return requested }- if let current { return current }+ if let requested {+ return requested+ }+ if let current {+ return current+ }throw VPhoneNetworkingError.bridgeInterfaceMustBeNamed}@@ -85,7 +92,7 @@ public enum VPhoneNetworking {if let current, available.contains(current) {return current}- return available[0] // non-empty, guarded above+ return available[0] // non-empty, guarded above}/// Merge partial edits onto an existing config, validating the result.@@ -93,7 +100,7 @@ public enum VPhoneNetworking {public static func merge(into current: NetworkConfig,mode: NetworkMode?,- bridgeInterface: String?+ bridgeInterface: String?,) throws -> NetworkConfig {let newMode = mode ?? current.modeif newMode == .hostOnly {@@ -131,7 +138,8 @@ public enum VPhoneNetworking {guard let iface = VZBridgedNetworkInterface.networkInterfaces.first(where: { $0.identifier == id }) else {throw VPhoneNetworkingError.bridgeInterfaceNotFound(requested: id,- available: availableBridgeInterfaces())+ available: availableBridgeInterfaces(),+ )}let net = VZVirtioNetworkDeviceConfiguration()net.attachment = VZBridgedNetworkDeviceAttachment(interface: iface)diff --git a/sources/VPhoneCore/VPhonePCCGPUDriver.swift b/sources/VPhoneCore/VPhonePCCGPUDriver.swiftindex a14d0e35..18114852 100644--- a/sources/VPhoneCore/VPhonePCCGPUDriver.swift+++ b/sources/VPhoneCore/VPhonePCCGPUDriver.swift@@ -65,28 +65,31 @@ public enum VPhonePCCGPUDriver {let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: encrypted) }try run("/usr/bin/aea", [- "decrypt", "-t", "4", "-i", encrypted.path, "-o", plain.path, "-key-value", key+ "decrypt", "-t", "4", "-i", encrypted.path, "-o", plain.path, "-key-value", key,])defer {_ = try? VPhoneProcessRunner.runCapturing(- URL(fileURLWithPath: "/usr/bin/hdiutil"), ["detach", mount.path]+ URL(fileURLWithPath: "/usr/bin/hdiutil"), ["detach", mount.path],)}try run("/usr/bin/hdiutil", ["attach", "-readonly", "-nobrowse", "-owners", "off",- "-mountpoint", mount.path, plain.path+ "-mountpoint", mount.path, plain.path,])let source = mount.appending(path: "System/Library/Extensions/\(name)")guard fm.fileExists(atPath: source.path) else { throw Error.missingBundle(source) }for file in ["AppleParavirtGPUMetalIOGPUFamily",- "libAppleParavirtCompilerPluginIOGPUFamily.dylib", "Info.plist"] {+ "libAppleParavirtCompilerPluginIOGPUFamily.dylib", "Info.plist"]+ {let member = source.appendingPathComponent(file)guard fm.fileExists(atPath: member.path) else { throw Error.missingBundle(member) }}try fm.createDirectory(at: destination.deletingLastPathComponent(),withIntermediateDirectories: true)- if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }+ if fm.fileExists(atPath: destination.path) {+ try fm.removeItem(at: destination)+ }try fm.copyItem(at: source, to: destination)print("[+] GPU driver staged from PCC OS: \(destination.path)")}diff --git a/sources/VPhoneCore/VPhoneProcessRunner.swift b/sources/VPhoneCore/VPhoneProcessRunner.swiftindex 284a714c..bda69de9 100644--- a/sources/VPhoneCore/VPhoneProcessRunner.swift+++ b/sources/VPhoneCore/VPhoneProcessRunner.swift@@ -13,7 +13,9 @@ public struct VPhoneProcessResult: Sendable {self.stderr = stderr}- public var succeeded: Bool { exitCode == 0 }+ public var succeeded: Bool {+ exitCode == 0+ }}// MARK: - VPhoneProcessRunner@@ -25,8 +27,13 @@ public enum VPhoneProcessRunner {private final class DataBox: @unchecked Sendable {private let lock = NSLock()private var data = Data()- func append(_ chunk: Data) { lock.lock(); data.append(chunk); lock.unlock() }- func take() -> Data { lock.lock(); defer { lock.unlock() }; return data }+ func append(_ chunk: Data) {+ lock.lock(); data.append(chunk); lock.unlock()+ }++ func take() -> Data {+ lock.lock(); defer { lock.unlock() }; return data+ }}/// Run `executable args` to completion, capturing stdout/stderr.@@ -40,13 +47,17 @@ public enum VPhoneProcessRunner {_ executable: URL,_ args: [String],cwd: URL? = nil,- env: [String: String]? = nil+ env: [String: String]? = nil,) throws -> VPhoneProcessResult {let process = Process()process.executableURL = executableprocess.arguments = args- if let cwd { process.currentDirectoryURL = cwd }- if let env { process.environment = env }+ if let cwd {+ process.currentDirectoryURL = cwd+ }+ if let env {+ process.environment = env+ }let outPipe = Pipe()let errPipe = Pipe()@@ -60,13 +71,19 @@ public enum VPhoneProcessRunner {group.enter()outPipe.fileHandleForReading.readabilityHandler = { handle inlet chunk = handle.availableData- if chunk.isEmpty { handle.readabilityHandler = nil; group.leave() }- else { outBox.append(chunk) }+ if chunk.isEmpty {+ handle.readabilityHandler = nil; group.leave()+ } else {+ outBox.append(chunk)+ }}errPipe.fileHandleForReading.readabilityHandler = { handle inlet chunk = handle.availableData- if chunk.isEmpty { handle.readabilityHandler = nil; group.leave() }- else { errBox.append(chunk) }+ if chunk.isEmpty {+ handle.readabilityHandler = nil; group.leave()+ } else {+ errBox.append(chunk)+ }}try process.run()@@ -76,7 +93,8 @@ public enum VPhoneProcessRunner {return VPhoneProcessResult(exitCode: process.terminationStatus,stdout: String(decoding: outBox.take(), as: UTF8.self),- stderr: String(decoding: errBox.take(), as: UTF8.self))+ stderr: String(decoding: errBox.take(), as: UTF8.self),+ )}// `runCountingTarPipe` lived here: a two-stage `/usr/bin/tar` pipe with a@@ -100,13 +118,17 @@ public enum VPhoneProcessRunner {_ args: [String],cwd: URL? = nil,env: [String: String]? = nil,- echo: Bool = true+ echo: Bool = true,) throws -> Int32 {let process = Process()process.executableURL = executableprocess.arguments = args- if let cwd { process.currentDirectoryURL = cwd }- if let env { process.environment = env }+ if let cwd {+ process.currentDirectoryURL = cwd+ }+ if let env {+ process.environment = env+ }if !echo {let devNull = FileHandle.nullDevice@@ -134,13 +156,17 @@ public enum VPhoneProcessRunner {_ args: [String],cwd: URL? = nil,env: [String: String]? = nil,- echo: Bool = true+ echo: Bool = true,) throws -> Int32 {let process = Process()process.executableURL = executableprocess.arguments = args- if let cwd { process.currentDirectoryURL = cwd }- if let env { process.environment = env }+ if let cwd {+ process.currentDirectoryURL = cwd+ }+ if let env {+ process.environment = env+ }// When echo is false, suppress the child's normal output — but it still// becomes the terminal's foreground group below, so an interactive sudo// it runs still prompts/reads via /dev/tty (independent of stdout/stderr).@@ -169,13 +195,17 @@ public enum VPhoneProcessRunner {defer {signal(SIGTTOU, prevTTOU)signal(SIGTTIN, prevTTIN)- if openedTTY { close(ttyFD) }+ if openedTTY {+ close(ttyFD)+ }}try process.run()- _ = tcsetpgrp(ttyFD, process.processIdentifier) // hand the tty to the child+ _ = tcsetpgrp(ttyFD, process.processIdentifier) // hand the tty to the childprocess.waitUntilExit()- if savedFg > 0 { _ = tcsetpgrp(ttyFD, savedFg) } // take it back+ if savedFg > 0 {+ _ = tcsetpgrp(ttyFD, savedFg)+ } // take it backreturn process.terminationStatus}@@ -187,9 +217,11 @@ public enum VPhoneProcessRunner {_ executable: URL,_ args: [String],env: [String: String] = [:],- echo: Bool = true+ echo: Bool = true,) throws -> Int32 {- func shQuote(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" }+ func shQuote(_ s: String) -> String {+ "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'"+ }var tokens = env.sorted { $0.key < $1.key }.map { "\($0.key)=\(shQuote($0.value))" }tokens.append(shQuote(executable.path))tokens += args.map(shQuote)diff --git a/sources/VPhoneCore/VPhoneRemoteZip.swift b/sources/VPhoneCore/VPhoneRemoteZip.swiftindex baa3029f..a493b2f0 100644--- a/sources/VPhoneCore/VPhoneRemoteZip.swift+++ b/sources/VPhoneCore/VPhoneRemoteZip.swift@@ -66,7 +66,7 @@ public struct VPhoneRemoteZip: Sendable {// The EOCD is 22 bytes plus up to 64 KiB of comment, so the last 64 KiB// and change always contains it.- let tailLength = min(size, 66_000)+ let tailLength = min(size, 66000)let tail = try await range(of: url, from: size - tailLength, count: tailLength)guard let eocd = lastIndex(of: [0x50, 0x4B, 0x05, 0x06], in: tail) else {@@ -95,8 +95,8 @@ public struct VPhoneRemoteZip: Sendable {}let directory = try await range(of: url, from: directoryOffset, count: directorySize)- return VPhoneRemoteZip(- url: url, entries: try parseCentralDirectory(directory, expected: entryCount)+ return try VPhoneRemoteZip(+ url: url, entries: parseCentralDirectory(directory, expected: entryCount),)}@@ -111,7 +111,9 @@ public struct VPhoneRemoteZip: Sendable {/// first in the central directory picked a nested one and then failed to/// find a ramdisk in it.public func entry(endingWith suffix: String) throws -> Entry {- if let exact = entries.first(where: { $0.name == suffix }) { return exact }+ if let exact = entries.first(where: { $0.name == suffix }) {+ return exact+ }let matches = entries.filter { $0.name.hasSuffix("/" + suffix) || $0.name.hasSuffix(suffix) }guard let shallowest = matches.min(by: {($0.name.count(where: { $0 == "/" }), $0.name.count)@@ -151,7 +153,7 @@ public struct VPhoneRemoteZip: Sendable {compression_decode_buffer(destination.baseAddress!.assumingMemoryBound(to: UInt8.self), size,source.baseAddress!.assumingMemoryBound(to: UInt8.self), data.count,- nil, COMPRESSION_ZLIB+ nil, COMPRESSION_ZLIB,)}}@@ -197,7 +199,7 @@ public struct VPhoneRemoteZip: Sendable {while offset + 46 <= data.count {guard data[data.startIndex + offset ..< data.startIndex + offset + 4]- == Data([0x50, 0x4B, 0x01, 0x02])+ == Data([0x50, 0x4B, 0x01, 0x02])else { break }let method = u16(data, offset + 10)@@ -242,7 +244,7 @@ public struct VPhoneRemoteZip: Sendable {compressedSize: compressed,uncompressedSize: uncompressed,localHeaderOffset: localOffset,- compressionMethod: method+ compressionMethod: method,))offset += 46 + nameLength + extraLength + commentLength}@@ -256,7 +258,9 @@ public struct VPhoneRemoteZip: Sendable {let bytes = [UInt8](data)var i = bytes.count - needle.countwhile i >= 0 {- if Array(bytes[i ..< i + needle.count]) == needle { return i }+ if Array(bytes[i ..< i + needle.count]) == needle {+ return i+ }i -= 1}return nildiff --git a/sources/VPhoneCore/VPhoneResources.swift b/sources/VPhoneCore/VPhoneResources.swiftindex 59ed5530..6a7af60f 100644--- a/sources/VPhoneCore/VPhoneResources.swift+++ b/sources/VPhoneCore/VPhoneResources.swift@@ -1,4 +1,4 @@-import Darwin // _NSGetExecutablePath+import Darwin // _NSGetExecutablePathimport Foundation// MARK: - VPhoneResources@@ -6,7 +6,9 @@ import Foundationpublic struct VPhoneResources: Sendable {public let base: URL- public init(base: URL) { self.base = base }+ public init(base: URL) {+ self.base = base+ }// MARK: - Resolution@@ -32,7 +34,9 @@ public struct VPhoneResources: Sendable {return realPath(URL(fileURLWithPath: path))}// Only reachable if PATH_MAX was somehow too small for our own path.- if let exe = Bundle.main.executableURL { return realPath(exe) }+ if let exe = Bundle.main.executableURL {+ return realPath(exe)+ }return realPath(URL(fileURLWithPath: CommandLine.arguments[0]))}@@ -73,14 +77,15 @@ public struct VPhoneResources: Sendable {public static func resolve(executablePath: String? = nil) -> VPhoneResources {let exe = executablePath.map { realPath(URL(fileURLWithPath: $0)) }?? runningExecutable()- let macos = exe.deletingLastPathComponent() // …/Contents/MacOS+ let macos = exe.deletingLastPathComponent() // …/Contents/MacOSif macos.lastPathComponent == "MacOS",- macos.deletingLastPathComponent().lastPathComponent == "Contents" {+ macos.deletingLastPathComponent().lastPathComponent == "Contents"+ {return VPhoneResources(base: macos.deletingLastPathComponent()- .appendingPathComponent("Resources")) // …/Contents/Resources+ .appendingPathComponent("Resources")) // …/Contents/Resources}var dir = macos- for _ in 0..<6 {+ for _ in 0 ..< 6 {if FileManager.default.fileExists(atPath: dir.appendingPathComponent("scripts").path) {return VPhoneResources(base: dir)}@@ -91,11 +96,15 @@ public struct VPhoneResources: Sendable {// MARK: - Assets- public var scriptsDir: URL { base.appendingPathComponent("scripts") }+ public var scriptsDir: URL {+ base.appendingPathComponent("scripts")+ }public var vphoned: URL {let bundled = base.appendingPathComponent("vphoned.signed")- if FileManager.default.fileExists(atPath: bundled.path) { return bundled }+ if FileManager.default.fileExists(atPath: bundled.path) {+ return bundled+ }// Dev fallback: build.sh stages the signed daemon under .build (a// gitignored build-output dir) rather than cluttering the repo root.return base.appendingPathComponent(".build/vphoned.signed")@@ -113,8 +122,13 @@ public struct VPhoneResources: Sendable {return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".vphone")}- public var ipswCacheDir: URL { Self.userDataRoot().appendingPathComponent("ipsws") }- public var sealVolumeCacheDir: URL { Self.userDataRoot().appendingPathComponent("tools") }+ public var ipswCacheDir: URL {+ Self.userDataRoot().appendingPathComponent("ipsws")+ }++ public var sealVolumeCacheDir: URL {+ Self.userDataRoot().appendingPathComponent("tools")+ }// MARK: - No interpreterdiff --git a/sources/VPhoneCore/VPhoneRestoreInfo.swift b/sources/VPhoneCore/VPhoneRestoreInfo.swiftindex 4637bd6d..d482b745 100644--- a/sources/VPhoneCore/VPhoneRestoreInfo.swift+++ b/sources/VPhoneCore/VPhoneRestoreInfo.swift@@ -45,7 +45,8 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {/// existed still report their versions. `nil` when neither is available.public static func load(fromBundle bundle: VPhoneBundle) -> VPhoneRestoreInfo? {if let data = try? Data(contentsOf: url(forBundle: bundle), options: .mappedIfSafe),- let info = try? JSONDecoder().decode(VPhoneRestoreInfo.self, from: data) {+ let info = try? JSONDecoder().decode(VPhoneRestoreInfo.self, from: data)+ {return info}return derive(fromBundle: bundle)@@ -80,7 +81,8 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {ios: base.ios,cloudOS: base.cloudOS,variant: variant,- device: device(forVariant: variant))+ device: device(forVariant: variant),+ )try merged.write(toBundle: bundle)return merged}@@ -99,7 +101,8 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {static func findRestoreDirectory(inBundle bundle: VPhoneBundle) -> URL? {let entries = (try? FileManager.default.contentsOfDirectory(at: bundle.url,- includingPropertiesForKeys: nil)) ?? []+ includingPropertiesForKeys: nil,+ )) ?? []return entries.filter { $0.lastPathComponent.hasPrefix("iPhone") && $0.lastPathComponent.hasSuffix("_Restore") }.max { $0.lastPathComponent < $1.lastPathComponent }diff --git a/sources/VPhoneCore/VPhoneRestoreOps.swift b/sources/VPhoneCore/VPhoneRestoreOps.swiftindex 3f50aee9..209ad54c 100644--- a/sources/VPhoneCore/VPhoneRestoreOps.swift+++ b/sources/VPhoneCore/VPhoneRestoreOps.swift@@ -36,7 +36,9 @@ public enum VPhoneRestoreOps {/// ECID from `--ecid`, else the `ECID=` line of the bundle's udid-prediction.txt.public static func resolveECID(explicit: String?, bundle: VPhoneBundle) -> String? {- if let explicit, !explicit.isEmpty { return explicit }+ if let explicit, !explicit.isEmpty {+ return explicit+ }return predictedValue(forKey: "ECID=", bundle: bundle)}@@ -80,7 +82,8 @@ public enum VPhoneRestoreOps {let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: aea) }let code = try VPhoneProcessRunner.runStreaming(URL(fileURLWithPath: "/usr/bin/aea"),- ["decrypt", "-i", aea.path, "-o", decrypted.path, "-key-value", key])+ ["decrypt", "-i", aea.path, "-o", decrypted.path, "-key-value", key],+ )guard code == 0 else { throw VPhoneRestoreError.aeaDecryptFailed(aea.lastPathComponent) }guard fm.fileExists(atPath: decrypted.path) else {throw VPhoneRestoreError.aeaDecryptFailed(aea.lastPathComponent)diff --git a/sources/VPhoneCore/VPhoneSudo.swift b/sources/VPhoneCore/VPhoneSudo.swiftindex f2885313..0e1f6795 100644--- a/sources/VPhoneCore/VPhoneSudo.swift+++ b/sources/VPhoneCore/VPhoneSudo.swift@@ -32,7 +32,9 @@ public enum VPhoneSudo {/// the running image, never through `PATH`, the same rule `vphone-vm`/// follows — a bypass planted earlier on `PATH` must not be able to answer/// a question about privilege.- public static var helper: URL { VPhoneResources.siblingExecutable("vphone-ask-for-permission") }+ public static var helper: URL {+ VPhoneResources.siblingExecutable("vphone-ask-for-permission")+ }/// Which of the three applies right now.///@@ -56,9 +58,13 @@ public enum VPhoneSudo {@discardableResultpublic static func authorize(reason: String, echo: Bool = true) throws -> Route {let route = route()- if route == .timestamp { return route }+ if route == .timestamp {+ return route+ }- if echo { print("[sudo] \(reason)") }+ if echo {+ print("[sudo] \(reason)")+ }let sudo = URL(fileURLWithPath: "/usr/bin/sudo")@@ -90,13 +96,13 @@ public enum VPhoneSudo {_ arguments: [String],reason: String,cwd: URL? = nil,- echo: Bool = true+ echo: Bool = true,) throws -> Int32 {try authorize(reason: reason, echo: echo)return try VPhoneProcessRunner.runForeground(URL(fileURLWithPath: "/usr/bin/sudo"),["--", executable.path] + arguments,- cwd: cwd+ cwd: cwd,)}}diff --git a/sources/VPhoneCore/VPhoneVMPicker.swift b/sources/VPhoneCore/VPhoneVMPicker.swiftindex 97520c9f..225d4e6b 100644--- a/sources/VPhoneCore/VPhoneVMPicker.swift+++ b/sources/VPhoneCore/VPhoneVMPicker.swift@@ -8,7 +8,7 @@ public enum VPhoneVMPickerError: Error, CustomStringConvertible, Equatable {public var description: String {switch self {- case .emptyLibrary(let root):+ case let .emptyLibrary(root):"No VMs found in \(root). Create one with 'vphone-cli vm create <name>'."case .notInteractive:"No VM name given, and this is not an interactive terminal. Pass the VM name as an argument."@@ -32,22 +32,32 @@ public enum VPhoneVMPicker {isInteractive: Bool,maxRetries: Int = 5,read: () -> String?,- write: (String) -> Void+ write: (String) -> Void,) throws -> String {- if let provided, !provided.isEmpty { return provided }+ if let provided, !provided.isEmpty {+ return provided+ }guard isInteractive else { throw VPhoneVMPickerError.notInteractive }guard !names.isEmpty else { throw VPhoneVMPickerError.emptyLibrary(root: libraryRoot) }write("Select a VM:")- for (i, name) in names.enumerated() { write(" [\(i + 1)] \(name)") }+ for (i, name) in names.enumerated() {+ write(" [\(i + 1)] \(name)")+ }- for _ in 0..<maxRetries {+ for _ in 0 ..< maxRetries {write("Enter number or name: ")guard let line = read() else { throw VPhoneVMPickerError.aborted }let choice = line.trimmingCharacters(in: .whitespacesAndNewlines)- if choice.isEmpty { continue }- if let idx = Int(choice), idx >= 1, idx <= names.count { return names[idx - 1] }- if let match = names.first(where: { $0 == choice }) { return match }+ if choice.isEmpty {+ continue+ }+ if let idx = Int(choice), idx >= 1, idx <= names.count {+ return names[idx - 1]+ }+ if let match = names.first(where: { $0 == choice }) {+ return match+ }write(" '\(choice)' is not a valid selection.")}throw VPhoneVMPickerError.invalidSelectiondiff --git a/sources/VPhoneCore/VPhoneVerbosity.swift b/sources/VPhoneCore/VPhoneVerbosity.swiftindex 3669adcf..ab294e49 100644--- a/sources/VPhoneCore/VPhoneVerbosity.swift+++ b/sources/VPhoneCore/VPhoneVerbosity.swift@@ -4,10 +4,10 @@/// `vm launch` always streams it, `vm create` never does — neither depends/// on the verbosity level.public enum VPhoneVerbosity: Int, Comparable, Sendable {- case quiet = 0 // tool banners + [*]/[+] markers only- case info = 1 // + wrapped-subprocess stdout + pmd3 restore log (INFO, colorful)- case debug = 2 // + pmd3 DEBUG logs (deeper restore detail)- case trace = 3 // + vphone-cli internal trace (spawned argv/env, managed-process events)+ case quiet = 0 // tool banners + [*]/[+] markers only+ case info = 1 // + wrapped-subprocess stdout + pmd3 restore log (INFO, colorful)+ case debug = 2 // + pmd3 DEBUG logs (deeper restore detail)+ case trace = 3 // + vphone-cli internal trace (spawned argv/env, managed-process events)public static func < (lhs: VPhoneVerbosity, rhs: VPhoneVerbosity) -> Bool {lhs.rawValue < rhs.rawValue@@ -18,6 +18,11 @@ public enum VPhoneVerbosity: Int, Comparable, Sendable {self = VPhoneVerbosity(rawValue: min(max(count, 0), 3)) ?? .trace}- public var showsToolDetail: Bool { self >= .info }- public var tracesInternals: Bool { self >= .trace }+ public var showsToolDetail: Bool {+ self >= .info+ }++ public var tracesInternals: Bool {+ self >= .trace+ }}diff --git a/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift b/sources/VPhoneCore/VPhoneVirtualMachineManifest.swiftindex 03cc3b21..a3d5229e 100644--- a/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift+++ b/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift@@ -19,7 +19,10 @@ extension VPhoneManifestError: CustomStringConvertible, LocalizedError {"Unable to save the VM configuration to \(path). Check that the file is writable and try again."}}- public var errorDescription: String? { description }++ public var errorDescription: String? {+ description+ }}/// VPhoneVirtualMachineManifest represents the on-disk VM configuration manifest.@@ -93,7 +96,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {width: 1290,height: 2796,pixelsPerInch: 460,- scale: 3.0+ scale: 3.0,)public init(width: Int, height: Int, pixelsPerInch: Int, scale: Double) {@@ -135,7 +138,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {/// The names `vm create` copies the ROMs in as.public static let `default` = ROMImages(avpBooter: "AVPBooter.vresearch1.bin",- avpSEPBooter: "AVPSEPBooter.vresearch1.bin"+ avpSEPBooter: "AVPSEPBooter.vresearch1.bin",)public init(avpBooter: String, avpSEPBooter: String) {@@ -157,7 +160,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {diskImage: String = "Disk.img",nvramStorage: String = "nvram.bin",romImages: ROMImages?,- sepStorage: String = "SEPStorage"+ sepStorage: String = "SEPStorage",) {self.platformType = platformTypeself.platformFusing = platformFusing@@ -187,13 +190,13 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {public static func newVM(cpuCount: UInt = 8,memoryMB: UInt64 = 8192,- platformFusing: PlatformFusing? = nil+ platformFusing: PlatformFusing? = nil,) -> VPhoneVirtualMachineManifest {VPhoneVirtualMachineManifest(platformFusing: platformFusing,cpuCount: cpuCount,memorySize: memoryMB * 1024 * 1024,- romImages: .default+ romImages: .default,)}@@ -242,7 +245,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {cpuCount: UInt? = nil,memorySize: UInt64? = nil,machineIdentifier: Data? = nil,- networkConfig: NetworkConfig? = nil+ networkConfig: NetworkConfig? = nil,) -> VPhoneVirtualMachineManifest {VPhoneVirtualMachineManifest(platformType: platformType,@@ -255,7 +258,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {diskImage: diskImage,nvramStorage: nvramStorage,romImages: romImages,- sepStorage: sepStorage+ sepStorage: sepStorage,)}}diff --git a/sources/VPhoneRestore/VPhoneRecoveryProbe.swift b/sources/VPhoneRestore/VPhoneRecoveryProbe.swiftindex f174977c..cee6fece 100644--- a/sources/VPhoneRestore/VPhoneRecoveryProbe.swift+++ b/sources/VPhoneRestore/VPhoneRecoveryProbe.swift@@ -12,7 +12,9 @@ import MobileRecoveryCorepublic struct VPhoneRecoveryMode: RawRepresentable, Sendable, Hashable, CustomStringConvertible {public let rawValue: Int32- public init(rawValue: Int32) { self.rawValue = rawValue }+ public init(rawValue: Int32) {+ self.rawValue = rawValue+ }public static let recovery1 = VPhoneRecoveryMode(rawValue: 0x1280)public static let recovery2 = VPhoneRecoveryMode(rawValue: 0x1281)@@ -26,7 +28,7 @@ public struct VPhoneRecoveryMode: RawRepresentable, Sendable, Hashable, CustomSt/// DFU. Port DFU is not in its enum at all; it is a DFU variant, so it/// answers `false` here, and an unknown mode does too.public var isRecovery: Bool {- (Self.recovery1.rawValue...Self.recovery4.rawValue).contains(rawValue)+ (Self.recovery1.rawValue ... Self.recovery4.rawValue).contains(rawValue)}public var description: String {@@ -78,7 +80,7 @@ public enum VPhoneRecoveryProbe {public static func probe(ecid: UInt64?,timeout: Int,- isRecovery: Bool? = nil+ isRecovery: Bool? = nil,) throws -> VPhoneRecoveryDevice {let deadline = DispatchTime.now() + .seconds(max(timeout, 0))while DispatchTime.now() < deadline {@@ -90,7 +92,7 @@ public enum VPhoneRecoveryProbe {// "dfu/recovery"` says "dfu/recovery" for None AND for False. Keeping// it means the message a user greps for has not changed.throw VPhoneRestoreBackendError.recoveryProbeTimedOut(- mode: isRecovery == true ? "recovery" : "dfu/recovery"+ mode: isRecovery == true ? "recovery" : "dfu/recovery",)}@@ -134,7 +136,7 @@ public enum VPhoneRecoveryProbe {boardID: UInt32(info.pointee.bdid),serialNumber: info.pointee.srnm.map { String(cString: $0) },productType: productType,- hardwareModel: hardwareModel+ hardwareModel: hardwareModel,)}@@ -150,7 +152,7 @@ public enum VPhoneRecoveryProbe {}return (device.pointee.product_type.map { String(cString: $0) },- device.pointee.hardware_model.map { String(cString: $0) }+ device.pointee.hardware_model.map { String(cString: $0) },)}}diff --git a/sources/VPhoneRestore/VPhoneRestoreBridge.swift b/sources/VPhoneRestore/VPhoneRestoreBridge.swiftindex bee1cc0c..e98f6c0d 100644--- a/sources/VPhoneRestore/VPhoneRestoreBridge.swift+++ b/sources/VPhoneRestore/VPhoneRestoreBridge.swift@@ -19,7 +19,7 @@ public enum VPhoneRestoreBridge {public static func recoveryProbe(ecid: UInt64?,timeout: Int,- isRecovery: Bool? = nil+ isRecovery: Bool? = nil,) throws -> VPhoneRecoveryDevice {try VPhoneRecoveryProbe.probe(ecid: ecid, timeout: timeout, isRecovery: isRecovery)}@@ -45,7 +45,7 @@ public enum VPhoneRestoreBridge {udid: String?,out: URL?,debugLevel: Int32 = 0,- onEvent: @escaping VPhoneRestoreEventHandler = { _ in }+ onEvent: @escaping VPhoneRestoreEventHandler = { _ in },) throws -> URL {let restoreDirectory = try VPhoneRestoreLayout.findRestoreDirectory(in: vmDir)@@ -67,9 +67,9 @@ public enum VPhoneRestoreBridge {ecid: ecid ?? 0,erase: true,shshOnly: true,- debugLevel: debugLevel+ debugLevel: debugLevel,),- onEvent: onEvent+ onEvent: onEvent,)let written = try locateWrittenSHSH(under: cacheDirectory, requestedECID: ecid)@@ -104,7 +104,7 @@ public enum VPhoneRestoreBridge {erase: Bool,ticketPath: URL?,debugLevel: Int32 = 0,- onEvent: @escaping VPhoneRestoreEventHandler = { _ in }+ onEvent: @escaping VPhoneRestoreEventHandler = { _ in },) throws {let restoreDirectory = try VPhoneRestoreLayout.findRestoreDirectory(in: vmDir)@@ -124,9 +124,9 @@ public enum VPhoneRestoreBridge {ecid: ecid ?? 0,erase: erase,ticketPath: ticketPath,- debugLevel: debugLevel+ debugLevel: debugLevel,),- onEvent: onEvent+ onEvent: onEvent,)}@@ -141,7 +141,7 @@ public enum VPhoneRestoreBridge {let shshDirectory = cacheDirectory.appendingPathComponent("shsh", isDirectory: true)let candidates = ((try? FileManager.default.contentsOfDirectory(at: shshDirectory,- includingPropertiesForKeys: nil+ includingPropertiesForKeys: nil,)) ?? []).filter { $0.pathExtension == "shsh" }.sorted { $0.lastPathComponent < $1.lastPathComponent }@@ -153,7 +153,9 @@ public enum VPhoneRestoreBridge {let match = candidates.first {VPhoneRestoreTicket.ecid(fromSHSHFilename: $0.lastPathComponent) == requestedECID}- if let match { return match }+ if let match {+ return match+ }}return candidates[0]}diff --git a/sources/VPhoneRestore/VPhoneRestoreError.swift b/sources/VPhoneRestore/VPhoneRestoreError.swiftindex 101aaf78..275b4813 100644--- a/sources/VPhoneRestore/VPhoneRestoreError.swift+++ b/sources/VPhoneRestore/VPhoneRestoreError.swift@@ -112,5 +112,7 @@ extension VPhoneRestoreBackendError: CustomStringConvertible {// MARK: - LocalizedErrorextension VPhoneRestoreBackendError: LocalizedError {- public var errorDescription: String? { description }+ public var errorDescription: String? {+ description+ }}diff --git a/sources/VPhoneRestore/VPhoneRestoreEvent.swift b/sources/VPhoneRestore/VPhoneRestoreEvent.swiftindex 4839000a..2069ebe7 100644--- a/sources/VPhoneRestore/VPhoneRestoreEvent.swift+++ b/sources/VPhoneRestore/VPhoneRestoreEvent.swift@@ -33,7 +33,9 @@ public enum VPhoneRestoreLogLevel: Int32, Sendable, Comparable, CaseIterable {public struct VPhoneRestoreStep: RawRepresentable, Sendable, Hashable, CustomStringConvertible {public let rawValue: Int32- public init(rawValue: Int32) { self.rawValue = rawValue }+ public init(rawValue: Int32) {+ self.rawValue = rawValue+ }public static let detect = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_DETECT)public static let prepare = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_PREPARE)@@ -49,7 +51,9 @@ public struct VPhoneRestoreStep: RawRepresentable, Sendable, Hashable, CustomStrString(cString: vphone_restore_step_name(rawValue))}- public var description: String { name }+ public var description: String {+ name+ }}// MARK: - VPhoneRestoreEvent@@ -101,7 +105,7 @@ public enum VPhoneRestoreConsole {/// `vphone_restore_bridge.c`; printing from here is the case it exists for.public static func handler(level: VPhoneRestoreLogLevel = .info,- showsProgress: Bool = false+ showsProgress: Bool = false,) -> VPhoneRestoreEventHandler {let lock = NSLock()return { event indiff --git a/sources/VPhoneRestore/VPhoneRestoreIdentity.swift b/sources/VPhoneRestore/VPhoneRestoreIdentity.swiftindex 4f5ba91d..09536903 100644--- a/sources/VPhoneRestore/VPhoneRestoreIdentity.swift+++ b/sources/VPhoneRestore/VPhoneRestoreIdentity.swift@@ -27,7 +27,9 @@ public enum VPhoneRestoreIdentity {guard let value, !value.isEmpty else { return nil }var raw = Substring(value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased())- if raw.hasPrefix("0x") { raw = raw.dropFirst(2) }+ if raw.hasPrefix("0x") {+ raw = raw.dropFirst(2)+ }guard !raw.isEmpty else { throw VPhoneRestoreBackendError.ecidEmpty }guard raw.allSatisfy(\.isHexDigitASCII) else {@@ -74,6 +76,6 @@ private extension Character {/// forms too, and `UInt64(_:radix:)` would then reject what this accepted.var isHexDigitASCII: Bool {guard let ascii = asciiValue else { return false }- return (0x30...0x39).contains(ascii) || (0x61...0x66).contains(ascii)+ return (0x30 ... 0x39).contains(ascii) || (0x61 ... 0x66).contains(ascii)}}diff --git a/sources/VPhoneRestore/VPhoneRestoreLayout.swift b/sources/VPhoneRestore/VPhoneRestoreLayout.swiftindex c26bc332..76c75405 100644--- a/sources/VPhoneRestore/VPhoneRestoreLayout.swift+++ b/sources/VPhoneRestore/VPhoneRestoreLayout.swift@@ -49,7 +49,7 @@ public enum VPhoneRestoreLayout {var isDirectory: ObjCBool = falselet exists = fm.fileExists(atPath: vmDir.appendingPathComponent(name).path,- isDirectory: &isDirectory+ isDirectory: &isDirectory,)return exists && isDirectory.boolValue}diff --git a/sources/VPhoneRestore/VPhoneRestoreOptions.swift b/sources/VPhoneRestore/VPhoneRestoreOptions.swiftindex 8cf66cf7..0511706c 100644--- a/sources/VPhoneRestore/VPhoneRestoreOptions.swift+++ b/sources/VPhoneRestore/VPhoneRestoreOptions.swift@@ -52,7 +52,7 @@ public struct VPhoneRestoreOptions: Sendable, Equatable {ticketPath: URL? = nil,shshOnly: Bool = false,keepPers: Bool = false,- debugLevel: Int32 = 0+ debugLevel: Int32 = 0,) {self.restoreDirectory = restoreDirectoryself.cacheDirectory = cacheDirectory@@ -113,7 +113,9 @@ final class VPhoneCStringBag {}func releaseAll() {- for allocation in allocations { free(allocation) }+ for allocation in allocations {+ free(allocation)+ }allocations.removeAll()}}diff --git a/sources/VPhoneRestore/VPhoneRestoreRunner.swift b/sources/VPhoneRestore/VPhoneRestoreRunner.swiftindex 1166a4fa..06a7f9c1 100644--- a/sources/VPhoneRestore/VPhoneRestoreRunner.swift+++ b/sources/VPhoneRestore/VPhoneRestoreRunner.swift@@ -25,7 +25,7 @@ public enum VPhoneRestoreRunner {/// which is why it is `@Sendable`.public static func run(_ options: VPhoneRestoreOptions,- onEvent: @escaping VPhoneRestoreEventHandler = { _ in }+ onEvent: @escaping VPhoneRestoreEventHandler = { _ in },) throws {let sink = VPhoneRestoreEventSink(onEvent)let result = options.withCOptions { base -> Int32 in@@ -36,7 +36,7 @@ public enum VPhoneRestoreRunner {let sink = Unmanaged<VPhoneRestoreEventSink>.fromOpaque(context).takeUnretainedValue()sink.handler(.log(level: VPhoneRestoreLogLevel(clamping: level),- message: String(cString: message)+ message: String(cString: message),))}c.progress_cb = { step, fraction, context in@@ -66,14 +66,14 @@ public enum VPhoneRestoreRunner {throw VPhoneRestoreBackendError.restoreDirectoryUnusable(options.restoreDirectory)case VPHONE_RESTORE_E_TICKET:throw VPhoneRestoreBackendError.ticketUnreadable(- options.ticketPath ?? options.restoreDirectory+ options.ticketPath ?? options.restoreDirectory,)default:// Everything else, including the small negatives idevicerestore// returns itself. The log stream carries what actually went wrong.throw VPhoneRestoreBackendError.restoreFailed(code: result,- reason: String(cString: vphone_restore_error_string(result))+ reason: String(cString: vphone_restore_error_string(result)),)}}diff --git a/sources/VPhoneRestore/VPhoneRestoreTicket.swift b/sources/VPhoneRestore/VPhoneRestoreTicket.swiftindex aa1bd424..915ec08b 100644--- a/sources/VPhoneRestore/VPhoneRestoreTicket.swift+++ b/sources/VPhoneRestore/VPhoneRestoreTicket.swift@@ -50,7 +50,7 @@ public enum VPhoneRestoreTicket {guard let object = try? PropertyListSerialization.propertyList(from: unwrapped,options: [],- format: nil+ format: nil,), object is [String: Any] else {throw VPhoneRestoreBackendError.shshMalformed(path)}@@ -75,7 +75,7 @@ public enum VPhoneRestoreTicket {&stream,15 + 32,zlibVersion(),- Int32(MemoryLayout<z_stream>.size)+ Int32(MemoryLayout<z_stream>.size),)guard initialized == Z_OK else { return nil }defer { inflateEnd(&stream) }@@ -96,7 +96,9 @@ public enum VPhoneRestoreTicket {return inflate(&stream, Z_NO_FLUSH)}let produced = chunkSize - Int(stream.avail_out)- if produced > 0 { output.append(contentsOf: chunk[0..<produced]) }+ if produced > 0 {+ output.append(contentsOf: chunk[0 ..< produced])+ }switch status {case Z_STREAM_END:@@ -106,7 +108,9 @@ public enum VPhoneRestoreTicket {// make no further progress and the stream ended without// its trailer — a truncated file, not a finished one. Z_OK// otherwise just means "call me again".- if produced == 0, stream.avail_in == 0 { return false }+ if produced == 0, stream.avail_in == 0 {+ return false+ }default:return false}diff --git a/sources/VPhoneSign/VPhoneCodeSignature.swift b/sources/VPhoneSign/VPhoneCodeSignature.swiftindex 6f8791da..ac298438 100644--- a/sources/VPhoneSign/VPhoneCodeSignature.swift+++ b/sources/VPhoneSign/VPhoneCodeSignature.swift@@ -15,9 +15,14 @@ struct VPhoneCodeSignature {enum Digest: Equatable {case sha1, sha256- var size: Int { self == .sha1 ? 20 : 32 }+ var size: Int {+ self == .sha1 ? 20 : 32+ }+/// `CS_HASHTYPE_SHA1` / `CS_HASHTYPE_SHA256`.- var type: UInt8 { self == .sha1 ? 1 : 2 }+ var type: UInt8 {+ self == .sha1 ? 1 : 2+ }func hash(_ data: Data) -> Data {self == .sha1 ? Data(Insecure.SHA1.hash(data: data)) : Data(SHA256.hash(data: data))@@ -105,7 +110,7 @@ struct VPhoneCodeSignature {code: Data,codeLimit: Int,executable: (base: UInt64, limit: UInt64),- cms: ((_ primary: Data, _ cdHashes: [Data]) throws -> Data)? = nil+ cms: ((_ primary: Data, _ cdHashes: [Data]) throws -> Data)? = nil,) throws -> Data {var blobs: [(slot: UInt32, bytes: Data)] = [(2, requirementsBlob)]if let entitlements {@@ -115,8 +120,8 @@ struct VPhoneCodeSignature {var directories: [Data] = []for (index, digest) in digests.enumerated() {- let directory = self.directory(- digest: digest, code: code, codeLimit: codeLimit, executable: executable, blobs: blobs+ let directory = directory(+ digest: digest, code: code, codeLimit: codeLimit, executable: executable, blobs: blobs,)directories.append(directory)blobs.append((index == 0 ? 0 : 0x1000 + UInt32(index) - 1, directory))@@ -126,7 +131,7 @@ struct VPhoneCodeSignature {// each CodeDirectory hashed with its own digest, at full length:// the attribute that carries them truncates to 20 bytes itselflet cdHashes = zip(digests, directories).map { $0.hash($1) }- blobs.append((0x10000, Self.wrapped(0xFADE_0B01, try cms(primary, cdHashes))))+ try blobs.append((0x10000, Self.wrapped(0xFADE_0B01, cms(primary, cdHashes))))}// ldid keeps the blobs in a map, so they come out in slot order@@ -149,7 +154,7 @@ struct VPhoneCodeSignature {code: Data,codeLimit: Int,executable: (base: UInt64, limit: UInt64),- blobs: [(slot: UInt32, bytes: Data)]+ blobs: [(slot: UInt32, bytes: Data)],) -> Data {let identifierBytes = Data(identifier.utf8) + [0]let teamBytes = teamIdentifier.isEmpty ? Data() : Data(teamIdentifier.utf8) + [0]@@ -164,7 +169,7 @@ struct VPhoneCodeSignature {directory.appendBigEndian(0x0002_0400 as UInt32) // the version with an executable segmentdirectory.appendBigEndian(flags)directory.appendBigEndian(UInt32(- Self.directoryHeader + identifierBytes.count + teamBytes.count + special * digest.size+ Self.directoryHeader + identifierBytes.count + teamBytes.count + special * digest.size,)) // hashOffsetdirectory.appendBigEndian(UInt32(Self.directoryHeader)) // identOffsetdirectory.appendBigEndian(UInt32(special))diff --git a/sources/VPhoneSign/VPhoneMachOImage.swift b/sources/VPhoneSign/VPhoneMachOImage.swiftindex 8c87ec21..048283ac 100644--- a/sources/VPhoneSign/VPhoneMachOImage.swift+++ b/sources/VPhoneSign/VPhoneMachOImage.swift@@ -83,7 +83,7 @@ struct VPhoneMachOImage {// none of that is exercised by anything.guard Self.armCPUTypes.contains(cpuType) else {throw VPhoneSignError.unsupportedSlice(- "slice at \(range.lowerBound) is cputype \(cpuType); this signer is ARM only"+ "slice at \(range.lowerBound) is cputype \(cpuType); this signer is ARM only",)}fileType = image.littleEndianValue(at: 12)@@ -122,7 +122,7 @@ struct VPhoneMachOImage {signature = (cursor,Int(image.littleEndianValue(at: start + 8) as UInt32),- Int(image.littleEndianValue(at: start + 12) as UInt32)+ Int(image.littleEndianValue(at: start + 12) as UInt32),)case UInt32(LC_SYMTAB):guard size >= MemoryLayout<symtab_command>.size else {@@ -133,7 +133,7 @@ struct VPhoneMachOImage {// an all-zero symbol table is no symbol table, as ldid reads itstringTableEnd = offset == 0 && length == 0 ? nil : UInt64(offset) + UInt64(length)case UInt32(LC_SEGMENT_64):- segments.append(try Self.segment(in: image, at: start, commandOffset: cursor, size: size))+ try segments.append(Self.segment(in: image, at: start, commandOffset: cursor, size: size))default:break}@@ -180,7 +180,7 @@ struct VPhoneMachOImage {sections.append((Self.name(in: image, at: section),image.littleEndianValue(at: section + 48),- image.littleEndianValue(at: section + 40)+ image.littleEndianValue(at: section + 40),))}return Segment(@@ -189,7 +189,7 @@ struct VPhoneMachOImage {fileOffset: fileOffset,fileSize: fileSize,initialProtection: Int32(bitPattern: image.littleEndianValue(at: start + 60) as UInt32),- sections: sections+ sections: sections,)}@@ -204,7 +204,7 @@ struct VPhoneMachOImage {/// number of CodeDirectories has a different CDHash. So it is/// reproduced, not corrected.private static func digests(- in image: Data, command: UInt32, at start: Int, size: Int+ in image: Data, command: UInt32, at start: Int, size: Int,) throws -> [VPhoneCodeSignature.Digest]? {/// A packed version: patch, minor, then major in the high 16 bits.func version(_ value: UInt32) -> (major: UInt32, minor: UInt32) {@@ -300,7 +300,9 @@ struct VPhoneMachOImage {/// in a fat file, and in a thin one what it takes the CPU's page to be./// ldid's table has an entry per CPU; only the ARM one can be reached/// here, because `init` refuses everything else.- var linkeditAlignment: Int { 14 }+ var linkeditAlignment: Int {+ 14+ }// MARK: Rewriting@@ -313,7 +315,7 @@ struct VPhoneMachOImage {func signed(alignment: Int,signatureSize: (_ codeLimit: Int) -> Int,- makeSignature: (_ code: Data, _ codeLimit: Int) throws -> Data+ makeSignature: (_ code: Data, _ codeLimit: Int) throws -> Data,) throws -> Data {let codeEnd = try codeEnd()let codeLimit = codeEnd.aligned(to: 16)@@ -436,9 +438,9 @@ struct VPhoneMachOFile {architectures.append(Architecture(cpuType: data.bigEndianValue(at: entry),cpuSubtype: data.bigEndianValue(at: entry + 4),- alignment: alignment+ alignment: alignment,))- slices.append(try VPhoneMachOImage(file: data, range: offset ..< offset + length))+ try slices.append(VPhoneMachOImage(file: data, range: offset ..< offset + length))}self.architectures = architecturesself.slices = slices@@ -446,7 +448,7 @@ struct VPhoneMachOFile {throw VPhoneSignError.unsupportedSlice("a fat file this signer does not read")default:architectures = nil- slices = [try VPhoneMachOImage(file: data, range: 0 ..< data.count)]+ slices = try [VPhoneMachOImage(file: data, range: 0 ..< data.count)]}}diff --git a/sources/VPhoneSign/VPhoneSignDER.swift b/sources/VPhoneSign/VPhoneSignDER.swiftindex bc6138df..e99e436e 100644--- a/sources/VPhoneSign/VPhoneSignDER.swift+++ b/sources/VPhoneSign/VPhoneSignDER.swift@@ -22,7 +22,9 @@ enum VPhoneDER {/// Where the next element starts.let end: Int- var isConstructed: Bool { tag & 0x20 != 0 }+ var isConstructed: Bool {+ tag & 0x20 != 0+ }}// MARK: Reading@@ -54,7 +56,7 @@ enum VPhoneDER {tag: tag,content: data.subdata(in: cursor ..< cursor + length),encoded: data.subdata(in: index ..< cursor + length),- end: cursor + length+ end: cursor + length,)}@@ -126,7 +128,9 @@ enum VPhoneDER {}.reduce(Data(), +))}- static func octetString(_ content: Data) -> Data { encode(0x04, content) }+ static func octetString(_ content: Data) -> Data {+ encode(0x04, content)+ }static func integer(_ value: Int) -> Data {var bytes: [UInt8] = []@@ -170,7 +174,7 @@ enum VPhoneDER {let parts = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)let text = String(format: "%02d%02d%02d%02d%02d%02dZ",- parts.year! % 100, parts.month!, parts.day!, parts.hour!, parts.minute!, parts.second!+ parts.year! % 100, parts.month!, parts.day!, parts.hour!, parts.minute!, parts.second!,)return encode(0x17, Data(text.utf8))}diff --git a/sources/VPhoneSign/VPhoneSignEntitlements.swift b/sources/VPhoneSign/VPhoneSignEntitlements.swiftindex 88ba7c4c..1f99407f 100644--- a/sources/VPhoneSign/VPhoneSignEntitlements.swift+++ b/sources/VPhoneSign/VPhoneSignEntitlements.swift@@ -73,7 +73,9 @@ struct VPhoneSignEntitlements: Equatable {entries = try reader.read()}- var isEmpty: Bool { entries.isEmpty }+ var isEmpty: Bool {+ entries.isEmpty+ }/// Merges `other` in as `-M` does: each of its keys set to its value/// where the key already stands, appended where it does not.@@ -112,7 +114,7 @@ struct VPhoneSignEntitlements: Equatable {/// refused rather than signed.func xml() throws -> Data {let foundation = try? PropertyListSerialization.data(- fromPropertyList: Self.foundation(.dictionary(entries)), format: .xml, options: 0+ fromPropertyList: Self.foundation(.dictionary(entries)), format: .xml, options: 0,)guard Self.document(.dictionary(entries), sorted: true) == foundation else {throw VPhoneSignError.unsupportedEntitlements("Foundation and libplist would write this list differently")@@ -157,7 +159,7 @@ struct VPhoneSignEntitlements: Equatable {case let .dictionary(entries):NSDictionary(objects: entries.map { foundation($0.value) },- forKeys: entries.map { NSString(string: $0.key) }+ forKeys: entries.map { NSString(string: $0.key) },)}}@@ -237,7 +239,7 @@ struct VPhoneSignEntitlements: Equatable {0x31,entries.map { tagged(0x30, tagged(0x0C, Array($0.key.utf8)) + der($0.value)) }.sorted { $0.lexicographicallyPrecedes($1) }- .flatMap(\.self)+ .flatMap(\.self),)}}diff --git a/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift b/sources/VPhoneSign/VPhoneSignEntitlementsReader.swiftindex 3f8b2633..00648534 100644--- a/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift+++ b/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift@@ -128,7 +128,7 @@ extension VPhoneSignEntitlements {// libplist's decoder skips what it does not know; base64// that reads back the same is what the two agree onlet encoded = try empty ? "" : String(- decoding: text(closing: name, skippingSpace: true).filter { !Self.isSpace($0) }, as: UTF8.self+ decoding: text(closing: name, skippingSpace: true).filter { !Self.isSpace($0) }, as: UTF8.self,)guard let value = Data(base64Encoded: encoded), value.base64EncodedString() == encoded else {throw Self.refuse("a <data> whose base64 does not read back the same")@@ -337,7 +337,7 @@ extension VPhoneSignEntitlements {raw: isNegative ? 0 &- magnitude : magnitude,// libplist's `length == 16`: above INT64_MAX and unsigned,// which is the only case `plist_to_xml` prints with %llu- isUnsigned: !isNegative && magnitude > UInt64(Int64.max)+ isUnsigned: !isNegative && magnitude > UInt64(Int64.max),)}diff --git a/sources/VPhoneSign/VPhoneSignIdentity.swift b/sources/VPhoneSign/VPhoneSignIdentity.swiftindex fe1c2187..4cfff862 100644--- a/sources/VPhoneSign/VPhoneSignIdentity.swift+++ b/sources/VPhoneSign/VPhoneSignIdentity.swift@@ -34,7 +34,7 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {guard let key = SecKeyCreateWithData(container.privateKey as CFData,[kSecAttrKeyType: kSecAttrKeyTypeRSA, kSecAttrKeyClass: kSecAttrKeyClassPrivate] as CFDictionary,- nil+ nil,) else {throw VPhoneSignError.identityUnreadable("the private key is not an RSA key Security will take")}@@ -76,7 +76,7 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {// 1.2.840.113635.100.9.1: a plist of every cdhash, truncated to 20// bytes, which is the form the older attribute carries.if let plist = try? PropertyListSerialization.data(- fromPropertyList: ["cdhashes": cdHashes.map { $0.prefix(20) }], format: .xml, options: 0+ fromPropertyList: ["cdhashes": cdHashes.map { $0.prefix(20) }], format: .xml, options: 0,) {attributes.append(attribute(VPhoneDER.OID.hashAgility, [VPhoneDER.octetString(plist)]))}@@ -127,10 +127,10 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {private func sign(_ content: Data) throws -> Data {var error: Unmanaged<CFError>?guard let signature = SecKeyCreateSignature(- key, .rsaSignatureMessagePKCS1v15SHA256, content as CFData, &error+ key, .rsaSignatureMessagePKCS1v15SHA256, content as CFData, &error,) as Data? else {throw VPhoneSignError.signingFailed(- (error?.takeRetainedValue()).map { "\($0)" } ?? "SecKeyCreateSignature gave no signature"+ (error?.takeRetainedValue()).map { "\($0)" } ?? "SecKeyCreateSignature gave no signature",)}return signature@@ -143,9 +143,9 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {// MARK: Reading the certificateprivate static func certificateFields(_ certificate: Data) throws -> (- issuer: Data, subject: Data, serialNumber: Data+ issuer: Data, subject: Data, serialNumber: Data,) {- let tbs = try VPhoneDER.children(of: try VPhoneDER.element(in: certificate, at: 0).content)+ let tbs = try VPhoneDER.children(of: VPhoneDER.element(in: certificate, at: 0).content)guard let first = tbs.first else { throw VPhoneSignError.identityUnreadable("an empty certificate") }let fields = try VPhoneDER.children(of: first.content)// [0] EXPLICIT version is optional; everything after it shifts by one@@ -165,7 +165,7 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {/// One attribute of a `Name`: a SEQUENCE of SETs of type-and-value.private static func name(_ encoded: Data, oid: String) throws -> String {- for set in try VPhoneDER.children(of: try VPhoneDER.element(in: encoded, at: 0).content) {+ for set in try VPhoneDER.children(of: VPhoneDER.element(in: encoded, at: 0).content) {for pair in try VPhoneDER.children(of: set.content) {let fields = try VPhoneDER.children(of: pair.content)guard fields.count >= 2, VPhoneDER.objectIdentifier(fields[0].content) == oid else { continue }diff --git a/sources/VPhoneSign/VPhoneSignPKCS12.swift b/sources/VPhoneSign/VPhoneSignPKCS12.swiftindex e5c3d4a6..f653a77a 100644--- a/sources/VPhoneSign/VPhoneSignPKCS12.swift+++ b/sources/VPhoneSign/VPhoneSignPKCS12.swift@@ -23,7 +23,7 @@ struct VPhoneSignPKCS12 {init(data: Data, password: String) throws {// as in VPhoneMachOFile: the DER reader counts from zerolet data = data.startIndex == 0 ? data : Data(data)- let pfx = try VPhoneDER.children(of: try VPhoneDER.element(in: data, at: 0).content)+ let pfx = try VPhoneDER.children(of: VPhoneDER.element(in: data, at: 0).content)guard pfx.count >= 2 else { throw VPhoneSignError.identityUnreadable("a PFX with \(pfx.count) fields") }let authenticated = try Self.contentInfo(pfx[1], password: password)@@ -31,9 +31,9 @@ struct VPhoneSignPKCS12 {var privateKey: Data?// Each payload is the DER of a SEQUENCE, not its contents, so it is// unwrapped once more on the way in.- for content in try VPhoneDER.children(of: try VPhoneDER.element(in: authenticated, at: 0).content) {+ for content in try VPhoneDER.children(of: VPhoneDER.element(in: authenticated, at: 0).content) {let safeContents = try Self.contentInfo(content, password: password)- for bag in try VPhoneDER.children(of: try VPhoneDER.element(in: safeContents, at: 0).content) {+ for bag in try VPhoneDER.children(of: VPhoneDER.element(in: safeContents, at: 0).content) {let fields = try VPhoneDER.children(of: bag.content)guard fields.count >= 2 else { continue }let value = try VPhoneDER.element(in: fields[1].content, at: 0)@@ -43,9 +43,9 @@ struct VPhoneSignPKCS12 {guard certificate.count >= 2,VPhoneDER.objectIdentifier(certificate[0].content) == VPhoneDER.OID.x509Certificateelse { continue }- certificates.append(try VPhoneDER.element(in: certificate[1].content, at: 0).content)+ try certificates.append(VPhoneDER.element(in: certificate[1].content, at: 0).content)case VPhoneDER.OID.shroudedKeyBag:- privateKey = try Self.privateKey(in: try Self.decryptPrivateKey(value.encoded, password: password))+ privateKey = try Self.privateKey(in: Self.decryptPrivateKey(value.encoded, password: password))case VPhoneDER.OID.keyBag:privateKey = try Self.privateKey(in: value.encoded)default:@@ -71,7 +71,7 @@ struct VPhoneSignPKCS12 {// BER; DER keeps it in onereturn try VPhoneDER.element(in: fields[1].content, at: 0).contentcase VPhoneDER.OID.encryptedData:- let encrypted = try VPhoneDER.children(of: try VPhoneDER.element(in: fields[1].content, at: 0).content)+ let encrypted = try VPhoneDER.children(of: VPhoneDER.element(in: fields[1].content, at: 0).content)guard encrypted.count >= 2 else { throw VPhoneSignError.identityUnreadable("an EncryptedData without content") }let info = try VPhoneDER.children(of: encrypted[1].content)guard info.count >= 3 else { throw VPhoneSignError.identityUnreadable("an EncryptedContentInfo without content") }@@ -79,21 +79,21 @@ struct VPhoneSignPKCS12 {return try decrypt(info[2].content, algorithm: info[1], password: password)default:throw VPhoneSignError.identityUnreadable(- "a PKCS#12 bag of type \(VPhoneDER.objectIdentifier(fields[0].content))"+ "a PKCS#12 bag of type \(VPhoneDER.objectIdentifier(fields[0].content))",)}}/// An EncryptedPrivateKeyInfo.private static func decryptPrivateKey(_ encoded: Data, password: String) throws -> Data {- let fields = try VPhoneDER.children(of: try VPhoneDER.element(in: encoded, at: 0).content)+ let fields = try VPhoneDER.children(of: VPhoneDER.element(in: encoded, at: 0).content)guard fields.count >= 2 else { throw VPhoneSignError.identityUnreadable("an EncryptedPrivateKeyInfo without content") }return try decrypt(fields[1].content, algorithm: fields[0], password: password)}/// The PKCS#1 `RSAPrivateKey` inside a PKCS#8 `PrivateKeyInfo`.private static func privateKey(in pkcs8: Data) throws -> Data {- let fields = try VPhoneDER.children(of: try VPhoneDER.element(in: pkcs8, at: 0).content)+ let fields = try VPhoneDER.children(of: VPhoneDER.element(in: pkcs8, at: 0).content)guard fields.count >= 3 else { throw VPhoneSignError.identityUnreadable("a PrivateKeyInfo without a key") }let algorithm = try VPhoneDER.children(of: fields[1].content)guard let first = algorithm.first,@@ -173,7 +173,7 @@ struct VPhoneSignPKCS12 {bytes.baseAddress.map { UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self) }, bytes.count,salt.baseAddress, salt.count,prf, UInt32(iterations),- &key, key.count+ &key, key.count,)}}@@ -189,7 +189,7 @@ struct VPhoneSignPKCS12 {CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding),key, key.count, iv.baseAddress,input.baseAddress, input.count,- &plaintext, plaintext.count, &written+ &plaintext, plaintext.count, &written,)}}@@ -198,7 +198,7 @@ struct VPhoneSignPKCS12 {throw VPhoneSignError.identityUnreadable(status == kCCDecodeError || status == kCCAlignmentError? "the PKCS#12 password is wrong"- : "decrypting the PKCS#12 failed with \(status)"+ : "decrypting the PKCS#12 failed with \(status)",)}return Data(plaintext.prefix(written))diff --git a/sources/VPhoneSign/VPhoneSigner.swift b/sources/VPhoneSign/VPhoneSigner.swiftindex 053354d1..20c3312e 100644--- a/sources/VPhoneSign/VPhoneSigner.swift+++ b/sources/VPhoneSign/VPhoneSigner.swift@@ -48,7 +48,7 @@ public struct VPhoneSignOptions {entitlements: Data? = nil,mergesExisting: Bool = false,style: Style = .ldid,- identity: (any VPhoneSigningIdentity)? = nil+ identity: (any VPhoneSigningIdentity)? = nil,) {self.identifier = identifierself.entitlements = entitlements@@ -123,11 +123,11 @@ public enum VPhoneSigner {var images: [Data] = []for (index, slice) in file.slices.enumerated() {let alignment = file.architectures.map { Int($0[index].alignment) } ?? slice.linkeditAlignment- let signature = try self.signature(- for: slice, identifier: identifier, digests: digests, options: options+ let signature = try signature(+ for: slice, identifier: identifier, digests: digests, options: options,)let executable = slice.executableSegment- images.append(try slice.signed(+ try images.append(slice.signed(alignment: alignment,signatureSize: { signature.allocation(codeLimit: $0) },makeSignature: { code, codeLimit in@@ -135,16 +135,16 @@ public enum VPhoneSigner {code: code,codeLimit: codeLimit,executable: executable,- cms: cmsBuilder(options: options)+ cms: cmsBuilder(options: options),)- }+ },))}return try file.assembled(images)}private static func cmsBuilder(- options: VPhoneSignOptions+ options: VPhoneSignOptions,) -> ((Data, [Data]) throws -> Data)? {if let identity = options.identity {return { try identity.cms(codeDirectory: $0, cdHashes: $1) }@@ -159,7 +159,7 @@ public enum VPhoneSigner {for slice: VPhoneMachOImage,identifier: String,digests: [VPhoneCodeSignature.Digest],- options: VPhoneSignOptions+ options: VPhoneSignOptions,) throws -> VPhoneCodeSignature {var signature = VPhoneCodeSignature(identifier: identifier)signature.digests = digests@@ -170,7 +170,7 @@ public enum VPhoneSigner {case .ldid:signature.teamIdentifier = options.identity?.teamIdentifier ?? ""signature.requirementsBlob = VPhoneCodeSignature.requirements(- identifier: identifier, commonName: options.identity?.commonName ?? ""+ identifier: identifier, commonName: options.identity?.commonName ?? "",)signature.cmsReservation = options.identity == nil ? nil : cmsReservationcase .appleAdHoc:@@ -182,8 +182,8 @@ public enum VPhoneSigner {let existing = options.mergesExisting ? slice.embeddedEntitlements : nilif existing?.isEmpty == false || options.entitlements?.isEmpty == false {var combined = try VPhoneSignEntitlements(xml: existing ?? Data())- combined.merge(try VPhoneSignEntitlements(xml: options.entitlements ?? Data()))- signature.entitlements = (try combined.xml(), combined.der)+ try combined.merge(VPhoneSignEntitlements(xml: options.entitlements ?? Data()))+ signature.entitlements = try (combined.xml(), combined.der)signature.executableSegmentFlags = combined.executableSegmentFlags(mainBinary: mainBinary)} else {signature.executableSegmentFlags = mainBinary ? 1 : 0diff --git a/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift b/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swiftindex 2a28761a..89944180 100644--- a/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift+++ b/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift@@ -23,14 +23,14 @@ final class VPhoneCameraServer {enum SourceKind: String {case offcase testPattern- case videoFile // .mov / .mp4 / .m4v via AVAssetReader+ case videoFile // .mov / .mp4 / .m4v via AVAssetReader}nonisolated static let vsockPort: UInt32 = 1338nonisolated static let defaultWidth: Int = 1280nonisolated static let defaultHeight: Int = 720nonisolated static let defaultFPS: Double = 30.0- nonisolated static let pixelFormat: UInt32 = 0x4247_5241 // 'BGRA' — kCMPixelFormat_32BGRA+ nonisolated static let pixelFormat: UInt32 = 0x4247_5241 // 'BGRA' — kCMPixelFormat_32BGRAprivate(set) var sourceKind: SourceKind = .offprivate(set) var isConnected = false@@ -44,11 +44,11 @@ final class VPhoneCameraServer {private let sendQueue = DispatchQueue(label: "com.vphone.camera.send",- qos: .userInteractive+ qos: .userInteractive,)private let producerQueue = DispatchQueue(label: "com.vphone.camera.producer",- qos: .userInteractive+ qos: .userInteractive,)var onConnectionStateChange: ((Bool) -> Void)?@@ -76,9 +76,13 @@ final class VPhoneCameraServer {// MARK: - Source selectionfunc setSource(_ kind: SourceKind, videoURL: URL? = nil) {- if sourceKind == kind, kind != .videoFile { return }+ if sourceKind == kind, kind != .videoFile {+ return+ }let wasStreaming = (timer != nil)- if wasStreaming { stopStreaming() }+ if wasStreaming {+ stopStreaming()+ }sourceKind = kindswitch kind {case .off:@@ -86,7 +90,7 @@ final class VPhoneCameraServer {case .testPattern:producer = VPhoneTestPatternProducer(width: Self.defaultWidth,- height: Self.defaultHeight+ height: Self.defaultHeight,)case .videoFile:guard let url = videoURL else {@@ -99,7 +103,7 @@ final class VPhoneCameraServer {producer = try VPhoneVideoFileProducer(url: url,width: Self.defaultWidth,- height: Self.defaultHeight+ height: Self.defaultHeight,)print("[camera] video file source = \(url.lastPathComponent)")} catch {@@ -117,7 +121,9 @@ final class VPhoneCameraServer {func startStreaming() {guard producer != nil, isConnected else { return }- if timer != nil { return }+ if timer != nil {+ return+ }let interval = 1.0 / Self.defaultFPS// Timer fires on the main queue so MainActor-isolated state// (producer, connectionFD) can be read directly without tripping@@ -128,10 +134,10 @@ final class VPhoneCameraServer {t.schedule(deadline: .now(), repeating: interval, leeway: .milliseconds(2))t.setEventHandler { [weak self] inguard let self else { return }- guard let producer = self.producer else { return }- let fd = self.connectionFD+ guard let producer else { return }+ let fd = connectionFDguard fd >= 0 else { return }- let q = self.producerQueue+ let q = producerQueueq.async {guard let frame = producer.nextFrame() else { return }let ok = Self.send(fd: fd, frame: frame)@@ -140,8 +146,8 @@ final class VPhoneCameraServer {guard let self else { return }// Avoid double-handling if a parallel write already// dropped the connection.- if self.connectionFD == fd {- self.handleDisconnect()+ if connectionFD == fd {+ handleDisconnect()}}}@@ -171,7 +177,9 @@ final class VPhoneCameraServer {isConnected = falseonConnectionStateChange?(false)}- if oldFD >= 0 { close(oldFD) }+ if oldFD >= 0 {+ close(oldFD)+ }// Note: streaming timer continues running but ticks no-op until// connectionFD becomes valid again.attemptConnect()@@ -195,7 +203,9 @@ final class VPhoneCameraServer {self.isConnected = trueprint("[camera] connected on vsock port \(Self.vsockPort)")self.onConnectionStateChange?(true)- if self.sourceKind != .off { self.startStreaming() }+ if self.sourceKind != .off {+ self.startStreaming()+ }case let .failure(error):print("[camera] connect failed: \(error). Retrying in 3s.")DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { [weak self] in@@ -213,7 +223,7 @@ final class VPhoneCameraServer {// MARK: - Wire@discardableResult- nonisolated private static func send(fd: Int32, frame: VPhoneCameraFrame) -> Bool {+ private nonisolated static func send(fd: Int32, frame: VPhoneCameraFrame) -> Bool {// headerlet headerDict: [String: Any] = ["w": frame.width,@@ -239,19 +249,23 @@ final class VPhoneCameraServer {out.append(headerData)out.append(frame.pixels)var ok = true- out.withUnsafeBytes { bytes -> Void in+ out.withUnsafeBytes { bytes inguard let base = bytes.baseAddress else { ok = false; return }var remaining = bytes.countvar cursor = basewhile remaining > 0 {let n = write(fd, cursor, remaining)if n < 0 {- if errno == EINTR { continue }+ if errno == EINTR {+ continue+ }print("[camera] write errno=\(errno)")ok = falsereturn}- if n == 0 { ok = false; return }+ if n == 0 {+ ok = false; return+ }remaining -= ncursor = cursor.advanced(by: n)}diff --git a/sources/VPhoneVMKit/Devices/VPhoneFrameProducer.swift b/sources/VPhoneVMKit/Devices/VPhoneFrameProducer.swiftindex a3fe1d31..8c0559f6 100644--- a/sources/VPhoneVMKit/Devices/VPhoneFrameProducer.swift+++ b/sources/VPhoneVMKit/Devices/VPhoneFrameProducer.swift@@ -42,8 +42,8 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendable// IOSurfaces and BGRA hardware paths. For 1280 width: 1280*4 = 5120// (already 16-aligned).let stride = ((width * 4) + 15) & ~15- self.bytesPerRow = stride- self.startedAt = ProcessInfo.processInfo.systemUptime+ bytesPerRow = stride+ startedAt = ProcessInfo.processInfo.systemUptime}func nextFrame() -> VPhoneCameraFrame? {@@ -53,8 +53,8 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendablevar bytes = [UInt8](repeating: 0, count: pixelCount)// Vertical gradient. Hue rolls with time.- let hueOffset = elapsed * 0.4 // turns per second- for y in 0..<height {+ let hueOffset = elapsed * 0.4 // turns per second+ for y in 0 ..< height {let v = Double(y) / Double(height)// Simple HSV → RGB on hue, full sat/val.let h = (v + hueOffset).truncatingRemainder(dividingBy: 1.0)@@ -66,11 +66,11 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendablelet rowStart = y * bytesPerRowvar idx = rowStart// BGRA order on little-endian Apple platforms.- for _ in 0..<width {- bytes[idx + 0] = bB // B- bytes[idx + 1] = gB // G- bytes[idx + 2] = rB // R- bytes[idx + 3] = 255 // A+ for _ in 0 ..< width {+ bytes[idx + 0] = bB // B+ bytes[idx + 1] = gB // G+ bytes[idx + 2] = rB // R+ bytes[idx + 3] = 255 // Aidx += 4}}@@ -80,9 +80,9 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendablelet sqSize = 32let xPos = Int(elapsed * 200) % max(1, width - sqSize)let yPos = max(8, (height - sqSize) / 8)- for dy in 0..<sqSize {+ for dy in 0 ..< sqSize {let row = (yPos + dy) * bytesPerRow- for dx in 0..<sqSize {+ for dx in 0 ..< sqSize {let off = row + (xPos + dx) * 4bytes[off + 0] = 255bytes[off + 1] = 255@@ -97,7 +97,7 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendableheight: height,bytesPerRow: bytesPerRow,timestampNS: ts,- pixels: Data(bytes)+ pixels: Data(bytes),)}@@ -146,9 +146,9 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {self.url = urlself.width = widthself.height = height- self.bytesPerRow = ((width * 4) + 15) & ~15- self.asset = AVURLAsset(url: url)- self.ciContext = CIContext(options: [.useSoftwareRenderer: false])+ bytesPerRow = ((width * 4) + 15) & ~15+ asset = AVURLAsset(url: url)+ ciContext = CIContext(options: [.useSoftwareRenderer: false])try restartReader()}@@ -158,7 +158,8 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {domain: "VPhoneVideoFileProducer",code: 1,userInfo: [NSLocalizedDescriptionKey:- "\(url.lastPathComponent): no video track"])+ "\(url.lastPathComponent): no video track"],+ )}let r = try AVAssetReader(asset: asset)let output = AVAssetReaderTrackOutput(@@ -166,7 +167,8 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {outputSettings: [kCVPixelBufferPixelFormatTypeKey as String:Int(kCVPixelFormatType_32BGRA),- ])+ ],+ )output.alwaysCopiesSampleData = falser.add(output)guard r.startReading() else {@@ -174,10 +176,11 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {domain: "VPhoneVideoFileProducer",code: 2,userInfo: [NSLocalizedDescriptionKey:- "AVAssetReader.startReading failed: \(r.error?.localizedDescription ?? "?")"])+ "AVAssetReader.startReading failed: \(r.error?.localizedDescription ?? "?")"],+ )}- self.reader = r- self.readerOutput = output+ reader = r+ readerOutput = output}func nextFrame() -> VPhoneCameraFrame? {@@ -200,7 +203,8 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {// BGRA — copy the planar bytes directly without going through Core// Image. Saves the GPU render.if srcWidth == width, srcHeight == height,- CVPixelBufferGetPixelFormatType(pb) == kCVPixelFormatType_32BGRA {+ CVPixelBufferGetPixelFormatType(pb) == kCVPixelFormatType_32BGRA+ {CVPixelBufferLockBaseAddress(pb, .readOnly)defer { CVPixelBufferUnlockBaseAddress(pb, .readOnly) }let srcBPR = CVPixelBufferGetBytesPerRow(pb)@@ -208,7 +212,7 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {var out = Data(count: bytesPerRow * height)out.withUnsafeMutableBytes { dst inlet dstBase = dst.baseAddress!- for y in 0..<height {+ for y in 0 ..< height {let dstRow = dstBase.advanced(by: y * bytesPerRow)let srcRow = base.advanced(by: y * srcBPR)let copyLen = min(srcBPR, bytesPerRow)@@ -220,7 +224,7 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {height: height,bytesPerRow: bytesPerRow,timestampNS: UInt64(ProcessInfo.processInfo.systemUptime * 1e9),- pixels: out+ pixels: out,)}@@ -230,7 +234,8 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {let scaleX = CGFloat(width) / CGFloat(srcWidth)let scaleY = CGFloat(height) / CGFloat(srcHeight)let scaled = srcImage.transformed(- by: CGAffineTransform(scaleX: scaleX, y: scaleY))+ by: CGAffineTransform(scaleX: scaleX, y: scaleY),+ )var out = Data(count: bytesPerRow * height)out.withUnsafeMutableBytes { dst in@@ -241,7 +246,7 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {rowBytes: bytesPerRow,bounds: CGRect(x: 0, y: 0, width: width, height: height),format: .BGRA8,- colorSpace: CGColorSpaceCreateDeviceRGB()+ colorSpace: CGColorSpaceCreateDeviceRGB(),)}return VPhoneCameraFrame(@@ -249,7 +254,7 @@ final class VPhoneVideoFileProducer: VPhoneFrameProducer, @unchecked Sendable {height: height,bytesPerRow: bytesPerRow,timestampNS: UInt64(ProcessInfo.processInfo.systemUptime * 1e9),- pixels: out+ pixels: out,)}}diff --git a/sources/VPhoneVMKit/Devices/VPhoneLocationProvider.swift b/sources/VPhoneVMKit/Devices/VPhoneLocationProvider.swiftindex 5edcb174..5b58e2ad 100644--- a/sources/VPhoneVMKit/Devices/VPhoneLocationProvider.swift+++ b/sources/VPhoneVMKit/Devices/VPhoneLocationProvider.swift@@ -25,7 +25,7 @@ class VPhoneLocationProvider: NSObject {horizontalAccuracy: Double = 5,verticalAccuracy: Double = 8,speed: Double = 0,- course: Double = -1+ course: Double = -1,) {self.latitude = latitudeself.longitude = longitude@@ -101,7 +101,7 @@ class VPhoneLocationProvider: NSObject {horizontalAccuracy: 5,verticalAccuracy: 8,speed: 0,- course: -1+ course: -1,)print("[location] applied preset '\(name)' (\(latitude), \(longitude))")}@@ -111,7 +111,7 @@ class VPhoneLocationProvider: NSObject {name: String,points: [ReplayPoint],intervalSeconds: Double = 1.5,- loop: Bool = true+ loop: Bool = true,) {guard !points.isEmpty else {print("[location] replay '\(name)' ignored: no points")@@ -124,7 +124,7 @@ class VPhoneLocationProvider: NSObject {replayName = namelet sleepNanos = UInt64((max(intervalSeconds, 0.1) * 1_000_000_000).rounded())print(- "[location] starting replay '\(name)' (\(points.count) points, interval \(String(format: "%.1f", intervalSeconds))s, loop=\(loop))"+ "[location] starting replay '\(name)' (\(points.count) points, interval \(String(format: "%.1f", intervalSeconds))s, loop=\(loop))",)replayTask = Task { @MainActor [weak self] in@@ -144,7 +144,7 @@ class VPhoneLocationProvider: NSObject {horizontalAccuracy: point.horizontalAccuracy,verticalAccuracy: point.verticalAccuracy,speed: point.speed,- course: point.course+ course: point.course,)index += 1@@ -191,7 +191,7 @@ class VPhoneLocationProvider: NSObject {horizontalAccuracy: location.horizontalAccuracy,verticalAccuracy: location.verticalAccuracy,speed: location.speed,- course: location.course+ course: location.course,)}@@ -202,7 +202,7 @@ class VPhoneLocationProvider: NSObject {horizontalAccuracy: Double,verticalAccuracy: Double,speed: Double,- course: Double+ course: Double,) {let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)lastLocation = CLLocation(@@ -210,7 +210,7 @@ class VPhoneLocationProvider: NSObject {altitude: altitude,horizontalAccuracy: horizontalAccuracy,verticalAccuracy: verticalAccuracy,- timestamp: Date()+ timestamp: Date(),)guard control.isConnected else {@@ -225,7 +225,7 @@ class VPhoneLocationProvider: NSObject {horizontalAccuracy: horizontalAccuracy,verticalAccuracy: verticalAccuracy,speed: speed,- course: course+ course: course,)}}@@ -244,7 +244,7 @@ private class LocationDelegateProxy: NSObject, CLLocationManagerDelegate {guard let location = locations.last else { return }let c = location.coordinateprint(- "[location] got location: \(String(format: "%.6f,%.6f", c.latitude, c.longitude)) (+/-\(String(format: "%.0f", location.horizontalAccuracy))m)"+ "[location] got location: \(String(format: "%.6f,%.6f", c.latitude, c.longitude)) (+/-\(String(format: "%.0f", location.horizontalAccuracy))m)",)handler(location)}@@ -252,7 +252,9 @@ private class LocationDelegateProxy: NSObject, CLLocationManagerDelegate {func locationManager(_: CLLocationManager, didFailWithError error: any Error) {let clErr = (error as NSError).code// kCLErrorLocationUnknown (0) = transient, just waiting for fix- if clErr == 0 { return }+ if clErr == 0 {+ return+ }print("[location] CLLocationManager error: \(error.localizedDescription) (code \(clErr))")}diff --git a/sources/VPhoneVMKit/Devices/VPhoneScreenRecorder.swift b/sources/VPhoneVMKit/Devices/VPhoneScreenRecorder.swiftindex 0365a249..20179d76 100644--- a/sources/VPhoneVMKit/Devices/VPhoneScreenRecorder.swift+++ b/sources/VPhoneVMKit/Devices/VPhoneScreenRecorder.swift@@ -1,7 +1,7 @@import AppKit-import ImageIOimport AVFoundationimport CoreVideo+import ImageIOimport ObjectiveC.runtimeimport Virtualization@@ -71,7 +71,7 @@ class VPhoneScreenRecorder {]let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input,- sourcePixelBufferAttributes: bufferAttrs+ sourcePixelBufferAttributes: bufferAttrs,)writer.add(input)@@ -94,7 +94,7 @@ class VPhoneScreenRecorder {}print(- "[record] started - \(url.lastPathComponent) (\(width)x\(height), source: private VZGraphicsDisplay screenshots)"+ "[record] started - \(url.lastPathComponent) (\(width)x\(height), source: private VZGraphicsDisplay screenshots)",)}@@ -153,7 +153,7 @@ class VPhoneScreenRecorder {url as CFURL,utType as CFString,1,- nil+ nil,) else {throw CaptureError.encodingFailed}@@ -179,7 +179,7 @@ class VPhoneScreenRecorder {private func captureGraphicsDisplayFrame(_ graphicsDisplay: VZGraphicsDisplay,- adaptor: AVAssetWriterInputPixelBufferAdaptor+ adaptor: AVAssetWriterInputPixelBufferAdaptor,) {guard !screenshotInFlight else { return }@@ -233,7 +233,7 @@ class VPhoneScreenRecorder {bytesPerRow: CVPixelBufferGetBytesPerRow(pb),space: CGColorSpaceCreateDeviceRGB(),bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue- | CGBitmapInfo.byteOrder32Little.rawValue+ | CGBitmapInfo.byteOrder32Little.rawValue,) {ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: pbWidth, height: pbHeight))}@@ -256,7 +256,7 @@ class VPhoneScreenRecorder {private func takeGraphicsScreenshot(from graphicsDisplay: VZGraphicsDisplay,- completion: @escaping (CGImage?) -> Void+ completion: @escaping (CGImage?) -> Void,) {let selector = NSSelectorFromString("_takeScreenshotWithCompletionHandler:")guard graphicsDisplay.responds(to: selector),diff --git a/sources/VPhoneVMKit/Devices/VPhoneTouchIDMonitor.swift b/sources/VPhoneVMKit/Devices/VPhoneTouchIDMonitor.swiftindex df11e04f..9a51a665 100644--- a/sources/VPhoneVMKit/Devices/VPhoneTouchIDMonitor.swift+++ b/sources/VPhoneVMKit/Devices/VPhoneTouchIDMonitor.swift@@ -21,14 +21,22 @@ private final class VPhoneBiometricDelegate: NSObject {/// First param: non-zero = finger pressed, 0 = finger released (or context ID on some versions).@objc func touchIDButtonPressed(_ pressed: Int, client: AnyObject?) {print("[touchid-bk] touchIDButtonPressed: %ld (client: %@)", pressed, client.debugDescription)- if pressed != 0 { onFingerDown?() } else { onFingerUp?() }+ if pressed != 0 {+ onFingerDown?()+ } else {+ onFingerUp?()+ }}/// Fired by BKPresenceDetectOperation when finger presence changes./// Second param is BOOL-encoded: non-zero = finger on sensor, 0 = finger off.- @objc func operation(_ operation: AnyObject, presenceStateChanged state: Int) {+ @objc func operation(_: AnyObject, presenceStateChanged state: Int) {print("[touchid-bk] presenceStateChanged: %ld", state)- if state != 0 { onFingerDown?() } else { onFingerUp?() }+ if state != 0 {+ onFingerDown?()+ } else {+ onFingerUp?()+ }}/// Called by BiometricKit singleton on finger presence change.@@ -47,18 +55,18 @@ private final class VPhoneBiometricDelegate: NSObject {@objc func statusMessage(_ status: UInt, client: AnyObject?) {print("[touchid-bk] statusMessage: %lu (client: %@)", status, client.debugDescription)switch status {- case 1: onFingerDown?()- case 0: onFingerUp?()+ case 1: onFingerDown?()+ case 0: onFingerUp?()default: break}}/// 3-arg variant of statusMessage seen on BKDevice (some OS versions).- @objc func statusMessage(_ status: UInt, details: AnyObject?, client: AnyObject?) {+ @objc func statusMessage(_ status: UInt, details _: AnyObject?, client _: AnyObject?) {print("[touchid-bk] statusMessage:details: %lu", status)switch status {- case 1: onFingerDown?()- case 0: onFingerUp?()+ case 1: onFingerDown?()+ case 0: onFingerUp?()default: break}}@@ -80,13 +88,13 @@ private final class VPhoneBiometricDelegate: NSObject {// MARK: - Debug: catch unexpected messages in dev builds#if DEBUG- override func responds(to aSelector: Selector!) -> Bool {- let result = super.responds(to: aSelector)- if !result {- print("[touchid-bk] delegate asked about unknown selector: %@", NSStringFromSelector(aSelector))+ override func responds(to aSelector: Selector!) -> Bool {+ let result = super.responds(to: aSelector)+ if !result {+ print("[touchid-bk] delegate asked about unknown selector: %@", NSStringFromSelector(aSelector))+ }+ return result}- return result- }#endif}@@ -115,8 +123,8 @@ final class VPhoneTouchIDMonitor {}// BiometricKit objects, retained as AnyObject via Dynamic- private var bkManager: AnyObject? // BiometricKit singleton- private var bkDelegate: VPhoneBiometricDelegate? // strong ref so it lives as long as the session+ private var bkManager: AnyObject? // BiometricKit singleton+ private var bkDelegate: VPhoneBiometricDelegate? // strong ref so it lives as long as the sessionprivate var reconnectTimer: DispatchWorkItem?// Tap detection state — all MainActor-isolated@@ -137,7 +145,9 @@ final class VPhoneTouchIDMonitor {func start(control: VPhoneControl, window: NSWindow) {self.control = controlself.window = window- if isEnabled { connectBiometricKit() }+ if isEnabled {+ connectBiometricKit()+ }}func stop() {@@ -239,9 +249,9 @@ final class VPhoneTouchIDMonitor {// and transitions us back to the finger-up state.fingerLiftedTimer?.cancel()let liftTimer = DispatchWorkItem { [weak self] in- guard let self, self.fingerIsDown else { return }- self.fingerIsDown = false- self.fingerLiftedTimer = nil+ guard let self, fingerIsDown else { return }+ fingerIsDown = false+ fingerLiftedTimer = nil}fingerLiftedTimer = liftTimerDispatchQueue.main.asyncAfter(deadline: .now() + fingerLiftDebounce, execute: liftTimer)@@ -274,10 +284,10 @@ final class VPhoneTouchIDMonitor {doubleTapTimer?.cancel()let timer = DispatchWorkItem { [weak self] inguard let self else { return }- self.tapCount = 0- self.doubleTapTimer = nil+ tapCount = 0+ doubleTapTimer = nilguard let control = self.control,- self.window?.isKeyWindow == true,+ window?.isKeyWindow == true,control.isConnected else { return }control.sendHIDPress(page: 0x0C, usage: 0x40)print("[touchid] Home sent")diff --git a/sources/VPhoneVMKit/Guest/VPhoneControl.swift b/sources/VPhoneVMKit/Guest/VPhoneControl.swiftindex 2c6e4ed6..c05f6a70 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControl.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControl.swift@@ -41,6 +41,7 @@ class VPhoneControl {else { return false }return major < 26}+/// Path to the signed vphoned binary. When set, enables auto-update.var guestBinaryURL: URL?@@ -56,7 +57,7 @@ class VPhoneControl {private var connectionAttemptToken: UInt64 = 0private var reconnectWorkItem: DispatchWorkItem?init() {}-+// MARK: - Pending Requests/// Callback for a pending request. Called on the read-loop queue.@@ -69,7 +70,7 @@ class VPhoneControl {private nonisolated func addPending(id: String,- handler: @escaping (Result<([String: Any], Data?), any Error>) -> Void+ handler: @escaping (Result<([String: Any], Data?), any Error>) -> Void,) {pendingLock.lock()pendingRequests[id] = PendingRequest(handler: handler)@@ -125,7 +126,7 @@ class VPhoneControl {guestBinaryData = dataguestBinaryHash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()print(- "[control] vphoned binary: \(url.lastPathComponent) (\(data.count) bytes, \(guestBinaryHash!.prefix(12))...)"+ "[control] vphoned binary: \(url.lastPathComponent) (\(data.count) bytes, \(guestBinaryHash!.prefix(12))...)",)}@@ -197,7 +198,7 @@ class VPhoneControl {guard self.isCurrentAttempt(attemptToken, fd: fd) else { return }guard type == "hello", version == Self.protocolVersion else {print(- "[control] handshake: version mismatch (guest v\(version), host v\(Self.protocolVersion))"+ "[control] handshake: version mismatch (guest v\(version), host v\(Self.protocolVersion))",)self.disconnect(ifCurrentAttempt: attemptToken)return@@ -280,14 +281,16 @@ class VPhoneControl {"page": page,"usage": usage,]- if let down { msg["down"] = down }+ if let down {+ msg["down"] = down+ }guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else {print("[control] send failed (not connected)")return}let suffix = down.map { $0 ? " down" : " up" } ?? ""print(- "[control] hid page=0x\(String(page, radix: 16)) usage=0x\(String(usage, radix: 16))\(suffix)"+ "[control] hid page=0x\(String(page, radix: 16)) usage=0x\(String(usage, radix: 16))\(suffix)",)}@@ -434,7 +437,7 @@ class VPhoneControl {return try await installIPAWithBuiltInInstaller(localURL: localURL)} catch let ControlError.guestError(message) where message == "unknown type: ipa_install" {throw ControlError.guestError(- "Guest vphoned does not support ipa_install yet. Reconnect or reboot the guest so the updated daemon can take over."+ "Guest vphoned does not support ipa_install yet. Reconnect or reboot the guest so the updated daemon can take over.",)}}@@ -497,7 +500,7 @@ class VPhoneControl {types: types,hasImage: hasImage,changeCount: changeCount,- imageData: data+ imageData: data,)}@@ -556,7 +559,7 @@ class VPhoneControl {horizontalAccuracy: Double,verticalAccuracy: Double,speed: Double,- course: Double+ course: Double,) {nextRequestId += 1let msg: [String: Any] = [@@ -586,7 +589,9 @@ class VPhoneControl {"t": "location_stop","id": String(nextRequestId, radix: 16),]- if let fd = connection?.fileDescriptor { writeMessage(fd: fd, dict: msg) }+ if let fd = connection?.fileDescriptor {+ writeMessage(fd: fd, dict: msg)+ }}// MARK: - Disconnect & Reconnect@@ -674,7 +679,7 @@ class VPhoneControl {buf.deallocate()DispatchQueue.main.async {pending.handler(- .failure(ControlError.protocolError("failed to read clipboard image data"))+ .failure(ControlError.protocolError("failed to read clipboard image data")),)}}@@ -693,7 +698,9 @@ class VPhoneControl {switch type {case "ok":let detail = msg["msg"] as? String ?? ""- if !detail.isEmpty { print("[vphoned] ok: \(detail)") }+ if !detail.isEmpty {+ print("[vphoned] ok: \(detail)")+ }case "pong":print("[vphoned] pong")case "version":@@ -827,7 +834,9 @@ class VPhoneControl {var offset = 0while offset < count {let n = Darwin.read(fd, buf + offset, count - offset)- if n <= 0 { return false }+ if n <= 0 {+ return false+ }offset += n}return true@@ -837,7 +846,9 @@ class VPhoneControl {var offset = 0while offset < count {let n = Darwin.write(fd, buf + offset, count - offset)- if n <= 0 { return false }+ if n <= 0 {+ return false+ }offset += n}return truediff --git a/sources/VPhoneVMKit/Guest/VPhoneControlApps.swift b/sources/VPhoneVMKit/Guest/VPhoneControlApps.swiftindex ccfbb947..47e57e5a 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControlApps.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControlApps.swift@@ -26,14 +26,16 @@ extension VPhoneControl {type: app["type"] as? String ?? "",state: app["state"] as? String ?? "",pid: app["pid"] as? Int ?? 0,- path: app["path"] as? String ?? ""+ path: app["path"] as? String ?? "",)}}func appLaunch(bundleId: String, url: String? = nil) async throws -> Int {var req: [String: Any] = ["t": "app_launch", "bundle_id": bundleId]- if let url { req["url"] = url }+ if let url {+ req["url"] = url+ }let (resp, _) = try await sendRequest(req)return resp["pid"] as? Int ?? 0}@@ -47,7 +49,7 @@ extension VPhoneControl {return (bundleId: resp["bundle_id"] as? String ?? "",name: resp["name"] as? String ?? "",- pid: resp["pid"] as? Int ?? 0+ pid: resp["pid"] as? Int ?? 0,)}}diff --git a/sources/VPhoneVMKit/Guest/VPhoneControlKeychain.swift b/sources/VPhoneVMKit/Guest/VPhoneControlKeychain.swiftindex b3cec996..12efafc0 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControlKeychain.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControlKeychain.swift@@ -21,7 +21,7 @@ extension VPhoneControl {func addKeychainItem(account: String = "vphone-test",service: String = "vphone",- password: String = "testpass123"+ password: String = "testpass123",) async throws {let req: [String: Any] = ["t": "keychain_add", "account": account, "service": service, "password": password,diff --git a/sources/VPhoneVMKit/Guest/VPhoneControlSystem.swift b/sources/VPhoneVMKit/Guest/VPhoneControlSystem.swiftindex d0b06e93..22f7fd69 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControlSystem.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControlSystem.swift@@ -16,14 +16,18 @@ extension VPhoneControl {func settingsGet(domain: String, key: String? = nil) async throws -> Any? {var req: [String: Any] = ["t": "settings_get", "domain": domain]- if let key { req["key"] = key }+ if let key {+ req["key"] = key+ }let (resp, _) = try await sendRequest(req)return resp["value"]}func settingsSet(domain: String, key: String, value: Any, type: String? = nil) async throws {var req: [String: Any] = ["t": "settings_set", "domain": domain, "key": key, "value": value]- if let type { req["type"] = type }+ if let type {+ req["type"] = type+ }_ = try await sendRequest(req)}diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserView.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserView.swiftindex 789afc00..8fc01717 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserView.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserView.swift@@ -17,8 +17,8 @@ struct VPhoneAppBrowserView: View {description: Text(model.searchText.isEmpty? "No apps are installed on the guest."- : "No apps match your search."- )+ : "No apps match your search.",+ ),)} else {appTable@@ -35,8 +35,12 @@ struct VPhoneAppBrowserView: View {"Error",isPresented: .init(get: { model.error != nil },- set: { if !$0 { model.error = nil } }- )+ set: {+ if !$0 {+ model.error = nil+ }+ },+ ),) {Button("OK") { model.error = nil }} message: {@@ -110,7 +114,7 @@ struct VPhoneAppBrowserView: View {.padding(.vertical, 1).background(app.type == "system"- ? Color.blue.opacity(0.15) : Color.green.opacity(0.15)+ ? Color.blue.opacity(0.15) : Color.green.opacity(0.15),).cornerRadius(3)}diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppWindowController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppWindowController.swiftindex eaa8514b..066a1356 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppWindowController.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppWindowController.swift@@ -22,7 +22,7 @@ class VPhoneAppWindowController {contentRect: NSRect(x: 0, y: 0, width: 650, height: 500),styleMask: [.titled, .closable, .resizable, .miniaturizable],backing: .buffered,- defer: false+ defer: false,)window.title = "Apps"window.subtitle = "vphone"@@ -42,7 +42,7 @@ class VPhoneAppWindowController {NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,object: window,- queue: .main+ queue: .main,) { [weak self] _ inTask { @MainActor inself?.window = nildiff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserModel.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserModel.swiftindex 319525ca..c552e215 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserModel.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserModel.swift@@ -98,8 +98,13 @@ class VPhoneFileBrowserModel {navigate(to: path)}- var canGoBack: Bool { !pathHistory.isEmpty }- var canGoForward: Bool { !forwardHistory.isEmpty }+ var canGoBack: Bool {+ !pathHistory.isEmpty+ }++ var canGoForward: Bool {+ !forwardHistory.isEmpty+ }func openItem(_ file: VPhoneRemoteFile) {if file.isDirectoryLike {@@ -161,7 +166,9 @@ class VPhoneFileBrowserModel {} else {await downloadFile(remotePath: file.path, name: file.name, size: file.size, to: directory)}- if error != nil { break }+ if error != nil {+ break+ }}transferName = nil}@@ -207,10 +214,12 @@ class VPhoneFileBrowserModel {remotePath: child.path,name: child.name,size: child.size,- to: localDir+ to: localDir,)}- if error != nil { return }+ if error != nil {+ return+ }}}@@ -240,7 +249,9 @@ class VPhoneFileBrowserModel {transferName = nilawait refresh()// Set error after refresh so refresh() doesn't clear it before the alert fires.- if let e = uploadError { error = e }+ if let e = uploadError {+ error = e+ }}func createNewFolder(name: String) async {diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserView.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserView.swiftindex d7434687..1e57500d 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserView.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserView.swift@@ -33,8 +33,12 @@ struct VPhoneFileBrowserView: View {"Error",isPresented: .init(get: { model.error != nil },- set: { if !$0 { model.error = nil } }- )+ set: {+ if !$0 {+ model.error = nil+ }+ },+ ),) {Button("OK") { model.error = nil }} message: {diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileWindowController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileWindowController.swiftindex 5b4de047..09ed9620 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileWindowController.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileWindowController.swift@@ -23,7 +23,7 @@ class VPhoneFileWindowController {contentRect: NSRect(x: 0, y: 0, width: 700, height: 500),styleMask: [.titled, .closable, .resizable, .miniaturizable],backing: .buffered,- defer: false+ defer: false,)window.title = "Files"window.subtitle = "vphone"@@ -45,7 +45,7 @@ class VPhoneFileWindowController {NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,object: window,- queue: .main+ queue: .main,) { [weak self] _ inTask { @MainActor inself?.model?.closeQuickLook()diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserView.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserView.swiftindex 64ccf277..26894215 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserView.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserView.swift@@ -29,8 +29,12 @@ struct VPhoneKeychainBrowserView: View {"Error",isPresented: .init(get: { model.error != nil },- set: { if !$0 { model.error = nil } }- )+ set: {+ if !$0 {+ model.error = nil+ }+ },+ ),) {Button("OK") { model.error = nil }} message: {diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainItem.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainItem.swiftindex 5508102f..7e9c5461 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainItem.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainItem.swift@@ -38,7 +38,9 @@ struct VPhoneKeychainItem: Identifiable, Hashable {}var displayValue: String {- if value.isEmpty { return "-" }+ if value.isEmpty {+ return "-"+ }if valueEncoding == "base64" {return "[\(ByteCountFormatter.string(fromByteCount: Int64(valueSize), countStyle: .file)) binary]"}@@ -46,10 +48,18 @@ struct VPhoneKeychainItem: Identifiable, Hashable {}var displayName: String {- if !label.isEmpty { return label }- if !account.isEmpty { return account }- if !service.isEmpty { return service }- if !server.isEmpty { return server }+ if !label.isEmpty {+ return label+ }+ if !account.isEmpty {+ return account+ }+ if !service.isEmpty {+ return service+ }+ if !server.isEmpty {+ return server+ }return "(unnamed)"}diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainWindowController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainWindowController.swiftindex 15e2a4d8..ab29e435 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainWindowController.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainWindowController.swift@@ -22,7 +22,7 @@ class VPhoneKeychainWindowController {contentRect: NSRect(x: 0, y: 0, width: 900, height: 500),styleMask: [.titled, .closable, .resizable, .miniaturizable],backing: .buffered,- defer: false+ defer: false,)window.title = "Keychain"window.subtitle = "vphone"@@ -42,7 +42,7 @@ class VPhoneKeychainWindowController {NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,object: window,- queue: .main+ queue: .main,) { [weak self] _ inTask { @MainActor inself?.window = nildiff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneQuickLookController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneQuickLookController.swiftindex 61f4d251..0c365373 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneQuickLookController.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneQuickLookController.swift@@ -3,7 +3,6 @@ import AppKit@MainActorfinal class VPhoneQuickLookController: NSResponder, QLPreviewPanelDataSource {-private var tempDir: URL?private(set) var previewURL: URL?@@ -44,30 +43,32 @@ final class VPhoneQuickLookController: NSResponder, QLPreviewPanelDataSource {}// MARK: - QLPreviewPanelDataSource+// AppKit calls these on the main thread.- nonisolated func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int {+ nonisolated func numberOfPreviewItems(in _: QLPreviewPanel!) -> Int {MainActor.assumeIsolated { previewURL != nil ? 1 : 0 }}- nonisolated func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> any QLPreviewItem {+ nonisolated func previewPanel(_: QLPreviewPanel!, previewItemAt _: Int) -> any QLPreviewItem {MainActor.assumeIsolated { (previewURL ?? URL(fileURLWithPath: "/dev/null")) as NSURL }}// MARK: - QLPreviewPanelController+// AppKit calls these when walking the responder chain.- nonisolated override func acceptsPreviewPanelControl(_ panel: QLPreviewPanel!) -> Bool {+ override nonisolated func acceptsPreviewPanelControl(_: QLPreviewPanel!) -> Bool {// Called on main thread; synchronous return required.MainActor.assumeIsolated { previewURL != nil }}- nonisolated override func beginPreviewPanelControl(_ panel: QLPreviewPanel!) {+ override nonisolated func beginPreviewPanelControl(_: QLPreviewPanel!) {// `open()` already sets panel.dataSource synchronously before showing the panel.// Nothing to do here; the conformance method must exist for QLPreviewPanelController.}- nonisolated override func endPreviewPanelControl(_ panel: QLPreviewPanel!) {+ override nonisolated func endPreviewPanelControl(_: QLPreviewPanel!) {Task { @MainActor incleanupTempFiles()}diff --git a/sources/VPhoneVMKit/Interface/Browsers/VPhoneRemoteFile.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneRemoteFile.swiftindex fb5dfe10..00c520a4 100644--- a/sources/VPhoneVMKit/Interface/Browsers/VPhoneRemoteFile.swift+++ b/sources/VPhoneVMKit/Interface/Browsers/VPhoneRemoteFile.swift@@ -30,7 +30,9 @@ struct VPhoneRemoteFile: Identifiable, Hashable {}var displaySize: String {- if isDirectory || isSymbolicLink { return "-" }+ if isDirectory || isSymbolicLink {+ return "-"+ }return ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file)}diff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swiftindex bad29792..f2fcd7fa 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swift@@ -74,9 +74,9 @@ extension VPhoneMenuController {title: "Install App Package",message: VPhoneInstallPackage.successMessage(for: url.lastPathComponent,- detail: result+ detail: result,),- style: .informational+ style: .informational,)} catch {showAlert(title: "Install App Package", message: "\(error)", style: .warning)@@ -89,7 +89,7 @@ extension VPhoneMenuController {contentRect: NSRect(x: 0, y: 0, width: 420, height: 110),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = "Open URL"panel.center()diff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuBattery.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuBattery.swiftindex 863299b3..37f6acc4 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuBattery.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuBattery.swift@@ -64,7 +64,9 @@ extension VPhoneMenuController {@objc func setBatteryLevel(_ sender: NSMenuItem) {guard let menu = sender.menu else { return }for mi in menu.items {- if mi.isSeparatorItem { break }+ if mi.isSeparatorItem {+ break+ }mi.state = mi === sender ? .on : .off}let charge = Double(sender.tag)@@ -77,8 +79,12 @@ extension VPhoneMenuController {guard let menu = sender.menu else { return }var pastSeparator = falsefor mi in menu.items {- if mi.isSeparatorItem { pastSeparator = true; continue }- if pastSeparator { mi.state = mi === sender ? .on : .off }+ if mi.isSeparatorItem {+ pastSeparator = true; continue+ }+ if pastSeparator {+ mi.state = mi === sender ? .on : .off+ }}let charge = currentBatteryCharge(in: menu)vm?.setBattery(charge: charge, connectivity: sender.tag)@@ -144,7 +150,7 @@ extension VPhoneMenuController {Task {do {try await control.lowPowerMode(enabled: enabled)- syncBatteryFromHost() // refresh status label with updated LPM state+ syncBatteryFromHost() // refresh status label with updated LPM stateprint("[battery] sync LPM: \(enabled)")} catch {print("[battery] sync LPM failed: \(error)")@@ -189,7 +195,7 @@ extension VPhoneMenuController {lowPowerObserver = NotificationCenter.default.addObserver(forName: Notification.Name("NSProcessInfoPowerStateDidChangeNotification"),object: nil,- queue: .main+ queue: .main,) { [weak self] _ inTask { @MainActor in self?.syncLowPowerModeFromHost() }}@@ -214,8 +220,12 @@ extension VPhoneMenuController {private func currentBatteryCharge(in menu: NSMenu) -> Double {for mi in menu.items {- if mi.isSeparatorItem { break }- if mi.state == .on { return Double(mi.tag) }+ if mi.isSeparatorItem {+ break+ }+ if mi.state == .on {+ return Double(mi.tag)+ }}return 100.0}@@ -223,8 +233,12 @@ extension VPhoneMenuController {private func currentBatteryConnectivity(in menu: NSMenu) -> Int {var pastSeparator = falsefor mi in menu.items {- if mi.isSeparatorItem { pastSeparator = true; continue }- if pastSeparator, mi.state == .on { return mi.tag }+ if mi.isSeparatorItem {+ pastSeparator = true; continue+ }+ if pastSeparator, mi.state == .on {+ return mi.tag+ }}return 1}diff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuCamera.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuCamera.swiftindex e606081d..97481339 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuCamera.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuCamera.swift@@ -11,7 +11,7 @@ extension VPhoneMenuController {let status = NSMenuItem(title: "Camera server: disconnected",action: nil,- keyEquivalent: ""+ keyEquivalent: "",)status.isEnabled = falsecameraStatusItem = status@@ -26,14 +26,14 @@ extension VPhoneMenuController {let testPattern = makeItem("Source: Test Pattern",- action: #selector(setCameraSourceTestPattern)+ action: #selector(setCameraSourceTestPattern),)cameraSourceTestPatternItem = testPatternmenu.addItem(testPattern)let videoFile = makeItem("Source: Video File…",- action: #selector(setCameraSourceVideoFile)+ action: #selector(setCameraSourceVideoFile),)cameraSourceVideoFileItem = videoFilemenu.addItem(videoFile)@@ -42,7 +42,7 @@ extension VPhoneMenuController {let startStop = makeItem("Start Streaming",- action: #selector(toggleCameraStreaming)+ action: #selector(toggleCameraStreaming),)startStop.isEnabled = falsecameraStartStopItem = startStopdiff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuConnect.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuConnect.swiftindex 5cdca345..df92097c 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuConnect.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuConnect.swift@@ -99,14 +99,14 @@ extension VPhoneMenuController {showAlert(title: "Developer Mode",message: enabled ? "Developer Mode is enabled." : "Developer Mode is disabled.",- style: .informational+ style: .informational,)} catch {showAlert(title: "Developer Mode",message: "Unable to read Developer Mode status. Check that the guest agent is connected, "+ "then try again.",- style: .warning+ style: .warning,)}}@@ -121,7 +121,7 @@ extension VPhoneMenuController {showAlert(title: "Ping",message: "The guest did not respond. Check that the guest agent is connected, then try again.",- style: .warning+ style: .warning,)}}@@ -137,7 +137,7 @@ extension VPhoneMenuController {title: "Guest Version",message: "Unable to read the guest version. Check that the guest agent is connected, "+ "then try again.",- style: .warning+ style: .warning,)}}@@ -167,7 +167,7 @@ extension VPhoneMenuController {showAlert(title: "Clipboard",message: "Unable to read the guest clipboard. Try again.",- style: .warning+ style: .warning,)}}@@ -178,7 +178,7 @@ extension VPhoneMenuController {contentRect: NSRect(x: 0, y: 0, width: 420, height: 150),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = "Set Clipboard Text"panel.center()@@ -222,7 +222,7 @@ extension VPhoneMenuController {showAlert(title: "Clipboard",message: "Unable to set the guest clipboard. Try again.",- style: .warning+ style: .warning,)}}@@ -235,7 +235,7 @@ extension VPhoneMenuController {contentRect: NSRect(x: 0, y: 0, width: 420, height: 160),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = "Read Setting"panel.center()@@ -286,7 +286,7 @@ extension VPhoneMenuController {if let dict = value as? [String: Any] {let data = try JSONSerialization.data(withJSONObject: dict,- options: [.prettyPrinted, .sortedKeys]+ options: [.prettyPrinted, .sortedKeys],)display = String(data: data, encoding: .utf8) ?? "\(dict)"} else {@@ -296,13 +296,13 @@ extension VPhoneMenuController {showAlert(title: "Setting: \(domain)\(key.map { ".\($0)" } ?? "")",message: truncated,- style: .informational+ style: .informational,)} catch {showAlert(title: "Read Setting",message: "Unable to read that setting. Check the domain and key, then try again.",- style: .warning+ style: .warning,)}}@@ -313,7 +313,7 @@ extension VPhoneMenuController {contentRect: NSRect(x: 0, y: 0, width: 420, height: 240),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = "Write Setting"panel.center()@@ -391,18 +391,18 @@ extension VPhoneMenuController {domain: domain,key: key,value: value,- type: type.isEmpty ? nil : type+ type: type.isEmpty ? nil : type,)showAlert(title: "Write Setting",message: "Set \(domain).\(key) = \(rawValue)",- style: .informational+ style: .informational,)} catch {showAlert(title: "Write Setting",message: "Unable to write that setting. Check the domain, key and type, then try again.",- style: .warning+ style: .warning,)}}@@ -410,12 +410,12 @@ extension VPhoneMenuController {// MARK: - Alert- func showAlert(title: String, message: String, style: NSAlert.Style) {+ func showAlert(title: String, message: String, style _: NSAlert.Style) {let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 380, height: 120),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = titlepanel.center()diff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuController.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuController.swiftindex 113b94bd..09dc3c23 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuController.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuController.swift@@ -27,6 +27,7 @@ class VPhoneMenuController {var touchIDMonitor: VPhoneTouchIDMonitor? {didSet { touchIDMonitor?.isEnabled = touchIDMenuItem?.state == .on }}+var touchIDMenuItem: NSMenuItem?var locationProvider: VPhoneLocationProvider?var locationMenuItem: NSMenuItem?@@ -68,7 +69,7 @@ class VPhoneMenuController {let buildItem = NSMenuItem(title: "Build: \(VPhoneBuildInfo.commitHash)",action: nil,- keyEquivalent: ""+ keyEquivalent: "",)#elselet buildItem = NSMenuItem(title: "Build: unknown", action: nil, keyEquivalent: "")@@ -79,7 +80,7 @@ class VPhoneMenuController {appMenu.addItem(withTitle: "Quit vphone",action: #selector(NSApplication.terminate(_:)),- keyEquivalent: "q"+ keyEquivalent: "q",)appMenuItem.submenu = appMenumainMenu.addItem(appMenuItem)@@ -95,12 +96,12 @@ class VPhoneMenuController {windowMenu.addItem(withTitle: "Close",action: #selector(NSWindow.performClose(_:)),- keyEquivalent: "w"+ keyEquivalent: "w",)windowMenu.addItem(withTitle: "Minimize",action: #selector(NSWindow.performMiniaturize(_:)),- keyEquivalent: "m"+ keyEquivalent: "m",)windowMenuItem.submenu = windowMenumainMenu.addItem(windowMenuItem)diff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuLocation.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuLocation.swiftindex 9d03d2f1..96ac84bd 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuLocation.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuLocation.swift@@ -12,25 +12,25 @@ private let locationPresets: [LocationPreset] = [title: "Apple Park (Cupertino)",latitude: 37.334606,longitude: -122.009102,- altitude: 14+ altitude: 14,),LocationPreset(title: "SF Ferry Building",latitude: 37.795490,longitude: -122.393738,- altitude: 5+ altitude: 5,),LocationPreset(title: "Times Square (NYC)",latitude: 40.758000,longitude: -73.985500,- altitude: 12+ altitude: 12,),LocationPreset(title: "Shibuya Crossing (Tokyo)",latitude: 35.659500,longitude: 139.700500,- altitude: 38+ altitude: 38,),]@@ -122,7 +122,7 @@ extension VPhoneMenuController {name: preset.title,latitude: preset.latitude,longitude: preset.longitude,- altitude: preset.altitude+ altitude: preset.altitude,)refreshLocationReplayState(available: true)}@@ -134,7 +134,7 @@ extension VPhoneMenuController {name: locationReplayName,points: locationReplayPoints,intervalSeconds: 1.5,- loop: true+ loop: true,)refreshLocationReplayState(available: true)}diff --git a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuRecord.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuRecord.swiftindex 274b2caf..47164783 100644--- a/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuRecord.swift+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuRecord.swift@@ -30,7 +30,7 @@ extension VPhoneMenuController {showAlert(title: "Recording",message: "No VM window is open. Start a VM, then try again.",- style: .warning+ style: .warning,)return}@@ -49,7 +49,7 @@ extension VPhoneMenuController {showAlert(title: "Screenshot",message: "No VM window is open. Start a VM, then try again.",- style: .warning+ style: .warning,)return}@@ -70,7 +70,7 @@ extension VPhoneMenuController {showAlert(title: "Screenshot",message: "No VM window is open. Start a VM, then try again.",- style: .warning+ style: .warning,)return}@@ -95,7 +95,7 @@ extension VPhoneMenuController {contentRect: NSRect(x: 0, y: 0, width: 420, height: 110),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = "Recording"panel.center()@@ -122,8 +122,13 @@ extension VPhoneMenuController {// Use a custom approach: reveal button stops modal with code 100class RevealHelper: NSObject {var action: () -> Void- init(_ action: @escaping () -> Void) { self.action = action }- @objc func clicked() { action() }+ init(_ action: @escaping () -> Void) {+ self.action = action+ }++ @objc func clicked() {+ action()+ }}let helper = RevealHelper {NSApp.stopModal(withCode: NSApplication.ModalResponse(rawValue: 100))diff --git a/sources/VPhoneVMKit/Interface/VPhoneKeyHelper.swift b/sources/VPhoneVMKit/Interface/VPhoneKeyHelper.swiftindex fea18d4e..796dbce0 100644--- a/sources/VPhoneVMKit/Interface/VPhoneKeyHelper.swift+++ b/sources/VPhoneVMKit/Interface/VPhoneKeyHelper.swift@@ -25,19 +25,21 @@ class VPhoneKeyHelper {// MARK: - Connection Guardprivate func requireConnection() -> Bool {- if control.isConnected { return true }+ if control.isConnected {+ return true+ }let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 380, height: 110),styleMask: [.titled, .closable],backing: .buffered,- defer: false+ defer: false,)panel.title = "Guest Agent Not Connected"panel.center()let msg = NSTextField(- labelWithString: "The guest agent is not connected. Wait for it to connect, then try again."+ labelWithString: "The guest agent is not connected. Wait for it to connect, then try again.",)msg.frame = NSRect(x: 20, y: 50, width: 340, height: 44)msg.lineBreakMode = .byWordWrappingdiff --git a/sources/VPhoneVMKit/Interface/VPhoneWindowController.swift b/sources/VPhoneVMKit/Interface/VPhoneWindowController.swiftindex 1fd7da96..bb23b13d 100644--- a/sources/VPhoneVMKit/Interface/VPhoneWindowController.swift+++ b/sources/VPhoneVMKit/Interface/VPhoneWindowController.swift@@ -24,7 +24,7 @@ class VPhoneWindowController: NSObject, NSToolbarDelegate {screenScale: Double,keyHelper: VPhoneKeyHelper,control: VPhoneControl,- ecid: String?+ ecid: String?,) {self.control = controlself.ecid = ecid@@ -40,14 +40,14 @@ class VPhoneWindowController: NSObject, NSToolbarDelegate {let scale = CGFloat(screenScale)let windowSize = NSSize(width: CGFloat(screenWidth) / scale,- height: CGFloat(screenHeight) / scale+ height: CGFloat(screenHeight) / scale,)let window = NSWindow(contentRect: NSRect(origin: .zero, size: windowSize),styleMask: [.titled, .closable, .resizable, .miniaturizable],backing: .buffered,- defer: false+ defer: false,)window.isReleasedWhenClosed = false@@ -108,7 +108,7 @@ class VPhoneWindowController: NSObject, NSToolbarDelegate {nonisolated func toolbar(_: NSToolbar,itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier,- willBeInsertedIntoToolbar _: Bool+ willBeInsertedIntoToolbar _: Bool,) -> NSToolbarItem? {MainActor.assumeIsolated {if itemIdentifier == Self.homeItemID {@@ -117,7 +117,7 @@ class VPhoneWindowController: NSObject, NSToolbarDelegate {item.toolTip = "Home Button"item.image = NSImage(systemSymbolName: "circle.circle",- accessibilityDescription: "Home"+ accessibilityDescription: "Home",)item.target = selfitem.action = #selector(homePressed)diff --git a/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift b/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swiftindex c72798cd..e6162fb6 100644--- a/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift+++ b/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift@@ -68,7 +68,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {diskImage: manifest.diskImage,nvramStorage: manifest.nvramStorage,romImages: manifest.romImages,- sepStorage: manifest.sepStorage+ sepStorage: manifest.sepStorage,)try manifest.write(to: options.configURL)@@ -84,7 +84,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {print("[vphone] ECID: \(ecidHex!)")print("[vphone] Predicted UDID: \(identity.udid)")let outputURL = options.configURL.deletingLastPathComponent().appendingPathComponent(- "udid-prediction.txt"+ "udid-prediction.txt",)do {try Self.writeUDIDPrediction(identity: identity, to: outputURL)@@ -100,7 +100,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {let auxStorage = try VZMacAuxiliaryStorage(creatingStorageAt: options.nvramURL,hardwareModel: hwModel,- options: .allowOverwrite+ options: .allowOverwrite,)platform.auxiliaryStorage = auxStorageplatform.hardwareModel = hwModel@@ -112,7 +112,9 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {Dynamic(auxStorage)._setDataValue(bootArgsData, forNVRAMVariableNamed: "boot-args", error: nil).asBool ?? false- if ok { print("[vphone] NVRAM boot-args: \(bootArgs)") }+ if ok {+ print("[vphone] NVRAM boot-args: \(bootArgs)")+ }}// --- Boot loader with custom ROM ---@@ -128,7 +130,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {config.cpuCount = max(options.cpuCount, VZVirtualMachineConfiguration.minimumAllowedCPUCount)config.memorySize = max(options.memorySize,- VZVirtualMachineConfiguration.minimumAllowedMemorySize+ VZVirtualMachineConfiguration.minimumAllowedMemorySize,)// Display@@ -137,7 +139,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {VZMacGraphicsDisplayConfiguration(widthInPixels: options.screenWidth,heightInPixels: options.screenHeight,- pixelsPerInch: options.screenPPI+ pixelsPerInch: options.screenPPI,),]config.graphicsDevices = [gfx]@@ -174,7 +176,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {serialPort.attachment = VZFileHandleSerialPortAttachment(fileHandleForReading: inputPipe.fileHandleForReading,- fileHandleForWriting: outputPipe.fileHandleForWriting+ fileHandleForWriting: outputPipe.fileHandleForWriting,)// Forward host stdin -> VM serial input@@ -184,7 +186,9 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {var buf = [UInt8](repeating: 0, count: 4096)while true {let n = read(stdinFD, &buf, buf.count)- if n <= 0 { break }+ if n <= 0 {+ break+ }writeHandle.write(Data(buf[..<n]))}}@@ -194,12 +198,12 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {config.serialPorts = [serialPort]print("[vphone] PL011 serial port attached (interactive)")}-+if let obj1 = Dynamic._VZMacVideoToolboxDeviceConfiguration().asObject,let obj2 = Dynamic._VZMacNeuralEngineDeviceConfiguration().asObject,let obj3 = Dynamic._VZMacScalerAcceleratorDeviceConfiguration().asObject{- Dynamic(config)._setAcceleratorDevices([obj1,obj2,obj3])+ Dynamic(config)._setAcceleratorDevices([obj1, obj2, obj3])print("[vphone] Accelerator devices configured")}@@ -208,7 +212,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {Dynamic(config)._setMultiTouchDevices([obj])print("[vphone] USB touch screen configured")}-+let obj = VZVirtioEntropyDeviceConfiguration()config.entropyDevices = [obj]print("[vphone] Entropy device configured")@@ -272,7 +276,9 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {if let readHandle = serialOutputReadHandle {readHandle.readabilityHandler = { handle inlet data = handle.availableData- if data.isEmpty { return }+ if data.isEmpty {+ return+ }FileHandle.standardOutput.write(data)}}@@ -363,7 +369,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {nonisolated func virtualMachine(_: VZVirtualMachine,networkDevice _: VZNetworkDevice,- attachmentWasDisconnectedWithError error: Error+ attachmentWasDisconnectedWithError error: Error,) {print("[vphone] Network error: \(error)")}diff --git a/sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swift b/sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swiftindex 32d5be2f..046458e3 100644--- a/sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swift+++ b/sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swift@@ -53,13 +53,17 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {window?.makeFirstResponder(self)let localPoint = convert(event.locationInWindow, from: nil)currentTouchSwipeAim = hitTestEdge(at: localPoint)- if sendTouchEvent(phase: 0, localPoint: localPoint, timestamp: event.timestamp) { return }+ if sendTouchEvent(phase: 0, localPoint: localPoint, timestamp: event.timestamp) {+ return+ }super.mouseDown(with: event)}override func mouseDragged(with event: NSEvent) {let localPoint = convert(event.locationInWindow, from: nil)- if sendTouchEvent(phase: 1, localPoint: localPoint, timestamp: event.timestamp) { return }+ if sendTouchEvent(phase: 1, localPoint: localPoint, timestamp: event.timestamp) {+ return+ }super.mouseDragged(with: event)}@@ -119,9 +123,9 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {title: "Install App Package",message: VPhoneInstallPackage.successMessage(for: url.lastPathComponent,- detail: result+ detail: result,),- style: .informational+ style: .informational,)} catch {showAlert(title: "Install App Package", message: "\(error)", style: .warning)@@ -136,7 +140,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {]guard let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self],- options: options+ options: options,) as? [URL] else {return nil}@@ -186,7 +190,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {context: nil,eventNumber: 0,clickCount: type == .leftMouseUp ? 0 : 1,- pressure: type == .leftMouseUp ? 0.0 : 1.0+ pressure: type == .leftMouseUp ? 0.0 : 1.0,)}@@ -196,7 +200,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {pixelX: pixelX,pixelY: pixelY,screenWidth: screenWidth,- screenHeight: screenHeight+ screenHeight: screenHeight,)let windowPoint = convert(localPoint, to: nil)@@ -205,8 +209,8 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {}DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) { [weak self] inguard let self else { return }- if let upEvent = self.synthesizeMouseEvent(type: .leftMouseUp, at: windowPoint) {- self.mouseUp(with: upEvent)+ if let upEvent = synthesizeMouseEvent(type: .leftMouseUp, at: windowPoint) {+ mouseUp(with: upEvent)}}}@@ -219,13 +223,13 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {toY: Double,screenWidth: Int,screenHeight: Int,- durationMs: Int = 300+ durationMs: Int = 300,) {let startLocal = pixelToLocal(pixelX: fromX,pixelY: fromY,screenWidth: screenWidth,- screenHeight: screenHeight+ screenHeight: screenHeight,)let endLocal = pixelToLocal(pixelX: toX, pixelY: toY, screenWidth: screenWidth, screenHeight: screenHeight)let startWindow = convert(startLocal, to: nil)@@ -238,7 +242,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {mouseDown(with: downEvent)}- for i in 1...steps {+ for i in 1 ... steps {let t = Double(i) / Double(steps)let x = startWindow.x + (endWindow.x - startWindow.x) * tlet y = startWindow.y + (endWindow.y - startWindow.y) * t@@ -248,15 +252,15 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {if i < steps {DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] inguard let self else { return }- if let dragEvent = self.synthesizeMouseEvent(type: .leftMouseDragged, at: pt) {- self.mouseDragged(with: dragEvent)+ if let dragEvent = synthesizeMouseEvent(type: .leftMouseDragged, at: pt) {+ mouseDragged(with: dragEvent)}}} else {DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] inguard let self else { return }- if let upEvent = self.synthesizeMouseEvent(type: .leftMouseUp, at: pt) {- self.mouseUp(with: upEvent)+ if let upEvent = synthesizeMouseEvent(type: .leftMouseUp, at: pt) {+ mouseUp(with: upEvent)}}}@@ -287,7 +291,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {phase: phase,location: normalizedPoint,swipeAim: currentTouchSwipeAim,- timestamp: timestamp+ timestamp: timestamp,)guard let touchObj = touch.asObject else {diff --git a/sources/VPhoneVMKit/VPhoneAppDelegate.swift b/sources/VPhoneVMKit/VPhoneAppDelegate.swiftindex 5ae0cee4..075ec9be 100644--- a/sources/VPhoneVMKit/VPhoneAppDelegate.swift+++ b/sources/VPhoneVMKit/VPhoneAppDelegate.swift@@ -61,7 +61,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {print("CPU : \(options.cpuCount)")print("Memory : \(options.memorySize / 1024 / 1024) MB")print(- "Screen: \(options.screenWidth)x\(options.screenHeight) @ \(options.screenPPI) PPI (scale \(options.screenScale)x)"+ "Screen: \(options.screenWidth)x\(options.screenHeight) @ \(options.screenPPI) PPI (scale \(options.screenScale)x)",)if let kernelDebugPort = options.kernelDebugPort {print("Kernel debug stub : 127.0.0.1:\(kernelDebugPort)")@@ -108,7 +108,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {screenScale: options.screenScale,keyHelper: keyHelper,control: control,- ecid: vm.ecidHex+ ecid: vm.ecidHex,)windowController = wc@@ -161,7 +161,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {screenRecorder: recorder,control: control,screenWidth: options.screenWidth,- screenHeight: options.screenHeight+ screenHeight: options.screenHeight,)hostControl = hc@@ -235,7 +235,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {}guard caps.contains("ipa_install") else {print(- "[install] guest does not advertise ipa_install; reconnect or reboot the guest so the updated daemon can take over"+ "[install] guest does not advertise ipa_install; reconnect or reboot the guest so the updated daemon can take over",)return}diff --git a/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift b/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swiftindex e3f951ab..e89ed078 100644--- a/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift+++ b/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift@@ -1,9 +1,9 @@import Foundationimport VPhoneCore-// The half of VPhoneBootCLI that needs the Virtualization framework. The-// options themselves live in VPhoneCore so vphone-cli can parse and forward-// them without linking any of this.+/// The half of VPhoneBootCLI that needs the Virtualization framework. The+/// options themselves live in VPhoneCore so vphone-cli can parse and forward+/// them without linking any of this.extension VPhoneBootCLI {/// Resolve final options by merging manifest values.func resolveOptions() throws -> VPhoneVirtualMachine.Options {@@ -29,7 +29,7 @@ extension VPhoneBootCLI {screenHeight: manifest.screenConfig.height,screenPPI: manifest.screenConfig.pixelsPerInch,screenScale: manifest.screenConfig.scale,- kernelDebugPort: kernelDebugPort+ kernelDebugPort: kernelDebugPort,)}}diff --git a/sources/VPhoneVMKit/VPhoneHostControl.swift b/sources/VPhoneVMKit/VPhoneHostControl.swiftindex a6b1ba73..c2d1fb76 100644--- a/sources/VPhoneVMKit/VPhoneHostControl.swift+++ b/sources/VPhoneVMKit/VPhoneHostControl.swift@@ -57,7 +57,7 @@ class VPhoneHostControl {screenRecorder: VPhoneScreenRecorder,control: VPhoneControl,screenWidth: Int,- screenHeight: Int+ screenHeight: Int,) {self.captureView = captureViewself.screenRecorder = screenRecorder@@ -149,7 +149,7 @@ class VPhoneHostControl {bitsPerComponent: 8,bytesPerRow: dstW,space: gray,- bitmapInfo: CGImageAlphaInfo.none.rawValue+ bitmapInfo: CGImageAlphaInfo.none.rawValue,) else { return nil }// High contrast: bump brightness@@ -272,7 +272,7 @@ class VPhoneHostControl {pixelX: x,pixelY: y,screenWidth: controller.screenWidth,- screenHeight: controller.screenHeight+ screenHeight: controller.screenHeight,)result.ok = trueif wantScreen {@@ -308,7 +308,7 @@ class VPhoneHostControl {toY: y2,screenWidth: controller.screenWidth,screenHeight: controller.screenHeight,- durationMs: durationMs+ durationMs: durationMs,)result.ok = trueif wantScreen {@@ -402,7 +402,9 @@ class VPhoneHostControl {let n = read(fd, &buffer, buffer.count)guard n > 0 else { break }accumulated.append(contentsOf: buffer[..<n])- if accumulated.contains(0x0A) { break }+ if accumulated.contains(0x0A) {+ break+ }}if let nlRange = accumulated.firstIndex(of: 0x0A) {@@ -416,12 +418,18 @@ class VPhoneHostControl {ok: Bool,path: String? = nil,error: String? = nil,- image: String? = nil+ image: String? = nil,) {var dict: [String: Any] = ["ok": ok]- if let path { dict["path"] = path }- if let error { dict["error"] = error }- if let image { dict["image"] = image }+ if let path {+ dict["path"] = path+ }+ if let error {+ dict["error"] = error+ }+ if let image {+ dict["image"] = image+ }guard let data = try? JSONSerialization.data(withJSONObject: dict),var json = String(data: data, encoding: .utf8)@@ -433,7 +441,9 @@ class VPhoneHostControl {var offset = 0while remaining > 0 {let written = write(fd, ptr.advanced(by: offset), remaining)- if written <= 0 { break }+ if written <= 0 {+ break+ }offset += writtenremaining -= written}diff --git a/sources/vphone-archive/main.swift b/sources/vphone-archive/main.swiftindex 584b5452..877de2ce 100644--- a/sources/vphone-archive/main.swift+++ b/sources/vphone-archive/main.swift@@ -26,7 +26,7 @@ struct VPhoneArchiveCLI: ParsableCommand {Extract.self, Create.self, Decompress.self,List.self, Cat.self, Fingerprint.self,],- defaultSubcommand: Extract.self+ defaultSubcommand: Extract.self,)}@@ -35,7 +35,7 @@ struct VPhoneArchiveCLI: ParsableCommand {struct Extract: ParsableCommand {static let configuration = CommandConfiguration(commandName: "extract",- abstract: "Unpack an archive into a directory"+ abstract: "Unpack an archive into a directory",)@Option(name: [.customShort("f"), .long], help: "Archive to read",@@ -44,7 +44,7 @@ struct Extract: ParsableCommand {@Option(name: [.customShort("C"), .customLong("directory")],help: "Where to unpack it", transform: URL.init(fileURLWithPath:))- var destination: URL = URL(fileURLWithPath: ".")+ var destination: URL = .init(fileURLWithPath: ".")@Flag(name: [.customShort("p"), .customLong("preserve-permissions")],help: "Restore modes, and — as root — the archive's numeric uid/gid")@@ -74,9 +74,11 @@ struct Extract: ParsableCommand {let written = try VPhoneArchiveExtractor.extract(file, into: destination, options: options,- progress: verbose ? { print($0.currentPath) } : nil+ progress: verbose ? { print($0.currentPath) } : nil,)- if !verbose { print("extracted \(written) entries to \(destination.path)") }+ if !verbose {+ print("extracted \(written) entries to \(destination.path)")+ }}}@@ -85,7 +87,7 @@ struct Extract: ParsableCommand {struct Create: ParsableCommand {static let configuration = CommandConfiguration(commandName: "create",- abstract: "Pack a directory into an archive"+ abstract: "Pack a directory into an archive",)@Option(name: [.customShort("f"), .long], help: "Archive to write",@@ -94,7 +96,7 @@ struct Create: ParsableCommand {@Option(name: [.customShort("C"), .customLong("directory")],help: "Directory to pack", transform: URL.init(fileURLWithPath:))- var source: URL = URL(fileURLWithPath: ".")+ var source: URL = .init(fileURLWithPath: ".")@Option(help: "tar dialect: gnutar, pax or ustar")var format: String = "gnutar"@@ -115,10 +117,12 @@ struct Create: ParsableCommand {var verbose = falsefunc validate() throws {- if zstd, xz { throw ValidationError("choose one of --zstd or --xz") }+ if zstd, xz {+ throw ValidationError("choose one of --zstd or --xz")+ }guard VPhoneArchiveFormat(rawValue: format) != nil else {throw ValidationError(- "unknown format '\(format)' (gnutar, pax, ustar)"+ "unknown format '\(format)' (gnutar, pax, ustar)",)}}@@ -139,9 +143,11 @@ struct Create: ParsableCommand {let written = try VPhoneArchiveWriter.create(archive: file, from: source,format: tarFormat, compression: compression, excluding: exclude,- progress: verbose ? { print($0.currentPath) } : nil+ progress: verbose ? { print($0.currentPath) } : nil,)- if !verbose { print("packed \(written) entries into \(file.path)") }+ if !verbose {+ print("packed \(written) entries into \(file.path)")+ }}}@@ -154,7 +160,7 @@ struct Decompress: ParsableCommand {discussion: """What `zstd -d -f x.tar.zst -o x.tar` does. The result is still a tar;use `extract` to unpack it.- """+ """,)@Option(name: [.customShort("f"), .long], help: "File to decompress",@@ -175,7 +181,7 @@ struct Decompress: ParsableCommand {struct List: ParsableCommand {static let configuration = CommandConfiguration(- commandName: "list", abstract: "List an archive's members"+ commandName: "list", abstract: "List an archive's members",)@Option(name: [.customShort("f"), .long], help: "Archive to read",@@ -203,7 +209,7 @@ struct List: ParsableCommand {struct Cat: ParsableCommand {static let configuration = CommandConfiguration(commandName: "cat",- abstract: "Write one member to stdout without unpacking the archive"+ abstract: "Write one member to stdout without unpacking the archive",)@Option(name: [.customShort("f"), .long], help: "Archive to read",@@ -234,7 +240,7 @@ struct Fingerprint: ParsableCommand {With one path, writes JSON. With two, prints the differences and exitsnon-zero if there are any.- """+ """,)@Argument(help: "Tree to describe", transform: URL.init(fileURLWithPath:))@@ -254,16 +260,18 @@ struct Fingerprint: ParsableCommand {guard let other else {let encoder = JSONEncoder()encoder.outputFormatting = [.prettyPrinted, .sortedKeys]- print(String(decoding: try encoder.encode(first), as: UTF8.self))+ try print(String(decoding: encoder.encode(first), as: UTF8.self))return}let second = try VPhoneTreeFingerprint.capture(- other, includeContentHashes: !noContentHashes+ other, includeContentHashes: !noContentHashes,)let differences = first.differences(from: second)guard differences.isEmpty else {- for line in differences { print(line) }+ for line in differences {+ print(line)+ }print("\n\(differences.count) difference(s)")throw ExitCode(1)}diff --git a/sources/vphone-cli/VPhoneCFWDSCVerbsCLI.swift b/sources/vphone-cli/VPhoneCFWDSCVerbsCLI.swiftindex 491e3aed..32a15209 100644--- a/sources/vphone-cli/VPhoneCFWDSCVerbsCLI.swift+++ b/sources/vphone-cli/VPhoneCFWDSCVerbsCLI.swift@@ -87,12 +87,12 @@ struct VPhoneCFWPatchHVVMMDSCCommand: ParsableCommand {Runs while the SystemOS cryptex is mounted on the host, wrapped by`scripts/patch_hv_vmm_userland.sh dsc`.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@@ -103,7 +103,7 @@ struct VPhoneCFWPatchHVVMMDSCCommand: ParsableCommand {try DSCHVVMMPatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}@@ -132,19 +132,19 @@ struct VPhoneCFWPatchIOMFBSwapEndCommand: ParsableCommand {Already-correct is a no-op that still re-attests, so re-running over apatched cache is safe.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@Option(name: .customLong("target-size"),help: "Payload size the base kernel's userclient accepts (hex or decimal)",- transform: VPhoneCFWDSCVerbs.parseCInteger+ transform: VPhoneCFWDSCVerbs.parseCInteger,)var targetSize: UInt32 = DSCIOMFBSwapEndPatcher.defaultTargetSize@@ -156,7 +156,7 @@ struct VPhoneCFWPatchIOMFBSwapEndCommand: ParsableCommand {chunksDirectory: chunksDirectory,targetSize: targetSize,dryRun: dryRun,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}@@ -187,12 +187,12 @@ struct VPhoneCFWPatchIOMFBForceKernCommand: ParsableCommand {Pairs with the KernelJBPatchIomfbSwap kernel patches, which make theuserclient accept 27's native 0x6e0 SwapEnd struct. Modified pages arere-attested; an already-forced cache is a no-op.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@@ -203,7 +203,7 @@ struct VPhoneCFWPatchIOMFBForceKernCommand: ParsableCommand {try DSCIOMFBForceKernPatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}@@ -231,12 +231,12 @@ struct VPhoneCFWPatchDSCMaxSlideCommand: ParsableCommand {No re-attestation: maxSlide lives in the cache header, which is not oneof the cs_validate'd code pages.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@@ -250,7 +250,7 @@ struct VPhoneCFWPatchDSCMaxSlideCommand: ParsableCommand {try DSCMaxSlidePatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,- force: force+ force: force,)}}@@ -278,12 +278,12 @@ struct VPhoneCFWPatchLSDEmbeddedRegCommand: ParsableCommand {error — a LaunchServices rewrite has to stop the install rather than beguessed at, because the silent alternative boots a guest in which no appcan register.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@@ -294,7 +294,7 @@ struct VPhoneCFWPatchLSDEmbeddedRegCommand: ParsableCommand {try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}@@ -320,12 +320,12 @@ struct VPhoneCFWPatchXPCLWCRCommand: ParsableCommand {Self-gating: the symbol is absent on pre-iOS-27 libxpc, which isreported and exits 0, and a cache already carrying the patched shape isa no-op. A cache with the symbol but neither shape is an error.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@@ -336,7 +336,7 @@ struct VPhoneCFWPatchXPCLWCRCommand: ParsableCommand {try DSCXPCLWCRPatcher.apply(directory: chunksDirectory,dryRun: dryRun,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}@@ -360,12 +360,12 @@ struct VPhoneCFWPatchLockdownModeCommand: ParsableCommand {Self-gating: pre-iOS-27 userlands have no such symbol, which is reportedand exits 0, and a cache already patched is a no-op.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@@ -376,7 +376,7 @@ struct VPhoneCFWPatchLockdownModeCommand: ParsableCommand {try DSCLockdownModePatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}@@ -404,18 +404,18 @@ struct VPhoneCFWPatchCameraDSCCommand: ParsableCommand {`pacibsp` nor the replacement already in place, which is otherwiserefused rather than overwritten blind. Modified pages are re-attested;an already-patched cache is a no-op.- """+ """,)@Argument(help: "The guest's /System/Library/Caches/com.apple.dyld directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var chunksDirectory: URL@Argument(help: "The dyld_shared_cache_arm64e file symbols resolve against (not a chunk)",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var dscHeader: URL@@ -431,7 +431,7 @@ struct VPhoneCFWPatchCameraDSCCommand: ParsableCommand {symbolCacheURL: dscHeader,dryRun: dryRun,force: force,- log: VPhoneCFWDSCVerbs.stdout+ log: VPhoneCFWDSCVerbs.stdout,)}}diff --git a/sources/vphone-cli/VPhoneCFWInstaller.swift b/sources/vphone-cli/VPhoneCFWInstaller.swiftindex 95484830..21617652 100644--- a/sources/vphone-cli/VPhoneCFWInstaller.swift+++ b/sources/vphone-cli/VPhoneCFWInstaller.swift@@ -12,8 +12,13 @@ struct VPhoneCFWInstaller {let resources: VPhoneResourceslet forceDSCMaxSlide: Bool- private var executable: URL { VPhoneResources.runningExecutable() }- private var fm: FileManager { .default }+ private var executable: URL {+ VPhoneResources.runningExecutable()+ }++ private var fm: FileManager {+ .default+ }static func elevate(bundle: URL,@@ -21,14 +26,16 @@ struct VPhoneCFWInstaller {forceDSCMaxSlide: Bool,rootPopup: Bool,environment: [String: String] = [:],- verbose: Bool = true+ verbose: Bool = true,) throws -> Int32 {let exe = VPhoneResources.runningExecutable()var args = ["cfw", "install-root", bundle.path, "--resources", resources.base.path]- if forceDSCMaxSlide { args.append("--force-dsc-maxslide") }+ if forceDSCMaxSlide {+ args.append("--force-dsc-maxslide")+ }if geteuid() == 0 {try VPhoneCFWInstaller(bundle: bundle, resources: resources,- forceDSCMaxSlide: forceDSCMaxSlide).run()+ forceDSCMaxSlide: forceDSCMaxSlide).run()return 0}if rootPopup {@@ -36,15 +43,17 @@ struct VPhoneCFWInstaller {env["SUDO_USER"] = NSUserName()env["SUDO_UID"] = String(getuid())return try VPhoneProcessRunner.runWithAdminPrivileges(- exe, args, env: env, echo: verbose+ exe, args, env: env, echo: verbose,)}var env = ProcessInfo.processInfo.environmentenv.merge(environment) { _, new in new }args.insert(contentsOf: ["-E", exe.path], at: 0)- if env["SUDO_ASKPASS"] != nil { args.insert("-A", at: 0) }+ if env["SUDO_ASKPASS"] != nil {+ args.insert("-A", at: 0)+ }return try VPhoneProcessRunner.runForeground(- URL(fileURLWithPath: "/usr/bin/sudo"), args, env: env, echo: verbose+ URL(fileURLWithPath: "/usr/bin/sudo"), args, env: env, echo: verbose,)}@@ -55,7 +64,7 @@ struct VPhoneCFWInstaller {throw ValidationError("Disk.img is missing: \(diskImage.path)")}let busy = try VPhoneProcessRunner.runCapturing(- URL(fileURLWithPath: "/usr/sbin/lsof"), [diskImage.path]+ URL(fileURLWithPath: "/usr/sbin/lsof"), [diskImage.path],)guard busy.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {throw ValidationError("VM disk is in use; stop the VM before installing CFW")@@ -67,20 +76,23 @@ struct VPhoneCFWInstaller {}let attached = try tool("/usr/bin/hdiutil", [- "attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", diskImage.path+ "attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", diskImage.path,])guard let baseDisk = attached.split(whereSeparator: \.isNewline).first?.split(whereSeparator: \.isWhitespace).first.map(String.init),- baseDisk.hasPrefix("/dev/disk") else {+ baseDisk.hasPrefix("/dev/disk")+ else {throw ValidationError("hdiutil attached no disk device")}defer { _ = try? tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true) }let info = try tool("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"], quiet: true)guard let plist = try PropertyListSerialization.propertyList(- from: Data(info.utf8), format: nil) as? [String: Any],- let container = plist["APFSContainerReference"] as? String,- container.hasPrefix("disk") else {+ from: Data(info.utf8), format: nil,+ ) as? [String: Any],+ let container = plist["APFSContainerReference"] as? String,+ container.hasPrefix("disk")+ else {throw ValidationError("Could not resolve the APFS container for \(baseDisk)")}let work = bundle.appendingPathComponent(".cfw-native-\(UUID().uuidString)")@@ -104,7 +116,9 @@ struct VPhoneCFWInstaller {try VPhoneAPFSSnapshot.rename(imageAt: diskImage)if let uid = ProcessInfo.processInfo.environment["SUDO_UID"].flatMap(UInt32.init) {let signed = bundle.appendingPathComponent(".vphoned.signed")- if fm.fileExists(atPath: signed.path) { _ = chown(signed.path, uid, gid_t.max) }+ if fm.fileExists(atPath: signed.path) {+ _ = chown(signed.path, uid, gid_t.max)+ }}print("[+] JB system install complete; vphoned is installed, no package bootstrap was staged")}@@ -112,7 +126,9 @@ struct VPhoneCFWInstaller {private func installMounted(system: URL, data: URL, work: URL) throws {guard let restore = try fm.contentsOfDirectory(at: bundle, includingPropertiesForKeys: [.isDirectoryKey]).first(where: { $0.lastPathComponent.contains("Restore") &&- fm.fileExists(atPath: $0.appendingPathComponent("iPhone-BuildManifest.plist").path) }) else {+ fm.fileExists(atPath: $0.appendingPathComponent("iPhone-BuildManifest.plist").path)+ })+ else {throw ValidationError("No prepared iPhone restore tree exists in \(bundle.path)")}try installCryptexes(restore: restore, system: system, work: work)@@ -130,10 +146,10 @@ struct VPhoneCFWInstaller {try patch("patch-dsc-maxslide", [dsc.path, "--force"])}try patchMachO(system: system, work: work,- path: "usr/libexec/seputil", verb: "patch-seputil", identifier: "com.apple.seputil")+ path: "usr/libexec/seputil", verb: "patch-seputil", identifier: "com.apple.seputil")if version.hasPrefix("27.") {try patchMachO(system: system, work: work,- path: "usr/libexec/diskimagesiod", verb: "patch-diskimagesiod", preserveEntitlements: true)+ path: "usr/libexec/diskimagesiod", verb: "patch-diskimagesiod", preserveEntitlements: true)}try renameGigalocker(data: data)let gpuSource = VPhonePCCGPUDriver.stagedBundle(in: restore)@@ -141,58 +157,68 @@ struct VPhoneCFWInstaller {throw ValidationError("PCC GPU driver is missing: \(gpuSource.path). Re-run fw prepare with the PCC IPSW.")}let gpu = system.appendingPathComponent(- "System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")- if fm.fileExists(atPath: gpu.path) { try fm.removeItem(at: gpu) }+ "System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle",+ )+ if fm.fileExists(atPath: gpu.path) {+ try fm.removeItem(at: gpu)+ }try fm.copyItem(at: gpuSource, to: gpu)try tool("/usr/sbin/chown", ["-R", "0:0", gpu.path])for file in [gpu, gpu.appendingPathComponent("AppleParavirtGPUMetalIOGPUFamily"),gpu.appendingPathComponent("libAppleParavirtCompilerPluginIOGPUFamily.dylib"),- gpu.appendingPathComponent("_CodeSignature")] {+ gpu.appendingPathComponent("_CodeSignature")]+ {try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: file.path)}for file in [gpu.appendingPathComponent("Info.plist"),- gpu.appendingPathComponent("_CodeSignature/CodeResources")] {+ gpu.appendingPathComponent("_CodeSignature/CodeResources")]+ {try fm.setAttributes([.posixPermissions: NSNumber(value: 0o644)], ofItemAtPath: file.path)}try patchMachO(system: system, work: work,- path: "usr/libexec/launchd_cache_loader", verb: "patch-launchd-cache-loader",- identifier: "com.apple.launchd_cache_loader")+ path: "usr/libexec/launchd_cache_loader", verb: "patch-launchd-cache-loader",+ identifier: "com.apple.launchd_cache_loader")try patchMachO(system: system, work: work,- path: "usr/libexec/mobileactivationd", verb: "patch-mobileactivationd")+ path: "usr/libexec/mobileactivationd", verb: "patch-mobileactivationd")try installVphoned(system: system, work: work)try patchMachO(system: system, work: work,- path: "sbin/launchd", verb: "patch-launchd-jetsam", preserveEntitlements: true)+ path: "sbin/launchd", verb: "patch-launchd-jetsam", preserveEntitlements: true)try patchDebugserver(system: system, work: work)- if version.hasPrefix("27.") { try patchCampo(system: system, work: work) }+ if version.hasPrefix("27.") {+ try patchCampo(system: system, work: work)+ }}private func installCryptexes(restore: URL, system: URL, work: URL) throws {let os = system.appendingPathComponent("System/Cryptexes/OS")let app = system.appendingPathComponent("System/Cryptexes/App")if !((try? fm.contentsOfDirectory(atPath: os.path))?.isEmpty == false &&- (try? fm.contentsOfDirectory(atPath: app.path))?.isEmpty == false) {+ (try? fm.contentsOfDirectory(atPath: app.path))?.isEmpty == false)+ {let paths = try CFWDaemons.cryptexPaths(- buildManifest: restore.appendingPathComponent("iPhone-BuildManifest.plist"))+ buildManifest: restore.appendingPathComponent("iPhone-BuildManifest.plist"),+ )let encrypted = restore.appendingPathComponent(paths.systemOS)let plain = work.appendingPathComponent("SystemOS.dmg")let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: encrypted) }try tool("/usr/bin/aea", ["decrypt", "-i", encrypted.path,- "-o", plain.path, "-key-value", key], quiet: true)+ "-o", plain.path, "-key-value", key], quiet: true)let osMount = work.appendingPathComponent("mnt-os")let appMount = work.appendingPathComponent("mnt-app")try fm.createDirectory(at: osMount, withIntermediateDirectories: true)try fm.createDirectory(at: appMount, withIntermediateDirectories: true)try tool("/usr/bin/hdiutil", ["attach", "-mountpoint", osMount.path,- plain.path, "-nobrowse", "-owners", "off"], quiet: true)+ plain.path, "-nobrowse", "-owners", "off"], quiet: true)defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", osMount.path], quiet: true) }try tool("/usr/bin/hdiutil", ["attach", "-mountpoint", appMount.path,- restore.appendingPathComponent(paths.appOS).path, "-nobrowse", "-owners", "off"], quiet: true)+ restore.appendingPathComponent(paths.appOS).path, "-nobrowse", "-owners", "off"], quiet: true)defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", appMount.path], quiet: true) }for (source, destination) in [(osMount, os), (appMount, app)] {// The restored rootfs has dangling Cryptex symlinks. fileExists// follows those links and reports false until Preboot is populated.if fm.fileExists(atPath: destination.path) ||- (try? fm.destinationOfSymbolicLink(atPath: destination.path)) != nil {+ (try? fm.destinationOfSymbolicLink(atPath: destination.path)) != nil+ {try fm.removeItem(at: destination)}try fm.createDirectory(at: destination, withIntermediateDirectories: true)@@ -200,9 +226,9 @@ struct VPhoneCFWInstaller {}}try symlink("../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",- at: system.appendingPathComponent("System/Library/Caches/com.apple.dyld"))+ at: system.appendingPathComponent("System/Library/Caches/com.apple.dyld"))try symlink("../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",- at: system.appendingPathComponent("System/DriverKit/System/Library/dyld"))+ at: system.appendingPathComponent("System/DriverKit/System/Library/dyld"))}private func installVphoned(system: URL, work: URL) throws {@@ -212,17 +238,22 @@ struct VPhoneCFWInstaller {let entitlementsURL = resources.scriptsDir.appendingPathComponent("vphoned/entitlements.plist")let entitlements = try Data(contentsOf: entitlementsURL, options: .mappedIfSafe)try VPhoneSigner.sign(fileAt: staged,- options: .init(entitlements: entitlements, mergesExisting: true))+ options: .init(entitlements: entitlements, mergesExisting: true))try replace(staged, at: system.appendingPathComponent("usr/bin/vphoned"), mode: 0o755)let signed = bundle.appendingPathComponent(".vphoned.signed")- if fm.fileExists(atPath: signed.path) { try fm.removeItem(at: signed) }+ if fm.fileExists(atPath: signed.path) {+ try fm.removeItem(at: signed)+ }try fm.copyItem(at: staged, to: signed)let daemon = resources.scriptsDir.appendingPathComponent("vphoned/vphoned.plist")try replace(daemon, at: system.appendingPathComponent(- "System/Library/LaunchDaemons/vphoned.plist"), mode: 0o644)+ "System/Library/LaunchDaemons/vphoned.plist",+ ), mode: 0o644)let launchd = system.appendingPathComponent("System/Library/xpc/launchd.plist")let backup = launchd.appendingPathExtension("bak")- if !fm.fileExists(atPath: backup.path) { try fm.copyItem(at: launchd, to: backup) }+ if !fm.fileExists(atPath: backup.path) {+ try fm.copyItem(at: launchd, to: backup)+ }let temp = work.appendingPathComponent("launchd.plist")try fm.copyItem(at: backup, to: temp)try CFWDaemons.injectDaemon(into: temp, name: "vphoned", from: daemon)@@ -230,19 +261,24 @@ struct VPhoneCFWInstaller {}private func patchMachO(system: URL, work: URL, path: String, verb: String,- identifier: String? = nil, preserveEntitlements: Bool = false) throws {+ identifier: String? = nil, preserveEntitlements: Bool = false) throws+ {let target = system.appendingPathComponent(path)let backup = target.appendingPathExtension("bak")- if !fm.fileExists(atPath: backup.path) { try fm.copyItem(at: target, to: backup) }+ if !fm.fileExists(atPath: backup.path) {+ try fm.copyItem(at: target, to: backup)+ }let staged = work.appendingPathComponent(target.lastPathComponent)- if fm.fileExists(atPath: staged.path) { try fm.removeItem(at: staged) }+ if fm.fileExists(atPath: staged.path) {+ try fm.removeItem(at: staged)+ }try fm.copyItem(at: backup, to: staged)let entitlements = preserveEntitlements? try VPhoneSigner.entitlements(ofFileAt: backup).first(where: { !$0.isEmpty }): niltry patch(verb, [staged.path])try VPhoneSigner.sign(fileAt: staged,- options: .init(identifier: identifier, entitlements: entitlements, mergesExisting: true))+ options: .init(identifier: identifier, entitlements: entitlements, mergesExisting: true))try replace(staged, at: target, mode: 0o755)}@@ -254,19 +290,21 @@ struct VPhoneCFWInstaller {}guard let source = try VPhoneSigner.entitlements(ofFileAt: target).first(where: { !$0.isEmpty }),- var plist = try PropertyListSerialization.propertyList(- from: source, format: nil) as? [String: Any] else {+ var plist = try PropertyListSerialization.propertyList(+ from: source, format: nil,+ ) as? [String: Any]+ else {print("[!] debugserver has no readable entitlements; patch skipped")return}plist.removeValue(forKey: "seatbelt-profiles")plist["task_for_pid-allow"] = truelet data = try PropertyListSerialization.data(fromPropertyList: plist,- format: .xml, options: 0)+ format: .xml, options: 0)let staged = work.appendingPathComponent("debugserver")try fm.copyItem(at: target, to: staged)try VPhoneSigner.sign(fileAt: staged,- options: .init(entitlements: data, mergesExisting: true))+ options: .init(entitlements: data, mergesExisting: true))try replace(staged, at: target, mode: 0o755)}@@ -277,7 +315,8 @@ struct VPhoneCFWInstaller {return}guard let source = try VPhoneSigner.entitlements(ofFileAt: target)- .first(where: { !$0.isEmpty }) else {+ .first(where: { !$0.isEmpty })+ else {print("[!] Campo has no readable entitlements; patch skipped")return}@@ -287,7 +326,7 @@ struct VPhoneCFWInstaller {let staged = work.appendingPathComponent("Campo")try fm.copyItem(at: target, to: staged)try VPhoneSigner.sign(fileAt: staged,- options: .init(entitlements: try Data(contentsOf: ent, options: .mappedIfSafe), mergesExisting: true))+ options: .init(entitlements: Data(contentsOf: ent, options: .mappedIfSafe), mergesExisting: true))try replace(staged, at: target, mode: 0o755)}@@ -295,18 +334,25 @@ struct VPhoneCFWInstaller {let files = try fm.contentsOfDirectory(at: data, includingPropertiesForKeys: nil)for source in files where source.pathExtension == "gl" {let destination = data.appendingPathComponent("AA.gl")- if source == destination { continue }- if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }+ if source == destination {+ continue+ }+ if fm.fileExists(atPath: destination.path) {+ try fm.removeItem(at: destination)+ }try fm.moveItem(at: source, to: destination)}}private func productVersion(system: URL) throws -> String {let plist = system.appendingPathComponent(- "System/Library/CoreServices/SystemVersion.plist")+ "System/Library/CoreServices/SystemVersion.plist",+ )guard let value = try PropertyListSerialization.propertyList(- from: Data(contentsOf: plist, options: .mappedIfSafe), format: nil) as? [String: Any],- let version = value["ProductVersion"] as? String else {+ from: Data(contentsOf: plist, options: .mappedIfSafe), format: nil,+ ) as? [String: Any],+ let version = value["ProductVersion"] as? String+ else {throw ValidationError("SystemVersion.plist has no ProductVersion")}return version@@ -333,8 +379,12 @@ struct VPhoneCFWInstaller {private func tool(_ path: String, _ arguments: [String], quiet: Bool = false) throws -> String {let result = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: path), arguments)if !quiet {- if !result.stdout.isEmpty { print(result.stdout, terminator: "") }- if !result.stderr.isEmpty { fputs(result.stderr, stderr) }+ if !result.stdout.isEmpty {+ print(result.stdout, terminator: "")+ }+ if !result.stderr.isEmpty {+ fputs(result.stderr, stderr)+ }}guard result.succeeded else {throw ValidationError("\(URL(fileURLWithPath: path).lastPathComponent) failed (\(result.exitCode)): \(result.stderr)")@@ -346,7 +396,7 @@ struct VPhoneCFWInstaller {struct VPhoneCFWInstallRootCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "install-root", abstract: "Internal privileged JB disk install",- shouldDisplay: false+ shouldDisplay: false,)@Argument(help: "VM bundle path") var bundle: String@@ -357,7 +407,7 @@ struct VPhoneCFWInstallRootCommand: ParsableCommand {try VPhoneCFWInstaller(bundle: URL(fileURLWithPath: bundle),resources: VPhoneResources(base: URL(fileURLWithPath: resources)),- forceDSCMaxSlide: forceDSCMaxSlide+ forceDSCMaxSlide: forceDSCMaxSlide,).run()}}diff --git a/sources/vphone-cli/VPhoneCFWMachOVerbsCLI.swift b/sources/vphone-cli/VPhoneCFWMachOVerbsCLI.swiftindex 4d611d57..73a11fc5 100644--- a/sources/vphone-cli/VPhoneCFWMachOVerbsCLI.swift+++ b/sources/vphone-cli/VPhoneCFWMachOVerbsCLI.swift@@ -83,7 +83,7 @@ private func requireUntruncatedMachO(at url: URL) throws {throw PatcherError.invalidFormat("\(url.lastPathComponent): truncated Mach-O — the header claims "+ "\(numberOfCommands) load command(s) in \(sizeOfCommands) bytes, "- + "and the file is \(fileSize) bytes"+ + "and the file is \(fileSize) bytes",)}}@@ -108,7 +108,7 @@ struct VPhoneCFWPatchSeputilCommand: ParsableCommand {Idempotent: a binary already reading "/AA.gl" is reported and leftalone. The Python exits 1 there, because the string it searches for isno longer in the file.- """+ """,)@Argument(help: "Path to the seputil Mach-O, patched in place", transform: URL.init(fileURLWithPath:))@@ -143,7 +143,7 @@ struct VPhoneCFWPatchLaunchdCacheLoaderCommand: ParsableCommand {Idempotent: a gate already holding a NOP is reported and left alone.The Python exits 1 there — a NOP is not one of the branches it looksfor.- """+ """,)@Argument(help: "Path to the launchd_cache_loader Mach-O, patched in place", transform: URL.init(fileURLWithPath:))@@ -156,7 +156,7 @@ struct VPhoneCFWPatchLaunchdCacheLoaderCommand: ParsableCommand {try CFWCacheLoaderPatcher.patch(fileAt: binary,reattestsCodeSignature: false,- log: machOVerbLog+ log: machOVerbLog,)}}@@ -180,7 +180,7 @@ struct VPhoneCFWPatchMobileactivationdCommand: ParsableCommand {Idempotent: a getter already reading `mov x0, #1 ; ret` is reported andthe file is not rewritten, so even its mtime survives.- """+ """,)@Argument(help: "Path to the mobileactivationd Mach-O, patched in place", transform: URL.init(fileURLWithPath:))@@ -213,7 +213,7 @@ struct VPhoneCFWPatchLaunchdJetsamCommand: ParsableCommand {sitting ahead of every conditional one means a previous run did thework, and nothing is written. Neither implementation would otherwisepick the same site twice.- """+ """,)@Argument(help: "Path to the /sbin/launchd Mach-O, patched in place", transform: URL.init(fileURLWithPath:))@@ -249,7 +249,7 @@ struct VPhoneCFWPatchWatchdogdCommand: ParsableCommand {unparseable binary or a missing anchor is fatal. Unlike the other fiveverbs this one re-attests the pages it dirties, because its Python doestoo.- """+ """,)@Argument(help: "Path to the watchdogd Mach-O, patched in place", transform: URL.init(fileURLWithPath:))@@ -281,7 +281,7 @@ struct VPhoneCFWPatchDiskimagesiodCommand: ParsableCommand {Idempotent: a prologue already reading `mov x0, #1 ; ret` is reportedand the file is left byte-for-byte alone.- """+ """,)@Argument(help: "Path to the diskimagesiod Mach-O, patched in place", transform: URL.init(fileURLWithPath:))diff --git a/sources/vphone-cli/VPhoneCFWPatchCLI.swift b/sources/vphone-cli/VPhoneCFWPatchCLI.swiftindex 8399b9a6..659322e0 100644--- a/sources/vphone-cli/VPhoneCFWPatchCLI.swift+++ b/sources/vphone-cli/VPhoneCFWPatchCLI.swift@@ -30,7 +30,7 @@ struct VPhoneCFWCryptexPathsCommand: ParsableCommand {in a real manifest has none at all. The first identity carrying bothwins. When no identity carries both, this exits non-zero rather thanprinting a blank line the caller would read as a path.- """+ """,)@Argument(help: "Path to BuildManifest.plist", transform: URL.init(fileURLWithPath:))@@ -63,7 +63,7 @@ struct VPhoneCFWInjectDaemonsCommand: ParsableCommand {dropbear's ProgramArguments are rewritten on the way through to point atthe /var/dropbear host keys — see `patch-dropbear-plist`.- """+ """,)@Argument(help: "Path to the guest's /System/Library/xpc/launchd.plist", transform: URL.init(fileURLWithPath:))@@ -98,7 +98,7 @@ struct VPhoneCFWInjectDaemonCommand: ParsableCommand {installs as `com.vphone.jb-setup.plist`. It is the key launchd looks thedaemon up by, so it has to match the file written into/System/Library/LaunchDaemons.- """+ """,)@Argument(help: "Path to the guest's /System/Library/xpc/launchd.plist", transform: URL.init(fileURLWithPath:))@@ -129,7 +129,7 @@ struct VPhoneCFWPatchDropbearPlistCommand: ParsableCommand {An empty or missing ProgramArguments list is left alone: there isnothing there to point at a key.- """+ """,)@Argument(help: "Path to dropbear.plist", transform: URL.init(fileURLWithPath:))@@ -155,7 +155,7 @@ struct VPhoneCFWInjectDylibCommand: ParsableCommand {place boots instead of panicking, and the existing LC_CODE_SIGNATURE andits blob are removed — exactly what insert_dylib does by default. Thebinary is not left unsigned: the install re-signs it on the next line.- """+ """,)@Argument(help: "The Mach-O to patch, in place", transform: URL.init(fileURLWithPath:))@@ -194,7 +194,7 @@ struct VPhoneCFWPatchBuildVersionCommand: ParsableCommand {Idempotent — a re-run on an already-patched plist reports and exitswithout rewriting.- """+ """,)@Argument(help: "Path to SystemVersion.plist", transform: URL.init(fileURLWithPath:))@@ -230,7 +230,7 @@ struct VPhoneCFWPatchCampoEntitlementsCommand: ParsableCommand {downgrade.The file is written back as XML, which is what the signer expects.- """+ """,)@Argument(help: "Path to the dumped entitlements plist", transform: URL.init(fileURLWithPath:))@@ -260,7 +260,7 @@ struct VPhoneCFWPatchPostRestoreDTCommand: ParsableCommand {Takes a devicetree.img4 (preferred) or a bare .im4p. An encryptedpayload is refused, not guessed at.- """+ """,)@Argument(help: "Path to devicetree.img4 or devicetree.im4p", transform: URL.init(fileURLWithPath:))diff --git a/sources/vphone-cli/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swiftindex 38d03426..d3612abd 100644--- a/sources/vphone-cli/VPhoneCLI.swift+++ b/sources/vphone-cli/VPhoneCLI.swift@@ -14,7 +14,7 @@ struct VPhoneCLI: ParsableCommand {VPhoneHostCommand.self,VPhoneSignCommand.self, VPhoneDumpEntitlementsCommand.self,],- defaultSubcommand: VPhoneBootCLI.self+ defaultSubcommand: VPhoneBootCLI.self,)}@@ -24,34 +24,34 @@ struct VPhoneCLI: ParsableCommand {struct PatchFirmwareCLI: ParsableCommand {static let configuration = CommandConfiguration(commandName: "patch-firmware",- abstract: "Patch boot-chain firmware in a VM directory using the Swift pipeline"+ abstract: "Patch boot-chain firmware in a VM directory using the Swift pipeline",)@Option(name: [.customLong("vm-directory"), .customShort("d")],help: "Path to the VM directory that contains the *Restore* folder.",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var vmDirectory: URL@Option(name: .customLong("records-out"),- help: "Optional path to write emitted PatchRecord JSON."+ help: "Optional path to write emitted PatchRecord JSON.",)var recordsOut: String?@Flag(name: [.customShort("q"), .customLong("quiet")], help: "Suppress per-component progress output.")var quiet: Bool = false-+@Flag(name: .customLong("force-exc-guard"),- help: "Force-enable the EXC_GUARD (Mach port guard) disable patch on regular/jb/exp, even on bases where it isn't required to boot. Use if a third-party app's crash-reporting/RASP SDK trips a fatal GUARD_TYPE_MACH_PORT violation on launch. Always on for iOS 18 bases regardless of this flag."+ help: "Force-enable the EXC_GUARD (Mach port guard) disable patch on regular/jb/exp, even on bases where it isn't required to boot. Use if a third-party app's crash-reporting/RASP SDK trips a fatal GUARD_TYPE_MACH_PORT violation on launch. Always on for iOS 18 bases regardless of this flag.",)var forceExcGuard: Bool = false@Flag(name: .customLong("frida"),- help: "Opt in to Frida Stalker kernel relaxations (existing-thread follow + repeated VM_PROT_COPY). jb/exp only."+ help: "Opt in to Frida Stalker kernel relaxations (existing-thread follow + repeated VM_PROT_COPY). jb/exp only.",)var frida: Bool = false@@ -62,7 +62,7 @@ struct PatchFirmwareCLI: ParsableCommand {verbose: !quiet,noBinpack: true,forceExcGuard: forceExcGuard,- enableFrida: frida+ enableFrida: frida,)let records = try pipeline.patchAll()@@ -82,17 +82,17 @@ struct PatchComponentCLI: ParsableCommand {enum ComponentOption: String, CaseIterable, ExpressibleByArgument {case txmcase kernelBase = "kernel-base"- // TESTING/DIAGNOSTICS ONLY — not part of any production flow.- // Production JB patching runs through `patch-firmware`; this- // standalone option exists so `tests/test_jb_kernel_patches.sh` can run the- // JB kernel layer over a single kernelcache and dump records via --records-out.- // (txm / kernel-base, by contrast, are standalone single-component patchers.)+ /// TESTING/DIAGNOSTICS ONLY — not part of any production flow.+ /// Production JB patching runs through `patch-firmware`; this+ /// standalone option exists so `tests/test_jb_kernel_patches.sh` can run the+ /// JB kernel layer over a single kernelcache and dump records via --records-out.+ /// (txm / kernel-base, by contrast, are standalone single-component patchers.)case kernelJB = "kernel-jb"}static let configuration = CommandConfiguration(commandName: "patch-component",- abstract: "Patch a single firmware component payload and write the patched raw bytes"+ abstract: "Patch a single firmware component payload and write the patched raw bytes",)@Option(help: "Component to patch.")@@ -101,14 +101,14 @@ struct PatchComponentCLI: ParsableCommand {@Option(name: [.customShort("i"), .customLong("input")],help: "Path to the source firmware file (IM4P or raw).",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var input: URL@Option(name: [.customShort("o"), .customLong("output")],help: "Path to write the patched raw payload bytes.",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var output: URL@@ -117,19 +117,19 @@ struct PatchComponentCLI: ParsableCommand {@Option(name: .customLong("records-out"),- help: "Optional path to write emitted PatchRecord JSON (for fast-loop validation)."+ help: "Optional path to write emitted PatchRecord JSON (for fast-loop validation).",)var recordsOut: String?@Option(name: .customLong("target-os"),- help: "kernel-jb only: base iOS version the kernel will run under (e.g. 27.0). Gates the iOS-27-only JB patches exactly as the pipeline does. Omit to apply the full set (dev/test default)."+ help: "kernel-jb only: base iOS version the kernel will run under (e.g. 27.0). Gates the iOS-27-only JB patches exactly as the pipeline does. Omit to apply the full set (dev/test default).",)var targetOS: String?@Flag(name: .customLong("frida"),- help: "kernel-jb only: opt in to the Frida Stalker kernel relaxations."+ help: "kernel-jb only: opt in to the Frida Stalker kernel relaxations.",)var frida: Bool = falsediff --git a/sources/vphone-cli/VPhoneCreateOptions.swift b/sources/vphone-cli/VPhoneCreateOptions.swiftindex 5ff555d6..ade93d5c 100644--- a/sources/vphone-cli/VPhoneCreateOptions.swift+++ b/sources/vphone-cli/VPhoneCreateOptions.swift@@ -2,8 +2,8 @@ import VPhoneCore// MARK: - Create Options-extension VPhoneCreateOrchestrator {- public struct Options {+public extension VPhoneCreateOrchestrator {+ struct Options {public var name: Stringpublic var iphoneSource: String?public var cloudosSource: String?@@ -29,7 +29,7 @@ extension VPhoneCreateOrchestrator {memoryMB: UInt64 = 8192,diskSizeGB: UInt64 = 64,verbosity: VPhoneVerbosity = .quiet,- keepArtifacts: Bool = false+ keepArtifacts: Bool = false,) {self.name = nameself.iphoneSource = iphoneSourcediff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swiftindex 259d5764..9069e7c0 100644--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift@@ -56,7 +56,9 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {}extension VPhoneCreateError: LocalizedError {- var errorDescription: String? { description }+ var errorDescription: String? {+ description+ }}// MARK: - VPhoneCreateOrchestrator@@ -83,7 +85,7 @@ public struct VPhoneCreateOrchestrator {public init(library: VPhoneLibrary,resources: VPhoneResources,- launcher: VPhoneGuestLaunchPlanner+ launcher: VPhoneGuestLaunchPlanner,) {self.library = libraryself.resources = resources@@ -114,7 +116,11 @@ public struct VPhoneCreateOrchestrator {// never sees it.var sudoEnvExtras: [String: String] = [:]var askpassScript: URL?- defer { if let askpassScript { try? FileManager.default.removeItem(at: askpassScript) } }+ defer {+ if let askpassScript {+ try? FileManager.default.removeItem(at: askpassScript)+ }+ }if let password = options.sudoPassword, !password.isEmpty {let script = try makeSudoAskpassScript()askpassScript = script@@ -124,13 +130,15 @@ public struct VPhoneCreateOrchestrator {} else {print("[!] --sudo-password failed validation; will still try at CFW-install time")}- } else if !options.rootPopup && isatty(FileHandle.standardInput.fileDescriptor) == 0 {+ } else if !options.rootPopup, isatty(FileHandle.standardInput.fileDescriptor) == 0 {// A preconfigured passwordless sudo is valid in a non-interactive// session. Probe it now so a failure happens before the restore.let sudo = try? VPhoneProcessRunner.runCapturing(- URL(fileURLWithPath: "/usr/bin/sudo"), ["-n", "/usr/bin/true"]+ URL(fileURLWithPath: "/usr/bin/sudo"), ["-n", "/usr/bin/true"],)- if sudo?.succeeded != true { throw VPhoneCreateError.sudoPasswordRequired }+ if sudo?.succeeded != true {+ throw VPhoneCreateError.sudoPasswordRequired+ }}print("\n=== vm new ===")@@ -140,7 +148,7 @@ public struct VPhoneCreateOrchestrator {memoryMB: options.memoryMB,diskSizeGB: options.diskSizeGB,romSource: VPhoneBundleOps.defaultROMSource(),- sepromSource: VPhoneBundleOps.defaultSEPROMSource()+ sepromSource: VPhoneBundleOps.defaultSEPROMSource(),)let bundle = try VPhoneBundleOps.create(spec, in: library)print("created \(bundle.url.path)")@@ -162,7 +170,8 @@ public struct VPhoneCreateOrchestrator {// CFW install is the last consumer of the built restore tree (it copies// the SystemOS/AppOS cryptexes from it onto Disk.img); reclaim it now.if !options.keepArtifacts, let bundle = try? VPhoneBundle.load(at: bundleURL),- let removed = try? VPhoneRestoreInfo.removeBuiltFirmware(fromBundle: bundle) {+ let removed = try? VPhoneRestoreInfo.removeBuiltFirmware(fromBundle: bundle)+ {print("[+] Removed built firmware \(removed)/ to save space (--keep-artifacts to keep)")}@@ -216,12 +225,14 @@ public struct VPhoneCreateOrchestrator {/// (`sudo -A -v`). Returns whether it succeeded.private func preloadSudoCredential(env extras: [String: String], verbosity v: VPhoneVerbosity) -> Bool {var env = ProcessInfo.processInfo.environment- for (key, value) in extras { env[key] = value }+ for (key, value) in extras {+ env[key] = value+ }trace("spawn /usr/bin/sudo -A -v (env keys added: \(extras.keys.sorted().joined(separator: ", ")))", v)let result = try? VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/bin/sudo"),["-A", "-v"],- env: env+ env: env,)return result?.succeeded == true}@@ -235,7 +246,7 @@ public struct VPhoneCreateOrchestrator {let bundle = try VPhoneBundle.load(at: bundleURL)try VPhoneFirmwarePreparer.prepare(iPhoneSource: phone, cloudOSSource: cloud,- bundle: bundle, cacheDirectory: resources.ipswCacheDir+ bundle: bundle, cacheDirectory: resources.ipswCacheDir,)print("[+] Firmware prepared (iPhone + cloudOS merged into bundle).")}@@ -243,7 +254,7 @@ public struct VPhoneCreateOrchestrator {private func runFWPatch(enableFrida: Bool,bundleURL: URL,- verbosity v: VPhoneVerbosity+ verbosity v: VPhoneVerbosity,) throws {// In-process pipeline (no subprocess) — CryptexFilesystemPatcher's// apfs_sealvolume read honors VPHONE_SEAL_DIR from *this* process's@@ -258,7 +269,7 @@ public struct VPhoneCreateOrchestrator {verbose: v.showsToolDetail,noBinpack: true,forceExcGuard: false,- enableFrida: enableFrida+ enableFrida: enableFrida,)let records = try pipeline.patchAll()print("[fw patch] applied \(records.count) JB patches")@@ -301,7 +312,7 @@ public struct VPhoneCreateOrchestrator {erase: true,ticketPath: nil,debugLevel: v.restoreDebugLevel,- onEvent: onEvent+ onEvent: onEvent,)} catch {throw VPhoneCreateError.restoreUpdateFailed("\(error)")@@ -359,10 +370,14 @@ public struct VPhoneCreateOrchestrator {var ecid = ""for line in text.split(whereSeparator: \.isNewline) {guard let eq = line.firstIndex(of: "=") else { continue }- let key = line[line.startIndex..<eq]+ let key = line[line.startIndex ..< eq]let value = String(line[line.index(after: eq)...])- if key == "UDID" { udid = value.uppercased() }- if key == "ECID" { ecid = VPhoneBootPatterns.normalizeECID(value) ?? "" }+ if key == "UDID" {+ udid = value.uppercased()+ }+ if key == "ECID" {+ ecid = VPhoneBootPatterns.normalizeECID(value) ?? ""+ }}guard udid.range(of: "^[0-9A-F]{8}-[0-9A-F]{16}$", options: .regularExpression) != nil else {@@ -387,7 +402,7 @@ public struct VPhoneCreateOrchestrator {/// wait is now one `irecv_open_with_ecid_and_attempts` poll per round.private func waitForRecovery(ecid: UInt64?, verbosity v: VPhoneVerbosity) throws {print("[*] Waiting for recovery/DFU endpoint...")- for _ in 1...90 {+ for _ in 1 ... 90 {if let device = try? VPhoneRestoreBridge.recoveryProbe(ecid: ecid, timeout: 2) {print("[+] Device endpoint is reachable")trace("recovery-probe: \(device.productType ?? "device") in \(device.mode)", v)@@ -409,12 +424,13 @@ public struct VPhoneCreateOrchestrator {let code = try VPhoneCFWInstaller.elevate(bundle: bundleURL, resources: resources,forceDSCMaxSlide: options.forceDSCMaxSlide,- rootPopup: usePopup, environment: sudoEnvExtras+ rootPopup: usePopup, environment: sudoEnvExtras,)guard code == 0 else { throw VPhoneCreateError.cfwInstallFailed(code) }print("[+] JB CFW installed.")if let bundle = try? VPhoneBundle.load(at: bundleURL),- let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {+ let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil+ {print("[+] Recorded variant jb, device \(info.device ?? "?")")}}@@ -455,5 +471,4 @@ public struct VPhoneCreateOrchestrator {print("[-] Boot analysis timeout (300s); stopping VM.")throw VPhoneCreateError.bootAnalysisTimeout}-}diff --git a/sources/vphone-cli/VPhoneFWAEACLI.swift b/sources/vphone-cli/VPhoneFWAEACLI.swiftindex 752628d4..319cfadc 100644--- a/sources/vphone-cli/VPhoneFWAEACLI.swift+++ b/sources/vphone-cli/VPhoneFWAEACLI.swift@@ -30,18 +30,18 @@ struct VPhoneFWAEAKeyCommand: ParsableCommand {This makes one network request, to the wkms-public.apple.com URL thearchive itself names. There is no offline path: the key is not in thefile, by design. Fetching it is what `ipsw fw aea --key` did too.- """+ """,)@Argument(help: "The .aea archive", transform: URL.init(fileURLWithPath:))var file: URL- // Not `AsyncParsableCommand`: this command tree is dispatched synchronously- // from main.swift, and an async `run()` there is never called — the default- // synchronous one is, which prints help and exits zero. That failure is- // silent, so the one await is bridged here instead.+ /// Not `AsyncParsableCommand`: this command tree is dispatched synchronously+ /// from main.swift, and an async `run()` there is never called — the default+ /// synchronous one is, which prints help and exits zero. That failure is+ /// silent, so the one await is bridged here instead.func run() throws {- print(try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: file) })+ try print(vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: file) })}}@@ -56,7 +56,7 @@ struct VPhoneFWIM4PCreateCommand: ParsableCommand {there: `--version 0` writes the one-character description "0". It is nota format version, and it is not optional — an IM4P with an emptydescription is not valid.- """+ """,)@Argument(help: "The payload to wrap", transform: URL.init(fileURLWithPath:))@@ -74,7 +74,7 @@ struct VPhoneFWIM4PCreateCommand: ParsableCommand {func run() throws {let im4p = try IM4P(fourcc: fourcc, description: version,- payload: Data(contentsOf: file, options: .mappedIfSafe)+ payload: Data(contentsOf: file, options: .mappedIfSafe),)try im4p.data.write(to: output)}@@ -83,7 +83,7 @@ struct VPhoneFWIM4PCreateCommand: ParsableCommand {struct VPhoneFWIM4PExtractCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "im4p-extract",- abstract: "Unwrap an IM4P's payload (replaces `ipsw img4 im4p extract`)"+ abstract: "Unwrap an IM4P's payload (replaces `ipsw img4 im4p extract`)",)@Argument(help: "The IM4P container", transform: URL.init(fileURLWithPath:))diff --git a/sources/vphone-cli/VPhoneFWCLI.swift b/sources/vphone-cli/VPhoneFWCLI.swiftindex 336af782..9b978673 100644--- a/sources/vphone-cli/VPhoneFWCLI.swift+++ b/sources/vphone-cli/VPhoneFWCLI.swift@@ -1,6 +1,6 @@import ArgumentParser-import Foundationimport FirmwarePatcher+import Foundationimport VPhoneCorestruct VPhoneFWCommand: ParsableCommand {@@ -20,7 +20,8 @@ struct VPhoneFWCommand: ParsableCommand {VPhoneFWIM4PExtractCommand.self,VPhoneFWURLsCommand.self,VPhoneFWSealToolCommand.self,- ])+ ],+ )}/// Check a PCC IPSW's build identities using HTTP ranges before committing@@ -28,7 +29,7 @@ struct VPhoneFWCommand: ParsableCommand {struct VPhoneFWInspectCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "inspect",- abstract: "Inspect a remote IPSW manifest without downloading the archive"+ abstract: "Inspect a remote IPSW manifest without downloading the archive",)@Argument(help: "Remote IPSW URL") var source: String@@ -42,8 +43,9 @@ struct VPhoneFWInspectCommand: ParsableCommand {return try await zip.read(zip.entry(endingWith: "BuildManifest.plist"))}guard let manifest = try PropertyListSerialization.propertyList(from: data, format: nil)- as? [String: Any],- let identities = manifest["BuildIdentities"] as? [[String: Any]] else {+ as? [String: Any],+ let identities = manifest["BuildIdentities"] as? [[String: Any]]+ else {throw VPhoneRemoteZip.Error.malformed("BuildManifest.plist has no BuildIdentities")}print("\(manifest["ProductVersion"] ?? "unknown") (\(manifest["ProductBuildVersion"] ?? "unknown"))")@@ -68,7 +70,7 @@ struct VPhoneFWInspectCommand: ParsableCommand {struct VPhoneFWListCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "list",- abstract: "Print the downloadable-firmware support matrix for a device"+ abstract: "Print the downloadable-firmware support matrix for a device",)@Option(help: "Device identifier, e.g. iPhone17,3") var device: String@@ -78,9 +80,11 @@ struct VPhoneFWListCommand: ParsableCommand {let code = VPhoneFirmwareMatrixCommandLine.list(device: device,readmePath: readme,- downloadURLs: ProcessInfo.processInfo.environment["DOWNLOADABLE_IPSW_URLS"] ?? ""+ downloadURLs: ProcessInfo.processInfo.environment["DOWNLOADABLE_IPSW_URLS"] ?? "",)- if code != 0 { throw ExitCode(code) }+ if code != 0 {+ throw ExitCode(code)+ }}}@@ -94,7 +98,7 @@ struct VPhoneFWResolveCommand: ParsableCommand {Exits 2 — not 1 — when a bare version matches more than one build, so acaller can tell "pick a build" from "there is no such firmware". An empty--version or --build means unconstrained.- """+ """,)@Option(help: "Device identifier, e.g. iPhone17,3") var device: String@@ -108,9 +112,11 @@ struct VPhoneFWResolveCommand: ParsableCommand {version: version,build: build,readmePath: readme,- downloadURLs: ProcessInfo.processInfo.environment["DOWNLOADABLE_IPSW_URLS"] ?? ""+ downloadURLs: ProcessInfo.processInfo.environment["DOWNLOADABLE_IPSW_URLS"] ?? "",)- if code != 0 { throw ExitCode(code) }+ if code != 0 {+ throw ExitCode(code)+ }}}@@ -128,18 +134,18 @@ struct VPhoneFWManifestCommand: ParsableCommand {Both files are written into <iphone-dir>, replacing what is there.`fw prepare` keeps the original as iPhone-BuildManifest.plist first.- """+ """,)@Argument(help: "Extracted iPhone IPSW directory — also where the output is written",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var iPhoneDirectory: URL@Argument(help: "Extracted cloudOS IPSW directory",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var cloudOSDirectory: URL@@ -150,7 +156,7 @@ struct VPhoneFWManifestCommand: ParsableCommand {try FirmwareManifest.generate(iPhoneDir: iPhoneDirectory,cloudOSDir: cloudOSDirectory,- verbose: true+ verbose: true,)}}@@ -160,7 +166,7 @@ struct VPhoneFWManifestCommand: ParsableCommand {struct VPhoneFWCatalogCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "catalog",- abstract: "Show the known iOS ↔ cloudOS firmware pairings (recommended per iOS build)"+ abstract: "Show the known iOS ↔ cloudOS firmware pairings (recommended per iOS build)",)@Flag(name: .shortAndLong, help: "Emit JSON") var json = false@@ -168,7 +174,7 @@ struct VPhoneFWCatalogCommand: ParsableCommand {func run() throws {let report = VPhoneFirmwareCatalog.reportif json {- print(String(decoding: try JSONEncoder().encode(report), as: UTF8.self))+ try print(String(decoding: JSONEncoder().encode(report), as: UTF8.self))return}print("Firmware catalog (\(report.device))")@@ -187,7 +193,7 @@ struct VPhoneFWCatalogCommand: ParsableCommand {struct VPhoneFWPrepareCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "prepare",- abstract: "Download + merge IPSWs into a VM bundle"+ abstract: "Download + merge IPSWs into a VM bundle",)@OptionGroup var lib: VPhoneLibraryOption@@ -210,13 +216,17 @@ struct VPhoneFWPrepareCommand: ParsableCommand {try vphoneRunBlocking {try await VPhoneFirmwareIndex.restoreURLs(forDevice: "iPhone17,3")}.joined(separator: "\n")- } else { "" }+ } else {+ ""+ }if list {let code = VPhoneFirmwareMatrixCommandLine.list(- device: "iPhone17,3", readmePath: readme, downloadURLs: urls+ device: "iPhone17,3", readmePath: readme, downloadURLs: urls,)- if code != 0 { throw ExitCode(code) }+ if code != 0 {+ throw ExitCode(code)+ }return}@@ -229,7 +239,7 @@ struct VPhoneFWPrepareCommand: ParsableCommand {device: "iPhone17,3", version: iphoneVersion ?? "", build: iphoneBuild ?? "",readme: try? String(contentsOfFile: readme, encoding: .utf8),downloadURLs: urls,- style: .forStream(FileHandle.standardError.fileDescriptor)+ style: .forStream(FileHandle.standardError.fileDescriptor),)switch selection {case let .selected(release, _): source = release.url@@ -246,7 +256,7 @@ struct VPhoneFWPrepareCommand: ParsableCommand {let bundle = try lib.library.bundle(named: name)try VPhoneFirmwarePreparer.prepare(iPhoneSource: phone, cloudOSSource: cloud,- bundle: bundle, cacheDirectory: resources.ipswCacheDir+ bundle: bundle, cacheDirectory: resources.ipswCacheDir,)}}@@ -256,7 +266,7 @@ struct VPhoneFWPrepareCommand: ParsableCommand {struct VPhoneFWPatchCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "patch",- abstract: "Patch the boot chain (native Swift FirmwarePipeline)"+ abstract: "Patch the boot chain (native Swift FirmwarePipeline)",)@OptionGroup var lib: VPhoneLibraryOption@@ -283,7 +293,7 @@ struct VPhoneFWPatchCommand: ParsableCommand {verbose: !quiet,noBinpack: true,forceExcGuard: forceExcGuard,- enableFrida: frida+ enableFrida: frida,)let records = try pipeline.patchAll()print("[fw patch] applied \(records.count) JB patches")diff --git a/sources/vphone-cli/VPhoneFWDownloadCLI.swift b/sources/vphone-cli/VPhoneFWDownloadCLI.swiftindex 775111da..0d9e3c03 100644--- a/sources/vphone-cli/VPhoneFWDownloadCLI.swift+++ b/sources/vphone-cli/VPhoneFWDownloadCLI.swift@@ -29,7 +29,7 @@ struct VPhoneFWURLsCommand: ParsableCommand {Reads Apple's own iTunes version plist — the document Finder consults todecide what it can restore a device to. One URL per line, which is whatfw_prepare.sh feeds into DOWNLOADABLE_IPSW_URLS.- """+ """,)@Option(help: "Device identifier, e.g. iPhone17,3") var device: String@@ -38,7 +38,9 @@ struct VPhoneFWURLsCommand: ParsableCommand {let urls = try vphoneRunBlocking {try await VPhoneFirmwareIndex.restoreURLs(forDevice: device)}- for url in urls { print(url) }+ for url in urls {+ print(url)+ }}}@@ -61,7 +63,7 @@ struct VPhoneFWSealToolCommand: ParsableCommand {The result is ad-hoc signed before it is used, because a binary liftedout of a ramdisk carries a signature that does not validate once it issomewhere else.- """+ """,)@Option(help: "OS marketing version, e.g. 26.1") var version: String@@ -93,7 +95,7 @@ struct VPhoneFWSealToolCommand: ParsableCommand {let result = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: tool), args)guard result.succeeded else {throw VPhoneRemoteZip.Error.malformed(- "\(tool) exited \(result.exitCode): \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))"+ "\(tool) exited \(result.exitCode): \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))",)}return result.stdout@@ -110,11 +112,12 @@ struct VPhoneFWSealToolCommand: ParsableCommand {let manifestData = try await zip.read(manifestEntry)guard let manifest = try PropertyListSerialization.propertyList(- from: manifestData, format: nil) as? [String: Any],- let identities = manifest["BuildIdentities"] as? [[String: Any]]+ from: manifestData, format: nil,+ ) as? [String: Any],+ let identities = manifest["BuildIdentities"] as? [[String: Any]]else {throw VPhoneRemoteZip.Error.malformed(- "\(manifestEntry.name) (\(manifestData.count) bytes) has no BuildIdentities"+ "\(manifestEntry.name) (\(manifestData.count) bytes) has no BuildIdentities",)}// Any identity will do — every one of them names the same restore@@ -122,10 +125,10 @@ struct VPhoneFWSealToolCommand: ParsableCommand {// that does rather than assuming identity 0.guard let path = identities.lazy.compactMap({ identity -> String? in(((identity["Manifest"] as? [String: Any])?["RestoreRamDisk"]- as? [String: Any])?["Info"] as? [String: Any])?["Path"] as? String+ as? [String: Any])?["Info"] as? [String: Any])?["Path"] as? String}).first else {throw VPhoneRemoteZip.Error.malformed(- "none of \(identities.count) build identities names a RestoreRamDisk"+ "none of \(identities.count) build identities names a RestoreRamDisk",)}print(" ramdisk: \(path)")@@ -144,14 +147,15 @@ struct VPhoneFWSealToolCommand: ParsableCommand {let attached = try run("/usr/bin/hdiutil",["attach", "-readonly", "-nobrowse", "-plist", dmg.path])guard let plist = try PropertyListSerialization.propertyList(- from: Data(attached.utf8), format: nil) as? [String: Any],- let entities = plist["system-entities"] as? [[String: Any]],- let mount = entities.compactMap({ $0["mount-point"] as? String }).first+ from: Data(attached.utf8), format: nil,+ ) as? [String: Any],+ let entities = plist["system-entities"] as? [[String: Any]],+ let mount = entities.compactMap({ $0["mount-point"] as? String }).firstelse { throw VPhoneRemoteZip.Error.malformed("hdiutil attached nothing with a mount point") }defer { try? run("/usr/bin/hdiutil", ["detach", mount]) }let source = URL(fileURLWithPath: mount).appending(- path: "System/Library/Filesystems/apfs.fs/Contents/Resources/apfs_sealvolume"+ path: "System/Library/Filesystems/apfs.fs/Contents/Resources/apfs_sealvolume",)try FileManager.default.copyItem(at: source, to: destination)try FileManager.default.setAttributes([.posixPermissions: 0o755],diff --git a/sources/vphone-cli/VPhoneFirmwarePreparer.swift b/sources/vphone-cli/VPhoneFirmwarePreparer.swiftindex 0953200c..600a1ea1 100644--- a/sources/vphone-cli/VPhoneFirmwarePreparer.swift+++ b/sources/vphone-cli/VPhoneFirmwarePreparer.swift@@ -30,11 +30,11 @@ enum VPhoneFirmwarePreparer {iPhoneSource: String,cloudOSSource: String,bundle: VPhoneBundle,- cacheDirectory: URL+ cacheDirectory: URL,) throws {let fm = FileManager.defaultlet existing = try fm.contentsOfDirectory(- at: bundle.url, includingPropertiesForKeys: [.isDirectoryKey]+ at: bundle.url, includingPropertiesForKeys: [.isDirectoryKey],)for candidate in existing where candidate.lastPathComponent.contains("Restore") {if try candidate.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true {@@ -117,14 +117,16 @@ enum VPhoneFirmwarePreparer {from source: URL,into destination: URL,overwrite: Bool = true,- where predicate: (String) -> Bool+ where predicate: (String) -> Bool,) throws {let fm = FileManager.defaultguard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }let names = try fm.contentsOfDirectory(atPath: source.path).filter(predicate)for name in names {let to = destination.appendingPathComponent(name)- if !overwrite, fm.fileExists(atPath: to.path) { continue }+ if !overwrite, fm.fileExists(atPath: to.path) {+ continue+ }try clone(source.appendingPathComponent(name), to: to)}}@@ -132,24 +134,32 @@ enum VPhoneFirmwarePreparer {private static func clone(_ source: URL, to destination: URL) throws {let fm = FileManager.defaultguard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }- if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }- if clonefile(source.path, destination.path, 0) == 0 { return }- if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }+ if fm.fileExists(atPath: destination.path) {+ try fm.removeItem(at: destination)+ }+ if clonefile(source.path, destination.path, 0) == 0 {+ return+ }+ if fm.fileExists(atPath: destination.path) {+ try fm.removeItem(at: destination)+ }try fm.copyItem(at: source, to: destination)}private static func makeUserWritable(_ directory: URL) throws {let fm = FileManager.defaultguard let entries = fm.enumerator(- at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey]+ at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey],) else { return }for case let file as URL in entries {let values = try file.resourceValues(forKeys: [.isSymbolicLinkKey])- if values.isSymbolicLink == true { continue }+ if values.isSymbolicLink == true {+ continue+ }let attributes = try fm.attributesOfItem(atPath: file.path)let mode = (attributes[.posixPermissions] as? NSNumber)?.uint16Value ?? 0o644try fm.setAttributes(- [.posixPermissions: NSNumber(value: mode | 0o200)], ofItemAtPath: file.path+ [.posixPermissions: NSNumber(value: mode | 0o200)], ofItemAtPath: file.path,)}}diff --git a/sources/vphone-cli/VPhoneFirmwareSelection.swift b/sources/vphone-cli/VPhoneFirmwareSelection.swiftindex 4612d2fe..a885f81c 100644--- a/sources/vphone-cli/VPhoneFirmwareSelection.swift+++ b/sources/vphone-cli/VPhoneFirmwareSelection.swift@@ -2,8 +2,13 @@ import Foundationimport VPhoneCoreenum VPhoneFirmwareSelection {- private static var isTTY: Bool { isatty(FileHandle.standardInput.fileDescriptor) != 0 }- private static func err(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }+ private static var isTTY: Bool {+ isatty(FileHandle.standardInput.fileDescriptor) != 0+ }++ private static func err(_ s: String) {+ FileHandle.standardError.write(Data((s + "\n").utf8))+ }/// Resolve `vm create`'s iPhone/cloudOS sources, prompting on a TTY for/// whichever component the user didn't pass. Non-interactive or fully@@ -14,7 +19,7 @@ enum VPhoneFirmwareSelection {cloudos: cloudos,isInteractive: isTTY,read: { readLine(strippingNewline: true) },- write: { err($0) }+ write: { err($0) },)}}diff --git a/sources/vphone-cli/VPhoneHostControlProbe.swift b/sources/vphone-cli/VPhoneHostControlProbe.swiftindex 9c3b91b2..cc2c4bb6 100644--- a/sources/vphone-cli/VPhoneHostControlProbe.swift+++ b/sources/vphone-cli/VPhoneHostControlProbe.swift@@ -11,7 +11,9 @@ enum VPhoneHostControlProbe {address.sun_family = sa_family_t(AF_UNIX)withUnsafeMutablePointer(to: &address.sun_path) { pointer inpointer.withMemoryRebound(to: CChar.self, capacity: path.count) { destination in- for (index, byte) in path.enumerated() { destination[index] = byte }+ for (index, byte) in path.enumerated() {+ destination[index] = byte+ }}}@@ -49,7 +51,8 @@ enum VPhoneHostControlProbe {guard count > 0 else { return false }reply.append(contentsOf: buffer.prefix(count))if let newline = reply.firstIndex(of: 0x0A),- let json = try? JSONSerialization.jsonObject(with: Data(reply[..<newline])) as? [String: Any] {+ let json = try? JSONSerialization.jsonObject(with: Data(reply[..<newline])) as? [String: Any]+ {return json["ok"] as? Bool == true}}diff --git a/sources/vphone-cli/VPhoneHostPreflight.swift b/sources/vphone-cli/VPhoneHostPreflight.swiftindex 8a28bbb0..d496c427 100644--- a/sources/vphone-cli/VPhoneHostPreflight.swift+++ b/sources/vphone-cli/VPhoneHostPreflight.swift@@ -8,10 +8,11 @@ import VPhoneCoreenum VPhoneHostPreflight {static func check() throws -> VPhoneGuestLaunchPlanner {let probe = try VPhoneProcessRunner.runCapturing(- URL(fileURLWithPath: "/usr/sbin/sysctl"), ["-n", "kern.hv_vmm_present"]+ URL(fileURLWithPath: "/usr/sbin/sysctl"), ["-n", "kern.hv_vmm_present"],)if probe.succeeded,- probe.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "1" {+ probe.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "1"+ {throw ValidationError("Nested virtualization is unavailable for this VM")}return try VPhoneGuestLaunchPlanner()@@ -20,20 +21,22 @@ enum VPhoneHostPreflight {struct VPhoneHostCommand: ParsableCommand {static let configuration = CommandConfiguration(- commandName: "host", subcommands: [VPhoneHostPreflightCommand.self]+ commandName: "host", subcommands: [VPhoneHostPreflightCommand.self],)}struct VPhoneHostPreflightCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "preflight",- abstract: "Check whether the entitled VM binary can launch on this host"+ abstract: "Check whether the entitled VM binary can launch on this host",)@Flag(help: "Suppress the success message") var quiet = falsefunc run() throws {_ = try VPhoneHostPreflight.check()- if !quiet { print("Host preflight passed: vphone-vm can launch") }+ if !quiet {+ print("Host preflight passed: vphone-vm can launch")+ }}}diff --git a/sources/vphone-cli/VPhoneProgressBar.swift b/sources/vphone-cli/VPhoneProgressBar.swiftindex 5c2bbdc3..44d22a4e 100644--- a/sources/vphone-cli/VPhoneProgressBar.swift+++ b/sources/vphone-cli/VPhoneProgressBar.swift@@ -15,14 +15,16 @@ final class VPhoneProgressBar {init(label: String) {self.label = label- self.enabled = isatty(FileHandle.standardError.fileDescriptor) != 0+ enabled = isatty(FileHandle.standardError.fileDescriptor) != 0}func update(done: Int64, total: Int64) {guard enabled else { return }self.total = totallet now = Date()- if done < total, now.timeIntervalSince(lastRender) < 0.066 { return } // ~15 fps+ if done < total, now.timeIntervalSince(lastRender) < 0.066 {+ return+ } // ~15 fpslastRender = nowrender(done: done, now: now)}@@ -41,17 +43,25 @@ final class VPhoneProgressBar {let rate = elapsed > 0 ? Double(done) / elapsed : 0var line = "\r\(label) [\(bar)] \(Int(frac * 100))% \(Self.bytes(done))"- if total > 0 { line += "/\(Self.bytes(total))" }- if rate > 0 { line += " \(Self.bytes(Int64(rate)))/s" }- if total > 0, rate > 0, done < total { line += " eta \(Self.clock(Double(total - done) / rate))" }- line += "\u{1B}[K" // clear to end of line+ if total > 0 {+ line += "/\(Self.bytes(total))"+ }+ if rate > 0 {+ line += " \(Self.bytes(Int64(rate)))/s"+ }+ if total > 0, rate > 0, done < total {+ line += " eta \(Self.clock(Double(total - done) / rate))"+ }+ line += "\u{1B}[K" // clear to end of lineFileHandle.standardError.write(Data(line.utf8))}static func bytes(_ n: Int64) -> String {let units = ["B", "KB", "MB", "GB", "TB"]var value = Double(n), i = 0- while value >= 1024, i < units.count - 1 { value /= 1024; i += 1 }+ while value >= 1024, i < units.count - 1 {+ value /= 1024; i += 1+ }return i == 0 ? "\(n) B" : String(format: "%.1f %@", value, units[i])}diff --git a/sources/vphone-cli/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swiftindex 192a912f..73acfe95 100644--- a/sources/vphone-cli/VPhoneRestoreCLI.swift+++ b/sources/vphone-cli/VPhoneRestoreCLI.swift@@ -10,12 +10,16 @@ extension VPhoneVerbosity {/// for `.info` (pymobiledevice3's colorful INFO), two for `.debug` and/// `.trace`. In process that single count becomes two knobs, and both are/// needed — see `restoreDebugLevel`.- var restoreLogLevel: VPhoneRestoreLogLevel { self >= .debug ? .debug : .info }+ var restoreLogLevel: VPhoneRestoreLogLevel {+ self >= .debug ? .debug : .info+ }/// idevicerestore's own level ceiling (`-d`). Raising the console sink/// without raising this one prints nothing extra, because the messages it/// would show are never emitted.- var restoreDebugLevel: Int32 { self >= .debug ? 1 : 0 }+ var restoreDebugLevel: Int32 {+ self >= .debug ? 1 : 0+ }}// MARK: - restore@@ -23,7 +27,7 @@ extension VPhoneVerbosity {struct VPhoneRestoreCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "restore",- abstract: "DFU-restore firmware into a VM bundle (requires a running DFU boot)"+ abstract: "DFU-restore firmware into a VM bundle (requires a running DFU boot)",)@OptionGroup var lib: VPhoneLibraryOption@@ -34,10 +38,10 @@ struct VPhoneRestoreCommand: ParsableCommand {@Option(name: .shortAndLong, help: "Device UDID (optional)") var udid: String?@Option(name: .shortAndLong, help: "Device ECID (default: read from the bundle's udid-prediction.txt)")var ecid: String?- // The Python exposed this as `--erase/--no-erase`, defaulting to erase, and- // `VPhoneRestoreOptions.erase` has carried it since the port. Only the flag- // was missing, which left `Behavior.Update` reachable from the library and- // its unit test but not from the command line.+ /// The Python exposed this as `--erase/--no-erase`, defaulting to erase, and+ /// `VPhoneRestoreOptions.erase` has carried it since the port. Only the flag+ /// was missing, which left `Behavior.Update` reachable from the library and+ /// its unit test but not from the command line.@Flag(name: .customLong("no-erase"), help: "Update in place instead of erasing (upstream's Behavior.Update)")var noErase = false@Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")@@ -69,7 +73,7 @@ struct VPhoneRestoreCommand: ParsableCommand {udid: udid,out: nil,debugLevel: v.restoreDebugLevel,- onEvent: onEvent+ onEvent: onEvent,)return}@@ -100,7 +104,7 @@ struct VPhoneRestoreCommand: ParsableCommand {erase: !noErase,ticketPath: ticket,debugLevel: v.restoreDebugLevel,- onEvent: onEvent+ onEvent: onEvent,)recordRestoreVersions(bundle: bundle)}@@ -111,7 +115,7 @@ struct VPhoneRestoreCommand: ParsableCommand {private func recordRestoreVersions(bundle: VPhoneBundle) {guard let info = VPhoneRestoreInfo.derive(fromBundle: bundle) else {FileHandle.standardError.write(- Data("warning: could not record restore versions (metadata not found)\n".utf8)+ Data("warning: could not record restore versions (metadata not found)\n".utf8),)return}@@ -134,7 +138,7 @@ struct VPhoneRestoreCommand: ParsableCommand {struct VPhoneRecoveryProbeCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "recovery-probe",- abstract: "Wait briefly for a DFU/recovery endpoint; exit 0 if one answered"+ abstract: "Wait briefly for a DFU/recovery endpoint; exit 0 if one answered",)@Option(name: .shortAndLong, help: "Device ECID (hex, 0x optional; default: the only device attached)")@@ -143,8 +147,8 @@ struct VPhoneRecoveryProbeCommand: ParsableCommand {func run() throws {let device = try VPhoneRestoreBridge.recoveryProbe(- ecid: try VPhoneRestoreIdentity.parseECID(ecid),- timeout: timeout+ ecid: VPhoneRestoreIdentity.parseECID(ecid),+ timeout: timeout,)// The Python printed nothing at all and its one caller discarded both// streams. One line costs that caller nothing and is the difference@@ -174,7 +178,8 @@ struct VPhoneCFWCommand: ParsableCommand {VPhoneCFWPatchBuildVersionCommand.self,VPhoneCFWPatchCampoEntitlementsCommand.self,VPhoneCFWPatchPostRestoreDTCommand.self,- ] + VPhoneCFWMachOVerbs.all + VPhoneCFWDSCVerbs.all)+ ] + VPhoneCFWMachOVerbs.all + VPhoneCFWDSCVerbs.all,+ )}/// Replaces `tools/apfs_snap_rename.py`, called from `cfw_install_host.sh`@@ -193,7 +198,7 @@ struct VPhoneCFWFlipSnapshotCommand: ParsableCommand {so identical strings baked into on-volume binaries are left alone.The VM must be powered off.- """+ """,)@Argument(help: "Path to the VM's Disk.img", transform: URL.init(fileURLWithPath:))@@ -204,7 +209,7 @@ struct VPhoneCFWFlipSnapshotCommand: ParsableCommand {@Option(name: .customLong("new-prefix"),- help: "Replacement prefix. Must be exactly as long as 'com.apple.os.update-'."+ help: "Replacement prefix. Must be exactly as long as 'com.apple.os.update-'.",)var newPrefix: String = VPhoneAPFSSnapshot.defaultNewPrefix@@ -216,24 +221,24 @@ struct VPhoneCFWFlipSnapshotCommand: ParsableCommand {struct VPhoneCFWInstallCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "install",- abstract: "Install CFW into a VM bundle via host mount"+ abstract: "Install CFW into a VM bundle via host mount",)@OptionGroup var lib: VPhoneLibraryOption@Argument(help: "VM name") var name: String?@Flag(name: .customLong("force-dsc-maxslide"),- help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)"+ help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)",)var forceDSCMaxSlide = false@Flag(name: .customLong("root-popup"),- help: "Elevate via macOS's native authentication dialog (osascript) instead of the sudo re-exec"+ help: "Elevate via macOS's native authentication dialog (osascript) instead of the sudo re-exec",)var rootPopup = false@Flag(name: .customLong("keep-artifacts"),- help: "Keep the extracted firmware after install (default: removed to save space)"+ help: "Keep the extracted firmware after install (default: removed to save space)",)var keepArtifacts = false@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")@@ -250,7 +255,7 @@ struct VPhoneCFWInstallCommand: ParsableCommand {let code = try VPhoneCFWInstaller.elevate(bundle: bundle.url, resources: resources,forceDSCMaxSlide: forceDSCMaxSlide, rootPopup: rootPopup,- verbose: v.showsToolDetail+ verbose: v.showsToolDetail,)if code == 0 {if let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {diff --git a/sources/vphone-cli/VPhoneSignCLI.swift b/sources/vphone-cli/VPhoneSignCLI.swiftindex b49200df..fe957c56 100644--- a/sources/vphone-cli/VPhoneSignCLI.swift+++ b/sources/vphone-cli/VPhoneSignCLI.swift@@ -47,26 +47,26 @@ struct VPhoneSignCommand: ParsableCommand {the file already carries, rather than replacing them. Without it, are-sign silently drops the sandbox profile and private entitlements abinary like diskimagesiod cannot run without.- """+ """,)@Argument(help: "The Mach-O to sign, in place", transform: URL.init(fileURLWithPath:))var file: URL- // Long spellings only, deliberately. ldid's short flags take their value- // attached (-S"$ent", -K"$p12"), which ArgumentParser reads as an unknown- // option; offering -S and -K here would invite exactly that call and answer- // it with a parse error about something else.+ /// Long spellings only, deliberately. ldid's short flags take their value+ /// attached (-S"$ent", -K"$p12"), which ArgumentParser reads as an unknown+ /// option; offering -S and -K here would invite exactly that call and answer+ /// it with a parse error about something else.@Option(name: .customLong("entitlements"),help: "Entitlements plist to embed, as the file holds it",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var entitlements: URL?@Option(name: .customLong("identifier"),- help: "Signing identifier. Defaults to the file's name, as ldid does."+ help: "Signing identifier. Defaults to the file's name, as ldid does.",)var identifier: String?@@ -76,13 +76,13 @@ struct VPhoneSignCommand: ParsableCommand {@Option(name: .customLong("pkcs12"),help: "Sign for real with this .p12 (no password) instead of ad-hoc",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)var pkcs12: URL?@Flag(name: .customLong("apple-adhoc"),- help: "Write an ad-hoc signature in Apple's shape (codesign --sign -) rather than ldid's"+ help: "Write an ad-hoc signature in Apple's shape (codesign --sign -) rather than ldid's",)var appleAdHoc = false@@ -96,7 +96,7 @@ struct VPhoneSignCommand: ParsableCommand {options.style = appleAdHoc ? .appleAdHoc : .ldidif let pkcs12 {options.identity = try VPhoneSignIdentity(- pkcs12: Data(contentsOf: pkcs12, options: .mappedIfSafe), password: ""+ pkcs12: Data(contentsOf: pkcs12, options: .mappedIfSafe), password: "",)}try VPhoneSigner.sign(fileAt: file, options: options)@@ -117,7 +117,7 @@ struct VPhoneDumpEntitlementsCommand: ParsableCommand {A slice with no entitlements contributes nothing, so a file with none atall prints nothing and still exits zero.- """+ """,)@Argument(help: "The Mach-O to read", transform: URL.init(fileURLWithPath:))diff --git a/sources/vphone-cli/VPhoneVMCLI.swift b/sources/vphone-cli/VPhoneVMCLI.swiftindex 16ffc907..de8263ab 100644--- a/sources/vphone-cli/VPhoneVMCLI.swift+++ b/sources/vphone-cli/VPhoneVMCLI.swift@@ -22,7 +22,7 @@ struct VPhoneVMCommand: ParsableCommand {VPhoneVMStopCommand.self,VPhoneVMCreateCommand.self,VPhoneVMWriteManifestCommand.self,- ]+ ],)}@@ -31,15 +31,15 @@ struct VPhoneVMCommand: ParsableCommand {struct VPhoneVMWriteManifestCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "write-manifest",- abstract: "Write a fresh config.plist into a VM directory"+ abstract: "Write a fresh config.plist into a VM directory",)@Option(name: .customLong("vm-dir"),help: "VM directory to write config.plist into",- transform: URL.init(fileURLWithPath:)+ transform: URL.init(fileURLWithPath:),)- var vmDirectory: URL = URL(fileURLWithPath: "vm")+ var vmDirectory: URL = .init(fileURLWithPath: "vm")@Option(name: .customLong("cpu"), help: "CPU core count")var cpuCount: UInt = 8@@ -49,14 +49,14 @@ struct VPhoneVMWriteManifestCommand: ParsableCommand {@Option(name: .customLong("platform-fusing"),- help: "prod or dev. Omit to let the host OS decide."+ help: "prod or dev. Omit to let the host OS decide.",)var platformFusing: VPhoneVirtualMachineManifest.PlatformFusing?func run() throws {var isDirectory: ObjCBool = falseguard FileManager.default.fileExists(- atPath: vmDirectory.path, isDirectory: &isDirectory+ atPath: vmDirectory.path, isDirectory: &isDirectory,), isDirectory.boolValue else {throw ValidationError("VM directory does not exist: \(vmDirectory.path)")}@@ -64,7 +64,7 @@ struct VPhoneVMWriteManifestCommand: ParsableCommand {let manifest = VPhoneVirtualMachineManifest.newVM(cpuCount: cpuCount,memoryMB: memoryMB,- platformFusing: platformFusing+ platformFusing: platformFusing,)let configURL = vmDirectory.appendingPathComponent("config.plist")try manifest.write(to: configURL)@@ -107,7 +107,7 @@ struct VPhoneVMListCommand: ParsableCommand {print("(no VMs in \(library.root.path))")} else {for r in reports {- var line = "\(r.name) \(r.cpuCount) CPU \(r.memoryMB) MB \(r.diskSizeBytes / (1024*1024*1024)) GB disk"+ var line = "\(r.name) \(r.cpuCount) CPU \(r.memoryMB) MB \(r.diskSizeBytes / (1024 * 1024 * 1024)) GB disk"if let info = r.restoreInfo {line += " iOS \(info.ios.version) / cloudOS \(info.cloudOS.version)"}@@ -131,19 +131,25 @@ struct VPhoneVMInfoCommand: ParsableCommand {let bundle = try lib.library.bundle(named: name)let report = VPhoneBundleReport(bundle: bundle)if json {- print(String(decoding: try JSONEncoder().encode(report), as: UTF8.self))+ try print(String(decoding: JSONEncoder().encode(report), as: UTF8.self))} else {print("name: \(report.name)")print("cpu: \(report.cpuCount)")print("mem: \(report.memoryMB) MB")print("disk: \(report.diskSizeBytes) bytes")print("net: \(describeNetwork(report.network))")- if let udid = report.udid { print("udid: \(udid)") }+ if let udid = report.udid {+ print("udid: \(udid)")+ }if let info = report.restoreInfo {print("iOS: \(info.ios.version) (\(info.ios.build))")print("cloudOS: \(info.cloudOS.version) (\(info.cloudOS.build))")- if let variant = info.variant { print("variant: \(variant)") }- if let device = info.device { print("device: \(device)") }+ if let variant = info.variant {+ print("variant: \(variant)")+ }+ if let device = info.device {+ print("device: \(device)")+ }}}}@@ -169,7 +175,7 @@ struct VPhoneVMNewCommand: ParsableCommand {memoryMB: memory,diskSizeGB: diskSize,romSource: rom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOps.defaultROMSource(),- sepromSource: seprom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOps.defaultSEPROMSource()+ sepromSource: seprom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOps.defaultSEPROMSource(),)let bundle = try VPhoneBundleOps.create(spec, in: lib.library)print("created \(bundle.url.path)")@@ -181,7 +187,7 @@ struct VPhoneVMNewCommand: ParsableCommand {struct VPhoneVMConfigCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "config",- abstract: "Edit VM manifest fields (cpu/memory/network)"+ abstract: "Edit VM manifest fields (cpu/memory/network)",)@OptionGroup var lib: VPhoneLibraryOption@@ -201,10 +207,10 @@ struct VPhoneVMConfigCommand: ParsableCommand {cpuCount: cpu,memoryMB: memory,networkMode: mode,- bridgeInterface: bridgeInterface+ bridgeInterface: bridgeInterface,)let m = updated.manifest- print("updated \(updated.name): \(m.cpuCount) CPU, \(m.memorySize / (1024*1024)) MB, "+ print("updated \(updated.name): \(m.cpuCount) CPU, \(m.memorySize / (1024 * 1024)) MB, "+ "net=\(describeNetwork(m.networkConfig))")}@@ -225,7 +231,9 @@ struct VPhoneVMConfigCommand: ParsableCommand {private func describeNetwork(_ net: VPhoneVirtualMachineManifest.NetworkConfig) -> String {var s = net.mode.rawValue- if net.mode == .bridged, let iface = net.bridgeInterface { s += "(\(iface))" }+ if net.mode == .bridged, let iface = net.bridgeInterface {+ s += "(\(iface))"+ }return s}diff --git a/sources/vphone-cli/VPhoneVMCreateCLI.swift b/sources/vphone-cli/VPhoneVMCreateCLI.swiftindex accb4c30..d15c813c 100644--- a/sources/vphone-cli/VPhoneVMCreateCLI.swift+++ b/sources/vphone-cli/VPhoneVMCreateCLI.swift@@ -7,7 +7,7 @@ struct VPhoneVMCreateCommand: ParsableCommand {commandName: "create",abstract: "Create a VM end-to-end (prepare → patch → restore → CFW → first boot)",discussion: "Runs the JB pipeline for a fresh VM. Needs an internet connection "- + "(IPSW download), a non-nested macOS host, and sudo (CFW host-mount)."+ + "(IPSW download), a non-nested macOS host, and sudo (CFW host-mount).",)@OptionGroup var lib: VPhoneLibraryOption@@ -19,22 +19,22 @@ struct VPhoneVMCreateCommand: ParsableCommand {var sudoPassword: String?@Flag(name: .customLong("force-dsc-maxslide"),- help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)"+ help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)",)var forceDSCMaxSlide = false@Flag(name: .customLong("frida"),- help: "Opt in to Frida Stalker kernel relaxations"+ help: "Opt in to Frida Stalker kernel relaxations",)var frida = false@Flag(name: .customLong("root-popup"),- help: "Elevate the CFW host-mount via macOS's native authentication dialog (osascript) instead of a sudo prompt"+ help: "Elevate the CFW host-mount via macOS's native authentication dialog (osascript) instead of a sudo prompt",)var rootPopup = false@Flag(name: .customLong("keep-artifacts"),- help: "Keep the prepared restore tree after installation. Source IPSWs are always kept."+ help: "Keep the prepared restore tree after installation. Source IPSWs are always kept.",)var keepArtifacts = false@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")@@ -56,7 +56,7 @@ struct VPhoneVMCreateCommand: ParsableCommand {let orchestrator = VPhoneCreateOrchestrator(library: lib.library,resources: resources,- launcher: launcher+ launcher: launcher,)try orchestrator.run(.init(name: name,@@ -68,7 +68,7 @@ struct VPhoneVMCreateCommand: ParsableCommand {rootPopup: rootPopup,diskSizeGB: diskSize,verbosity: VPhoneVerbosity(count: verboseCount),- keepArtifacts: keepArtifacts+ keepArtifacts: keepArtifacts,))}}diff --git a/sources/vphone-cli/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swiftindex f9961e0c..c0f40709 100644--- a/sources/vphone-cli/VPhoneVMLaunchCLI.swift+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift@@ -5,7 +5,7 @@ import VPhoneCorestruct VPhoneVMLaunchCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "launch",- abstract: "Boot a VM bundle (runs host preflight first)"+ abstract: "Boot a VM bundle (runs host preflight first)",)@OptionGroup var lib: VPhoneLibraryOption@@ -42,9 +42,15 @@ struct VPhoneVMLaunchCommand: ParsableCommand {}var args = ["--config", bundle.configURL.path]- if dfu { args.append("--dfu") }- if headless { args.append("--headless") }- if let kernelDebugPort { args += ["--kernel-debug-port", String(kernelDebugPort)] }+ if dfu {+ args.append("--dfu")+ }+ if headless {+ args.append("--headless")+ }+ if let kernelDebugPort {+ args += ["--kernel-debug-port", String(kernelDebugPort)]+ }if v.tracesInternals {let (exe, spawned) = launcher.plan(args)@@ -54,7 +60,7 @@ struct VPhoneVMLaunchCommand: ParsableCommand {// `vm launch` always streams the guest serial console (inherits our// stdio); it is intentionally not gated on verbosity. run() also hands// the terminal to the child, which is what lets Ctrl-C reach the guest.- throw ExitCode(try launcher.run(args, cwd: bundle.url))+ throw try ExitCode(launcher.run(args, cwd: bundle.url))}}@@ -63,7 +69,7 @@ struct VPhoneVMLaunchCommand: ParsableCommand {struct VPhoneVMStopCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "stop",- abstract: "Stop a running VM bundle"+ abstract: "Stop a running VM bundle",)@OptionGroup var lib: VPhoneLibraryOption@@ -78,7 +84,7 @@ struct VPhoneVMStopCommand: ParsableCommand {func runningPIDs() -> [Int32] {guard let r = try? VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/sbin/lsof"),- ["-t", "--", disk.path]+ ["-t", "--", disk.path],) else { return [] }return VPhoneLsof.parsePIDs(r.stdout)}@@ -87,7 +93,9 @@ struct VPhoneVMStopCommand: ParsableCommand {guard !pids.isEmpty else { print("\(name): not running"); return }print("\(name): sending SIGINT to \(pids.map(String.init).joined(separator: ", "))")- for pid in pids { kill(pid, SIGINT) }+ for pid in pids {+ kill(pid, SIGINT)+ }var waited = 0while waited < timeout, !runningPIDs().isEmpty {@@ -97,7 +105,9 @@ struct VPhoneVMStopCommand: ParsableCommand {let survivors = runningPIDs()if !survivors.isEmpty {print("\(name): force-killing \(survivors.map(String.init).joined(separator: ", "))")- for pid in survivors { kill(pid, SIGKILL) }+ for pid in survivors {+ kill(pid, SIGKILL)+ }}print("\(name): stopped")}diff --git a/sources/vphone-cli/VPhoneVMSelection.swift b/sources/vphone-cli/VPhoneVMSelection.swiftindex 24e37306..58dff902 100644--- a/sources/vphone-cli/VPhoneVMSelection.swift+++ b/sources/vphone-cli/VPhoneVMSelection.swift@@ -2,30 +2,40 @@ import Foundationimport VPhoneCoreenum VPhoneVMSelection {- private static var isTTY: Bool { isatty(FileHandle.standardInput.fileDescriptor) != 0 }- private static func err(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }+ private static var isTTY: Bool {+ isatty(FileHandle.standardInput.fileDescriptor) != 0+ }++ private static func err(_ s: String) {+ FileHandle.standardError.write(Data((s + "\n").utf8))+ }/// Resolve an existing-VM name, prompting with a numbered picker when omitted.static func resolveExisting(_ provided: String?, in library: VPhoneLibrary) throws -> String {- if let provided, !provided.isEmpty { return provided } // supplied name → no library scan- let names = try library.bundles().map(\.name).sorted() // no-name path: propagate real scan errors+ if let provided, !provided.isEmpty {+ return provided+ } // supplied name → no library scan+ let names = try library.bundles().map(\.name).sorted() // no-name path: propagate real scan errorsreturn try VPhoneVMPicker.resolve(provided: nil,names: names,libraryRoot: library.root.path,isInteractive: isTTY,read: { readLine(strippingNewline: true) },- write: { err($0) }+ write: { err($0) },)}/// Resolve a NEW name (rename/clone destination): return it if given, else prompt for text.static func resolveNewName(_ provided: String?, prompt: String) throws -> String {- if let provided, !provided.isEmpty { return provided }+ if let provided, !provided.isEmpty {+ return provided+ }guard isTTY else { throw VPhoneVMPickerError.notInteractive }FileHandle.standardError.write(Data((prompt + " ").utf8))guard let line = readLine(strippingNewline: true)?- .trimmingCharacters(in: .whitespacesAndNewlines), !line.isEmpty else {+ .trimmingCharacters(in: .whitespacesAndNewlines), !line.isEmpty+ else {throw VPhoneVMPickerError.aborted}return linediff --git a/sources/vphone-cli/VPhoneVMTransferCLI.swift b/sources/vphone-cli/VPhoneVMTransferCLI.swiftindex 965ee168..3b73acb0 100644--- a/sources/vphone-cli/VPhoneVMTransferCLI.swift+++ b/sources/vphone-cli/VPhoneVMTransferCLI.swift@@ -8,7 +8,7 @@ struct VPhoneVMCloneCommand: ParsableCommand {commandName: "clone",abstract: "Clone a VM bundle (fast APFS clone; resets device identity)",discussion: "The clone boots as a fresh device (nvram/machineIdentifier/shsh cleared). "- + "SEPStorage is copied as-is; a cloned, already-restored VM may need re-restoring."+ + "SEPStorage is copied as-is; a cloned, already-restored VM may need re-restoring.",)@OptionGroup var lib: VPhoneLibraryOption@@ -26,7 +26,7 @@ struct VPhoneVMCloneCommand: ParsableCommand {struct VPhoneVMExportCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "export",- abstract: "Export a VM bundle to a compressed archive (.tzst, or .txz with --max)"+ abstract: "Export a VM bundle to a compressed archive (.tzst, or .txz with --max)",)@OptionGroup var lib: VPhoneLibraryOption@@ -45,7 +45,7 @@ struct VPhoneVMExportCommand: ParsableCommand {includeIPSW: includeIpsw,compression: compression,in: lib.library,- progress: { done, total in bar.update(done: done, total: total) }+ progress: { done, total in bar.update(done: done, total: total) },)bar.finish()print("exported \(name) → \(outURL.path)")@@ -55,7 +55,7 @@ struct VPhoneVMExportCommand: ParsableCommand {struct VPhoneVMImportCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "import",- abstract: "Import a VM bundle from a compressed archive (compressor auto-detected)"+ abstract: "Import a VM bundle from a compressed archive (compressor auto-detected)",)@OptionGroup var lib: VPhoneLibraryOption@@ -68,7 +68,7 @@ struct VPhoneVMImportCommand: ParsableCommand {from: URL(fileURLWithPath: input),name: name,in: lib.library,- progress: { done, total in bar.update(done: done, total: total) }+ progress: { done, total in bar.update(done: done, total: total) },)bar.finish()print("imported → \(bundle.name)")diff --git a/sources/vphone-cli/main.swift b/sources/vphone-cli/main.swiftindex e9e6cefb..85a5bf89 100644--- a/sources/vphone-cli/main.swift+++ b/sources/vphone-cli/main.swift@@ -23,7 +23,9 @@ do {// `boot` is a request for a guest, not work this process does. Hand it// to vphone-vm and report back whatever the guest exits with.let status = try VPhoneGuestLaunchPlanner().run(boot.bootArguments)- if status != 0 { throw ExitCode(status) }+ if status != 0 {+ throw ExitCode(status)+ }default:var runnable = commanddiff --git a/tests/FirmwarePatcherTests/ARM64EncoderTests.swift b/tests/FirmwarePatcherTests/ARM64EncoderTests.swiftindex 03aa1df2..e5d62db7 100644--- a/tests/FirmwarePatcherTests/ARM64EncoderTests.swift+++ b/tests/FirmwarePatcherTests/ARM64EncoderTests.swift@@ -35,7 +35,9 @@ struct ARM64EncodingCase: Sendable, CustomStringConvertible {/// The patcher call site this instruction comes from, or the field being covered.let origin: String- var description: String { "\(source) [\(origin)]" }+ var description: String {+ "\(source) [\(origin)]"+ }}private func word(_ data: Data) -> UInt32 {@@ -64,81 +66,81 @@ struct ARM64EncoderKeystoneParityTests {ARM64EncodingCase(source: "mov w0, #0", keystone: 0x5280_0000,encoded: ARM64Encoder.encodeMovzW(rd: 0, imm16: 0),- origin: #"camera_dsc asm("mov w0, #0\nret")"#+ origin: #"camera_dsc asm("mov w0, #0\nret")"#,),// asm("mov w0, #3\nret")ARM64EncodingCase(source: "mov w0, #3", keystone: 0x5280_0060,encoded: ARM64Encoder.encodeMovzW(rd: 0, imm16: 3),- origin: #"camera_dsc asm("mov w0, #3\nret")"#+ origin: #"camera_dsc asm("mov w0, #3\nret")"#,),// asm_at(f"b #{kern_va}", pub_va) — redirect the public stub at its own addressARM64EncodingCase(source: "b #0x1010 @0x1000", keystone: 0x1400_0004,encoded: ARM64Encoder.encodeB(from: 0x1000, to: 0x1010),- origin: #"iomfb_force_kern asm_at("b #{kern_va}", pub_va)"#+ origin: #"iomfb_force_kern asm_at("b #{kern_va}", pub_va)"#,),// asm_at(f"b #0x{patch_target:X}", patch_off) — the same shape, backwardsARM64EncodingCase(source: "b #0x1000 @0x2000", keystone: 0x17FF_FC00,encoded: ARM64Encoder.encodeB(from: 0x2000, to: 0x1000),- origin: #"jetsam asm_at("b #{patch_target}", patch_off)"#+ origin: #"jetsam asm_at("b #{patch_target}", patch_off)"#,),// asm(f"mov w3, #{target_size}"), where TARGET_SIZE == 0x588ARM64EncodingCase(source: "mov w3, #0x588", keystone: 0x5280_B103,encoded: ARM64Encoder.encodeMovzW(rd: 3, imm16: 0x588),- origin: #"iomfb_swapend asm("mov w3, #{target_size}")"#+ origin: #"iomfb_swapend asm("mov w3, #{target_size}")"#,),// The next seven build the SwapEnd call-setup sequence in _self_test().ARM64EncodingCase(source: "ldr w0, [x0, #0x14]", keystone: 0xB940_1400,encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 0, offset: 0x14),- origin: #"iomfb_swapend asm("ldr w0, [x0, #0x14]")"#+ origin: #"iomfb_swapend asm("ldr w0, [x0, #0x14]")"#,),ARM64EncodingCase(source: "add x2, x19, #0x18", keystone: 0x9100_6262,encoded: ARM64Encoder.encodeAddImm12(rd: 2, rn: 19, imm12: 0x18),- origin: #"iomfb_swapend asm("add x2, x19, #0x18")"#+ origin: #"iomfb_swapend asm("add x2, x19, #0x18")"#,),ARM64EncodingCase(source: "mov w1, #5", keystone: 0x5280_00A1,encoded: ARM64Encoder.encodeMovzW(rd: 1, imm16: 5),- origin: #"iomfb_swapend asm("mov w1, #5")"#+ origin: #"iomfb_swapend asm("mov w1, #5")"#,),ARM64EncodingCase(source: "mov w3, #0x548", keystone: 0x5280_A903,encoded: ARM64Encoder.encodeMovzW(rd: 3, imm16: 0x548),- origin: #"iomfb_swapend asm("mov w3, #0x548")"#+ origin: #"iomfb_swapend asm("mov w3, #0x548")"#,),ARM64EncodingCase(source: "mov x4, #0", keystone: 0xD280_0004,encoded: ARM64Encoder.encodeMovzX(rd: 4, imm16: 0),- origin: #"iomfb_swapend asm("mov x4, #0")"#+ origin: #"iomfb_swapend asm("mov x4, #0")"#,),ARM64EncodingCase(source: "mov x5, #0", keystone: 0xD280_0005,encoded: ARM64Encoder.encodeMovzX(rd: 5, imm16: 0),- origin: #"iomfb_swapend asm("mov x5, #0")"#+ origin: #"iomfb_swapend asm("mov x5, #0")"#,),// asm("bl #0x40") — plain asm(), so keystone assembles it at address 0.ARM64EncodingCase(source: "bl #0x40 @0x0", keystone: 0x9400_0010,encoded: ARM64Encoder.encodeBL(from: 0, to: 0x40),- origin: #"iomfb_swapend asm("bl #0x40")"#+ origin: #"iomfb_swapend asm("bl #0x40")"#,),// asm(f"mov {m['cset_reg']}, #1") — cset_reg is always a W register; the// matcher rejects any destination that does not start with "w".ARM64EncodingCase(source: "mov w8, #1", keystone: 0x5280_0028,encoded: ARM64Encoder.encodeMovzW(rd: 8, imm16: 1),- origin: #"watchdogd asm("mov {cset_reg}, #1")"#+ origin: #"watchdogd asm("mov {cset_reg}, #1")"#,),// asm("cset w0, eq") — the one instruction with no encoder before this changeARM64EncodingCase(source: "cset w0, eq", keystone: 0x1A9F_17E0,encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .eq),- origin: #"xpc_lwcr asm("cset w0, eq")"#+ origin: #"xpc_lwcr asm("cset w0, eq")"#,),]@@ -148,206 +150,206 @@ struct ARM64EncoderKeystoneParityTests {// --- encodeB: both signs, and both ends of the imm26 range -------ARM64EncodingCase(source: "b #0x7FFFFFC @0x0", keystone: 0x15FF_FFFF,- encoded: ARM64Encoder.encodeB(from: 0, to: 0x7FF_FFFC),- origin: "B max forward"+ encoded: ARM64Encoder.encodeB(from: 0, to: 0x7FFFFFC),+ origin: "B max forward",),ARM64EncodingCase(source: "b #0x0 @0x8000000", keystone: 0x1600_0000,- encoded: ARM64Encoder.encodeB(from: 0x800_0000, to: 0),- origin: "B max backward"+ encoded: ARM64Encoder.encodeB(from: 0x8000000, to: 0),+ origin: "B max backward",),// --- encodeBL ----------------------------------------------------ARM64EncodingCase(source: "bl #0x1100 @0x1000", keystone: 0x9400_0040,encoded: ARM64Encoder.encodeBL(from: 0x1000, to: 0x1100),- origin: "BL forward"+ origin: "BL forward",),ARM64EncodingCase(source: "bl #0x2000 @0x3000", keystone: 0x97FF_FC00,encoded: ARM64Encoder.encodeBL(from: 0x3000, to: 0x2000),- origin: "BL backward"+ origin: "BL backward",),// --- encodeTestBitBranch: b5 both ways, TBZ and TBNZ, both signs --ARM64EncodingCase(source: "tbz w8, #0xb, #0x14", keystone: 0x3658_00A8,encoded: ARM64Encoder.encodeTestBitBranch(- nonzero: false, register: 8, bit: 11, from: 0, to: 0x14+ nonzero: false, register: 8, bit: 11, from: 0, to: 0x14,),- origin: "TBZ W, bit<32"+ origin: "TBZ W, bit<32",),ARM64EncodingCase(source: "tbz w8, #0xa, #0x14", keystone: 0x3650_00A8,encoded: ARM64Encoder.encodeTestBitBranch(- nonzero: false, register: 8, bit: 10, from: 0, to: 0x14+ nonzero: false, register: 8, bit: 10, from: 0, to: 0x14,),- origin: "TBZ W, bit<32"+ origin: "TBZ W, bit<32",),ARM64EncodingCase(source: "tbnz w0, #0, #0x8", keystone: 0x3700_0040,encoded: ARM64Encoder.encodeTestBitBranch(- nonzero: true, register: 0, bit: 0, from: 0, to: 8+ nonzero: true, register: 0, bit: 0, from: 0, to: 8,),- origin: "TBNZ bit 0"+ origin: "TBNZ bit 0",),ARM64EncodingCase(source: "tbz x9, #32, #0x40", keystone: 0xB600_0209,encoded: ARM64Encoder.encodeTestBitBranch(- nonzero: false, register: 9, bit: 32, from: 0, to: 0x40+ nonzero: false, register: 9, bit: 32, from: 0, to: 0x40,),- origin: "TBZ X, b5 set"+ origin: "TBZ X, b5 set",),ARM64EncodingCase(source: "tbnz x3, #63, #0x0 @0x100", keystone: 0xB7FF_F803,encoded: ARM64Encoder.encodeTestBitBranch(- nonzero: true, register: 3, bit: 63, from: 0x100, to: 0+ nonzero: true, register: 3, bit: 63, from: 0x100, to: 0,),- origin: "TBNZ bit 63, backward"+ origin: "TBNZ bit 63, backward",),// --- encodeADRP: forward, backward, and same page ----------------ARM64EncodingCase(source: "adrp x2, #0x5000 @0x1000", keystone: 0x9000_0022,encoded: ARM64Encoder.encodeADRP(rd: 2, pc: 0x1000, target: 0x5000),- origin: "ADRP forward"+ origin: "ADRP forward",),ARM64EncodingCase(source: "adrp x0, #0x1000 @0x9000", keystone: 0x90FF_FFC0,encoded: ARM64Encoder.encodeADRP(rd: 0, pc: 0x9000, target: 0x1000),- origin: "ADRP backward"+ origin: "ADRP backward",),ARM64EncodingCase(source: "adrp x17, #0x1000 @0x1FFF", keystone: 0x9000_0011,encoded: ARM64Encoder.encodeADRP(rd: 17, pc: 0x1FFF, target: 0x1000),- origin: "ADRP same page, unaligned PC"+ origin: "ADRP same page, unaligned PC",),// --- encodeAddImm12 ----------------------------------------------ARM64EncodingCase(source: "add x2, x2, #0xabc", keystone: 0x912A_F042,encoded: ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: 0xABC),- origin: "ADD imm12"+ origin: "ADD imm12",),ARM64EncodingCase(source: "add x0, x0, #0", keystone: 0x9100_0000,encoded: ARM64Encoder.encodeAddImm12(rd: 0, rn: 0, imm12: 0),- origin: "ADD imm12 = 0"+ origin: "ADD imm12 = 0",),// --- encodeMovzW / encodeMovzX: every legal hw --------------------ARM64EncodingCase(source: "movz w5, #0x1234, lsl #16", keystone: 0x52A2_4685,encoded: ARM64Encoder.encodeMovzW(rd: 5, imm16: 0x1234, shift: 16),- origin: "MOVZ W hw=1"+ origin: "MOVZ W hw=1",),ARM64EncodingCase(source: "movz x3, #0x4000", keystone: 0xD288_0003,encoded: ARM64Encoder.encodeMovzX(rd: 3, imm16: 0x4000, shift: 0),- origin: "MOVZ X hw=0"+ origin: "MOVZ X hw=0",),ARM64EncodingCase(source: "movz x9, #0xbeef, lsl #32", keystone: 0xD2D7_DDE9,encoded: ARM64Encoder.encodeMovzX(rd: 9, imm16: 0xBEEF, shift: 32),- origin: "MOVZ X hw=2"+ origin: "MOVZ X hw=2",),ARM64EncodingCase(source: "movz x1, #0xdead, lsl #48", keystone: 0xD2FB_D5A1,encoded: ARM64Encoder.encodeMovzX(rd: 1, imm16: 0xDEAD, shift: 48),- origin: "MOVZ X hw=3"+ origin: "MOVZ X hw=3",),// --- encodeMovX ---------------------------------------------------ARM64EncodingCase(source: "mov x0, x20", keystone: 0xAA14_03E0,encoded: ARM64Encoder.encodeMovX(rd: 0, rm: 20),- origin: "MOV X reg"+ origin: "MOV X reg",),ARM64EncodingCase(source: "mov x9, xzr", keystone: 0xAA1F_03E9,encoded: ARM64Encoder.encodeMovX(rd: 9, rm: 31),- origin: "MOV X from XZR"+ origin: "MOV X from XZR",),ARM64EncodingCase(source: "mov x30, x1", keystone: 0xAA01_03FE,encoded: ARM64Encoder.encodeMovX(rd: 30, rm: 1),- origin: "MOV X high Rd"+ origin: "MOV X high Rd",),// --- encodeCsetW: all 14 conditions, plus other destinations ------ARM64EncodingCase(source: "cset w0, ne", keystone: 0x1A9F_07E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ne), origin: "CSET ne"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ne), origin: "CSET ne",),ARM64EncodingCase(source: "cset w0, hs", keystone: 0x1A9F_37E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .hs), origin: "CSET hs"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .hs), origin: "CSET hs",),ARM64EncodingCase(source: "cset w0, lo", keystone: 0x1A9F_27E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .lo), origin: "CSET lo"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .lo), origin: "CSET lo",),ARM64EncodingCase(source: "cset w0, mi", keystone: 0x1A9F_57E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .mi), origin: "CSET mi"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .mi), origin: "CSET mi",),ARM64EncodingCase(source: "cset w0, pl", keystone: 0x1A9F_47E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .pl), origin: "CSET pl"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .pl), origin: "CSET pl",),ARM64EncodingCase(source: "cset w0, vs", keystone: 0x1A9F_77E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .vs), origin: "CSET vs"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .vs), origin: "CSET vs",),ARM64EncodingCase(source: "cset w0, vc", keystone: 0x1A9F_67E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .vc), origin: "CSET vc"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .vc), origin: "CSET vc",),ARM64EncodingCase(source: "cset w0, hi", keystone: 0x1A9F_97E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .hi), origin: "CSET hi"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .hi), origin: "CSET hi",),ARM64EncodingCase(source: "cset w0, ls", keystone: 0x1A9F_87E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ls), origin: "CSET ls"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ls), origin: "CSET ls",),ARM64EncodingCase(source: "cset w0, ge", keystone: 0x1A9F_B7E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ge), origin: "CSET ge"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ge), origin: "CSET ge",),ARM64EncodingCase(source: "cset w0, lt", keystone: 0x1A9F_A7E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .lt), origin: "CSET lt"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .lt), origin: "CSET lt",),ARM64EncodingCase(source: "cset w0, gt", keystone: 0x1A9F_D7E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .gt), origin: "CSET gt"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .gt), origin: "CSET gt",),ARM64EncodingCase(source: "cset w0, le", keystone: 0x1A9F_C7E0,- encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .le), origin: "CSET le"+ encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .le), origin: "CSET le",),ARM64EncodingCase(source: "cset w8, ne", keystone: 0x1A9F_07E8,- encoded: ARM64Encoder.encodeCsetW(rd: 8, condition: .ne), origin: "CSET Rd=8"+ encoded: ARM64Encoder.encodeCsetW(rd: 8, condition: .ne), origin: "CSET Rd=8",),ARM64EncodingCase(source: "cset w19, eq", keystone: 0x1A9F_17F3,- encoded: ARM64Encoder.encodeCsetW(rd: 19, condition: .eq), origin: "CSET Rd=19"+ encoded: ARM64Encoder.encodeCsetW(rd: 19, condition: .eq), origin: "CSET Rd=19",),// --- encodeLdrWUnsignedOffset: zero, SP base, both imm12 ends -----ARM64EncodingCase(source: "ldr w7, [x19]", keystone: 0xB940_0267,encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 7, rn: 19, offset: 0),- origin: "LDR W offset 0"+ origin: "LDR W offset 0",),ARM64EncodingCase(source: "ldr w8, [sp, #0xcc]", keystone: 0xB940_CFE8,encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 8, rn: 31, offset: 0xCC),- origin: "LDR W base = SP"+ origin: "LDR W base = SP",),ARM64EncodingCase(source: "ldr w8, [x0, #0x454]", keystone: 0xB944_5408,encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 8, rn: 0, offset: 0x454),- origin: "LDR W mid offset"+ origin: "LDR W mid offset",),ARM64EncodingCase(source: "ldr w30, [x29, #0x3ffc]", keystone: 0xB97F_FFBE,encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 30, rn: 29, offset: 0x3FFC),- origin: "LDR W max imm12"+ origin: "LDR W max imm12",),]@@ -356,7 +358,7 @@ struct ARM64EncoderKeystoneParityTests {// MARK: Parity@Test(arguments: ARM64EncoderKeystoneParityTests.allCases)- func matchesKeystone(_ testCase: ARM64EncodingCase) throws {+ func `matches keystone`(_ testCase: ARM64EncodingCase) throws {let data = try #require(testCase.encoded, "encoder refused \(testCase.source)")#expect(data.count == 4, "\(testCase.source): expected 4 bytes, got \(data.count)")let produced = word(data)@@ -366,21 +368,21 @@ struct ARM64EncoderKeystoneParityTests {\(testCase.source) [\(testCase.origin)]ARM64Encoder: 0x\(String(produced, radix: 16, uppercase: true))keystone: 0x\(String(testCase.keystone, radix: 16, uppercase: true))- """+ """,)}/// Every `asm(...)` site the patchers had is represented, and each one/// disassembles back to the mnemonic the Python source named.@Test(arguments: ARM64EncoderKeystoneParityTests.allCases)- func roundTripsThroughCapstone(_ testCase: ARM64EncodingCase) throws {+ func `round trips through capstone`(_ testCase: ARM64EncodingCase) throws {let data = try #require(testCase.encoded)let disasm = ARM64Disassembler()// Address 0 is fine: only the mnemonic is asserted, and the keystone parity// test above already pins the PC-relative operand bits exactly.let insn = try #require(disasm.disassembleOne(data, at: 0),- "capstone could not decode \(testCase.source)"+ "capstone could not decode \(testCase.source)",)let expectedMnemonic = String(testCase.source.prefix(while: { $0 != " " }))// A MOVZ with any `hw` is expressible as MOV (wide immediate), and capstone@@ -390,7 +392,7 @@ struct ARM64EncoderKeystoneParityTests {: [expectedMnemonic]#expect(accepted.contains(insn.mnemonic),- "\(testCase.source): capstone read it as '\(insn.mnemonic) \(insn.operandString)'"+ "\(testCase.source): capstone read it as '\(insn.mnemonic) \(insn.operandString)'",)}@@ -404,7 +406,7 @@ struct ARM64EncoderKeystoneParityTests {/// mnemonics (KS_ERR_ASM_MNEMONICFAIL). `pacibsp` is checked through its `hint/// #27` spelling, which keystone does accept; retaa/retab stay on the capstone/// round-trip in ARM64ConstantTests.- @Test func constantsMatchKeystone() {+ @Test func `constants match keystone`() {let expected: [(String, Data, UInt32)] = [("nop", ARM64.nop, 0xD503_201F),("ret", ARM64.ret, 0xD65F_03C0),@@ -431,7 +433,7 @@ struct ARM64EncoderKeystoneParityTests {/// The three constants that stand in for `asm()` results are byte-identical to/// the encoder path, so a patcher may use either without a behaviour change.- @Test func constantsAgreeWithEncoders() {+ @Test func `constants agree with encoders`() {#expect(ARM64.movX0_1 == ARM64Encoder.encodeMovzX(rd: 0, imm16: 1))#expect(ARM64.movX0_0 == ARM64Encoder.encodeMovzX(rd: 0, imm16: 0))#expect(ARM64.movW0_0 == ARM64Encoder.encodeMovzW(rd: 0, imm16: 0))@@ -445,51 +447,51 @@ struct ARM64EncoderKeystoneParityTests {struct ARM64EncoderRangeTests {// MARK: Branches- @Test func branchRefusesUnalignedAndOutOfRange() {+ @Test func `branch refuses unaligned and out of range`() {#expect(ARM64Encoder.encodeB(from: 0, to: 2) == nil, "unaligned target")- #expect(ARM64Encoder.encodeB(from: 0, to: 0x800_0000) == nil, "one past +128 MB")- #expect(ARM64Encoder.encodeB(from: 0x800_0004, to: 0) == nil, "one past -128 MB")+ #expect(ARM64Encoder.encodeB(from: 0, to: 0x8000000) == nil, "one past +128 MB")+ #expect(ARM64Encoder.encodeB(from: 0x8000004, to: 0) == nil, "one past -128 MB")#expect(ARM64Encoder.encodeBL(from: 0, to: 1) == nil, "unaligned target")- #expect(ARM64Encoder.encodeBL(from: 0, to: 0x800_0000) == nil, "one past +128 MB")+ #expect(ARM64Encoder.encodeBL(from: 0, to: 0x8000000) == nil, "one past +128 MB")}- @Test func testBitBranchRefusesBadOperands() {+ @Test func `bit branch refuses bad operands`() {#expect(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 32, bit: 0, from: 0, to: 4) == nil,- "register out of range"+ "register out of range",)#expect(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 0, bit: 64, from: 0, to: 4) == nil,- "bit out of range"+ "bit out of range",)#expect(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 0, bit: 0, from: 0, to: 0x8000) == nil,- "one past +32 KB"+ "one past +32 KB",)}// MARK: ADRP / ADD / MOVZ- @Test func adrpAndAddRefuseOutOfRange() {+ @Test func `adrp and add refuse out of range`() {// ADRP reaches +/-4 GB; one page past that must be refused.#expect(ARM64Encoder.encodeADRP(rd: 0, pc: 0, target: 1 << 32) == nil)#expect(ARM64Encoder.encodeAddImm12(rd: 0, rn: 0, imm12: 4096) == nil)}- @Test func movzRefusesUnrepresentableShift() {+ @Test func `movz refuses unrepresentable shift`() {#expect(ARM64Encoder.encodeMovzW(rd: 0, imm16: 1, shift: 32) == nil, "W has hw 0..1")#expect(ARM64Encoder.encodeMovzX(rd: 0, imm16: 1, shift: 64) == nil, "X has hw 0..3")}// MARK: CSET- @Test func csetRefusesInvalidRegister() {+ @Test func `cset refuses invalid register`() {#expect(ARM64Encoder.encodeCsetW(rd: 32, condition: .eq) == nil)}/// CSET encodes the inverse of the written condition, so inverting twice has to/// be the identity — otherwise the alias silently means the opposite thing.- @Test func conditionInversionIsAnInvolution() {+ @Test func `condition inversion is an involution`() {for condition in ARM64Condition.allCases {#expect(condition.inverted.inverted == condition, "\(condition) inverted twice")#expect(condition.inverted != condition, "\(condition) is its own inverse")@@ -499,14 +501,14 @@ struct ARM64EncoderRangeTests {// MARK: LDR- @Test func ldrRefusesUnscalableOffsets() {+ @Test func `ldr refuses unscalable offsets`() {#expect(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 0, offset: 0x13) == nil,- "offset must be a multiple of 4"+ "offset must be a multiple of 4",)#expect(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 0, offset: 0x4000) == nil,- "one past the scaled imm12 range"+ "one past the scaled imm12 range",)#expect(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 32, rn: 0, offset: 0) == nil)#expect(ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 32, offset: 0) == nil)@@ -517,9 +519,9 @@ struct ARM64EncoderRangeTests {/// `decodeBranchTarget` is the inverse of `encodeB` / `encodeBL`; the two must/// agree, because the patchers use the decoder to find the site they then/// re-encode.- @Test func decodeBranchTargetInvertsEncode() throws {+ @Test func `decode branch target inverts encode`() throws {let sites: [(UInt64, UInt64)] = [- (0x1000, 0x1010), (0x2000, 0x1000), (0, 0x40), (0x800_0000, 0),+ (0x1000, 0x1010), (0x2000, 0x1000), (0, 0x40), (0x8000000, 0),]for (pc, target) in sites {let branch = try #require(ARM64Encoder.encodeB(from: Int(pc), to: Int(target)))@@ -533,7 +535,7 @@ struct ARM64EncoderRangeTests {}}- @Test func decodeBranchTargetRejectsNonBranches() {+ @Test func `decode branch target rejects non branches`() {#expect(ARM64Encoder.decodeBranchTarget(insn: ARM64.nopU32, pc: 0) == nil)#expect(ARM64Encoder.decodeBranchTarget(insn: ARM64.retU32, pc: 0) == nil)}diff --git a/tests/FirmwarePatcherTests/CFWCacheloaderTests.swift b/tests/FirmwarePatcherTests/CFWCacheloaderTests.swiftindex e62c0a02..791aa8aa 100644--- a/tests/FirmwarePatcherTests/CFWCacheloaderTests.swift+++ b/tests/FirmwarePatcherTests/CFWCacheloaderTests.swift@@ -48,7 +48,9 @@ private enum CacheLoaderFixture {}/// The suite runs unless the binary is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 launchd_cache_loader is required — put it at \@@ -75,7 +77,7 @@ private enum CacheLoaderFixture {/// SHA-256 as `shasum -a 256` prints it, so a digest asserted here can be/// taken again from a shell over the same file.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}/// Clone the pristine binary into a file the caller may write to.@@ -89,7 +91,7 @@ private enum CacheLoaderFixture {let pristine = try #require(self.pristine, missing)try FileManager.default.createDirectory(at: scratchRoot,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let destination = scratchRoot.appendingPathComponent(name)try? FileManager.default.removeItem(at: destination)@@ -97,9 +99,11 @@ private enum CacheLoaderFixture {for flags in [["-c"], []] {let result = try Shell.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: flags + [pristine.path, destination.path]+ arguments: flags + [pristine.path, destination.path],)- if result.status == 0 { return destination }+ if result.status == 0 {+ return destination+ }}Issue.record("could not clone \(pristine.path) to \(destination.path)")throw CocoaError(.fileWriteUnknown)@@ -124,11 +128,13 @@ private enum CacheLoaderFixture {static func codesignVerify(_ binary: URL) throws -> Shell.Result {try Shell.run(executable: URL(fileURLWithPath: "/usr/bin/codesign"),- arguments: ["-v", "--verbose=2", binary.path]+ arguments: ["-v", "--verbose=2", binary.path],)}- static func bytes(of url: URL) throws -> Data { try Data(contentsOf: url) }+ static func bytes(of url: URL) throws -> Data {+ try Data(contentsOf: url)+ }}// MARK: - Subprocess helper@@ -138,19 +144,23 @@ private enum Shell {let status: Int32let stdout: Stringlet stderr: String- var output: String { stdout + stderr }+ var output: String {+ stdout + stderr+ }}@discardableResultstatic func run(executable: URL,arguments: [String],- currentDirectory: URL? = nil+ currentDirectory: URL? = nil,) throws -> Result {let process = Process()process.executableURL = executableprocess.arguments = arguments- if let currentDirectory { process.currentDirectoryURL = currentDirectory }+ if let currentDirectory {+ process.currentDirectoryURL = currentDirectory+ }let out = Pipe()let err = Pipe()process.standardOutput = out@@ -162,7 +172,7 @@ private enum Shell {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -222,13 +232,13 @@ private enum ByteComparison {@Suite("launchd_cache_loader gate discovery",- .enabled(if: CacheLoaderFixture.runs, CacheLoaderFixture.missing)+ .enabled(if: CacheLoaderFixture.runs, CacheLoaderFixture.missing),)struct CFWCacheLoaderGateTests {- @Test("the anchor is the whole launchd_unsecure_cache= literal, found in __cstring")- func anchorIsTheBootArgLiteral() throws {+ @Test+ func `the anchor is the whole launchd_unsecure_cache= literal, found in __cstring`() throws {let data = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let located = try CFWCacheLoaderPatcher.locateGate(in: data)let anchor = located.anchor@@ -246,10 +256,10 @@ struct CFWCacheLoaderGateTests {#expect(data[anchor.stringFileOffset - 1] == 0)}- @Test("the xref is an ADRP+ADD that really computes the literal's address")- func referenceComputesTheString() throws {+ @Test+ func `the xref is an ADRP+ADD that really computes the literal's address`() throws {let data = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let anchor = try CFWCacheLoaderPatcher.locateGate(in: data).anchorlet sections = MachOParser.parseSections(from: data)@@ -259,10 +269,10 @@ struct CFWCacheLoaderGateTests {// Recomputed here from the two instructions, independently of how the// patcher found them: page(ADRP) + imm(ADD) has to be the literal.let adrp = try #require(disassembler.disassembleOne(- in: data, at: anchor.referenceFileOffset, address: anchor.referenceVMA+ in: data, at: anchor.referenceFileOffset, address: anchor.referenceVMA,))let add = try #require(disassembler.disassembleOne(- in: data, at: anchor.referenceFileOffset + 4, address: anchor.referenceVMA + 4+ in: data, at: anchor.referenceFileOffset + 4, address: anchor.referenceVMA + 4,))#expect(adrp.mnemonic == "adrp")#expect(add.mnemonic == "add")@@ -277,10 +287,10 @@ struct CFWCacheLoaderGateTests {#expect(anchor.referenceVMA < text.address + text.size)}- @Test("the gate is a forward cbz on the boot-arg lookup's result")- func gateShape() throws {+ @Test+ func `the gate is a forward cbz on the boot-arg lookup's result`() throws {let data = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let located = try CFWCacheLoaderPatcher.locateGate(in: data)let gate = located.gate@@ -297,10 +307,10 @@ struct CFWCacheLoaderGateTests {#expect(target > gate.vma)}- @Test("the fixture's code directory is the SHA-256, short-tail shape this port assumes")- func fixtureSignatureShape() throws {+ @Test+ func `the fixture's code directory is the SHA-256, short-tail shape this port assumes`() throws {let data = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let directories = try #require(CFWMachOCodeSignature.codeDirectories(in: data))let directory = try #require(directories.first)@@ -319,7 +329,7 @@ struct CFWCacheLoaderGateTests {let bounds = try #require(CFWMachOCodeSignature.pageBounds(fileOffset: gate.fileOffset,pageSize: directory.pageSize,- codeLimit: directory.codeLimit+ codeLimit: directory.codeLimit,))#expect(bounds.index == 0)}@@ -330,14 +340,14 @@ struct CFWCacheLoaderGateTests {@Suite("launchd_cache_loader parity",.enabled(if: CacheLoaderFixture.runs, CacheLoaderFixture.missing),- .serialized+ .serialized,)struct CFWCacheLoaderParityTests {/// The fixture the frozen digests were taken over. Without this a digest/// mismatch below would read as a patcher bug when the real cause is a/// different firmware's `launchd_cache_loader`.- @Test("the fixture is the one the goldens were recorded from")- func fixtureMatchesTheGoldens() throws {+ @Test+ func `the fixture is the one the goldens were recorded from`() throws {let pristine = try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)#expect(try CacheLoaderFixture.digest(of: pristine) == CacheLoaderGolden.pristine,@@ -345,12 +355,12 @@ struct CFWCacheLoaderParityTests {this is not the 24A435 launchd_cache_loader CacheLoaderGolden was \recorded from — re-derive the goldens before reading a failure \below as a patcher bug- """+ """,)}- @Test("Swift reproduces the reference's bytes")- func byteForByteParity() throws {+ @Test+ func `Swift reproduces the reference's bytes`() throws {let swiftClone = try CacheLoaderFixture.clone(named: "swift")defer { CacheLoaderFixture.discard(swiftClone) }@@ -364,17 +374,17 @@ struct CFWCacheLoaderParityTests {#expect(try CacheLoaderFixture.digest(of: swiftClone) == CacheLoaderGolden.patched,- "Swift and the frozen reference disagree"+ "Swift and the frozen reference disagree",)}- @Test("exactly one instruction changes, and it is the gate")- func onlyTheGateChanges() throws {+ @Test+ func `exactly one instruction changes, and it is the gate`() throws {let clone = try CacheLoaderFixture.clone(named: "single-site")defer { CacheLoaderFixture.discard(clone) }let pristine = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let report = try CFWCacheLoaderPatcher.patch(fileAt: clone, log: nil)let patched = try CacheLoaderFixture.bytes(of: clone)@@ -384,8 +394,8 @@ struct CFWCacheLoaderParityTests {#expect(patched[report.gate.fileOffset ..< report.gate.fileOffset + 4] == ARM64.nop)}- @Test("the record names the byte that changed, its address and the anchor")- func recordDescribesTheSite() throws {+ @Test+ func `the record names the byte that changed, its address and the anchor`() throws {let clone = try CacheLoaderFixture.clone(named: "record")defer { CacheLoaderFixture.discard(clone) }@@ -414,8 +424,8 @@ struct CFWCacheLoaderParityTests {/// before/after window starts two instructions ahead of the gate, and it/// once converted that negative delta with `UInt64(Int)` — a trap on every/// real patch that no `log: nil` test could see.- @Test("patching with logging on succeeds and prints the marked window")- func loggingPathDoesNotTrap() throws {+ @Test+ func `patching with logging on succeeds and prints the marked window`() throws {let clone = try CacheLoaderFixture.clone(named: "logged")defer { CacheLoaderFixture.discard(clone) }@@ -436,11 +446,11 @@ struct CFWCacheLoaderParityTests {@Suite("launchd_cache_loader re-runs",.enabled(if: CacheLoaderFixture.runs, CacheLoaderFixture.missing),- .serialized+ .serialized,)struct CFWCacheLoaderRerunTests {- @Test("a second run is a byte-for-byte no-op")- func secondRunChangesNothing() throws {+ @Test+ func `a second run is a byte-for-byte no-op`() throws {let clone = try CacheLoaderFixture.clone(named: "twice")defer { CacheLoaderFixture.discard(clone) }@@ -467,8 +477,8 @@ struct CFWCacheLoaderRerunTests {#expect(try CacheLoaderFixture.bytes(of: clone) == afterFirst)}- @Test("the reference double-applied where this port stops — the reason they diverge")- func referenceWasNotIdempotent() throws {+ @Test+ func `the reference double-applied where this port stops — the reason they diverge`() throws {let swiftClone = try CacheLoaderFixture.clone(named: "swift-twice")defer { CacheLoaderFixture.discard(swiftClone) }@@ -481,7 +491,7 @@ struct CFWCacheLoaderRerunTests {#expect(CacheLoaderGolden.secondRunOffsets.allSatisfy { !(CacheLoaderGolden.gateFileOffset ..< CacheLoaderGolden.gateFileOffset + 4).contains($0) },- "the reference's second write was a different instruction, not the gate again"+ "the reference's second write was a different instruction, not the gate again",)// The Swift half, measured: two runs land exactly on one reference run.@@ -494,7 +504,7 @@ struct CFWCacheLoaderRerunTests {// And the bytes the reference's second run would have touched are still// the instruction the pristine binary carries there.let pristine = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let patched = try CacheLoaderFixture.bytes(of: swiftClone)let second = CacheLoaderGolden.secondRunOffsets@@ -502,13 +512,13 @@ struct CFWCacheLoaderRerunTests {.allSatisfy { !second.contains($0) })}- @Test("a dry run locates the site and writes nothing")- func dryRunChangesNothing() throws {+ @Test+ func `a dry run locates the site and writes nothing`() throws {let clone = try CacheLoaderFixture.clone(named: "dry-run")defer { CacheLoaderFixture.discard(clone) }let pristine = try CacheLoaderFixture.bytes(- of: try #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing)+ of: #require(CacheLoaderFixture.pristine, CacheLoaderFixture.missing),)let report = try CFWCacheLoaderPatcher.patch(fileAt: clone, dryRun: true, log: nil)@@ -524,11 +534,11 @@ struct CFWCacheLoaderRerunTests {@Suite("launchd_cache_loader re-signing",.enabled(if: CacheLoaderFixture.runs, CacheLoaderFixture.missing),- .serialized+ .serialized,)struct CFWCacheLoaderSignatureTests {- @Test("the default output fails codesign, exactly as the reference's did")- func defaultOutputIsUnattested() throws {+ @Test+ func `the default output fails codesign, exactly as the reference's did`() throws {let swiftClone = try CacheLoaderFixture.clone(named: "unattested-swift")defer { CacheLoaderFixture.discard(swiftClone) }@@ -547,15 +557,15 @@ struct CFWCacheLoaderSignatureTests {#expect(try CacheLoaderFixture.digest(of: swiftClone) == CacheLoaderGolden.patched)}- @Test("re-attested output passes codesign and matches the reference's slot hashes")- func reattestedOutputVerifies() throws {+ @Test+ func `re-attested output passes codesign and matches the reference's slot hashes`() throws {let swiftClone = try CacheLoaderFixture.clone(named: "attested-swift")defer { CacheLoaderFixture.discard(swiftClone) }let report = try CFWCacheLoaderPatcher.patch(fileAt: swiftClone,reattestsCodeSignature: true,- log: nil+ log: nil,)#expect(report.outcome == .patched)let slot = try #require(report.reattestedSlots.first)@@ -573,12 +583,12 @@ struct CFWCacheLoaderSignatureTests {#expect(try CacheLoaderFixture.digest(of: swiftClone)== CacheLoaderGolden.patchedAndReattested,- "the re-attested slot hash must be the one the reference computed"+ "the re-attested slot hash must be the one the reference computed",)}- @Test("re-attesting an already-patched binary repairs it without moving an instruction")- func reattestRepairsAStaleSlot() throws {+ @Test+ func `re-attesting an already-patched binary repairs it without moving an instruction`() throws {let clone = try CacheLoaderFixture.clone(named: "repair")defer { CacheLoaderFixture.discard(clone) }@@ -590,7 +600,7 @@ struct CFWCacheLoaderSignatureTests {let report = try CFWCacheLoaderPatcher.patch(fileAt: clone,reattestsCodeSignature: true,- log: nil+ log: nil,)#expect(report.outcome == .alreadyPatched)#expect(report.sitesWritten == 0)diff --git a/tests/FirmwarePatcherTests/CFWDaemonsTests.swift b/tests/FirmwarePatcherTests/CFWDaemonsTests.swiftindex 84d7cca0..33d7532e 100644--- a/tests/FirmwarePatcherTests/CFWDaemonsTests.swift+++ b/tests/FirmwarePatcherTests/CFWDaemonsTests.swift@@ -1,7 +1,7 @@import CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing-@testable import FirmwarePatcher// MARK: - Plist semantics@@ -159,12 +159,13 @@ enum CFWDaemonsFixtures {@Suite("CFW daemon plist rewrites")struct CFWDaemonsTests {// MARK: - dropbear ProgramArguments+//// Both cases below came over verbatim from tests/test_dropbear_plist.py,// which covered this exact rewrite and which no runner ever invoked.- @Test("-R is dropped and the seeded host keys are appended")- func rewritesReadOnlyRootKeyGeneration() {+ @Test+ func `-R is dropped and the seeded host keys are appended`() {var daemon: PlistDict = ["ProgramArguments": ["/iosbinpack64/usr/local/bin/dropbear",@@ -187,8 +188,8 @@ struct CFWDaemonsTests {#expect(Array(strings.suffix(CFWDaemons.dropbearKeyArguments.count)) == CFWDaemons.dropbearKeyArguments)}- @Test("stale explicit -r key paths are replaced, not kept")- func replacesStaleExplicitKeyPaths() {+ @Test+ func `stale explicit -r key paths are replaced, not kept`() {var daemon: PlistDict = ["ProgramArguments": ["dropbear",@@ -210,25 +211,25 @@ struct CFWDaemonsTests {#expect(strings == ["dropbear", "-E", "-p", "22222"] + CFWDaemons.dropbearKeyArguments)}- @Test("an empty argument list is left alone — there is nothing to point at a key")- func leavesEmptyArgumentsAlone() {+ @Test+ func `an empty argument list is left alone — there is nothing to point at a key`() {var daemon: PlistDict = ["ProgramArguments": [String]()]CFWDaemons.patchDropbearDaemon(&daemon)#expect((daemon["ProgramArguments"] as? [Any])?.isEmpty == true)}- @Test("a trailing -r with no path does not read past the end")- func toleratesTrailingKeyFlag() {+ @Test+ func `a trailing -r with no path does not read past the end`() {#expect(CFWDaemons.patchedDropbearArguments(["dropbear", "-r"]).compactMap { $0 as? String }- == ["dropbear"] + CFWDaemons.dropbearKeyArguments+ == ["dropbear"] + CFWDaemons.dropbearKeyArguments,)}// MARK: - Cryptex paths- @Test("Cryptex paths are found in a later identity, not just the first")- func cryptexPathsSearchesEveryIdentity() throws {+ @Test+ func `Cryptex paths are found in a later identity, not just the first`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -251,8 +252,8 @@ struct CFWDaemonsTests {#expect(paths.appOS == "043-69297-784.dmg")}- @Test("an identity carrying only one of the two is not a match")- func cryptexPathsNeedsBoth() throws {+ @Test+ func `an identity carrying only one of the two is not a match`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -271,8 +272,8 @@ struct CFWDaemonsTests {// MARK: - launchd.plist injection- @Test("injection creates LaunchDaemons when the target has none")- func injectionCreatesLaunchDaemonsDictionary() throws {+ @Test+ func `injection creates LaunchDaemons when the target has none`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -281,7 +282,7 @@ struct CFWDaemonsTests {try CFWDaemons.inject([CFWDaemons.Daemon(name: "vphoned", contents: ["Label": "vphoned"])],- into: launchd+ into: launchd,)let result = try CFWDaemons.loadPlist(launchd)@@ -290,8 +291,8 @@ struct CFWDaemonsTests {#expect(result["VersionNumber"] as? Int == 1)}- @Test("injecting twice replaces rather than duplicates, so a re-run is safe")- func injectionIsIdempotent() throws {+ @Test+ func `injecting twice replaces rather than duplicates, so a re-run is safe`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -308,8 +309,8 @@ struct CFWDaemonsTests {#expect((second["LaunchDaemons"] as? PlistDict)?.count == 1)}- @Test("a daemon absent from the staging directory is reported, not fatal")- func missingDaemonsAreReported() throws {+ @Test+ func `a daemon absent from the staging directory is reported, not fatal`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -326,11 +327,13 @@ struct CFWDaemonsTests {// Scan order, not injected-then-missing: the caller logs one line each,// and those lines have always come out in the order the names are tried.#expect(staged.count == CFWDaemons.defaultDaemonNames.count)- if case .present = staged[0] {} else { Issue.record("bash should be first in scan order") }+ if case .present = staged[0] {} else {+ Issue.record("bash should be first in scan order")+ }}- @Test("the directory loader applies the dropbear rewrite on its way through")- func directoryLoaderPatchesDropbear() throws {+ @Test+ func `the directory loader applies the dropbear rewrite on its way through`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -338,7 +341,7 @@ struct CFWDaemonsTests {try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)try CFWDaemons.savePlist(["ProgramArguments": ["dropbear", "-R"]],- to: staging.appending(path: "dropbear.plist")+ to: staging.appending(path: "dropbear.plist"),)let staged = try CFWDaemons.loadDaemons(inDirectory: staging, names: ["dropbear"])@@ -347,38 +350,39 @@ struct CFWDaemonsTests {#expect(arguments == ["dropbear"] + CFWDaemons.dropbearKeyArguments)}- @Test("the installed label, not the source filename, is what launchd keys on")- func launchdKeyComesFromTheInstalledLabel() {+ @Test+ func `the installed label, not the source filename, is what launchd keys on`() {let daemon = CFWDaemons.Daemon(name: "com.vphone.jb-setup", contents: [:])#expect(daemon.launchdKey == "/System/Library/LaunchDaemons/com.vphone.jb-setup.plist")}// MARK: - The comparator itself+//// The equivalence tests below are only worth their run time if the thing// judging them can fail. These are what say it can.- @Test("the comparator catches a reordered array")- func comparatorCatchesArrayOrder() {+ @Test+ func `the comparator catches a reordered array`() {let differences = PlistSemantics.differences(["ProgramArguments": ["-r", "/a", "-r", "/b"]],- ["ProgramArguments": ["-r", "/b", "-r", "/a"]]+ ["ProgramArguments": ["-r", "/b", "-r", "/a"]],)#expect(differences.count == 2)}- @Test("the comparator catches true standing in for 1, and a missing key")- func comparatorCatchesTypeAndKeySet() {+ @Test+ func `the comparator catches true standing in for 1, and a missing key`() {#expect(!PlistSemantics.differences(["RunAtLoad": true], ["RunAtLoad": 1]).isEmpty)#expect(!PlistSemantics.differences(["Umask": 0], ["Umask": 0, "Extra": 1]).isEmpty)#expect(!PlistSemantics.differences(["Version": 1], ["Version": 1.0]).isEmpty)}- @Test("the comparator catches differing Data bytes of equal length")- func comparatorCatchesDataBytes() {+ @Test+ func `the comparator catches differing Data bytes of equal length`() {#expect(!PlistSemantics.differences(["Blob": Data([0x01, 0x02])],- ["Blob": Data([0x01, 0x03])]+ ["Blob": Data([0x01, 0x03])],).isEmpty)}}@@ -450,7 +454,7 @@ enum CFWDaemonsGolden {/// SHA-256 as `shasum -a 256` prints it.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}}@@ -463,18 +467,18 @@ enum CFWDaemonsGolden {/// out of an IPSW, and `ipsws/` is not in the repo.@Suite("CFW daemon rewrites match the Python they replaced",- .enabled(if: CFWDaemonsFixtures.referenceInputsAvailable)+ .enabled(if: CFWDaemonsFixtures.referenceInputsAvailable),)struct CFWDaemonsReferenceEquivalenceTests {- @Test("cryptex-paths on a real BuildManifest")- func cryptexPathsMatchTheReference() throws {+ @Test+ func `cryptex-paths on a real BuildManifest`() throws {let swift = try CFWDaemons.cryptexPaths(buildManifest: CFWDaemonsFixtures.buildManifest)#expect(swift.systemOS == CFWDaemonsGolden.cryptexSystemOS)#expect(swift.appOS == CFWDaemonsGolden.cryptexAppOS)}- @Test("patch-dropbear-plist on the installer's real dropbear.plist")- func dropbearPlistMatchesTheReference() throws {+ @Test+ func `patch-dropbear-plist on the installer's real dropbear.plist`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -482,7 +486,7 @@ struct CFWDaemonsReferenceEquivalenceTests {let source = staging.appending(path: "dropbear.plist")try #require(try CFWDaemonsGolden.digest(of: source) == CFWDaemonsGolden.dropbearSource,- "the archive's dropbear.plist is not the one the golden was recorded over"+ "the archive's dropbear.plist is not the one the golden was recorded over",)let before = try CFWDaemonsFixtures.loadPlist(source)@@ -492,7 +496,7 @@ struct CFWDaemonsReferenceEquivalenceTests {#expect((after["ProgramArguments"] as? [Any])?.compactMap { $0 as? String }- == CFWDaemonsGolden.dropbearProgramArguments+ == CFWDaemonsGolden.dropbearProgramArguments,)// …and nothing but that key moved, which is the other half of what the// Python's own output diff said.@@ -502,14 +506,14 @@ struct CFWDaemonsReferenceEquivalenceTests {#expect(differences.isEmpty, "\(differences)")}- @Test("inject-daemons on a real launchd.plist and the real staging directory")- func injectDaemonsMatchesTheReference() throws {+ @Test+ func `inject-daemons on a real launchd.plist and the real staging directory`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let staging = try CFWDaemonsFixtures.unpackLaunchDaemons(into: directory)let swiftCopy = try CFWDaemonsFixtures.writableCopy(- of: CFWDaemonsFixtures.hostLaunchdPlist, in: directory, named: "swift-launchd.plist"+ of: CFWDaemonsFixtures.hostLaunchdPlist, in: directory, named: "swift-launchd.plist",)let before = try CFWDaemonsFixtures.loadPlist(swiftCopy)@@ -522,7 +526,7 @@ struct CFWDaemonsReferenceEquivalenceTests {let after = try CFWDaemonsFixtures.loadPlist(swiftCopy)try assertOnlyAdded(CFWDaemonsGolden.injectedDaemonNames.map(CFWDaemonsGolden.launchdKey),- to: before, in: after+ to: before, in: after,)// Each added value is the staged plist verbatim — dropbear with the@@ -545,26 +549,26 @@ struct CFWDaemonsReferenceEquivalenceTests {/// `cfw_install_exp.sh:702-711`, measured against the same input as the/// Swift single-daemon form. This is what "one implementation, three call/// sites" has to mean: the inline snippet was not a second behaviour.- @Test("the installers' inline jb-setup merge is the same merge")- func inlineInstallerSnippetMatchesSwift() throws {+ @Test+ func `the installers' inline jb-setup merge is the same merge`() throws {let directory = try CFWDaemonsFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }try #require(try CFWDaemonsGolden.digest(of: CFWDaemonsFixtures.jbSetupPlist)== CFWDaemonsGolden.jbSetupSource,- "vphone_jb_setup.plist is not the one the golden was recorded over"+ "vphone_jb_setup.plist is not the one the golden was recorded over",)let swiftCopy = try CFWDaemonsFixtures.writableCopy(- of: CFWDaemonsFixtures.hostLaunchdPlist, in: directory, named: "swift-launchd.plist"+ of: CFWDaemonsFixtures.hostLaunchdPlist, in: directory, named: "swift-launchd.plist",)let before = try CFWDaemonsFixtures.loadPlist(swiftCopy)try CFWDaemons.injectDaemon(into: swiftCopy,name: "com.vphone.jb-setup",- from: CFWDaemonsFixtures.jbSetupPlist+ from: CFWDaemonsFixtures.jbSetupPlist,)let after = try CFWDaemonsFixtures.loadPlist(swiftCopy)@@ -584,7 +588,7 @@ struct CFWDaemonsReferenceEquivalenceTests {private func assertOnlyAdded(_ keys: [String],to before: [String: Any],- in after: [String: Any]+ in after: [String: Any],) throws {#expect(Set(before.keys).union(["LaunchDaemons"]) == Set(after.keys))for key in before.keys where key != "LaunchDaemons" {diff --git a/tests/FirmwarePatcherTests/CFWDiskimagesiodTests.swift b/tests/FirmwarePatcherTests/CFWDiskimagesiodTests.swiftindex e75486e0..a676b8d3 100644--- a/tests/FirmwarePatcherTests/CFWDiskimagesiodTests.swift+++ b/tests/FirmwarePatcherTests/CFWDiskimagesiodTests.swift@@ -52,11 +52,15 @@ private enum DiskImagesFixture {return FileManager.default.fileExists(atPath: main.path) ? url : nil}- static var pristine: URL? { pristineDirectory?.appendingPathComponent("diskimagesiod") }+ static var pristine: URL? {+ pristineDirectory?.appendingPathComponent("diskimagesiod")+ }/// A second real binary from the same firmware, used as the negative case:/// it has no `DIDiskArb`, so locating must fail rather than find something.- static var unrelated: URL? { pristineDirectory?.appendingPathComponent("watchdogd") }+ static var unrelated: URL? {+ pristineDirectory?.appendingPathComponent("watchdogd")+ }/// Opt-out for a machine that cannot carry the fixture.static var isOptional: Bool {@@ -64,7 +68,9 @@ private enum DiskImagesFixture {}/// The suite runs unless the fixture is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e diskimagesiod is required — put it at \@@ -87,7 +93,7 @@ private enum DiskImagesFixture {/// SHA-256 as `shasum -a 256` prints it, so a digest asserted here can be/// taken again from a shell over the same file.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}/// Clone the pristine binary into a fresh file the caller may write to.@@ -100,7 +106,7 @@ private enum DiskImagesFixture {let pristine = try #require(self.pristine, missing)try FileManager.default.createDirectory(at: scratchRoot,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let destination = scratchRoot.appendingPathComponent(name)try? FileManager.default.removeItem(at: destination)@@ -108,9 +114,11 @@ private enum DiskImagesFixture {for flags in [["-c"], []] {let result = try DiskImagesShell.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: flags + [pristine.path, destination.path]+ arguments: flags + [pristine.path, destination.path],)- if result.status == 0 { return destination }+ if result.status == 0 {+ return destination+ }}Issue.record("could not clone \(pristine.path) to \(destination.path)")throw CocoaError(.fileWriteUnknown)@@ -133,7 +141,7 @@ private enum DiskImagesFixture {static func codesignVerify(_ binary: URL) throws -> DiskImagesShell.Result {try DiskImagesShell.run(executable: URL(fileURLWithPath: "/usr/bin/codesign"),- arguments: ["-v", "--verbose=2", binary.path]+ arguments: ["-v", "--verbose=2", binary.path],)}}@@ -156,12 +164,14 @@ private enum DiskImagesShell {static func run(executable: URL,arguments: [String],- currentDirectory: URL? = nil+ currentDirectory: URL? = nil,) throws -> Result {let process = Process()process.executableURL = executableprocess.arguments = arguments- if let currentDirectory { process.currentDirectoryURL = currentDirectory }+ if let currentDirectory {+ process.currentDirectoryURL = currentDirectory+ }let out = Pipe()let err = Pipe()process.standardOutput = out@@ -185,7 +195,7 @@ private enum DiskImagesShell {return Result(status: process.terminationStatus,stdout: String(decoding: collected.standardOutput, as: UTF8.self),- stderr: String(decoding: collected.standardError, as: UTF8.self)+ stderr: String(decoding: collected.standardError, as: UTF8.self),)}@@ -198,11 +208,20 @@ private enum DiskImagesShell {func store(_ data: Data, isStandardOutput: Bool) {lock.lock()defer { lock.unlock() }- if isStandardOutput { out = data } else { err = data }+ if isStandardOutput {+ out = data+ } else {+ err = data+ }}- var standardOutput: Data { lock.withLock { out } }- var standardError: Data { lock.withLock { err } }+ var standardOutput: Data {+ lock.withLock { out }+ }++ var standardError: Data {+ lock.withLock { err }+ }}}@@ -226,7 +245,7 @@ private enum DiskImagesGolden {static let patched = "41daf01d25fc98317516c1aa4c3a095a0e449715907e9e71f1cff6310bcd9cbd"/// The IMP that run resolved, from that stdout line.- static let impFileOffset = 0x3_20C0+ static let impFileOffset = 0x320C0static let impVirtualAddress: UInt64 = 0x1_0003_20C0/// ``patched``, then@@ -268,7 +287,9 @@ private enum DiskImagesComparison {var offsets: [Int] = []for index in 0 ..< left.count where left[index] != right[index] {offsets.append(index)- if offsets.count >= limit { break }+ if offsets.count >= limit {+ break+ }}return offsets}@@ -282,21 +303,21 @@ private enum DiskImagesComparison {@Suite("diskimagesiod replacement encoding")struct CFWDiskimagesiodEncodingTests {- @Test("`mov x0, #1` built from ISA fields is the keystone-verified constant")- func movzAgreesWithKeystone() throws {+ @Test+ func `mov x0, #1 built from ISA fields is the keystone-verified constant`() throws {let encoded = try #require(ARM64Encoder.encodeMovzX(rd: 0, imm16: 1))#expect(encoded == ARM64.movX0_1)// 0xD2800020, little-endian on disk.#expect(encoded.hex == "200080d2")}- @Test("the patch writes exactly `mov x0, #1 ; ret`")- func replacementDisassembles() {+ @Test+ func `the patch writes exactly mov x0, #1 ; ret`() {#expect(CFWDiskimagesiod.replacement.count == 8)#expect(CFWDiskimagesiod.replacement == ARM64.movX0_1 + ARM64.ret)#expect(CFWDiskimagesiod.disassemblyText(of: CFWDiskimagesiod.replacement, at: nil)- == "mov x0, #1; ret"+ == "mov x0, #1; ret",)}}@@ -306,11 +327,11 @@ struct CFWDiskimagesiodEncodingTests {@Suite("diskimagesiod anchoring",.enabled(if: DiskImagesFixture.runs, DiskImagesFixture.missing),- .serialized+ .serialized,)struct CFWDiskimagesiodAnchorTests {- @Test("the IMP resolves through the relative method list, into __TEXT,__text")- func locatesImplementation() throws {+ @Test+ func `the IMP resolves through the relative method list, into __TEXT,__text`() throws {let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)let data = try Data(contentsOf: pristine)let site = try CFWDiskimagesiod.locate(in: data)@@ -336,8 +357,8 @@ struct CFWDiskimagesiodAnchorTests {.hasPrefix("pacibsp; stp"))}- @Test("the fixture is the one the goldens were recorded from")- func fixtureMatchesTheGoldens() throws {+ @Test+ func `the fixture is the one the goldens were recorded from`() throws {let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)#expect(try DiskImagesFixture.digest(of: pristine) == DiskImagesGolden.pristine,@@ -345,62 +366,62 @@ struct CFWDiskimagesiodAnchorTests {this is not the 24A435 diskimagesiod DiskImagesGolden was recorded \from — re-derive the goldens before reading a failure elsewhere in \this file as a patcher bug- """+ """,)}- @Test("the reference's own anchor walk agreed on the same offset")- func agreesWithTheFrozenAnchor() throws {+ @Test+ func `the reference's own anchor walk agreed on the same offset`() throws {let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)- let site = try CFWDiskimagesiod.locate(in: try Data(contentsOf: pristine))+ let site = try CFWDiskimagesiod.locate(in: Data(contentsOf: pristine))// The offset the Python printed; both walks must land on it.#expect(site.fileOffset == DiskImagesGolden.impFileOffset)#expect(site.virtualAddress == DiskImagesGolden.impVirtualAddress)}- @Test("the selector names exactly one implementation in the image")- func selectorIsUnique() throws {+ @Test+ func `the selector names exactly one implementation in the image`() throws {let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)let data = try Data(contentsOf: pristine)let sections = MachOParser.parseSections(from: data)let selectorVA = try #require(- CFWDiskimagesiod.selectorStringVA(in: data, sections: sections)+ CFWDiskimagesiod.selectorStringVA(in: data, sections: sections),)let selrefs = try #require(sections["__DATA,__objc_selrefs"])let selrefVA = try #require(CFWDiskimagesiod.selectorReferenceVA(in: data,selrefs: selrefs,selectorVA: selectorVA,- imageBase: CFWDiskimagesiod.imageBase(sections)+ imageBase: CFWDiskimagesiod.imageBase(sections),))let methlist = try #require(sections["__TEXT,__objc_methlist"])let imps = CFWDiskimagesiod.relativeMethodListIMPs(in: data,section: methlist,- naming: [selectorVA, selrefVA]+ naming: [selectorVA, selrefVA],)#expect(imps.count == 1)- #expect(imps.first == (try CFWDiskimagesiod.locate(in: data)).virtualAddress)+ #expect(try imps.first == (CFWDiskimagesiod.locate(in: data)).virtualAddress)}- @Test("the strided fallback scan lands on the same IMP as the structural walk")- func scanFallbackAgreesWithStructuralWalk() throws {+ @Test+ func `the strided fallback scan lands on the same IMP as the structural walk`() throws {let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)let data = try Data(contentsOf: pristine)let sections = MachOParser.parseSections(from: data)let selectorVA = try #require(- CFWDiskimagesiod.selectorStringVA(in: data, sections: sections)+ CFWDiskimagesiod.selectorStringVA(in: data, sections: sections),)let selrefs = try #require(sections["__DATA,__objc_selrefs"])let selrefVA = try #require(CFWDiskimagesiod.selectorReferenceVA(in: data,selrefs: selrefs,selectorVA: selectorVA,- imageBase: CFWDiskimagesiod.imageBase(sections)+ imageBase: CFWDiskimagesiod.imageBase(sections),))let methlist = try #require(sections["__TEXT,__objc_methlist"])let targets: Set<UInt64> = [selectorVA, selrefVA]@@ -412,19 +433,19 @@ struct CFWDiskimagesiodAnchorTests {let structural = CFWDiskimagesiod.relativeMethodListIMPs(in: data,section: methlist,- naming: targets+ naming: targets,)let strided = CFWDiskimagesiod.scanRelativeMethodEntryIMPs(in: data,section: methlist,- naming: targets+ naming: targets,)#expect(structural == strided)#expect(strided.count == 1)}- @Test("a binary without DIDiskArb is refused, not guessed at")- func unrelatedBinaryIsRefused() throws {+ @Test+ func `a binary without DIDiskArb is refused, not guessed at`() throws {let unrelated = try #require(DiskImagesFixture.unrelated, DiskImagesFixture.missing)let data = try Data(contentsOf: unrelated)#expect(throws: PatcherError.self) {@@ -438,11 +459,11 @@ struct CFWDiskimagesiodAnchorTests {@Suite("diskimagesiod parity",.enabled(if: DiskImagesFixture.runs, DiskImagesFixture.missing),- .serialized+ .serialized,)struct CFWDiskimagesiodParityTests {- @Test("Swift reproduces the reference's bytes, one site each")- func byteForByteParity() throws {+ @Test+ func `Swift reproduces the reference's bytes, one site each`() throws {let swiftClone = try DiskImagesFixture.clone(named: "swift")defer { DiskImagesFixture.discard(swiftClone) }@@ -456,12 +477,12 @@ struct CFWDiskimagesiodParityTests {#expect(try DiskImagesFixture.digest(of: swiftClone) == DiskImagesGolden.patched,- "Swift and the frozen reference disagree"+ "Swift and the frozen reference disagree",)}- @Test("the recorded write names the site, the bytes and both disassemblies")- func recordDescribesTheSite() throws {+ @Test+ func `the recorded write names the site, the bytes and both disassemblies`() throws {let clone = try DiskImagesFixture.clone(named: "record")defer { DiskImagesFixture.discard(clone) }@@ -484,8 +505,8 @@ struct CFWDiskimagesiodParityTests {#expect(patched[range] == record.patchedBytes)}- @Test("only the eight patched bytes differ from the pristine binary")- func onlyTheSiteChanges() throws {+ @Test+ func `only the eight patched bytes differ from the pristine binary`() throws {let clone = try DiskImagesFixture.clone(named: "minimal")defer { DiskImagesFixture.discard(clone) }let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)@@ -494,7 +515,7 @@ struct CFWDiskimagesiodParityTests {let differences = try DiskImagesComparison.differences(between: pristine,and: clone,- limit: 64+ limit: 64,)#expect(differences.allSatisfy {(report.site.fileOffset ..< report.site.fileOffset + 8).contains($0)@@ -508,11 +529,11 @@ struct CFWDiskimagesiodParityTests {@Suite("diskimagesiod re-attestation",.enabled(if: DiskImagesFixture.runs, DiskImagesFixture.missing),- .serialized+ .serialized,)struct CFWDiskimagesiodReattestTests {- @Test("the fixture really does have the short tail slot this path regressed on")- func fixtureHasShortTail() throws {+ @Test+ func `the fixture really does have the short tail slot this path regressed on`() throws {let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)let data = try Data(contentsOf: pristine)let directories = try #require(CFWMachOCodeSignature.codeDirectories(in: data))@@ -527,8 +548,8 @@ struct CFWDiskimagesiodReattestTests {#expect(tail.upperBound == directory.codeLimit)}- @Test("`codesign -v` rejects the un-attested patch and accepts the attested one")- func codesignAgrees() throws {+ @Test+ func `codesign -v rejects the un-attested patch and accepts the attested one`() throws {let bare = try DiskImagesFixture.clone(named: "bare")let attested = try DiskImagesFixture.clone(named: "attested")defer { DiskImagesFixture.discard(bare, attested) }@@ -549,8 +570,8 @@ struct CFWDiskimagesiodReattestTests {#expect(verification.status == 0, "codesign said: \(verification.stderr)")}- @Test("the re-attested bytes are the reference re-attest's bytes")- func reattestMatchesTheFrozenReference() throws {+ @Test+ func `the re-attested bytes are the reference re-attest's bytes`() throws {let swiftClone = try DiskImagesFixture.clone(named: "swift-attested")defer { DiskImagesFixture.discard(swiftClone) }@@ -558,12 +579,12 @@ struct CFWDiskimagesiodReattestTests {#expect(report.rehashes.first?.pageIndex == DiskImagesGolden.reattestedSlot)#expect(try DiskImagesFixture.digest(of: swiftClone) == DiskImagesGolden.patchedAndReattested,- "the re-attested slot hash must be the one the reference computed"+ "the re-attested slot hash must be the one the reference computed",)}- @Test("a short-tail slot is hashed to codeLimit, not to the end of its page")- func tailSlotStopsAtCodeLimit() throws {+ @Test+ func `a short-tail slot is hashed to codeLimit, not to the end of its page`() throws {let swiftClone = try DiskImagesFixture.clone(named: "swift-tail")defer { DiskImagesFixture.discard(swiftClone) }@@ -591,7 +612,7 @@ struct CFWDiskimagesiodReattestTests {#expect(try DiskImagesFixture.digest(of: swiftClone)== DiskImagesGolden.tailFlippedAndReattested,- "the tail slot hash must be the one the reference re-attester computed"+ "the tail slot hash must be the one the reference re-attester computed",)}}@@ -601,11 +622,11 @@ struct CFWDiskimagesiodReattestTests {@Suite("diskimagesiod idempotence",.enabled(if: DiskImagesFixture.runs, DiskImagesFixture.missing),- .serialized+ .serialized,)struct CFWDiskimagesiodIdempotenceTests {- @Test("a second Swift run recognises its own output and writes nothing")- func secondRunIsANoOp() throws {+ @Test+ func `a second Swift run recognises its own output and writes nothing`() throws {let clone = try DiskImagesFixture.clone(named: "twice")defer { DiskImagesFixture.discard(clone) }@@ -625,8 +646,8 @@ struct CFWDiskimagesiodIdempotenceTests {#expect(after[.modificationDate] as? Date == attributes[.modificationDate] as? Date)}- @Test("a second run with re-attestation leaves the slot hashes alone")- func secondAttestedRunIsANoOp() throws {+ @Test+ func `a second run with re-attestation leaves the slot hashes alone`() throws {let clone = try DiskImagesFixture.clone(named: "twice-attested")defer { DiskImagesFixture.discard(clone) }@@ -650,15 +671,15 @@ struct CFWDiskimagesiodIdempotenceTests {/// "the reference over its own output" — the two files are byte-identical/// by `byteForByteParity` — and what is left to measure is this side:/// Swift over the bytes the reference left behind must change nothing.- @Test("the reference's output is what this port reports as already patched")- func crossImplementationRerunsAgree() throws {+ @Test+ func `the reference's output is what this port reports as already patched`() throws {let referenceOutput = try DiskImagesFixture.clone(named: "reference-then-swift")defer { DiskImagesFixture.discard(referenceOutput) }// Reproduce the reference's output, and prove it is that, by digest.try CFWDiskimagesiod.patch(fileAt: referenceOutput, log: nil)try #require(- try DiskImagesFixture.digest(of: referenceOutput) == DiskImagesGolden.patched+ try DiskImagesFixture.digest(of: referenceOutput) == DiskImagesGolden.patched,)#expect(DiskImagesGolden.patchedTwice == DiskImagesGolden.patched)@@ -667,8 +688,8 @@ struct CFWDiskimagesiodIdempotenceTests {#expect(try DiskImagesFixture.digest(of: referenceOutput) == DiskImagesGolden.patched)}- @Test("a dry run locates the site and writes nothing")- func dryRunWritesNothing() throws {+ @Test+ func `a dry run locates the site and writes nothing`() throws {let clone = try DiskImagesFixture.clone(named: "dry")defer { DiskImagesFixture.discard(clone) }let pristine = try #require(DiskImagesFixture.pristine, DiskImagesFixture.missing)diff --git a/tests/FirmwarePatcherTests/CFWJetsamTests.swift b/tests/FirmwarePatcherTests/CFWJetsamTests.swiftindex b5566fe7..883b6e09 100644--- a/tests/FirmwarePatcherTests/CFWJetsamTests.swift+++ b/tests/FirmwarePatcherTests/CFWJetsamTests.swift@@ -40,15 +40,22 @@ enum JetsamFixture {.appending(path: "ipsws/ref_extract/macho_pristine/launchd")static let codesign = URL(filePath: "/usr/bin/codesign")- static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }+ static func exists(_ url: URL) -> Bool {+ FileManager.default.fileExists(atPath: url.path)+ }++ static var hasLaunchd: Bool {+ exists(pristineLaunchd)+ }- static var hasLaunchd: Bool { exists(pristineLaunchd) }- static var hasLaunchdAndCodesign: Bool { hasLaunchd && exists(codesign) }+ static var hasLaunchdAndCodesign: Bool {+ hasLaunchd && exists(codesign)+ }/// SHA-256 as `shasum -a 256` prints it, so a digest asserted here can be/// taken again from a shell over the same file.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}/// A directory for one test's artifacts. `VPHONE_JETSAM_ARTIFACTS` pins it@@ -73,7 +80,7 @@ enum JetsamFixture {static func run(_ tool: URL,_ arguments: [String],- workingDirectory: URL? = nil+ workingDirectory: URL? = nil,) throws -> (status: Int32, output: String) {let process = Process()process.executableURL = tool@@ -90,8 +97,12 @@ enum JetsamFixture {/// The first byte offset at which two files differ, or nil when equal.static func firstDifference(_ lhs: Data, _ rhs: Data) -> Int? {- if lhs.count != rhs.count { return min(lhs.count, rhs.count) }- for index in 0 ..< lhs.count where lhs[index] != rhs[index] { return index }+ if lhs.count != rhs.count {+ return min(lhs.count, rhs.count)+ }+ for index in 0 ..< lhs.count where lhs[index] != rhs[index] {+ return index+ }return nil}}@@ -151,19 +162,19 @@ struct CFWJetsamReferenceTests {/// mismatch below would read as a patcher bug when the real cause is a/// different firmware's `launchd`.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func fixtureMatchesTheGoldens() throws {+ func `fixture matches the goldens`() throws {#expect(try JetsamFixture.digest(of: JetsamFixture.pristineLaunchd) == JetsamGolden.pristine,"""this is not the 24A435 launchd JetsamGolden was recorded from — \re-derive the goldens before reading a failure below as a patcher bug- """+ """,)}/// The whole point of the port: same input, same bytes out.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func matchesTheFrozenReferenceByteForByte() throws {+ func `matches the frozen reference byte for byte`() throws {let work = try JetsamFixture.workDirectory("byte-equivalence")let swiftTarget = try JetsamFixture.launchdCopy(named: "launchd.swift", in: work)@@ -171,7 +182,7 @@ struct CFWJetsamReferenceTests {#expect(outcome.verdict == .patched)#expect(try JetsamFixture.digest(of: swiftTarget) == JetsamGolden.patched,- "Swift and the frozen reference diverge"+ "Swift and the frozen reference diverge",)// And the only thing that moved is inside the instruction the record@@ -193,7 +204,7 @@ struct CFWJetsamReferenceTests {/// reached it through too, so a port that agreed on the gate by luck is/// still caught.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func agreesWithTheFrozenReferenceOnTheSite() throws {+ func `agrees with the frozen reference on the site`() throws {let data = try Data(contentsOf: JetsamFixture.pristineLaunchd)let image = try CFWJetsamPatcher.Image(data: data)let site = try #require(try CFWJetsamPatcher.locate(in: image))@@ -215,7 +226,7 @@ struct CFWJetsamIdempotenceTests {/// different branch on an already-patched binary; this one recognises its/// own work and stops.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func secondRunChangesNothing() throws {+ func `second run changes nothing`() throws {let work = try JetsamFixture.workDirectory("idempotence")let target = try JetsamFixture.launchdCopy(named: "launchd", in: work)@@ -243,7 +254,7 @@ struct CFWJetsamIdempotenceTests {/// twice, and it landed a *second* site the pristine image never had/// patched. Frozen, so the divergence stays a measurement, not a claim.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func referenceWasNotIdempotentAndThisIs() throws {+ func `reference was not idempotent and this is`() throws {let work = try JetsamFixture.workDirectory("reference-double-apply")let swiftTarget = try JetsamFixture.launchdCopy(named: "launchd.swift", in: work)@@ -251,7 +262,7 @@ struct CFWJetsamIdempotenceTests {// different instruction than the gate it had already rewritten.#expect(JetsamGolden.patchedTwice != JetsamGolden.patched,- "the reference was recorded as non-idempotent — re-check what this port has to preserve"+ "the reference was recorded as non-idempotent — re-check what this port has to preserve",)#expect(JetsamGolden.secondRunGateOffset != JetsamGolden.gateOffset)@@ -281,7 +292,7 @@ struct CFWJetsamSignatureTests {/// Default is the reference's behaviour: the four bytes and nothing else,/// because every call site re-signs with `ldid` straight afterwards.@Test(.enabled(if: JetsamFixture.hasLaunchdAndCodesign))- func defaultLeavesTheSignatureStale() throws {+ func `default leaves the signature stale`() throws {let work = try JetsamFixture.workDirectory("stale-signature")let target = try JetsamFixture.launchdCopy(named: "launchd", in: work)@@ -295,7 +306,7 @@ struct CFWJetsamSignatureTests {/// `reattest: true` has to leave a binary `codesign` accepts — one page's/// slot hash, recomputed, tail slot included.@Test(.enabled(if: JetsamFixture.hasLaunchdAndCodesign))- func reattestedBinaryVerifies() throws {+ func `reattested binary verifies`() throws {let work = try JetsamFixture.workDirectory("reattested")let target = try JetsamFixture.launchdCopy(named: "launchd", in: work)@@ -307,7 +318,7 @@ struct CFWJetsamSignatureTests {let patched = try Data(contentsOf: target)let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: patched)?- .first { $0.hashType == CFWMachOCodeSignature.hashTypeSHA256 }+ .first { $0.hashType == CFWMachOCodeSignature.hashTypeSHA256 },)#expect(rehash.pageIndex == outcome.gateOffset / directory.pageSize)@@ -319,7 +330,7 @@ struct CFWJetsamSignatureTests {/// independent re-signer run over the Python's own patched bytes. Two/// implementations, one number.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func slotHashMatchesTheFrozenResigner() throws {+ func `slot hash matches the frozen resigner`() throws {let work = try JetsamFixture.workDirectory("slot-hash")let swiftTarget = try JetsamFixture.launchdCopy(named: "launchd.swift", in: work)@@ -329,7 +340,7 @@ struct CFWJetsamSignatureTests {#expect(outcome.rehashes.first?.pageIndex == JetsamGolden.reattestedSlot)#expect(try JetsamFixture.digest(of: swiftTarget) == JetsamGolden.patchedAndReattested,- "the re-attested slot hash must be the one the reference computed"+ "the re-attested slot hash must be the one the reference computed",)}}@@ -342,7 +353,7 @@ struct CFWJetsamAnchoringTests {/// the xref is inside the function, the gate is inside the function and/// before the xref, and the gate's target really does return.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func revealStepsAreSelfConsistent() throws {+ func `reveal steps are self consistent`() throws {let data = try Data(contentsOf: JetsamFixture.pristineLaunchd)let image = try CFWJetsamPatcher.Image(data: data)let site = try #require(try CFWJetsamPatcher.locate(in: image))@@ -361,7 +372,7 @@ struct CFWJetsamAnchoringTests {// The anchor string starts where the xref computes it to start.let page = CFWJetsamPatcher.adrpPage(data.loadLE(UInt32.self, at: site.xrefOffset),- at: image.virtualAddress(ofTextOffset: site.xrefOffset)+ at: image.virtualAddress(ofTextOffset: site.xrefOffset),)#expect(site.stringVMA & ~0xFFF == page)@@ -375,7 +386,7 @@ struct CFWJetsamAnchoringTests {/// The gate is the *earliest* qualifying branch in the function — any later/// one leaves more of the jetsam path running.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func gateIsTheEarliestQualifyingBranch() throws {+ func `gate is the earliest qualifying branch`() throws {let data = try Data(contentsOf: JetsamFixture.pristineLaunchd)let image = try CFWJetsamPatcher.Image(data: data)let site = try #require(try CFWJetsamPatcher.locate(in: image))@@ -390,7 +401,7 @@ struct CFWJetsamAnchoringTests {else { continue }#expect(!CFWJetsamPatcher.isReturnBlock(target, in: image),- "0x\(String(offset, radix: 16)) qualifies and is earlier than the chosen gate"+ "0x\(String(offset, radix: 16)) qualifies and is earlier than the chosen gate",)}}@@ -400,7 +411,7 @@ struct CFWJetsamAnchoringTests {/// different, later branch, so checking the picked site afterwards would/// not catch it.@Test(.enabled(if: JetsamFixture.hasLaunchd))- func patchedShapeIsRecognisedInPlace() throws {+ func `patched shape is recognised in place`() throws {var data = try Data(contentsOf: JetsamFixture.pristineLaunchd)let outcome = try CFWJetsamPatcher.patch(&data, log: nil)#expect(outcome.verdict == .patched)@@ -417,7 +428,7 @@ struct CFWJetsamAnchoringTests {let gate = try #require(CFWJetsamPatcher.findReturnGate(from: site.gateOffset + 4,to: site.xrefOffset,- in: image+ in: image,))#expect(!gate.isUnconditional)#expect(gate.offset > outcome.gateOffset)@@ -432,7 +443,7 @@ struct CFWJetsamDecodeTests {/// `ADD Xd, Xn, #imm12, LSL #0` only — an `LSL #12` form or a/// shifted-register add would make the xref land on the wrong string.@Test- func addImmediatePredicateRejectsTheNeighbours() throws {+ func `add immediate predicate rejects the neighbours`() throws {let disassembler = ARM64Disassembler()// The real thing: the ADD half of the string xref, straight out of the// project encoder rather than typed in.@@ -451,7 +462,7 @@ struct CFWJetsamDecodeTests {/// `adrpPage` against Capstone, which resolves the page for us. The inputs/// come from `ARM64Encoder.encodeADRP`, so nothing here is a typed-in word.@Test- func adrpPageAgreesWithCapstone() throws {+ func `adrp page agrees with capstone`() throws {let disassembler = ARM64Disassembler()for (pc, target) in [(UInt64(0x1_0000_FB0C), UInt64(0x1_0006_5A09)), // forward@@ -472,7 +483,7 @@ struct CFWJetsamDecodeTests {/// The replacement is `ARM64Encoder`'s, and it decodes back to a `b` at the/// intended target — never a hand-written instruction word.@Test- func replacementBranchRoundTrips() throws {+ func `replacement branch round trips`() throws {let disassembler = ARM64Disassembler()for (site, target) in [(0xFA98, 0xFAEC), (0x1000, 0x800), (0x40, 0x40)] {let encoded = try #require(ARM64Encoder.encodeB(from: site, to: target))@@ -488,7 +499,7 @@ struct CFWJetsamDecodeTests {/// mnemonic prefix gets each of the last three rows below wrong: `brk` is/// not a branch, and a conditional branch falls through.@Test- func blockBoundariesComeFromCapstoneGroups() throws {+ func `block boundaries come from capstone groups`() throws {let disassembler = ARM64Disassembler()func decode(_ bytes: Data) throws -> Instruction {try #require(disassembler.disassembleOne(bytes, at: 0))@@ -502,9 +513,9 @@ struct CFWJetsamDecodeTests {// Control leaves: an unconditional relative jump and a relative call,// both straight out of `ARM64Encoder`.- for bytes in [- try #require(ARM64Encoder.encodeB(from: 0, to: 8)),- try #require(ARM64Encoder.encodeBL(from: 0, to: 8)),+ for bytes in try [+ #require(ARM64Encoder.encodeB(from: 0, to: 8)),+ #require(ARM64Encoder.encodeBL(from: 0, to: 8)),] {let insn = try decode(bytes)#expect(CFWJetsamPatcher.leavesBlock(insn))@@ -545,12 +556,12 @@ struct CFWJetsamDecodeTests {/// `cbz`/`tbz` put the target last; reading the last immediate is what/// keeps one code path covering all of them.@Test- func branchTargetReadsTheLastImmediate() throws {+ func `branch target reads the last immediate`() throws {let disassembler = ARM64Disassembler()// tbz w8, #1, #8 — three operands, target last, from the encoder.let tbz = try #require(ARM64Encoder.encodeTestBitBranch(- nonzero: false, register: 8, bit: 1, from: 0, to: 8+ nonzero: false, register: 8, bit: 1, from: 0, to: 8,))let tbzInsn = try #require(disassembler.disassembleOne(tbz, at: 0))#expect(tbzInsn.mnemonic == "tbz")@@ -571,7 +582,7 @@ struct CFWJetsamDecodeTests {/// A substring anchor has to widen to the whole C string, because that is/// what an ADRP+ADD points at.@Test- func cStringStartWidensToTheWholeString() throws {+ func `c string start widens to the whole string`() throws {var bytes = Data("first\u{0}jetsam property category (%s) is not initialized\u{0}".utf8)var hit = try #require(bytes.range(of: Data("property".utf8))?.lowerBound)#expect(CFWJetsamPatcher.cStringStart(in: bytes, containing: hit, sectionStart: 0) == 6)diff --git a/tests/FirmwarePatcherTests/CFWMachOTests.swift b/tests/FirmwarePatcherTests/CFWMachOTests.swiftindex 2340ab88..d1ab5168 100644--- a/tests/FirmwarePatcherTests/CFWMachOTests.swift+++ b/tests/FirmwarePatcherTests/CFWMachOTests.swift@@ -68,7 +68,9 @@ enum MachOFixture {/// The fixture every signed-Mach-O test below operates on, or a failure/// that names what is missing instead of a silent skip.- static func signedBinary() throws -> URL { try #require(pristineSeputil, missing) }+ static func signedBinary() throws -> URL {+ try #require(pristineSeputil, missing)+ }/// Opt-out for a machine that cannot carry the extracted IPSW.static var fixtureIsOptional: Bool {@@ -77,7 +79,9 @@ enum MachOFixture {/// A fixture-backed test runs unless the binary is absent *and* the caller/// opted out, so a green run cannot mean the fixture quietly went away.- static var runs: Bool { pristineSeputil != nil || !fixtureIsOptional }+ static var runs: Bool {+ pristineSeputil != nil || !fixtureIsOptional+ }static let missing: Comment = """the real 24A435 seputil is required — put it at \@@ -88,14 +92,21 @@ enum MachOFixture {static let insertDylib = repositoryRoot.appending(path: ".tools/bin/insert_dylib")- static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }+ static func exists(_ url: URL) -> Bool {+ FileManager.default.fileExists(atPath: url.path)+ }- static var hasInsertDylib: Bool { exists(insertDylib) }- static var hasCodesign: Bool { exists(URL(filePath: "/usr/bin/codesign")) }+ static var hasInsertDylib: Bool {+ exists(insertDylib)+ }++ static var hasCodesign: Bool {+ exists(URL(filePath: "/usr/bin/codesign"))+ }/// SHA-256 as `shasum -a 256` prints it.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}/// A private copy of `source` — the fixture by default — that the caller@@ -110,7 +121,7 @@ enum MachOFixture {// The fixture is 0755 already; this is only so a reference tree// someone made read-only does not turn into a failing patch test.try FileManager.default.setAttributes(- [.posixPermissions: 0o755], ofItemAtPath: destination.path+ [.posixPermissions: 0o755], ofItemAtPath: destination.path,)return destination}@@ -169,8 +180,8 @@ struct CFWMachOCodeSignatureTests {/// that TXM kills the first time that page is faulted in, and nothing about/// the file looks wrong until then.@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func tailSlotHashesOnlyUpToCodeLimit() throws {- let data = try Data(contentsOf: try MachOFixture.signedBinary())+ func `tail slot hashes only up to code limit`() throws {+ let data = try Data(contentsOf: MachOFixture.signedBinary())let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: data)?.first)let lastSlot = directory.codeSlotCount - 1@@ -185,7 +196,7 @@ struct CFWMachOCodeSignatureTests {try MachOFixture.flipByte(at: directory.codeLimit - 1, in: file)let records = try CFWMachOCodeSignature.reattest(fileAt: file,- modifiedOffsets: [directory.codeLimit - 1]+ modifiedOffsets: [directory.codeLimit - 1],)let record = try #require(records.first)#expect(records.count == 1)@@ -198,7 +209,7 @@ struct CFWMachOCodeSignatureTests {#expect(record.after == shortHash)#expect(patched[record.hashFileOffset ..< record.hashFileOffset + directory.hashSize] == shortHash,- "the slot on disk must hold the hash of the short range"+ "the slot on disk must hold the hash of the short range",)// And state the failure mode directly: a full-page hash is a different@@ -213,11 +224,11 @@ struct CFWMachOCodeSignatureTests {/// tail, and the last slot must cover a whole page. No binary on a build/// machine reliably has a page-aligned codeLimit, so the boundary maths is/// pinned directly.- @Test func slotRangesFollowCodeLimitAlignment() {+ @Test func `slot ranges follow code limit alignment`() {let aligned = CFWCodeDirectory(slotType: 0, offset: 0, length: 0, hashOffset: 0, hashSize: 32,hashType: 2, pageSize: 4096, pageSizeLog2: 12,- codeSlotCount: 2, codeLimit: 8192+ codeSlotCount: 2, codeLimit: 8192,)#expect(aligned.slotRange(0) == 0 ..< 4096)#expect(aligned.slotRange(1) == 4096 ..< 8192)@@ -226,13 +237,13 @@ struct CFWMachOCodeSignatureTests {let short = CFWCodeDirectory(slotType: 0, offset: 0, length: 0, hashOffset: 0, hashSize: 32,hashType: 2, pageSize: 4096, pageSizeLog2: 12,- codeSlotCount: 2, codeLimit: 5000+ codeSlotCount: 2, codeLimit: 5000,)#expect(short.slotRange(0) == 0 ..< 4096)#expect(short.slotRange(1) == 4096 ..< 5000)}- @Test func offsetsPastCodeLimitBelongToNoSlot() {+ @Test func `offsets past code limit belong to no slot`() {#expect(CFWMachOCodeSignature.pageBounds(fileOffset: 4095, pageSize: 4096, codeLimit: 5000)?.index == 0)#expect(CFWMachOCodeSignature.pageBounds(fileOffset: 4999, pageSize: 4096, codeLimit: 5000)?.end == 5000)#expect(CFWMachOCodeSignature.pageBounds(fileOffset: 5000, pageSize: 4096, codeLimit: 5000) == nil)@@ -250,8 +261,8 @@ struct CFWMachOCodeSignatureTests {/// the two, so a reader that took the page size from the architecture, the/// file size or a constant would have to get one of them wrong.@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func pageSizeComesFromTheCodeDirectory() throws {- let shipped = try Data(contentsOf: try MachOFixture.signedBinary())+ func `page size comes from the code directory`() throws {+ let shipped = try Data(contentsOf: MachOFixture.signedBinary())let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: shipped)?.first)#expect(directory.pageSize == 1 << Int(directory.pageSizeLog2))#expect(directory.pageSize == 4096, "the shipped iOS signature uses 4 KiB pages")@@ -262,51 +273,51 @@ struct CFWMachOCodeSignatureTests {/// The other half of the same claim, and the one a constant gets wrong: the/// host signer covers the very same file with 16 KiB pages.@Test(.enabled(if: MachOFixture.runs && MachOFixture.hasCodesign, MachOFixture.missing))- func pageSizeFollowsWhoeverSignedTheFile() throws {- let shipped = try Data(contentsOf: try MachOFixture.signedBinary())+ func `page size follows whoever signed the file`() throws {+ let shipped = try Data(contentsOf: MachOFixture.signedBinary())let iOSDirectory = try #require(CFWMachOCodeSignature.codeDirectories(in: shipped)?.first)let file = try MachOFixture.scratchCopy("pagesize")defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }let signing = try MachOFixture.run(URL(filePath: "/usr/bin/codesign"),- ["-f", "-s", "-", "--digest-algorithm=sha256", file.path]+ ["-f", "-s", "-", "--digest-algorithm=sha256", file.path],)try #require(signing.status == 0, "could not re-sign the fixture: \(signing.output)")let hostDirectory = try #require(- CFWMachOCodeSignature.codeDirectories(in: try Data(contentsOf: file))?.first+ try CFWMachOCodeSignature.codeDirectories(in: Data(contentsOf: file))?.first,)#expect(hostDirectory.pageSize == 1 << Int(hostDirectory.pageSizeLog2))#expect(hostDirectory.pageSize == 16384, "the host signer uses 16 KiB pages")#expect(hostDirectory.pageSize != iOSDirectory.pageSize,- "one file, two page sizes — the whole point of reading it from the CD"+ "one file, two page sizes — the whole point of reading it from the CD",)// Same code, so the same codeLimit, covered by a quarter as many slots.#expect(hostDirectory.codeLimit == iOSDirectory.codeLimit)#expect(hostDirectory.codeSlotCount < iOSDirectory.codeSlotCount)}- @Test func unsignedDataIsRejected() {+ @Test func `unsigned data is rejected`() {var data = Data(repeating: 0, count: 4096)#expect(throws: PatcherError.self) {try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: [0])}}- @Test func noOffsetsIsANoOp() throws {+ @Test func `no offsets is A no op`() throws {var data = Data(repeating: 0, count: 16)#expect(try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: []).isEmpty)}@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func unchangedPagesAreNotRewritten() throws {+ func `unchanged pages are not rewritten`() throws {let file = try MachOFixture.scratchCopy("untouched")// Nothing was modified, so every slot already matches and no write happens.let records = try CFWMachOCodeSignature.reattest(fileAt: file, modifiedOffsets: [0, 4096, 8192])#expect(records.isEmpty)- #expect(try Data(contentsOf: file) == (try Data(contentsOf: try MachOFixture.signedBinary())))+ #expect(try Data(contentsOf: file) == Data(contentsOf: MachOFixture.signedBinary()))}// MARK: Multiple code directories@@ -315,11 +326,11 @@ struct CFWMachOCodeSignatureTests {/// SHA-256 CD is recomputed; the SHA-1 CD is left byte-for-byte alone and/// reported, which is what `unsupportedCodeDirectories(in:)` is for.@Test(.enabled(if: MachOFixture.runs && MachOFixture.hasCodesign, MachOFixture.missing))- func onlySHA256CodeDirectoriesAreUpdated() throws {+ func `only SHA 256 code directories are updated`() throws {let file = try MachOFixture.scratchCopy("dual")let signing = try MachOFixture.run(URL(filePath: "/usr/bin/codesign"),- ["-f", "-s", "-", "--digest-algorithm=sha1,sha256", file.path]+ ["-f", "-s", "-", "--digest-algorithm=sha1,sha256", file.path],)try #require(signing.status == 0, "could not build a dual-CD fixture: \(signing.output)")@@ -349,14 +360,14 @@ struct CFWMachOCodeSignatureTests {/// — so a fixture that drifted fails on the offsets rather than silently/// comparing a different experiment's digest.@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func matchesTheFrozenPythonReattester() throws {+ func `matches the frozen python reattester`() throws {let pristine = try MachOFixture.signedBinary()try #require(try MachOFixture.digest(of: pristine) == MachOCodeSignGolden.pristine,"""this is not the 24A435 seputil MachOCodeSignGolden was recorded \from — re-derive the golden before reading a failure here as a bug- """+ """,)let data = try Data(contentsOf: pristine)@@ -388,7 +399,7 @@ struct CFWMachOCodeSignatureTests {#expect(try MachOFixture.digest(of: swiftFile) == MachOCodeSignGolden.reattested,- "Swift and the frozen Python re-attestation must agree byte for byte"+ "Swift and the frozen Python re-attestation must agree byte for byte",)}}@@ -422,7 +433,7 @@ private enum MachOCodeSignGolden {static let pristine = "13e40e74d92928cf9e36fae75970dfcf4c0a4c1040eeac39d1c335407e841474"/// The four offsets above, and the codeLimit the last two straddle.- static let offsets = [16, 90_119, 183_887, 183_896]+ static let offsets = [16, 90119, 183_887, 183_896]static let codeLimit = 183_888/// The three slots the reference rewrote; the fourth offset was skipped.@@ -439,7 +450,7 @@ struct CFWInjectDylibTests {/// What `cfw_install_jb.sh` does to launchd, minus ldid: the weak load of/// `/b` has to appear and the header has to grow to match.@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func insertsAWeakLoadCommand() throws {+ func `inserts A weak load command`() throws {let file = try MachOFixture.scratchCopy("weak")let before = try Data(contentsOf: file)let injections = try CFWInjectDylib.inject(dylibPath: "/b", into: file)@@ -472,13 +483,13 @@ struct CFWInjectDylibTests {/// stripped LC_CODE_SIGNATURE would free, so it has to fit in the padding/// as shipped — 32 bytes in this fixture, for a 32-byte command.@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func keepingTheSignatureRehashesTheHeaderPage() throws {+ func `keeping the signature rehashes the header page`() throws {let file = try MachOFixture.scratchCopy("keep")let before = try Data(contentsOf: file)let injection = try #require(try CFWInjectDylib.inject(dylibPath: "/b",into: file,- policy: .keepAndReattest+ policy: .keepAndReattest,).first)#expect(!injection.removedCodeSignature)#expect(injection.rehashedSlots.map(\.pageIndex) == [0])@@ -497,7 +508,7 @@ struct CFWInjectDylibTests {/// space" and writes the command over the first section. Refusing is the/// deliberate difference; this pins it.@Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))- func refusesToOverwriteOccupiedPadding() throws {+ func `refuses to overwrite occupied padding`() throws {let file = try MachOFixture.scratchCopy("occupied")var data = try Data(contentsOf: file)let sizeofcmds = Int(data.loadLE(UInt32.self, at: 20))@@ -513,7 +524,7 @@ struct CFWInjectDylibTests {}}- @Test func rejectsWhatItCannotHandle() {+ @Test func `rejects what it cannot handle`() {var empty = Data([0xCA, 0xFE, 0xBA, 0xBF, 0, 0, 0, 1])#expect(throws: PatcherError.self) {try CFWInjectDylib.inject(dylibPath: "/b", into: &empty)@@ -527,21 +538,21 @@ struct CFWInjectDylibTests {/// The migration gate for this half: identical output to the C tool it/// replaces, on the exact command line the CFW scripts use.@Test(.enabled(if: MachOFixture.runs && MachOFixture.hasInsertDylib, MachOFixture.missing))- func matchesInsertDylib() throws {+ func `matches insert dylib`() throws {let swiftFile = try MachOFixture.scratchCopy("swift")let referenceFile = swiftFile.deletingLastPathComponent().appending(path: "reference")- try FileManager.default.copyItem(at: try MachOFixture.signedBinary(), to: referenceFile)+ try FileManager.default.copyItem(at: MachOFixture.signedBinary(), to: referenceFile)try CFWInjectDylib.inject(dylibPath: "/b", into: swiftFile)let reference = try MachOFixture.run(MachOFixture.insertDylib,- ["--weak", "--inplace", "--all-yes", "/b", referenceFile.path]+ ["--weak", "--inplace", "--all-yes", "/b", referenceFile.path],)try #require(reference.status == 0, "insert_dylib failed: \(reference.output)")#expect(- try Data(contentsOf: swiftFile) == (try Data(contentsOf: referenceFile)),- "Swift injection must match insert_dylib byte for byte"+ try Data(contentsOf: swiftFile) == Data(contentsOf: referenceFile),+ "Swift injection must match insert_dylib byte for byte",)}}diff --git a/tests/FirmwarePatcherTests/CFWMobileactivationdTests.swift b/tests/FirmwarePatcherTests/CFWMobileactivationdTests.swiftindex 2741596b..c4343ce5 100644--- a/tests/FirmwarePatcherTests/CFWMobileactivationdTests.swift+++ b/tests/FirmwarePatcherTests/CFWMobileactivationdTests.swift@@ -57,23 +57,35 @@ enum MobileactivationdFixture {return FileManager.default.temporaryDirectory.appending(path: "CFWMobileactivationdTests")}()- static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }+ static func exists(_ url: URL) -> Bool {+ FileManager.default.fileExists(atPath: url.path)+ }- static var hasPristine: Bool { exists(pristine) }- static var hasLaunchd: Bool { exists(launchd) }- static var hasCodesign: Bool { hasPristine && exists(codesign) }+ static var hasPristine: Bool {+ exists(pristine)+ }++ static var hasLaunchd: Bool {+ exists(launchd)+ }++ static var hasCodesign: Bool {+ hasPristine && exists(codesign)+ }/// SHA-256 as `shasum -a 256` prints it, so a digest asserted here can be/// taken again from a shell over the same file.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}/// A named, writable copy of the pristine binary under ``artifacts``.static func copyOfPristine(named name: String) throws -> URL {try FileManager.default.createDirectory(at: artifacts, withIntermediateDirectories: true)let destination = artifacts.appending(path: name)- if exists(destination) { try FileManager.default.removeItem(at: destination) }+ if exists(destination) {+ try FileManager.default.removeItem(at: destination)+ }try FileManager.default.copyItem(at: pristine, to: destination)return destination}@@ -92,7 +104,6 @@ enum MobileactivationdFixture {process.waitUntilExit()return (process.terminationStatus, String(decoding: output, as: UTF8.self))}-}// MARK: - The frozen reference@@ -115,7 +126,7 @@ enum MobileactivationdGolden {static let patched = "9f26bf92a2a80133e763c6426949e262ad26d51485b5184548744bd37e1f4095"/// The IMP the Python's symbol-table anchor resolved to, from that stdout.- static let impFileOffset = 0x2E_C368+ static let impFileOffset = 0x2EC368/// ``patched``, then/// `.venv/bin/python3 -c 'import sys; sys.path.insert(0, "scripts");@@ -149,7 +160,7 @@ enum MobileactivationdGolden {@Suite("mobileactivationd should_hactivate — shell runner")struct CFWMobileactivationdRunnerTests {@Test(.enabled(if: ProcessInfo.processInfo.environment["VPHONE_PATCH_FILE"] != nil))- func runPatcherFromEnvironment() throws {+ func `run patcher from environment`() throws {let environment = ProcessInfo.processInfo.environmentlet path = try #require(environment["VPHONE_PATCH_FILE"])let resign = environment["VPHONE_PATCH_RESIGN"] != "0"@@ -163,7 +174,7 @@ struct CFWMobileactivationdRunnerTests {+ " foff=0x\(String(report.anchor.fileOffset, radix: 16, uppercase: true))"+ " section=\(report.anchor.section)"+ " anchor=\(report.anchor.source.rawValue)"- + " rehashes=\(report.slotRehashes.count)"+ + " rehashes=\(report.slotRehashes.count)",)for rehash in report.slotRehashes {print("RUNNER \(rehash.description)")@@ -182,17 +193,17 @@ struct CFWMobileactivationdAnchorTests {/// other — and they agree. That agreement is the evidence the anchor is the/// method and not something that merely sorts first.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func bothAnchorsResolveAndAgree() throws {+ func `both anchors resolve and agree`() throws {let data = try Data(contentsOf: MobileactivationdFixture.pristine)let segments = MachOParser.parseSegments(from: data)let bySymbol = try #require(CFWMobileactivationd.symbolVirtualAddress(in: data),- "LC_SYMTAB should carry -[DeviceType should_hactivate]"+ "LC_SYMTAB should carry -[DeviceType should_hactivate]",)let byMetadata = try #require(CFWMobileactivationd.objcMetadataVirtualAddress(in: data, segments: segments),- "the ObjC method lists should carry the same IMP"+ "the ObjC method lists should carry the same IMP",)#expect(bySymbol == byMetadata)@@ -201,7 +212,7 @@ struct CFWMobileactivationdAnchorTests {#expect(anchor.virtualAddress == bySymbol)#expect(anchor.section == "__TEXT,__text", "the IMP must be code, not data")#expect(- MachOParser.vaToFileOffset(anchor.virtualAddress, segments: segments) == anchor.fileOffset+ MachOParser.vaToFileOffset(anchor.virtualAddress, segments: segments) == anchor.fileOffset,)}@@ -214,11 +225,11 @@ struct CFWMobileactivationdAnchorTests {/// The naive search is reproduced below rather than described, so the/// contrast is measured here and does not depend on that Python existing.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func selectorLookupSkipsTheIvarName() throws {+ func `selector lookup skips the ivar name`() throws {let data = try Data(contentsOf: MobileactivationdFixture.pristine)let sections = MachOParser.parseSections(from: data)let selectorVA = try #require(- CFWMobileactivationd.selectorVirtualAddress(in: data, sections: sections)+ CFWMobileactivationd.selectorVirtualAddress(in: data, sections: sections),)let methname = try #require(sections["__TEXT,__objc_methname"])@@ -237,7 +248,7 @@ struct CFWMobileactivationdAnchorTests {/// A binary without the method is a hard stop, not a silent skip: every/// caller of this patch needs it to have happened.@Test(.enabled(if: MobileactivationdFixture.hasLaunchd))- func missingMethodThrows() throws {+ func `missing method throws`() throws {let data = try Data(contentsOf: MobileactivationdFixture.launchd)#expect(throws: PatcherError.self) {try CFWMobileactivationd.locateIMP(in: data)@@ -248,7 +259,7 @@ struct CFWMobileactivationdAnchorTests {/// asserted against keystone in `ARM64EncoderTests`; this pins that the/// patch asks it for the right instruction, and that the pair reads back as/// `mov x0, #1 ; ret`.- @Test func replacementIsMovX0OneThenRet() throws {+ @Test func `replacement is mov X 0 one then ret`() throws {let bytes = try CFWMobileactivationd.replacementBytes()#expect(bytes.count == 8)#expect(bytes == ARM64.movX0_1 + ARM64.ret)@@ -266,12 +277,12 @@ struct CFWMobileactivationdAnchorTests {/// Both words of the getter are re-hashed, so a getter that straddles a/// page boundary does not leave the second page's slot stale.- @Test func touchedOffsetsCoverBothWords() throws {+ @Test func `touched offsets cover both words`() throws {let anchor = CFWMobileactivationd.Anchor(virtualAddress: 0x1_0000_0FFC,fileOffset: 0xFFC,source: .symbolTable,- section: "__TEXT,__text"+ section: "__TEXT,__text",)let bytes = try CFWMobileactivationd.replacementBytes()let offsets = CFWMobileactivationd.touchedOffsets(anchor, bytes)@@ -288,7 +299,7 @@ struct CFWMobileactivationdParityTests {/// mismatch below would read as a patcher bug when the real cause is a/// different firmware's `mobileactivationd`.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func fixtureMatchesTheGoldens() throws {+ func `fixture matches the goldens`() throws {#expect(try MobileactivationdFixture.digest(of: MobileactivationdFixture.pristine)== MobileactivationdGolden.pristine,@@ -296,7 +307,7 @@ struct CFWMobileactivationdParityTests {this is not the 24A435 mobileactivationd MobileactivationdGolden \was recorded from — re-derive the goldens before reading a failure \below as a patcher bug- """+ """,)}@@ -306,7 +317,7 @@ struct CFWMobileactivationdParityTests {/// `resign: false` because the Python patcher did not re-sign — the/// `ldid_sign` in `cfw_install.sh` does — so this compares like with like.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func matchesTheFrozenReferenceBytes() throws {+ func `matches the frozen reference bytes`() throws {let swiftFile = try MobileactivationdFixture.copyOfPristine(named: "swift.bin")let report = try CFWMobileactivationd.patch(fileAt: swiftFile, resign: false, log: nil)@@ -316,7 +327,7 @@ struct CFWMobileactivationdParityTests {#expect(report.slotRehashes.isEmpty, "resign: false must not touch the signature")#expect(try MobileactivationdFixture.digest(of: swiftFile) == MobileactivationdGolden.patched,- "Swift output must be byte-identical to the reference's"+ "Swift output must be byte-identical to the reference's",)// And the one site it changed is the one the reference's symtab anchor@@ -340,7 +351,7 @@ struct CFWMobileactivationdParityTests {/// The raw patch does not: `codesign` rejects it, which is what makes this/// step load-bearing rather than decorative.@Test(.enabled(if: MobileactivationdFixture.hasCodesign))- func reattestedOutputMatchesTheFrozenReferenceAndVerifies() throws {+ func `reattested output matches the frozen reference and verifies`() throws {let swiftFile = try MobileactivationdFixture.copyOfPristine(named: "swift-resigned.bin")let report = try CFWMobileactivationd.patch(fileAt: swiftFile, resign: true, log: nil)@@ -351,7 +362,7 @@ struct CFWMobileactivationdParityTests {let swiftBytes = try Data(contentsOf: swiftFile)#expect(Data(SHA256.hash(data: swiftBytes)).hex == MobileactivationdGolden.patchedAndReattested,- "re-attested output must match the reference's"+ "re-attested output must match the reference's",)// The slot hash itself, not just the file: read it back out.@@ -359,7 +370,7 @@ struct CFWMobileactivationdParityTests {#expect(swiftBytes[slot] == rehash.after)let verified = try MobileactivationdFixture.run(- MobileactivationdFixture.codesign, ["-v", swiftFile.path]+ MobileactivationdFixture.codesign, ["-v", swiftFile.path],)#expect(verified.status == 0, "codesign -v rejected the patched binary: \(verified.output)")@@ -367,7 +378,7 @@ struct CFWMobileactivationdParityTests {let unsigned = try MobileactivationdFixture.copyOfPristine(named: "swift-unsigned.bin")try CFWMobileactivationd.patch(fileAt: unsigned, resign: false, log: nil)let rejected = try MobileactivationdFixture.run(- MobileactivationdFixture.codesign, ["-v", unsigned.path]+ MobileactivationdFixture.codesign, ["-v", unsigned.path],)#expect(rejected.status != 0, "an un-re-attested patch should not verify")}@@ -376,7 +387,7 @@ struct CFWMobileactivationdParityTests {/// neither an error nor a double-apply. `8eb6c8b` fixed exactly this class/// of bug for the DSC gates; it does not get to come back here.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func secondRunChangesNothing() throws {+ func `second run changes nothing`() throws {let file = try MobileactivationdFixture.copyOfPristine(named: "swift-idempotent.bin")let first = try CFWMobileactivationd.patch(fileAt: file, log: nil)@@ -401,7 +412,7 @@ struct CFWMobileactivationdParityTests {/// on the next run rather than reported as already done and left to be/// SIGKILLed on first page-in.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func rerunRepairsAStaleSlot() throws {+ func `rerun repairs A stale slot`() throws {let file = try MobileactivationdFixture.copyOfPristine(named: "swift-stale-slot.bin")try CFWMobileactivationd.patch(fileAt: file, resign: false, log: nil)@@ -413,7 +424,7 @@ struct CFWMobileactivationdParityTests {/// A dry run reports the site and leaves the file exactly as it found it.@Test(.enabled(if: MobileactivationdFixture.hasPristine))- func dryRunWritesNothing() throws {+ func `dry run writes nothing`() throws {let file = try MobileactivationdFixture.copyOfPristine(named: "swift-dry-run.bin")let before = try Data(contentsOf: file)diff --git a/tests/FirmwarePatcherTests/CFWPlistPatchTests.swift b/tests/FirmwarePatcherTests/CFWPlistPatchTests.swiftindex 3a246a97..14576c12 100644--- a/tests/FirmwarePatcherTests/CFWPlistPatchTests.swift+++ b/tests/FirmwarePatcherTests/CFWPlistPatchTests.swift@@ -80,7 +80,7 @@ enum CFWPlistPatchGolden {/// SHA-256 as `shasum -a 256` prints it.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}}@@ -124,16 +124,20 @@ enum CFWPatchFixtures {let ipswDirectory = repoRoot.appending(path: "ipsws")let candidates = (try? FileManager.default.contentsOfDirectory(at: ipswDirectory,- includingPropertiesForKeys: nil+ includingPropertiesForKeys: nil,)) ?? []for candidate in candidates where candidate.pathExtension == "ipsw" {let listing = (try? run("/usr/bin/unzip", ["-l", candidate.path, deviceTreeEntry]))?.output ?? ""- if listing.contains(deviceTreeEntry) { return candidate }+ if listing.contains(deviceTreeEntry) {+ return candidate+ }}return nil}- static var deviceTreeAvailable: Bool { ipswWithDeviceTree() != nil }+ static var deviceTreeAvailable: Bool {+ ipswWithDeviceTree() != nil+ }/// Extract the device tree IM4P into `directory` and return its path.static func extractDeviceTree(into directory: URL) throws -> URL {@@ -167,8 +171,13 @@ enum CFWPatchFixtures {let status: Int32let outputData: Datalet errorData: Data- var output: String { String(decoding: outputData, as: UTF8.self) }- var combined: String { output + String(decoding: errorData, as: UTF8.self) }+ var output: String {+ String(decoding: outputData, as: UTF8.self)+ }++ var combined: String {+ output + String(decoding: errorData, as: UTF8.self)+ }}@discardableResult@@ -186,7 +195,7 @@ enum CFWPatchFixtures {return CommandResult(status: process.terminationStatus,outputData: outputData,- errorData: errorData+ errorData: errorData,)}@@ -218,6 +227,7 @@ enum CFWTestError: Error, CustomStringConvertible {}// MARK: - Semantic plist comparison+//// Migration plan §7.1: same key set, same array order, same value types,// same Data bytes. Serialized key order and the XML-vs-binary encoding are@@ -225,7 +235,9 @@ enum CFWTestError: Error, CustomStringConvertible {enum PlistComparison {static func tag(_ value: Any) -> String {- if CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID() { return "bool" }+ if CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID() {+ return "bool"+ }switch value {case is [String: Any]: return "dict"case is [Any]: return "array"@@ -292,7 +304,7 @@ enum PlistComparison {try PropertyListSerialization.propertyList(from: Data(contentsOf: url),options: [],- format: nil+ format: nil,)}}@@ -300,14 +312,14 @@ enum PlistComparison {// MARK: - CFWBuildVersionstruct CFWBuildVersionTests {- @Test func detectsXMLAndBinaryFormats() {+ @Test func `detects XML and binary formats`() {#expect(CFWBuildVersion.detectFormat(Data("<?xml version=\"1.0\"?>".utf8)) == .xml)#expect(CFWBuildVersion.detectFormat(Data("\n\t <plist>".utf8)) == .xml)#expect(CFWBuildVersion.detectFormat(Data("bplist00".utf8)) == .binary)#expect(CFWBuildVersion.detectFormat(Data()) == .binary)}- @Test func rewritesTheKeyAndLeavesEverythingElseAlone() throws {+ @Test func `rewrites the key and leaves everything else alone`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "SystemVersion.plist")@@ -329,7 +341,7 @@ struct CFWBuildVersionTests {#expect(patched?["ProductName"] as? String == "iPhone OS")}- @Test func isIdempotentAndHonoursDryRun() throws {+ @Test func `is idempotent and honours dry run`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "SystemVersion.plist")@@ -346,7 +358,7 @@ struct CFWBuildVersionTests {#expect(try Data(contentsOf: url) == before)}- @Test func refusesAPlistWithoutTheKey() throws {+ @Test func `refuses A plist without the key`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "SystemVersion.plist")@@ -358,7 +370,7 @@ struct CFWBuildVersionTests {}}- @Test func refusesANonDictionaryRoot() throws {+ @Test func `refuses A non dictionary root`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "root-array.plist")@@ -371,7 +383,7 @@ struct CFWBuildVersionTests {}@Test(.enabled(if: CFWPatchFixtures.systemVersionAvailable))- func matchesTheFrozenReferenceOnARealSystemVersionPlist() throws {+ func `matches the frozen reference on A real system version plist`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let target = CFWPlistPatchGolden.buildVersionTarget@@ -411,7 +423,7 @@ struct CFWMachLookupExceptionTests {.write(to: url)}- @Test func addsEveryServiceWhenTheKeyIsAbsent() throws {+ @Test func `adds every service when the key is absent`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "Campo.entitlements")@@ -427,7 +439,7 @@ struct CFWMachLookupExceptionTests {#expect(patched?["platform-application"] as? Bool == true)}- @Test func keepsExistingEntriesFirstAndDoesNotDuplicate() throws {+ @Test func `keeps existing entries first and does not duplicate`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "Campo.entitlements")@@ -444,7 +456,7 @@ struct CFWMachLookupExceptionTests {#expect(Set(merged).isSuperset(of: CFWMachLookupExceptions.services))}- @Test func isIdempotent() throws {+ @Test func `is idempotent`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "Campo.entitlements")@@ -457,7 +469,7 @@ struct CFWMachLookupExceptionTests {#expect(try Data(contentsOf: url) == once)}- @Test func refusesAnExceptionKeyThatIsNotAnArray() throws {+ @Test func `refuses an exception key that is not an array`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "Campo.entitlements")@@ -468,7 +480,7 @@ struct CFWMachLookupExceptionTests {}@Test(.enabled(if: CFWPatchFixtures.entitlementsDonorAvailable))- func matchesTheFrozenReferenceOnRealEntitlements() throws {+ func `matches the frozen reference on real entitlements`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let key = CFWPlistPatchGolden.exceptionKey@@ -494,14 +506,18 @@ struct CFWMachLookupExceptionTests {CFWPlistPatchGolden.countLine(total: outcome.total, added: outcome.added)== CFWPlistPatchGolden.countLine(total: expectedServices.count,- added: expectedServices.count - existing.count+ added: expectedServices.count - existing.count,),- "\(name)"+ "\(name)",)// Nothing but that key moved.var expected = after- if let original = before[key] { expected[key] = original } else { expected[key] = nil }+ if let original = before[key] {+ expected[key] = original+ } else {+ expected[key] = nil+ }let difference = PlistComparison.difference(before, expected)#expect(difference == nil, "\(name): \(difference ?? "")")}@@ -512,7 +528,9 @@ struct CFWMachLookupExceptionTests {enum DERTestEncoder {static func length(_ count: Int) -> Data {- if count < 0x80 { return Data([UInt8(count)]) }+ if count < 0x80 {+ return Data([UInt8(count)])+ }var bytes: [UInt8] = []var remaining = countwhile remaining > 0 {@@ -550,7 +568,9 @@ enum DERTestEncoder {if first & 0x80 != 0 {let byteCount = Int(first & 0x7F)count = 0- for index in 0 ..< byteCount { count = (count << 8) | Int(data[cursor + index]) }+ for index in 0 ..< byteCount {+ count = (count << 8) | Int(data[cursor + index])+ }cursor += byteCount}return (tag, cursor, count)@@ -572,7 +592,7 @@ enum DERTestEncoder {struct CFWPostRestoreDeviceTreeTests {@Test(.enabled(if: CFWPatchFixtures.deviceTreeAvailable))- func parseAndSerializeRoundTripsARealDeviceTree() throws {+ func `parse and serialize round trips A real device tree`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let im4p = try CFWPatchFixtures.extractDeviceTree(into: directory)@@ -590,7 +610,7 @@ struct CFWPostRestoreDeviceTreeTests {}@Test(.enabled(if: CFWPatchFixtures.deviceTreeAvailable))- func rewritesExactlyTheThreeRestoreFatalProperties() throws {+ func `rewrites exactly the three restore fatal properties`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let im4p = try CFWPatchFixtures.extractDeviceTree(into: directory)@@ -614,7 +634,7 @@ struct CFWPostRestoreDeviceTreeTests {}@Test(.enabled(if: CFWPatchFixtures.deviceTreeAvailable))- func matchesTheFrozenReferenceByteForByteOnARealDeviceTree() throws {+ func `matches the frozen reference byte for byte on A real device tree`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let source = try CFWPatchFixtures.extractDeviceTree(into: directory)@@ -629,7 +649,7 @@ struct CFWPostRestoreDeviceTreeTests {no frozen reference output for a DeviceTree.vphone600ap.im4p with \digest \(input) — re-derive CFWPlistPatchGolden.deviceTree for this \IPSW before reading a failure here as a patcher bug- """+ """,)let swiftOutput = directory.appending(path: "swift.im4p")@@ -640,7 +660,7 @@ struct CFWPostRestoreDeviceTreeTests {#expect(outcome.changes.count == 3)#expect(try CFWPlistPatchGolden.digest(of: swiftOutput) == expected,- "IM4P differs from the frozen reference output"+ "IM4P differs from the frozen reference output",)// And the re-run is a no-op, as the reference's was: it printed@@ -660,7 +680,7 @@ struct CFWPostRestoreDeviceTreeTests {/// every element around it must come back byte for byte, because the/// manifest and restore info are carried, never re-encoded.@Test(.enabled(if: CFWPatchFixtures.deviceTreeAvailable))- func preservesEverythingAroundTheIM4PInAnIMG4() throws {+ func `preserves everything around the IM 4 P in an IMG 4`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let source = try CFWPatchFixtures.extractDeviceTree(into: directory)@@ -698,7 +718,7 @@ struct CFWPostRestoreDeviceTreeTests {}@Test(.enabled(if: CFWPatchFixtures.deviceTreeAvailable))- func refusesAPayloadThatIsNotADeviceTree() throws {+ func `refuses A payload that is not A device tree`() throws {let directory = try CFWPatchFixtures.makeTemporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let url = directory.appending(path: "not-a-dt.im4p")diff --git a/tests/FirmwarePatcherTests/CFWSeputilTests.swift b/tests/FirmwarePatcherTests/CFWSeputilTests.swiftindex 8c0f4f59..b5f705a6 100644--- a/tests/FirmwarePatcherTests/CFWSeputilTests.swift+++ b/tests/FirmwarePatcherTests/CFWSeputilTests.swift@@ -64,7 +64,9 @@ private enum SeputilFixture {}/// The suite runs unless the binary is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 iPhone17,3 seputil is required — put it at \@@ -85,7 +87,7 @@ private enum SeputilFixture {/// SHA-256 as `shasum -a 256` prints it, so a digest asserted here can be/// taken again from a shell over the same file.static func digest(of url: URL) throws -> String {- Data(SHA256.hash(data: try Data(contentsOf: url))).hex+ try Data(SHA256.hash(data: Data(contentsOf: url))).hex}static var codesign: URL? {@@ -98,21 +100,21 @@ private enum SeputilFixture {guard let pristine else { throw CocoaError(.fileNoSuchFile) }try FileManager.default.createDirectory(at: scratchRoot,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let destination = scratchRoot.appendingPathComponent(name)try? FileManager.default.removeItem(at: destination)var result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: ["-c", pristine.path, destination.path]+ arguments: ["-c", pristine.path, destination.path],)if result.status != 0 {// A fixture on another volume cannot be cloned. Copying is slower// but correct, and a refusal here would look like a patch bug.result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: [pristine.path, destination.path]+ arguments: [pristine.path, destination.path],)}guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }@@ -122,7 +124,9 @@ private enum SeputilFixture {/// Discard clones, and the scratch root with them once the last one is/// gone, so a test run leaves the working tree as it found it.static func discard(_ clones: URL...) {- for clone in clones { try? FileManager.default.removeItem(at: clone) }+ for clone in clones {+ try? FileManager.default.removeItem(at: clone)+ }let remaining = (try? FileManager.default.contentsOfDirectory(atPath: scratchRoot.path)) ?? []if remaining.isEmpty {@@ -157,7 +161,7 @@ private enum Subprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -182,7 +186,7 @@ private enum SeputilGolden {/// The bytes the Python changed, from a byte diff of ``patched`` against/// ``pristine``: `%s` -> `AA` at 0x1BDD2, and nothing else in the file.- static let modifiedOffsets = [0x1_BDD2, 0x1_BDD3]+ static let modifiedOffsets = [0x1BDD2, 0x1BDD3]/// ``patched``, then/// `.venv/bin/python3 -c 'import sys; sys.path.insert(0, "scripts/patchers");@@ -203,7 +207,7 @@ struct CFWSeputilParityTests {/// The fixture the frozen digests were taken over. Without this the two/// tests below would report a digest mismatch when the real cause is a/// different firmware's `seputil`.- @Test func fixtureIsTheOneTheGoldensWereTakenFrom() throws {+ @Test func `fixture is the one the goldens were taken from`() throws {let pristine = try #require(SeputilFixture.pristine, SeputilFixture.missing)#expect(try SeputilFixture.digest(of: pristine) == SeputilGolden.pristine,@@ -211,7 +215,7 @@ struct CFWSeputilParityTests {this is not the 24A435 iPhone17,3 seputil the goldens in \SeputilGolden were recorded from — re-derive them before reading a \failure below as a patcher bug- """+ """,)}@@ -220,7 +224,7 @@ struct CFWSeputilParityTests {/// Run with `reattest: false`, which was the reference's own behaviour —/// `cfw_install.sh` re-signs with `ldid` right after, so the Python left/// the signature stale.- @Test func matchesTheFrozenReferencePatch() throws {+ @Test func `matches the frozen reference patch`() throws {let pristine = try #require(SeputilFixture.pristine, SeputilFixture.missing)let swiftFile = try SeputilFixture.clone(named: "swift-plain")defer { SeputilFixture.discard(swiftFile) }@@ -230,14 +234,14 @@ struct CFWSeputilParityTests {#expect(outcome.verdict == .patched)#expect(try SeputilFixture.digest(of: swiftFile) == SeputilGolden.patched,- "Swift must reproduce the seputil the reference wrote, byte for byte"+ "Swift must reproduce the seputil the reference wrote, byte for byte",)// The same two bytes, at the same two offsets, that the reference moved.#expect(outcome.site.modifiedOffsets == SeputilGolden.modifiedOffsets)// And the comparison is not two copies of the input: the file moved.#expect(try SeputilFixture.digest(of: swiftFile) != SeputilGolden.pristine)- #expect(try Data(contentsOf: swiftFile) != (try Data(contentsOf: pristine)))+ #expect(try Data(contentsOf: swiftFile) != Data(contentsOf: pristine))}/// The same for the whole pipeline, re-attestation included. The Python@@ -247,7 +251,7 @@ struct CFWSeputilParityTests {/// This is the slot-hash comparison: the hashes are covered where they/// live, in the file, by a digest of what the reference implementation/// computed.- @Test func matchesTheFrozenReferencePlusItsOwnReattester() throws {+ @Test func `matches the frozen reference plus its own reattester`() throws {let swiftFile = try SeputilFixture.clone(named: "swift-full")defer { SeputilFixture.discard(swiftFile) }@@ -257,14 +261,14 @@ struct CFWSeputilParityTests {#expect(outcome.rehashes.first?.pageIndex == SeputilGolden.reattestedSlot)#expect(try SeputilFixture.digest(of: swiftFile) == SeputilGolden.patchedAndReattested,- "the re-attested slot hash must be the one the reference computed"+ "the re-attested slot hash must be the one the reference computed",)}/// `codesign -v`, in both directions. The re-attested binary verifies; the/// one that reproduces the frozen Python bytes does not, which is why/// `cfw_install.sh` had to run `ldid_sign` after the Python.- @Test func reattestationIsWhatMakesTheBinaryVerify() throws {+ @Test func `reattestation is what makes the binary verify`() throws {let codesign = try #require(SeputilFixture.codesign)let pristine = try #require(SeputilFixture.pristine, SeputilFixture.missing)let reattested = try SeputilFixture.clone(named: "swift-verify")@@ -292,7 +296,7 @@ struct CFWSeputilParityTests {/// wrote: the literal no longer reads `%s/%s.gl`, so a patcher that only/// knows the pristine spelling fails here instead of reporting "already/// patched". That is the bug `8eb6c8b` fixed for two DSC gates.- @Test func aSecondRunChangesNothing() throws {+ @Test func `a second run changes nothing`() throws {let file = try SeputilFixture.clone(named: "twice")defer { SeputilFixture.discard(file) }@@ -316,7 +320,7 @@ struct CFWSeputilParityTests {}/// A dry run reports the site and leaves the file alone.- @Test func aDryRunWritesNothing() throws {+ @Test func `a dry run writes nothing`() throws {let file = try SeputilFixture.clone(named: "dry")defer { SeputilFixture.discard(file) }let before = try Data(contentsOf: file)@@ -332,7 +336,7 @@ struct CFWSeputilParityTests {/// What the patcher anchored on, stated in full: the literal, the field/// inside it, and the instruction that materialises its address.- @Test func anchorsOnTheReferencedGigalockerLiteral() throws {+ @Test func `anchors on the referenced gigalocker literal`() throws {let file = try SeputilFixture.clone(named: "anchor")defer { SeputilFixture.discard(file) }let data = try Data(contentsOf: file)@@ -363,7 +367,7 @@ struct CFWSeputilParityTests {/// The record carries the reference's own `patchID`, `component` and/// wording, so a captured reference JSON compares field for field.- @Test func recordsTheSiteTheWayTheReferenceDoes() throws {+ @Test func `records the site the way the reference does`() throws {let file = try SeputilFixture.clone(named: "record")defer { SeputilFixture.discard(file) }@@ -384,7 +388,7 @@ struct CFWSeputilParityTests {/// Exactly the dirtied page is re-hashed, and the short tail slot — which/// this fixture has, and which is the known regression in independent/// Mach-O re-signing — is left alone because nothing was written in it.- @Test func reattestationTouchesOnlyTheDirtiedPage() throws {+ @Test func `reattestation touches only the dirtied page`() throws {let file = try SeputilFixture.clone(named: "pages")defer { SeputilFixture.discard(file) }let before = try Data(contentsOf: file)@@ -392,7 +396,7 @@ struct CFWSeputilParityTests {let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: before)?.first)try #require(directory.codeLimit % directory.pageSize != 0,- "this fixture is supposed to have a short tail slot"+ "this fixture is supposed to have a short tail slot",)let outcome = try CFWSeputil.patch(fileAt: file, log: nil)@@ -425,7 +429,7 @@ struct CFWSeputilParityTests {/// and patches it. Here the `adrp`/`add` that materialises the literal is/// erased first, and the patcher has to stop rather than rewrite bytes no/// code reads.- @Test func refusesALiteralNothingReferences() throws {+ @Test func `refuses A literal nothing references`() throws {let file = try SeputilFixture.clone(named: "unreferenced")defer { SeputilFixture.discard(file) }var data = try Data(contentsOf: file)@@ -460,7 +464,7 @@ struct CFWSeputilShapeTests {sectionName: "__cstring",address: address,size: UInt64(size),- fileOffset: offset+ fileOffset: offset,)}@@ -474,7 +478,7 @@ struct CFWSeputilShapeTests {return data}- @Test func readsTheFieldAfterTheLastSeparator() {+ @Test func `reads the field after the last separator`() {// The mountpoint field is left alone; the one after the last "/" moves.let field = try? #require(CFWSeputil.fileField(of: Array("%s/%s.gl".utf8)))#expect(field == 3 ..< 5)@@ -487,19 +491,19 @@ struct CFWSeputilShapeTests {#expect(CFWSeputil.fileField(of: Array(".gl".utf8)) == nil)}- @Test func classifiesOnlyTheTwoSpellingsItWrites() {+ @Test func `classifies only the two spellings it writes`() {#expect(CFWSeputil.pristineness(of: ArraySlice("%s".utf8)) == true)#expect(CFWSeputil.pristineness(of: ArraySlice("AA".utf8)) == false)#expect(CFWSeputil.pristineness(of: ArraySlice("BB".utf8)) == nil)}- @Test func matchesWholeLiteralsOnly() throws {+ @Test func `matches whole literals only`() throws {// "%s.gl" is the next literal after "%s/%s.gl" on the real binary, and// also its tail; a substring search sees both, a literal search one.let data = cstrings(["%s/%s.gl", "%s.gl", "/mnt7"])let site = try CFWSeputil.findSite(in: data,- cstring: section(at: 0, size: data.count, address: 0x1_0000_0000)+ cstring: section(at: 0, size: data.count, address: 0x1_0000_0000),)#expect(site.literalOffset == 16)#expect(site.literal == "%s/%s.gl")@@ -507,34 +511,34 @@ struct CFWSeputilShapeTests {#expect(site.fieldVMA == 0x1_0000_0013)}- @Test func findsTheAlreadyPatchedSpelling() throws {+ @Test func `finds the already patched spelling`() throws {let data = cstrings(["%s/AA.gl"])let site = try CFWSeputil.findSite(in: data,- cstring: section(at: 0, size: data.count, address: 0x1_0000_0000)+ cstring: section(at: 0, size: data.count, address: 0x1_0000_0000),)#expect(site.isPristine == false)#expect(site.fieldOffset == 19)}- @Test func refusesWhenThereIsNoCandidate() {+ @Test func `refuses when there is no candidate`() {let data = cstrings(["%s.gl", "/mnt7", "/private/xarts"])#expect(throws: PatcherError.self) {try CFWSeputil.findSite(in: data,- cstring: section(at: 0, size: data.count, address: 0x1_0000_0000)+ cstring: section(at: 0, size: data.count, address: 0x1_0000_0000),)}}/// Two candidates is not a coin flip to be taken; it is a binary this/// patcher does not recognise.- @Test func refusesWhenThereAreTwoCandidates() {+ @Test func `refuses when there are two candidates`() {let data = cstrings(["%s/%s.gl", "/mnt7", "%s/%s.gl"])#expect(throws: PatcherError.self) {try CFWSeputil.findSite(in: data,- cstring: section(at: 0, size: data.count, address: 0x1_0000_0000)+ cstring: section(at: 0, size: data.count, address: 0x1_0000_0000),)}}@@ -547,26 +551,26 @@ struct CFWSeputilShapeTests {sectionName: "__text",address: address,size: UInt64(size),- fileOffset: 0+ fileOffset: 0,)}- @Test func pairsAnAdrpWithItsAdd() throws {+ @Test func `pairs an adrp with its add`() throws {let pc: UInt64 = 0x1_0000_0000let target: UInt64 = 0x1_0001_BDCFvar code = try #require(ARM64Encoder.encodeADRP(rd: 2, pc: pc, target: target))- code.append(try #require(ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: 0xDCF)))+ try code.append(#require(ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: 0xDCF)))#expect(CFWSeputil.references(to: target, in: code, text: text(size: 8, address: pc)) == [pc + 4])// A different literal on the same page is a different address.#expect(CFWSeputil.references(to: target + 1, in: code, text: text(size: 8, address: pc)).isEmpty)}- @Test func rejectsAnAddIntoAnotherRegister() throws {+ @Test func `rejects an add into another register`() throws {let pc: UInt64 = 0x1_0000_0000let target: UInt64 = 0x1_0001_BDCFvar code = try #require(ARM64Encoder.encodeADRP(rd: 2, pc: pc, target: target))- code.append(try #require(ARM64Encoder.encodeAddImm12(rd: 3, rn: 3, imm12: 0xDCF)))+ try code.append(#require(ARM64Encoder.encodeAddImm12(rd: 3, rn: 3, imm12: 0xDCF)))#expect(CFWSeputil.references(to: target, in: code, text: text(size: 8, address: pc)).isEmpty)}@@ -574,7 +578,7 @@ struct CFWSeputilShapeTests {/// Treating it as the latter would pair it with an `adrp` it has nothing to/// do with, so the `sh` bit is read off the encoding — the Swift Capstone/// wrapper does not expose an operand's shift.- @Test func rejectsAShiftedAddImmediate() throws {+ @Test func `rejects A shifted add immediate`() throws {let pc: UInt64 = 0x1_0000_0000let target: UInt64 = 0x1_0001_BDCFlet adrp = try #require(ARM64Encoder.encodeADRP(rd: 2, pc: pc, target: target))diff --git a/tests/FirmwarePatcherTests/CFWWatchdogdTests.swift b/tests/FirmwarePatcherTests/CFWWatchdogdTests.swiftindex bf4b9980..6ed1b0aa 100644--- a/tests/FirmwarePatcherTests/CFWWatchdogdTests.swift+++ b/tests/FirmwarePatcherTests/CFWWatchdogdTests.swift@@ -42,15 +42,27 @@ enum WatchdogdFixture {static let codesign = URL(filePath: "/usr/bin/codesign")- static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }+ static func exists(_ url: URL) -> Bool {+ FileManager.default.fileExists(atPath: url.path)+ }/// SHA-256 as `shasum -a 256` prints it, so a digest in this run's output/// can be compared against one taken from a shell.- static func digest(_ data: Data) -> String { Data(SHA256.hash(data: data)).hex }+ static func digest(_ data: Data) -> String {+ Data(SHA256.hash(data: data)).hex+ }++ static var hasWatchdogd: Bool {+ exists(watchdogd)+ }- static var hasWatchdogd: Bool { exists(watchdogd) }- static var hasSeputil: Bool { exists(seputil) }- static var hasCodesign: Bool { hasWatchdogd && exists(codesign) }+ static var hasSeputil: Bool {+ exists(seputil)+ }++ static var hasCodesign: Bool {+ hasWatchdogd && exists(codesign)+ }/// A private copy of `source` the caller may modify freely. Deliberately/// outside the working tree.@@ -102,9 +114,11 @@ enum WatchdogdFixture {where instruction.mnemonic == "bl"{guard let target = ARM64Encoder.decodeBranchTarget(- insn: CFWWatchdogd.word(of: instruction), pc: instruction.address+ insn: CFWWatchdogd.word(of: instruction), pc: instruction.address,) else { continue }- if symbols.name(forBranchTarget: target) == "_sysctlbyname" { found.append(instruction.address) }+ if symbols.name(forBranchTarget: target) == "_sysctlbyname" {+ found.append(instruction.address)+ }}return found}@@ -148,7 +162,7 @@ enum WatchdogdGolden {struct CFWWatchdogdAnchorTests {/// The shape the patch is written against, read off the real binary.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func locatesBothCacheSites() throws {+ func `locates both cache sites`() throws {let data = try Data(contentsOf: WatchdogdFixture.watchdogd)let sites = try CFWWatchdogd.locateSites(in: data)@@ -159,12 +173,12 @@ struct CFWWatchdogdAnchorTests {// The gate really is the `cbnz w0` right after the call...#expect(site.gateVMA == site.callVMA + 4)let gate = try #require(ARM64Disassembler().disassembleOne(- data.subdata(in: site.gateFileOffset ..< site.gateFileOffset + 4), at: site.gateVMA+ data.subdata(in: site.gateFileOffset ..< site.gateFileOffset + 4), at: site.gateVMA,))#expect(gate.mnemonic == "cbnz")// ...and the value really is a `cset`.let value = try #require(ARM64Disassembler().disassembleOne(- data.subdata(in: site.valueFileOffset ..< site.valueFileOffset + 4), at: site.valueVMA+ data.subdata(in: site.valueFileOffset ..< site.valueFileOffset + 4), at: site.valueVMA,))#expect(value.mnemonic == "cset")#expect(value.aarch64?.conditionCode == AArch64CC_NE)@@ -174,7 +188,7 @@ struct CFWWatchdogdAnchorTests {/// The cached byte is a zero-filled global, which is why the skipped store/// leaves it reading 0 and why forcing the stored value to 1 is the fix.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func cachedByteLivesInZeroFilledData() throws {+ func `cached byte lives in zero filled data`() throws {let data = try Data(contentsOf: WatchdogdFixture.watchdogd)let sites = try CFWWatchdogd.locateSites(in: data)let sections = MachOParser.parseSections(from: data)@@ -194,21 +208,23 @@ struct CFWWatchdogdAnchorTests {/// matched on "a call followed by cbnz w0" alone would have to be checked/// by hand; this states the number.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func rejectsTheOtherSysctlCallSites() throws {+ func `rejects the other sysctl call sites`() throws {let data = try Data(contentsOf: WatchdogdFixture.watchdogd)let calls = try WatchdogdFixture.sysctlCallSites(in: data)let sites = try CFWWatchdogd.locateSites(in: data)#expect(calls.count == 5, "24A435 watchdogd calls sysctlbyname five times")#expect(sites.count == 2)- for site in sites { #expect(calls.contains(site.callVMA)) }+ for site in sites {+ #expect(calls.contains(site.callVMA))+ }}/// The in-image symbol lookup the anchor rests on, checked on its own: a/// stub address in `__auth_stubs` resolves through the indirect symbol/// table to the imported name.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func resolvesTheImportThroughTheIndirectSymbolTable() throws {+ func `resolves the import through the indirect symbol table`() throws {let data = try Data(contentsOf: WatchdogdFixture.watchdogd)let symbols = try #require(CFWWatchdogdSymbolTargets(data: data))let sites = try CFWWatchdogd.locateSites(in: data)@@ -219,7 +235,7 @@ struct CFWWatchdogdAnchorTests {let offset = Int(call.callVMA - 0x1_0000_0000)return data.loadLE(UInt32.self, at: offset)}(),- pc: call.callVMA+ pc: call.callVMA,))#expect(symbols.importName(atStub: target) == "_sysctlbyname")// An address that is not a stub resolves to nothing rather than to the@@ -236,7 +252,7 @@ struct CFWWatchdogdAnchorTests {/// patch working when a later build schedules the argument differently, so/// it is checked here instead of assumed.@Test- func acceptsTheLiteralReachingX0ThroughAMove() throws {+ func `accepts the literal reaching X 0 through A move`() throws {let base: UInt64 = 0x1_0000_0000func stream(movingInto destination: UInt32?) throws -> [Instruction] {@@ -253,20 +269,20 @@ struct CFWWatchdogdAnchorTests {}// add x9, … ; mov x0, x9 ; bl — the literal is the call's argument.- #expect(CFWWatchdogd.passesLiteral(- inRegister: "x9", from: 1, toCallAt: 3, in: try stream(movingInto: 0)+ #expect(try CFWWatchdogd.passesLiteral(+ inRegister: "x9", from: 1, toCallAt: 3, in: stream(movingInto: 0),))// The same shape moving into x1 is some other call's argument.- #expect(!CFWWatchdogd.passesLiteral(- inRegister: "x9", from: 1, toCallAt: 3, in: try stream(movingInto: 1)+ #expect(try !CFWWatchdogd.passesLiteral(+ inRegister: "x9", from: 1, toCallAt: 3, in: stream(movingInto: 1),))// No move at all, and the pointer never reaches x0.- #expect(!CFWWatchdogd.passesLiteral(- inRegister: "x9", from: 1, toCallAt: 3, in: try stream(movingInto: nil)+ #expect(try !CFWWatchdogd.passesLiteral(+ inRegister: "x9", from: 1, toCallAt: 3, in: stream(movingInto: nil),))// The direct form the shipped binary uses needs no move.- #expect(CFWWatchdogd.passesLiteral(- inRegister: "x0", from: 1, toCallAt: 3, in: try stream(movingInto: nil)+ #expect(try CFWWatchdogd.passesLiteral(+ inRegister: "x0", from: 1, toCallAt: 3, in: stream(movingInto: nil),))}@@ -274,7 +290,7 @@ struct CFWWatchdogdAnchorTests {/// error, not a silent no-op: "no site" and "already patched" must not be/// the same answer.@Test(.enabled(if: WatchdogdFixture.hasSeputil))- func rejectsABinaryWithoutTheCacheSite() throws {+ func `rejects A binary without the cache site`() throws {let data = try Data(contentsOf: WatchdogdFixture.seputil)#expect(throws: PatcherError.self) {try CFWWatchdogd.locateSites(in: data)@@ -288,7 +304,7 @@ struct CFWWatchdogdAnchorTests {struct CFWWatchdogdPatchTests {/// Both instructions, and nothing else in `__TEXT`.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func rewritesTwoInstructionsPerSite() throws {+ func `rewrites two instructions per site`() throws {let original = try Data(contentsOf: WatchdogdFixture.watchdogd)var data = originallet report = try CFWWatchdogd.patch(&data, log: nil)@@ -320,7 +336,7 @@ struct CFWWatchdogdPatchTests {/// Every page that was written gets its slot re-hashed — checked against/// the code directory's own slot arithmetic rather than the patcher's.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func reattestsThePageOfEveryWrittenInstruction() throws {+ func `reattests the page of every written instruction`() throws {var data = try Data(contentsOf: WatchdogdFixture.watchdogd)let report = try CFWWatchdogd.patch(&data, log: nil)let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: data)?.first)@@ -332,7 +348,7 @@ struct CFWWatchdogdPatchTests {let range = try #require(directory.slotRange(slot.pageIndex))let stored = data.subdata(in: directory.slotHashOffset(slot.pageIndex)- ..< directory.slotHashOffset(slot.pageIndex) + directory.hashSize+ ..< directory.slotHashOffset(slot.pageIndex) + directory.hashSize,)#expect(stored == slot.after)#expect(slot.pageStart ..< slot.pageEnd == range)@@ -344,7 +360,7 @@ struct CFWWatchdogdPatchTests {/// second run must change nothing at all — not the instructions, not the/// code directory, not one byte of the file.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func secondRunChangesNothing() throws {+ func `second run changes nothing`() throws {var data = try Data(contentsOf: WatchdogdFixture.watchdogd)let first = try CFWWatchdogd.patch(&data, log: nil)#expect(first.outcome == .patched)@@ -366,7 +382,7 @@ struct CFWWatchdogdPatchTests {/// A dry run reports the sites and writes nothing.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func dryRunWritesNothing() throws {+ func `dry run writes nothing`() throws {let original = try Data(contentsOf: WatchdogdFixture.watchdogd)var data = originallet report = try CFWWatchdogd.patch(&data, dryRun: true, log: nil)@@ -377,7 +393,7 @@ struct CFWWatchdogdPatchTests {/// The file-backed entry point, which is what the install script calls.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func patchesInPlaceOnDisk() throws {+ func `patches in place on disk`() throws {let file = try WatchdogdFixture.scratchCopy(of: WatchdogdFixture.watchdogd, named: "watchdogd")defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }@@ -400,7 +416,7 @@ struct CFWWatchdogdPatchTests {/// A second run over a file on disk leaves its bytes, and its mtime,/// untouched — `.alreadyPatched` must not write at all.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func secondRunOnDiskWritesNothing() throws {+ func `second run on disk writes nothing`() throws {let file = try WatchdogdFixture.scratchCopy(of: WatchdogdFixture.watchdogd, named: "watchdogd")defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }@@ -425,30 +441,30 @@ struct CFWWatchdogdReferenceTests {/// mismatch below would read as a patcher bug when the real cause is a/// different firmware's `watchdogd`.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func fixtureMatchesTheGoldens() throws {+ func `fixture matches the goldens`() throws {#expect(- WatchdogdFixture.digest(try Data(contentsOf: WatchdogdFixture.watchdogd))+ try WatchdogdFixture.digest(Data(contentsOf: WatchdogdFixture.watchdogd))== WatchdogdGolden.pristine,"""this is not the 24A435 watchdogd WatchdogdGolden was recorded from \— re-derive the goldens before reading a failure below as a \patcher bug- """+ """,)}/// The migration plan's gate for P1.2: the Swift patcher and the Python it/// replaced must produce the same bytes from the same input.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func matchesTheFrozenReferenceByteForByte() throws {+ func `matches the frozen reference byte for byte`() throws {var mine = try Data(contentsOf: WatchdogdFixture.watchdogd)let report = try CFWWatchdogd.patch(&mine, log: nil)// Printed so the parity claim is checkable from outside this process:// `shasum -a 256` over this patcher's output has to read the same.- print("""+ try print("""watchdogd parity: \- pristine=\(WatchdogdFixture.digest(try Data(contentsOf: WatchdogdFixture.watchdogd))) \+ pristine=\(WatchdogdFixture.digest(Data(contentsOf: WatchdogdFixture.watchdogd))) \golden=\(WatchdogdGolden.patched) \swift=\(WatchdogdFixture.digest(mine))""")@@ -456,16 +472,16 @@ struct CFWWatchdogdReferenceTests {#expect(report.rehashedSlots.map(\.pageIndex).sorted() == WatchdogdGolden.reattestedSlots)#expect(WatchdogdFixture.digest(mine) == WatchdogdGolden.patched,- "Swift output must be identical to the frozen reference's"+ "Swift output must be identical to the frozen reference's",)}/// The reference's idempotent path, for the same reason: both/// implementations agree that a patched binary needs nothing done to it.@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))- func agreesWithTheFrozenReferenceOnAnAlreadyPatchedBinary() throws {+ func `agrees with the frozen reference on an already patched binary`() throws {let file = try WatchdogdFixture.scratchCopy(- of: WatchdogdFixture.watchdogd, named: "watchdogd-twice"+ of: WatchdogdFixture.watchdogd, named: "watchdogd-twice",)defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }@@ -478,16 +494,16 @@ struct CFWWatchdogdReferenceTests {// nothing. This port lands on the same bytes when it re-runs.let second = try CFWWatchdogd.patch(at: file, log: nil)#expect(second.outcome == .alreadyPatched)- #expect(WatchdogdFixture.digest(try Data(contentsOf: file)) == WatchdogdGolden.patchedTwice)+ #expect(try WatchdogdFixture.digest(Data(contentsOf: file)) == WatchdogdGolden.patchedTwice)}/// `codesign` recomputes the page hashes independently of this code. If the/// re-attestation were wrong — the short tail slot being the classic way —/// this is where it shows.@Test(.enabled(if: WatchdogdFixture.hasCodesign))- func patchedBinaryStillVerifiesUnderCodesign() throws {+ func `patched binary still verifies under codesign`() throws {let file = try WatchdogdFixture.scratchCopy(- of: WatchdogdFixture.watchdogd, named: "watchdogd-signed"+ of: WatchdogdFixture.watchdogd, named: "watchdogd-signed",)defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }diff --git a/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift b/tests/FirmwarePatcherTests/CryptexFileOpsTests.swiftindex 1f9f549c..e88c61a2 100644--- a/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift+++ b/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift@@ -71,14 +71,16 @@ struct CryptexFileOpsTests {String(cString: $0)}}- if name != "." && name != ".." { names.append(name) }+ if name != ".", name != ".." {+ names.append(name)+ }}return names.sorted()}// MARK: - chmod- @Test func theModeIsTheModeItWasGiven() throws {+ @Test func `the mode is the mode it was given`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -97,7 +99,7 @@ struct CryptexFileOpsTests {// MARK: - ln -sf- @Test func aSymlinkStoresItsDestinationVerbatim() throws {+ @Test func `a symlink stores its destination verbatim`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -113,7 +115,7 @@ struct CryptexFileOpsTests {#expect(stored == destination)}- @Test func rerunningReplacesTheLinkInsteadOfFailing() throws {+ @Test func `rerunning replaces the link instead of failing`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -127,7 +129,7 @@ struct CryptexFileOpsTests {#expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == "../second")}- @Test func aPlainFileInTheWayIsReplaced() throws {+ @Test func `a plain file in the way is replaced`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -139,7 +141,7 @@ struct CryptexFileOpsTests {#expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == "../elsewhere")}- @Test func aDirectoryInTheWayIsAnErrorRatherThanANestedLink() throws {+ @Test func `a directory in the way is an error rather than A nested link`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -160,7 +162,7 @@ struct CryptexFileOpsTests {// MARK: - find -name '._*' -delete- @Test func appleDoubleFilesGoIncludingNestedOnes() throws {+ @Test func `apple double files go including nested ones`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -178,7 +180,9 @@ struct CryptexFileOpsTests {bundle.appendingPathComponent("Info.plist"),codeSignature.appendingPathComponent("CodeResources"),]- for file in doomed + kept { try touch(file) }+ for file in doomed + kept {+ try touch(file)+ }// The fixture has to be real before the sweep is worth anything: if// `touch` had gone through Foundation, these names would not be here// and the sweep would "pass" by finding nothing.@@ -194,7 +198,7 @@ struct CryptexFileOpsTests {#expect(realEntryNames(in: codeSignature) == ["CodeResources"])}- @Test func aTreeWithNoneOfThemIsNotAFailure() throws {+ @Test func `a tree with none of them is not A failure`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -205,7 +209,7 @@ struct CryptexFileOpsTests {// MARK: - chown -R- @Test func theOwnershipWalkDoesNotFollowSymlinks() throws {+ @Test func `the ownership walk does not follow symlinks`() throws {let scratch = try makeScratch()defer { try? FileManager.default.removeItem(at: scratch) }let patcher = makePatcher(scratch)@@ -219,7 +223,7 @@ struct CryptexFileOpsTests {// defaults to the latter, and so must this.try FileManager.default.createSymbolicLink(atPath: nested.appendingPathComponent("dangling").path,- withDestinationPath: "../../gone/missing"+ withDestinationPath: "../../gone/missing",)// Re-applying the ids this process already has: a no-op that still@@ -243,33 +247,33 @@ struct CryptexFileOpsTests {</plist>"""- @Test func theMaxSizeComesBackAsTheStringDiskutilWantsBack() throws {+ @Test func `the max size comes back as the string diskutil wants back`() throws {#expect(try CryptexFilesystemPatcher.maxResizeSize(- fromDiskutilPlist: Self.sizesPlist+ fromDiskutilPlist: Self.sizesPlist,) == "21474836480")}- @Test func noiseInFrontOfThePlistDoesNotBreakTheParse() throws {+ @Test func `noise in front of the plist does not break the parse`() throws {// runProcess points stderr at the same pipe as stdout, so this is what// a diskutil with anything to say actually returns. The shell pipeline// this replaced handed that whole string to `--size`.let noisy = "Warning: some warning from diskutil\n" + Self.sizesPlist#expect(try CryptexFilesystemPatcher.maxResizeSize(- fromDiskutilPlist: noisy+ fromDiskutilPlist: noisy,) == "21474836480")}- @Test func outputThatIsNotAPlistIsAnError() {+ @Test func `output that is not A plist is an error`() {#expect(throws: ProcessError.self) {try CryptexFilesystemPatcher.maxResizeSize(- fromDiskutilPlist: "Could not find disk: /tmp/nope.img"+ fromDiskutilPlist: "Could not find disk: /tmp/nope.img",)}}- @Test func aPlistWithoutAMaxKeyIsAnError() {+ @Test func `a plist without A max key is an error`() {let withoutMax = Self.sizesPlist.replacingOccurrences(- of: "<key>max</key>", with: "<key>maximum</key>"+ of: "<key>max</key>", with: "<key>maximum</key>",)#expect(throws: ProcessError.self) {try CryptexFilesystemPatcher.maxResizeSize(fromDiskutilPlist: withoutMax)diff --git a/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift b/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swiftindex f4f8da19..ebd2db33 100644--- a/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift+++ b/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift@@ -27,8 +27,8 @@// instant and near-free on APFS — and are discarded afterwards.// `VPHONE_DSC_SCRATCH` moves them somewhere else on the same volume.-@testable import FirmwarePatcherimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -142,7 +142,9 @@ private enum CameraFixture {ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"}- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -172,15 +174,15 @@ private enum CameraFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let result = try CameraSubprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),arguments: ["-c", "-R"]- + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))+ + (FileManager.default.contentsOfDirectory(atPath: pristine.path)).sorted().map { pristine.appendingPathComponent($0).path }- + [destination.path]+ + [destination.path],)#expect(result.status == 0, "cp -c failed: \(result.stderr)")return destination@@ -237,12 +239,14 @@ private enum CameraSubprocess {static func run(executable: URL,arguments: [String],- environment: [String: String]? = nil+ environment: [String: String]? = nil,) throws -> Result {let process = Process()process.executableURL = executableprocess.arguments = arguments- if let environment { process.environment = environment }+ if let environment {+ process.environment = environment+ }let out = Pipe()let err = Pipe()process.standardOutput = out@@ -255,7 +259,7 @@ private enum CameraSubprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -266,8 +270,8 @@ private enum CameraSubprocess {struct DSCCameraPatcherParityTests {/// The gate. One clone, one run, one byte-for-byte comparison against the/// digests the reference left on every chunk file in the cache.- @Test("Swift leaves the real cache in the reference's bytes")- func matchesTheReferenceByteForByte() throws {+ @Test+ func `Swift leaves the real cache in the reference's bytes`() throws {let pristine = try #require(CameraFixture.pristine, CameraFixture.missing)let swiftSide = try CameraFixture.cloneCache(named: "camera_swift")@@ -276,7 +280,7 @@ struct DSCCameraPatcherParityTests {var log: [String] = []let result = try DSCCameraPatcher.applyAll(chunksDirectory: swiftSide,- log: { log.append($0) }+ log: { log.append($0) },)#expect(result.siteCount == 6, "the port wrote \(result.siteCount) sites, not 6")#expect(result.isComplete)@@ -289,7 +293,7 @@ struct DSCCameraPatcherParityTests {for site in result.sites {let theirs = try #require(reference[site.symbol],- "the reference did not report \(site.symbol)"+ "the reference did not report \(site.symbol)",)#expect(site.vma == theirs.vma, "\(site.symbol) address")#expect(site.originalBytes.hex == theirs.before, "\(site.symbol) original bytes")@@ -311,15 +315,17 @@ struct DSCCameraPatcherParityTests {print("[camera parity] \(result.siteCount) sites, "+ "\(result.reattestation?.updated.count ?? 0) slots rewritten, "+ "\(mine.count) chunk files, \(changed.count) with the reference's digests")- for line in log where line.contains("re-attest: wrote") { print(line) }+ for line in log where line.contains("re-attest: wrote") {+ print(line)+ }}/// The reference re-attested per family off bare addresses; this re-attests/// once at the end off recorded spans. Same pages on this cache — which is/// worth checking rather than assuming, because it is the only reason the/// two runs can come out identical.- @Test("The port re-attests exactly the pages the reference did")- func reattestedPagesMatchTheReference() throws {+ @Test+ func `The port re-attests exactly the pages the reference did`() throws {_ = try #require(CameraFixture.pristine, CameraFixture.missing)let swiftSide = try CameraFixture.cloneCache(named: "camera_pages_swift")@@ -329,19 +335,19 @@ struct DSCCameraPatcherParityTests {let minePages = Set((result.reattestation?.updated ?? []).map {"\($0.chunkURL.lastPathComponent):\($0.pageIndex)"- }+ },)#expect(minePages == FrozenReference.reattestedPages,- "swift \(minePages.sorted()) vs reference \(FrozenReference.reattestedPages.sorted())"+ "swift \(minePages.sorted()) vs reference \(FrozenReference.reattestedPages.sorted())",)print("[camera pages] \(minePages.sorted().joined(separator: ", "))")}/// Patch ids feed `cfw_records`, which is what a captured reference is/// keyed on. A port that renames them writes records nothing lines up with.- @Test("Patch ids match the reference's _sym_slug")- func patchIDsMatchTheReference() throws {+ @Test+ func `Patch ids match the reference's _sym_slug`() {let symbols = DSCCameraPatcher.styleTransferSymbols+ [DSCCameraPatcher.authorizationStatusSymbol]let mine = symbols.map(DSCCameraPatcher.symbolSlug)@@ -351,13 +357,13 @@ struct DSCCameraPatcherParityTests {/// Both replacements come out of the Keystone-checked encoders, and both/// have to be what keystone itself assembled.- @Test("Both replacements are the bytes keystone assembled")- func replacementsMatchKeystone() throws {+ @Test+ func `Both replacements are the bytes keystone assembled`() throws {let styleTransfer = try DSCCameraPatcher.replacement(- returning: DSCCameraPatcher.Family.neutrinoStyleTransfer.returnValue+ returning: DSCCameraPatcher.Family.neutrinoStyleTransfer.returnValue,)let authorization = try DSCCameraPatcher.replacement(- returning: DSCCameraPatcher.Family.avfAuthorization.returnValue+ returning: DSCCameraPatcher.Family.avfAuthorization.returnValue,)#expect(styleTransfer.hex == FrozenReference.keystoneReturningZero)#expect(authorization.hex == FrozenReference.keystoneReturningThree)@@ -371,8 +377,8 @@ struct DSCCameraPatcherParityTests {@Suite(.serialized, .enabled(if: CameraFixture.runs, CameraFixture.skipReason))struct DSCCameraPatcherBehaviourTests {- @Test("A dry run finds every site and writes nothing")- func dryRunWritesNothing() throws {+ @Test+ func `A dry run finds every site and writes nothing`() throws {let pristine = try #require(CameraFixture.pristine, CameraFixture.missing)let clone = try CameraFixture.cloneCache(named: "camera_dryrun")@@ -381,7 +387,7 @@ struct DSCCameraPatcherBehaviourTests {let result = try DSCCameraPatcher.applyAll(chunksDirectory: clone,dryRun: true,- log: nil+ log: nil,)#expect(result.siteCount == 6)#expect(result.dryRun)@@ -394,8 +400,8 @@ struct DSCCameraPatcherBehaviourTests {print("[camera dry run] \(result.siteCount) sites reported, \(after.count) files unchanged")}- @Test("AVF-only mode patches one site and leaves NeutrinoCore alone")- func avfOnlyPatchesOneSite() throws {+ @Test+ func `AVF-only mode patches one site and leaves NeutrinoCore alone`() throws {let pristine = try #require(CameraFixture.pristine, CameraFixture.missing)let clone = try CameraFixture.cloneCache(named: "camera_avf_only")@@ -403,7 +409,7 @@ struct DSCCameraPatcherBehaviourTests {let result = try DSCCameraPatcher.applyAVFAuthorizationOnly(chunksDirectory: clone,- log: nil+ log: nil,)#expect(result.siteCount == 1)#expect(result.sites.first?.family == .avfAuthorization)@@ -421,7 +427,7 @@ struct DSCCameraPatcherBehaviourTests {let resolver = try DSCSymbolResolver(chunks: chunks)let untouched = try resolver.addresses(of: DSCCameraPatcher.styleTransferSymbols,- inImage: DSCCameraPatcher.Family.neutrinoStyleTransfer.imagePath+ inImage: DSCCameraPatcher.Family.neutrinoStyleTransfer.imagePath,)for (symbol, vma) in untouched {let head = try chunks.bytesAtVMA(vma, length: 4)@@ -432,8 +438,8 @@ struct DSCCameraPatcherBehaviourTests {/// Three sibling DSC gates shipped a version that raised on their own/// output. This one recognises it.- @Test("A second run over an already-patched cache is inert, not an error")- func reRunIsIdempotent() throws {+ @Test+ func `A second run over an already-patched cache is inert, not an error`() throws {_ = try #require(CameraFixture.pristine, CameraFixture.missing)let clone = try CameraFixture.cloneCache(named: "camera_idempotent")@@ -447,8 +453,8 @@ struct DSCCameraPatcherBehaviourTests {let second = try DSCCameraPatcher.applyAll(chunksDirectory: clone, log: nil)#expect(second.siteCount == 6)#expect(- second.sites.allSatisfy { $0.wasAlreadyPatched },- "a re-run did not recognise its own output"+ second.sites.allSatisfy(\.wasAlreadyPatched),+ "a re-run did not recognise its own output",)#expect(second.reattestation?.updated.isEmpty == true, "a re-run rewrote slot hashes")#expect(second.isComplete)@@ -473,8 +479,8 @@ struct DSCCameraPatcherBehaviourTests {/// half-patched and unloadable — it SIGKILLs on the first demand-page-in of/// a modified page. `apply` now plans every family before it writes any of/// them, so a failure writes nothing at all.- @Test("A failure part-way through leaves the cache untouched")- func failureWritesNothing() throws {+ @Test+ func `A failure part-way through leaves the cache untouched`() throws {_ = try #require(CameraFixture.pristine, CameraFixture.missing)let clone = try CameraFixture.cloneCache(named: "camera_midrun_failure")@@ -487,7 +493,7 @@ struct DSCCameraPatcherBehaviourTests {let resolver = try DSCSymbolResolver(chunks: chunks)let avf = try resolver.address(of: DSCCameraPatcher.authorizationStatusSymbol,- inImage: DSCCameraPatcher.Family.avfAuthorization.imagePath+ inImage: DSCCameraPatcher.Family.avfAuthorization.imagePath,)try chunks.write(at: avf, ARM64.nop)try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: nil)@@ -504,13 +510,13 @@ struct DSCCameraPatcherBehaviourTests {print(changed.isEmpty? "[camera failure] applyAll threw and wrote nothing — \(before.count) files unchanged"- : "[camera failure] applyAll threw AFTER writing \(changed.joined(separator: ", "))"+ : "[camera failure] applyAll threw AFTER writing \(changed.joined(separator: ", "))",)}/// The reference's `--force`, and what it is a guard against.- @Test("An unexpected prologue is refused unless forced")- func unexpectedPrologueIsRefused() throws {+ @Test+ func `An unexpected prologue is refused unless forced`() throws {_ = try #require(CameraFixture.pristine, CameraFixture.missing)let clone = try CameraFixture.cloneCache(named: "camera_force")@@ -522,7 +528,7 @@ struct DSCCameraPatcherBehaviourTests {let resolver = try DSCSymbolResolver(chunks: chunks)let vma = try resolver.address(of: DSCCameraPatcher.authorizationStatusSymbol,- inImage: DSCCameraPatcher.Family.avfAuthorization.imagePath+ inImage: DSCCameraPatcher.Family.avfAuthorization.imagePath,)try chunks.write(at: vma, ARM64.nop)try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: nil)@@ -530,7 +536,7 @@ struct DSCCameraPatcherBehaviourTests {#expect(throws: PatcherError.self) {_ = try DSCCameraPatcher.applyAVFAuthorizationOnly(chunksDirectory: clone,- log: nil+ log: nil,)}@@ -538,7 +544,7 @@ struct DSCCameraPatcherBehaviourTests {let forced = try DSCCameraPatcher.applyAVFAuthorizationOnly(chunksDirectory: clone,force: true,- log: { log.append($0) }+ log: { log.append($0) },)#expect(forced.siteCount == 1)#expect(forced.sites.first?.wasAlreadyPatched == false)@@ -554,8 +560,8 @@ struct DSCCameraPatcherBehaviourTests {/// The prologue classifier decides whether a site may be written at all, so/// it is worth exercising away from the cache too — including the shape a/// byte comparison would get right only by coincidence.- @Test("The prologue classifier reads instructions, not bytes")- func prologueClassifierIsSemantic() throws {+ @Test+ func `The prologue classifier reads instructions, not bytes`() throws {let disassembler = ARM64Disassembler()let replacement = try DSCCameraPatcher.replacement(returning: 3)@@ -567,7 +573,7 @@ struct DSCCameraPatcherBehaviourTests {returning: 3,disassembler: disassembler,force: force,- log: nil+ log: nil,)}@@ -603,14 +609,14 @@ struct DSCCameraPatcherBehaviourTests {/// A cache with no `.symbols` side file cannot resolve an ObjC method, and/// has to say so rather than reporting six renamed symbols.- @Test("A cache without local symbols fails loudly")- func missingLocalSymbolsFailsLoudly() throws {+ @Test+ func `A cache without local symbols fails loudly`() throws {_ = try #require(CameraFixture.pristine, CameraFixture.missing)let clone = try CameraFixture.cloneCache(named: "camera_no_symbols")defer { CameraFixture.discard(clone) }try FileManager.default.removeItem(- at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols")+ at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols"),)#expect(throws: DSCError.self) {diff --git a/tests/FirmwarePatcherTests/DSCFoundationTests.swift b/tests/FirmwarePatcherTests/DSCFoundationTests.swiftindex 42cb869b..65708573 100644--- a/tests/FirmwarePatcherTests/DSCFoundationTests.swift+++ b/tests/FirmwarePatcherTests/DSCFoundationTests.swift@@ -27,8 +27,8 @@// Nothing here writes to the pristine directory. The re-signing tests clone it// — `clonefile`, so instant and free on APFS — and work in the copy.-@testable import FirmwarePatcherimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -105,9 +105,9 @@ private enum FrozenReference {static let images: [(site: UInt64, header: UInt64, installName: String)] = [(0x2_2AC0_C334, 0x2_2AC0_B000,"/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"),- (0x1BF4_33BD0, 0x1BF1_43000,+ (0x1_BF43_3BD0, 0x1_BF14_3000,"/System/Library/PrivateFrameworks/NeutrinoCore.framework/NeutrinoCore"),- (0x1AD8_A12D8, 0x1AD8_4B000,+ (0x1_AD8A_12D8, 0x1_AD84_B000,"/System/Library/PrivateFrameworks/AVFCapture.framework/AVFCapture"),]@@ -193,7 +193,9 @@ private enum FrozenReference {/// padding for addresses and file offsets, decimal for everything else, single/// spaces between fields, one trailing newline at the end of the table.private enum Canonical {- static func hex(_ value: UInt64) -> String { String(value, radix: 16) }+ static func hex(_ value: UInt64) -> String {+ String(value, radix: 16)+ }static func sha256(of text: String) -> String {SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined()@@ -210,7 +212,7 @@ private enum Canonical {/// `vma length chunk file_offset bytes`, in request order.static func probes(_ chunks: DSCChunkSet,- _ requests: [(UInt64, Int)]+ _ requests: [(UInt64, Int)],) throws -> String {try requests.map { vma, length inlet located = try #require(chunks.findChunk(forVMA: vma))@@ -265,7 +267,9 @@ private enum DSCFixture {}/// The suites run unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -301,15 +305,15 @@ private enum DSCFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),arguments: ["-c", "-R"]- + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))+ + (FileManager.default.contentsOfDirectory(atPath: pristine.path)).sorted().map { pristine.appendingPathComponent($0).path }- + [destination.path]+ + [destination.path],)guard result.status == 0 else {throw CocoaError(.fileWriteUnknown)@@ -345,12 +349,14 @@ private enum Subprocess {static func run(executable: URL,arguments: [String],- currentDirectory: URL? = nil+ currentDirectory: URL? = nil,) throws -> Result {let process = Process()process.executableURL = executableprocess.arguments = arguments- if let currentDirectory { process.currentDirectoryURL = currentDirectory }+ if let currentDirectory {+ process.currentDirectoryURL = currentDirectory+ }let out = Pipe()let err = Pipe()process.standardOutput = out@@ -363,7 +369,7 @@ private enum Subprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -377,29 +383,28 @@ private enum SlotState {static func read(directory: URL,chunk: String,- page: Int+ page: Int,) throws -> (computed: String, stored: String, isAttested: Bool) {let url = directory.appendingPathComponent(chunk)let cd = try #require(try DSCCodeSignature.readCodeDirectory(ofChunk: url),- "\(chunk) carries no code directory"+ "\(chunk) carries no code directory",)let (computed, stored) = try DSCCodeSignature.pageHashes(chunkURL: url,pageIndex: page,- directory: cd+ directory: cd,)return (computed.hex, stored.hex, computed == stored)}}-// MARK: - 3.1 · Flat addressing@Suite(.serialized, .enabled(if: DSCFixture.runs, DSCFixture.skipReason))struct DSCFlatAddressingTests {- @Test("Chunk enumeration and mapping table match the reference")- func layoutMatchesTheReference() throws {+ @Test+ func `Chunk enumeration and mapping table match the reference`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -412,12 +417,12 @@ struct DSCFlatAddressingTests {#expect(Canonical.sha256(of: Canonical.mappings(chunks))== FrozenReference.mappingsSHA256,- "the mapping table no longer matches the reference's"+ "the mapping table no longer matches the reference's",)print("[layout] \(chunks.chunkURLs.count) chunks, \(chunks.mappings.count) mappings, "+ "vm 0x\(String(chunks.addressRange.lowerBound, radix: 16, uppercase: true))"- + "..0x\(String(chunks.addressRange.upperBound, radix: 16, uppercase: true))"+ + "..0x\(String(chunks.addressRange.upperBound, radix: 16, uppercase: true))",)}@@ -436,14 +441,14 @@ struct DSCFlatAddressingTests {}}// Real code sites, not just mapping arithmetic.- for site: UInt64 in [0x2_2AC0_C334, 0x1BF4_33BD0, 0x1AD8_A12D8, 0x2_2AC0_C1B0] {+ for site: UInt64 in [0x2_2AC0_C334, 0x1_BF43_3BD0, 0x1_AD8A_12D8, 0x2_2AC0_C1B0] {requests.append((site, 32))}return requests}- @Test("bytesAtVMA matches the reference across every mapping and boundary")- func bytesMatchTheReference() throws {+ @Test+ func `bytesAtVMA matches the reference across every mapping and boundary`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -455,7 +460,7 @@ struct DSCFlatAddressingTests {#expect(try Canonical.sha256(of: Canonical.probes(chunks, requests))== FrozenReference.probesSHA256,- "a read, or its address-to-file translation, no longer matches the reference"+ "a read, or its address-to-file translation, no longer matches the reference",)var boundaryChecks = 0@@ -470,8 +475,8 @@ struct DSCFlatAddressingTests {#expect(boundaryChecks >= 2)}- @Test("A read or write that leaves its chunk is refused, not truncated")- func boundaryCrossingIsRefused() throws {+ @Test+ func `A read or write that leaves its chunk is refused, not truncated`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let mapping = try #require(chunks.mappings.first { $0.size > 64 })@@ -505,8 +510,8 @@ struct DSCFlatAddressingTests {/// as the bytes at those virtual addresses. This is the one place the Swift/// deliberately diverges, and the test pins both halves: what the reference/// returned, and that the Swift refuses it.- @Test("An over-running read returned the chunk's signature; here it throws")- func overrunningReadIsRefusedUnlikeTheReference() throws {+ @Test+ func `An over-running read returned the chunk's signature; here it throws`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -530,8 +535,8 @@ struct DSCFlatAddressingTests {print("[overrun] swift threw; its in-bounds 4 bytes are \(inBounds.hex)")}- @Test("resolveLocalSymbol matches the reference and ipsw")- func localSymbolMatchesReferences() throws {+ @Test+ func `resolveLocalSymbol matches the reference and ipsw`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -549,14 +554,14 @@ struct DSCFlatAddressingTests {/// The `try?` this replaced spelled "I could not open the table" and "that/// symbol does not exist" the same way, as `nil`. The reference raised/// `FileNotFoundError`; so does this, in its own vocabulary.- @Test("A missing local symbol table is not the same answer as a missing symbol")- func missingLocalSymbolTableIsNotAMissingSymbol() throws {+ @Test+ func `A missing local symbol table is not the same answer as a missing symbol`() throws {_ = try #require(DSCFixture.pristine, DSCFixture.missing)let clone = try DSCFixture.cloneCache(named: "symbols_removed")defer { DSCFixture.discard(clone) }try FileManager.default.removeItem(- at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols")+ at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols"),)let chunks = try DSCChunkSet(directory: clone)@@ -570,14 +575,14 @@ struct DSCFlatAddressingTests {// And the resolver built on the same cache says so rather than// reporting entry points with no siblings.let resolver = try DSCSymbolResolver(- mainCacheURL: clone.appendingPathComponent("dyld_shared_cache_arm64e")+ mainCacheURL: clone.appendingPathComponent("dyld_shared_cache_arm64e"),)#expect(!resolver.hasLocalSymbols)#expect(throws: DSCError.self) { try resolver.requireLocalSymbols() }#expect(throws: DSCError.self) {_ = try resolver.address(of: "_kern_SwapEnd",- inImage: "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"+ inImage: "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer",)}print("[symbols missing] resolveLocalSymbol and the resolver both report the absent table")@@ -586,8 +591,8 @@ struct DSCFlatAddressingTests {/// The two helpers P1.3's `hv_vmm` and canonical-site finders are built on:/// a C-string sweep of the executable mappings, and the walk back from an/// address to the image that owns it.- @Test("String search and image lookup match the reference")- func searchHelpersMatchTheReference() throws {+ @Test+ func `String search and image lookup match the reference`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -600,7 +605,7 @@ struct DSCFlatAddressingTests {#expect(Canonical.sha256(of: Canonical.addresses(mine))== FrozenReference.hvVMMStringsSHA256,- "the string sweep no longer finds the reference's hits"+ "the string sweep no longer finds the reference's hits",)print("[strings] \"\(needle)\": \(mine.count) hits, first 0x\(String(mine[0], radix: 16))")@@ -623,8 +628,8 @@ struct DSCCodeSignatureTests {/// whose slot a real patch would have to re-sign.private let patchSite = FrozenReference.patchSite- @Test("Chunk code directories match the reference")- func codeDirectoriesMatchTheReference() throws {+ @Test+ func `Chunk code directories match the reference`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -635,15 +640,15 @@ struct DSCCodeSignatureTests {#expect(Canonical.sha256(of: rows.joined(separator: "\n") + "\n")== FrozenReference.codeDirectoriesSHA256,- "a chunk's code directory no longer parses the way the reference parsed it"+ "a chunk's code directory no longer parses the way the reference parsed it",)print("[code directories] \(found) chunk signatures agreed with the reference")}/// The DSC path's stated invariants: 16 KiB pages, a single SHA-256 code/// directory, and no short tail slot.- @Test("Every signed chunk is 16 KiB paged, SHA-256, and chunk-aligned")- func dscPathShapeHolds() throws {+ @Test+ func `Every signed chunk is 16 KiB paged, SHA-256, and chunk-aligned`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)var checked = 0@@ -658,7 +663,7 @@ struct DSCCodeSignatureTests {let covered = directory.codeSlotCount * directory.pageSize#expect(covered == directory.codeLimit,- "\(url.lastPathComponent) has a short tail slot: codeLimit \(directory.codeLimit), slots cover \(covered)"+ "\(url.lastPathComponent) has a short tail slot: codeLimit \(directory.codeLimit), slots cover \(covered)",)checked += 1}@@ -668,8 +673,8 @@ struct DSCCodeSignatureTests {/// The gate from the plan: patch one byte, re-sign, and require the page/// and its slot to come out as the reference's did.- @Test("Re-signing produces the reference's slot hashes")- func reSigningMatchesTheReference() throws {+ @Test+ func `Re-signing produces the reference's slot hashes`() throws {_ = try #require(DSCFixture.pristine, DSCFixture.missing)let swiftSide = try DSCFixture.cloneCache(named: "resign_swift")@@ -692,7 +697,7 @@ struct DSCCodeSignatureTests {var log: [String] = []let result = try DSCCodeSignature.reattestRecordedWrites(in: chunks,- log: { log.append($0) }+ log: { log.append($0) },)#expect(result.updated.count == 1)#expect(result.isFullyAttested)@@ -711,12 +716,12 @@ struct DSCCodeSignatureTests {// stored slot has to be the digest of the page as it now stands.let chunkName = mine.chunkURL.lastPathComponentlet directory = try #require(- try DSCCodeSignature.readCodeDirectory(ofChunk: mine.chunkURL)+ try DSCCodeSignature.readCodeDirectory(ofChunk: mine.chunkURL),)let (computed, stored) = try DSCCodeSignature.pageHashes(chunkURL: mine.chunkURL,pageIndex: mine.pageIndex,- directory: directory+ directory: directory,)#expect(computed == stored)#expect(stored.hex == FrozenReference.resignHashAfter)@@ -724,7 +729,9 @@ struct DSCCodeSignatureTests {print("[re-sign] chunk \(chunkName) page \(mine.pageIndex) slot @0x\(String(mine.slotOffset, radix: 16))")print("[re-sign] swift \(mine.hashAfter.hex)")print("[re-sign] reference \(FrozenReference.resignHashAfter)")- for line in log { print(line) }+ for line in log {+ print(line)+ }}/// The finding all three verifiers reached independently, pinned.@@ -735,8 +742,8 @@ struct DSCCodeSignatureTests {/// covers one page; the other keeps its original slot hash, and the guest/// dies on the first demand-page-in of it. The reference did exactly that;/// this checks the Swift no longer can.- @Test("A write across a page boundary re-attests both pages, where the reference attested one")- func pageStraddlingWriteAttestsEveryDirtiedPage() throws {+ @Test+ func `A write across a page boundary re-attests both pages, where the reference attested one`() throws {_ = try #require(DSCFixture.pristine, DSCFixture.missing)let swiftSide = try DSCFixture.cloneCache(named: "straddle_swift")@@ -754,12 +761,12 @@ struct DSCCodeSignatureTests {#expect(span.length == 8)let (writtenChunk, writtenRange) = try chunks.fileRange(of: span)#expect(writtenChunk.lastPathComponent == chunkName)- #expect(writtenRange == 0x280_FFFC ..< 0x281_0004)+ #expect(writtenRange == 0x280FFFC ..< 0x2810004)var log: [String] = []let result = try DSCCodeSignature.reattestRecordedWrites(in: chunks,- log: { log.append($0) }+ log: { log.append($0) },)#expect(result.updated.map(\.pageIndex) == [firstPage, secondPage])#expect(result.isFullyAttested)@@ -787,7 +794,7 @@ struct DSCCodeSignatureTests {#expect(second.stored == FrozenReference.straddlePage2564Computed)#expect(FrozenReference.straddlePage2564Stored != FrozenReference.straddlePage2564Computed,- "the reference's own second page was stale, which is why this test exists"+ "the reference's own second page was stale, which is why this test exists",)print("[straddle reference] page \(secondPage) was left stored "+ "\(FrozenReference.straddlePage2564Stored.prefix(16))… vs computed "@@ -797,11 +804,13 @@ struct DSCCodeSignatureTests {// wrote them to.let swiftBytes = try DSCChunkSet.read(url: swiftSide.appendingPathComponent(chunkName),- offset: 0x280_FFFC,- length: 8+ offset: 0x280FFFC,+ length: 8,)#expect(swiftBytes == stub)- for line in log { print(line) }+ for line in log {+ print(line)+ }}/// A span may cross from one mapping into the next when the two are@@ -810,8 +819,8 @@ struct DSCCodeSignatureTests {/// mapping start addresses and refused all of them, where the reference/// wrote them happily. This one is accepted, and lands where the reference/// landed; the case where the file offsets break is still refused.- @Test("A write across contiguous mappings of one chunk lands where the reference put it")- func contiguousMappingSeamIsWritable() throws {+ @Test+ func `A write across contiguous mappings of one chunk lands where the reference put it`() throws {_ = try #require(DSCFixture.pristine, DSCFixture.missing)let swiftSide = try DSCFixture.cloneCache(named: "seam_swift")@@ -839,7 +848,7 @@ struct DSCCodeSignatureTests {let mine = try DSCChunkSet.read(url: swiftSide.appendingPathComponent(chunkName),offset: FrozenReference.seamFileOffset,- length: 4+ length: 4,)#expect(mine.hex == FrozenReference.seamBytes)#expect(mine == value)@@ -855,7 +864,7 @@ struct DSCCodeSignatureTests {chunks.mappings.first { mapping inguard let next = chunks.mapping(forVMA: mapping.endAddress) else { return false }return next.chunkURL != mapping.chunkURL- }+ },)#expect(throws: DSCError.self) {_ = try chunks.write(at: crossChunk.endAddress - 2, Data([0, 0, 0, 0]))@@ -865,8 +874,8 @@ struct DSCCodeSignatureTests {/// `8eb6c8b` fixed a patcher that did not recognise its own output. The/// same trap applies here: a second re-sign of an already-attested page has/// to be a no-op, not a rewrite and not an error.- @Test("Re-signing twice is a no-op the second time")- func reSigningIsIdempotent() throws {+ @Test+ func `Re-signing twice is a no-op the second time`() throws {_ = try #require(DSCFixture.pristine, DSCFixture.missing)let clone = try DSCFixture.cloneCache(named: "resign_idempotent")@@ -888,7 +897,7 @@ struct DSCCodeSignatureTests {let third = try DSCCodeSignature.reattest(in: chunks,modifiedSpans: [patchSite, patchSite + 4, patchSite + 8].map(DSCWriteSpan.byte(at:)),- log: nil+ log: nil,)#expect(third.updated.isEmpty)#expect(third.alreadyAttested.count == 1)@@ -899,8 +908,8 @@ struct DSCCodeSignatureTests {/// "I skipped an address I could not map", "everything already matched" and/// "you passed me nothing" were the same value. They are three different/// values now, and the default log is no longer silent.- @Test("A skipped page is distinguishable from nothing to do")- func skipsAreReportedNotSwallowed() throws {+ @Test+ func `A skipped page is distinguishable from nothing to do`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -908,7 +917,7 @@ struct DSCCodeSignatureTests {in: chunks,modifiedSpans: [DSCWriteSpan.byte(at: 0xDEAD_0000_0000)],dryRun: true,- log: nil+ log: nil,)#expect(stray.updated.isEmpty)#expect(stray.skipped.count == 1)@@ -923,7 +932,7 @@ struct DSCCodeSignatureTests {in: chunks,modifiedSpans: [] as [DSCWriteSpan],dryRun: true,- log: nil+ log: nil,)#expect(nothing.skipped.isEmpty)#expect(nothing.isFullyAttested, "nothing to do is a clean run")@@ -934,7 +943,7 @@ struct DSCCodeSignatureTests {in: chunks,modifiedSpans: [DSCWriteSpan(vma: mapping.endAddress - 2, length: 64)],dryRun: true,- log: nil+ log: nil,)#expect(overrun.skipped.count == 1)if case .spanNotAddressable = overrun.skipped[0].reason {} else {@@ -948,14 +957,16 @@ struct DSCCodeSignatureTests {in: chunks,modifiedSpans: [DSCWriteSpan.byte(at: 0xDEAD_0000_0000)],dryRun: true,- log: { spoken.append($0) }+ log: { spoken.append($0) },)#expect(spoken.contains { $0.contains("not mapped in any chunk") })- for line in spoken { print("[skip log] \(line)") }+ for line in spoken {+ print("[skip log] \(line)")+ }}- @Test("A dry run computes the same hash it would have written, and writes nothing")- func dryRunWritesNothing() throws {+ @Test+ func `A dry run computes the same hash it would have written, and writes nothing`() throws {_ = try #require(DSCFixture.pristine, DSCFixture.missing)let clone = try DSCFixture.cloneCache(named: "resign_dryrun")@@ -967,18 +978,18 @@ struct DSCCodeSignatureTests {let dry = try DSCCodeSignature.reattestRecordedWrites(in: chunks,dryRun: true,- log: nil+ log: nil,)#expect(dry.updated.count == 1)let record = try #require(dry.updated.first)let directory = try #require(- try DSCCodeSignature.readCodeDirectory(ofChunk: record.chunkURL)+ try DSCCodeSignature.readCodeDirectory(ofChunk: record.chunkURL),)let (_, storedAfterDryRun) = try DSCCodeSignature.pageHashes(chunkURL: record.chunkURL,pageIndex: record.pageIndex,- directory: directory+ directory: directory,)#expect(storedAfterDryRun == record.hashBefore, "a dry run must not touch the slot")@@ -1038,7 +1049,7 @@ struct DSCSymbolResolverTests {"dyld", "symaddr",cache.appendingPathComponent("dyld_shared_cache_arm64e").path,"--image", image,- ]+ ],)guard result.status == 0 else { return [:] }@@ -1053,21 +1064,23 @@ struct DSCSymbolResolverTests {else { continue }var rest = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)- guard rest.hasPrefix("(") , let close = rest.firstIndex(of: ")") else { continue }+ guard rest.hasPrefix("("), let close = rest.firstIndex(of: ")") else { continue }rest = String(rest[rest.index(after: close)...]).trimmingCharacters(in: .whitespaces)// The name may be followed by a tab and the image name; ObjC method// names contain spaces, so split on tabs only.let name = rest.split(separator: "\t").first.map(String.init) ?? rest- if symbols[name] == nil { symbols[name] = address }+ if symbols[name] == nil {+ symbols[name] = address+ }}return symbols}- @Test("Every symbol the three DSC patchers look up resolves, and agrees with ipsw")- func requiredSymbolsResolveAndAgree() throws {+ @Test+ func `Every symbol the three DSC patchers look up resolves, and agrees with ipsw`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let resolver = try DSCSymbolResolver(- mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e")+ mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e"),)#expect(resolver.hasLocalSymbols)@@ -1084,7 +1097,7 @@ struct DSCSymbolResolverTests {if let theirs = reference[name] {#expect(mine == theirs,- "\(name): swift 0x\(String(mine, radix: 16)) vs ipsw 0x\(String(theirs, radix: 16))"+ "\(name): swift 0x\(String(mine, radix: 16)) vs ipsw 0x\(String(theirs, radix: 16))",)agreed += 1print("[symbol] \(name) = 0x\(String(mine, radix: 16)) (ipsw agrees)")@@ -1098,11 +1111,11 @@ struct DSCSymbolResolverTests {#expect(agreed >= 13, "ipsw confirmed only \(agreed) symbols")}- @Test("The force-kern discovery shape is reproduced without ipsw")- func forceKernPairsAreDiscoverable() throws {+ @Test+ func `The force-kern discovery shape is reproduced without ipsw`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let resolver = try DSCSymbolResolver(- mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e")+ mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e"),)try resolver.requireLocalSymbols()@@ -1110,7 +1123,7 @@ struct DSCSymbolResolverTests {let all = try resolver.symbols(inImage: Self.ioMobileFramebuffer)let entryPoints = try resolver.symbols(inImage: Self.ioMobileFramebuffer,- withPrefix: publicPrefix+ withPrefix: publicPrefix,)var pairs: [(String, UInt64, String, UInt64)] = []@@ -1125,7 +1138,7 @@ struct DSCSymbolResolverTests {for required in ["SwapBegin", "SwapEnd", "SwapSetLayer"] {#expect(pairs.contains { $0.0 == publicPrefix + required.dropFirst(4) },- "missing entry point for \(required)"+ "missing entry point for \(required)",)}for pair in pairs {@@ -1134,16 +1147,16 @@ struct DSCSymbolResolverTests {#expect(pairs.count >= 3)}- @Test("A missing symbol and a missing image both fail loudly")- func missingLookupsThrow() throws {+ @Test+ func `A missing symbol and a missing image both fail loudly`() throws {let pristine = try #require(DSCFixture.pristine, DSCFixture.missing)let resolver = try DSCSymbolResolver(- mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e")+ mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e"),)#expect(throws: DSCError.self) {_ = try resolver.address(of: "_this_symbol_does_not_exist",- inImage: Self.ioMobileFramebuffer+ inImage: Self.ioMobileFramebuffer,)}#expect(throws: DSCError.self) {diff --git a/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift b/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swiftindex b812c1a4..21c80778 100644--- a/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift+++ b/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift@@ -29,8 +29,8 @@// are made with `clonefile` so a 6.7 GB copy is instant and costs almost no// disk.-@testable import FirmwarePatcherimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -131,7 +131,9 @@ private enum FrozenReference {]/// 29 sites across 29 dylibs; the other 15 entries above are the blacklist.- static var totalMangled: Int { mangledCountByInstallName.values.reduce(0, +) }+ static var totalMangled: Int {+ mangledCountByInstallName.values.reduce(0, +)+ }/// `cmp -s` against the pristine tree after the run: 17 chunks moved, with/// these digests (`shasum -a 256`). The Python logged 29 `re-attest: wrote@@ -228,23 +230,23 @@ private enum FrozenReference {sites: [MachOSite(stringVMA: 0x1_0001_1453,fileOffset: 70739,- section: "__TEXT,__cstring"+ section: "__TEXT,__cstring",)],pristineSHA256:"0309b868a214f9841279db3e2ef901f26e8c05b2dc616eeb551f2b2f0e06207f",patchedSHA256:- "95c9c25c89d20ee1d46b20ee8fd7a7b90c674ef57247a666e6cb19db123220e4"+ "95c9c25c89d20ee1d46b20ee8fd7a7b90c674ef57247a666e6cb19db123220e4",),"mobileactivationd": MachORun(sites: [MachOSite(stringVMA: 0x1_003B_BE2A,fileOffset: 3_915_306,- section: "__TEXT,__cstring"+ section: "__TEXT,__cstring",)],pristineSHA256:"89233513ce696cd01285f3432f3bcadd065cee07ac73bc5714836d13f24702d8",patchedSHA256:- "29814c1318b40cd1afc8ea021604f1b165c6ce3775e3a4f02106891b84ff4129"+ "29814c1318b40cd1afc8ea021604f1b165c6ce3775e3a4f02106891b84ff4129",),]}@@ -282,7 +284,9 @@ private enum HVVMMFixture {}/// The suites run unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }/// Same rule for the standalone Mach-O fixtures, which live under the same/// gitignored `ipsws/` tree and are therefore absent on a fresh clone.@@ -327,7 +331,7 @@ private enum HVVMMFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let sources = try FileManager.default.contentsOfDirectory(atPath: pristine.path)@@ -339,12 +343,12 @@ private enum HVVMMFixture {// than reporting a fixture problem as a patch failure.var result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: ["-c", "-R"] + sources + [destination.path]+ arguments: ["-c", "-R"] + sources + [destination.path],)if result.status != 0 {result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: ["-R"] + sources + [destination.path]+ arguments: ["-R"] + sources + [destination.path],)}guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }@@ -355,7 +359,7 @@ private enum HVVMMFixture {static func copyFile(_ source: URL, named name: String) throws -> URL {try FileManager.default.createDirectory(at: scratchRoot,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let destination = scratchRoot.appendingPathComponent(name)try? FileManager.default.removeItem(at: destination)@@ -404,7 +408,7 @@ private enum Subprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -420,8 +424,8 @@ private enum TreeComparison {/// after hashing 6.7 GB twice.static func changedNames(in directory: URL, against reference: URL) throws -> [String] {let manager = FileManager.default- let left = Set(try manager.contentsOfDirectory(atPath: reference.path))- let right = Set(try manager.contentsOfDirectory(atPath: directory.path))+ let left = try Set(manager.contentsOfDirectory(atPath: reference.path))+ let right = try Set(manager.contentsOfDirectory(atPath: directory.path))var differing = Array(left.symmetricDifference(right))for name in left.intersection(right) {@@ -431,9 +435,11 @@ private enum TreeComparison {"-s",reference.appendingPathComponent(name).path,directory.appendingPathComponent(name).path,- ]+ ],)- if result.status != 0 { differing.append(name) }+ if result.status != 0 {+ differing.append(name)+ }}return differing.sorted()}@@ -474,8 +480,8 @@ private enum Digest {/// port has to carry verbatim for anything else here to mean anything.@Suite(.serialized)struct DSCHVVMMConstantsTests {- @Test("The cstring, its mangle and the blacklist match the reference modules")- func constantsMatchTheReference() throws {+ @Test+ func `The cstring, its mangle and the blacklist match the reference modules`() {#expect(DSCHVVMMPatcher.needle.hex == FrozenReference.needleHex)#expect(DSCHVVMMPatcher.mangledNeedle.hex == FrozenReference.mangledNeedleHex)#expect(DSCHVVMMPatcher.mangleOffset == FrozenReference.mangleOffset)@@ -513,8 +519,8 @@ struct DSCHVVMMCacheParityTests {/// The idempotence and blacklist checks ride on the same clone rather than/// cloning 6.7 GB again for each: they are assertions about the state this/// test has already produced.- @Test("The Swift patch reproduces the reference's cache")- func swiftMatchesTheReferenceOnTheRealCache() throws {+ @Test+ func `The Swift patch reproduces the reference's cache`() throws {_ = try #require(HVVMMFixture.pristine, HVVMMFixture.missing)let swiftClone = try HVVMMFixture.cloneCache(named: "swift")@@ -541,7 +547,7 @@ struct DSCHVVMMCacheParityTests {print("[hv_vmm] \(result.mangled) site(s), "+ "\(result.skippedInBlacklist) blacklisted, "- + "\(slotsRewritten) slot(s) re-attested"+ + "\(slotsRewritten) slot(s) re-attested",)try Digest.expectMatches(swiftClone, FrozenReference.changedChunks)@@ -567,11 +573,11 @@ struct DSCHVVMMCacheParityTests {for vma in try chunks.findStringVMAs(DSCHVVMMPatcher.needle) {let installName = try #require(DSCHVVMMPatcher.classify(vma, in: chunks),- "a pristine cstring survived in a dylib that cannot be named"+ "a pristine cstring survived in a dylib that cannot be named",)#expect(DSCHVVMMPatcher.dontPatchSet.contains(installName),- "\(installName) is not blacklisted but kept the original cstring"+ "\(installName) is not blacklisted but kept the original cstring",)blacklistedSitesSeen += 1}@@ -581,13 +587,13 @@ struct DSCHVVMMCacheParityTests {let installName = try #require(DSCHVVMMPatcher.classify(vma, in: chunks))#expect(!DSCHVVMMPatcher.dontPatchSet.contains(installName),- "\(installName) is blacklisted but was mangled"+ "\(installName) is blacklisted but was mangled",)}}- @Test("A dry run reports the same sites and leaves every byte alone")- func dryRunTouchesNothing() throws {+ @Test+ func `A dry run reports the same sites and leaves every byte alone`() throws {let pristine = try #require(HVVMMFixture.pristine, HVVMMFixture.missing)let clone = try HVVMMFixture.cloneCache(named: "dryrun")@@ -596,7 +602,7 @@ struct DSCHVVMMCacheParityTests {let result = try DSCHVVMMPatcher.patch(chunksDirectory: clone,dryRun: true,- log: nil+ log: nil,)#expect(result.mangled == FrozenReference.totalMangled)// A dry run writes nothing, so every page still hashes to exactly what@@ -624,8 +630,8 @@ struct DSCHVVMMCacheParityTests {/// the page hash right and the operator's intent wrong. A port that "fixed"/// this by reverting, or by treating it as an error, would pass every other/// test in this file.- @Test("A blacklisted dylib found mangled is reported as drift, not reverted")- func blacklistDriftIsReportedNotReverted() throws {+ @Test+ func `A blacklisted dylib found mangled is reported as drift, not reverted`() throws {_ = try #require(HVVMMFixture.pristine, HVVMMFixture.missing)let swiftClone = try HVVMMFixture.cloneCache(named: "drift-swift")@@ -639,7 +645,7 @@ struct DSCHVVMMCacheParityTests {guard let name = DSCHVVMMPatcher.classify($0, in: probe) else { return false }return DSCHVVMMPatcher.dontPatchSet.contains(name)},- "no blacklisted dylib carries the cstring in this cache"+ "no blacklisted dylib carries the cstring in this cache",)let driftedDylib = try #require(DSCHVVMMPatcher.classify(driftVMA, in: probe))#expect(driftVMA == FrozenReference.driftVMA)@@ -650,7 +656,7 @@ struct DSCHVVMMCacheParityTests {let chunks = try DSCChunkSet(directory: swiftClone)try chunks.write(at: driftVMA &+ UInt64(DSCHVVMMPatcher.mangleOffset),- Data([DSCHVVMMPatcher.mangledByte])+ Data([DSCHVVMMPatcher.mangledByte]),)let result = try DSCHVVMMPatcher.patch(chunksDirectory: swiftClone, log: nil)@@ -661,7 +667,7 @@ struct DSCHVVMMCacheParityTests {#expect(result.refused == 0)#expect(result.skippedInBlacklist == DSCHVVMMPatcher.dontPatchInstallNames.count - 1,- "the drifted site is no longer pristine, so it is not counted as skipped"+ "the drifted site is no longer pristine, so it is not counted as skipped",)#expect(result.mangledCountByInstallName[driftedDylib] == nil)#expect(result.isFullyAttested)@@ -686,20 +692,19 @@ struct DSCHVVMMStandaloneTests {/// keeps pristine copies of. Each carries one occurrence of the cstring on/// this build.@Test(- "Standalone Mach-O mangling matches the reference",- arguments: ["watchdogd", "mobileactivationd"]+ arguments: ["watchdogd", "mobileactivationd"],)- func standaloneMatchesTheReference(name: String) throws {+ func `Standalone Mach-O mangling matches the reference`(name: String) throws {let pristine = try #require(HVVMMFixture.machO(name),"""ipsws/ref_extract/macho_pristine/\(name) is required — it is the \only standalone Mach-O fixture this half of the port has- """+ """,)let reference = try #require(FrozenReference.machO[name],- "no frozen reference run for this binary"+ "no frozen reference run for this binary",)// The reference saw this exact file; if it has been replaced, nothing// below is a comparison.@@ -710,7 +715,7 @@ struct DSCHVVMMStandaloneTests {// Same sites, in the same order, before anything is written.let sites = try DSCHVVMMPatcher.findStringSites(- inMachO: Data(contentsOf: pristine)+ inMachO: Data(contentsOf: pristine),)#expect(sites.count == reference.sites.count)#expect(!sites.isEmpty, "\(name) holds no kern.hv_vmm_present cstring")diff --git a/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift b/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swiftindex bbaf1392..4908d2a9 100644--- a/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift+++ b/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift@@ -25,8 +25,8 @@// `cp -c` — an APFS clone, so instant and near-free — into// `ipsws/scratch_dsc_forcekern`, and removed again at the end.-@testable import FirmwarePatcherimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -219,7 +219,9 @@ private enum ForceKernFixture {}/// The suite runs unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real arm64e shared cache is required — put it at \@@ -249,15 +251,15 @@ private enum ForceKernFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let result = try ForceKernShell.run(executable: URL(fileURLWithPath: "/bin/cp"),arguments: ["-c", "-R"]- + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))+ + (FileManager.default.contentsOfDirectory(atPath: pristine.path)).sorted().map { pristine.appendingPathComponent($0).path }- + [destination.path]+ + [destination.path],)guard result.status == 0 else {throw CocoaError(.fileWriteUnknown)@@ -306,7 +308,7 @@ private enum ForceKernShell {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}@@ -327,9 +329,11 @@ private enum ForceKernShell {"-s",left.appendingPathComponent(name).path,right.appendingPathComponent(name).path,- ]+ ],)- if result.status != 0 { differing.append(name) }+ if result.status != 0 {+ differing.append(name)+ }}return (differing, leftNames.count)}@@ -381,8 +385,8 @@ private enum Digest {@Suite(.serialized, .enabled(if: ForceKernFixture.runs, ForceKernFixture.skipReason))struct DSCIOMFBForceKernParityTests {/// The one test that decides whether this port is done.- @Test("Swift force-kern reproduces the reference cache byte for byte")- func matchesReferenceByteForByte() throws {+ @Test+ func `Swift force-kern reproduces the reference cache byte for byte`() throws {_ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let swiftClone = try ForceKernFixture.cloneCache(named: "swift")@@ -390,17 +394,17 @@ struct DSCIOMFBForceKernParityTests {let outcome = try DSCIOMFBForceKernPatcher.patch(chunksDirectory: swiftClone,- log: nil+ log: nil,)#expect(outcome.writtenSiteCount == FrozenReference.newlyForced,- "swift wrote \(outcome.writtenSiteCount) sites, reference \(FrozenReference.newlyForced)"+ "swift wrote \(outcome.writtenSiteCount) sites, reference \(FrozenReference.newlyForced)",)// The same entry points, not merely the same count.#expect(Set(outcome.forced.map(\.entry.publicName))- == Set(FrozenReference.forcedPairs.map(\.publicName))+ == Set(FrozenReference.forcedPairs.map(\.publicName)),)#expect(Set(outcome.notTrampolines.map(\.entry.publicName))== Set(FrozenReference.leftOnVirtPath))@@ -412,8 +416,8 @@ struct DSCIOMFBForceKernParityTests {/// patch already forced must write nothing and leave every byte alone. The/// Python printed `all 31 entrypoint(s) already forced; nothing to/// patch/re-attest` here, with its digest unchanged.- @Test("A second run is a no-op on an already-forced cache")- func secondRunIsANoOp() throws {+ @Test+ func `A second run is a no-op on an already-forced cache`() throws {_ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let clone = try ForceKernFixture.cloneCache(named: "idempotence")@@ -435,8 +439,8 @@ struct DSCIOMFBForceKernParityTests {}/// A dry run must classify everything and touch nothing.- @Test("A dry run reports the reference's sites and writes no bytes")- func dryRunWritesNothing() throws {+ @Test+ func `A dry run reports the reference's sites and writes no bytes`() throws {_ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let clone = try ForceKernFixture.cloneCache(named: "dryrun")@@ -446,7 +450,7 @@ struct DSCIOMFBForceKernParityTests {let dry = try DSCIOMFBForceKernPatcher.patch(chunksDirectory: clone,dryRun: true,- log: nil+ log: nil,)#expect(dry.writtenSiteCount == FrozenReference.newlyForced)#expect(dry.records.isEmpty)@@ -466,12 +470,12 @@ struct DSCIOMFBForceKernDiscoveryTests {/// Discovery has to agree with the reference's, which read the same image/// through `ipsw dyld symaddr`. Compared here without `ipsw`: the pairs the/// resolver finds are the pairs the reference logged.- @Test("Every discovered pair matches the reference's, name and address")- func discoveryMatchesReference() throws {+ @Test+ func `Every discovered pair matches the reference's, name and address`() throws {let pristine = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let resolver = try DSCSymbolResolver(- mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e")+ mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e"),)let entries = try DSCIOMFBForceKernPatcher.discoverEntryPoints(resolver: resolver)#expect(entries.count >= DSCIOMFBForceKernPatcher.requiredSuffixes.count)@@ -490,7 +494,7 @@ struct DSCIOMFBForceKernDiscoveryTests {let theirs = String(pair.publicAddress, radix: 16, uppercase: true)#expect(entry.publicAddress == pair.publicAddress,- "\(pair.publicName): swift 0x\(mine) vs reference 0x\(theirs)"+ "\(pair.publicName): swift 0x\(mine) vs reference 0x\(theirs)",)// …and the sibling it would branch to, which is the half of the// pair a name-only comparison would miss.@@ -500,8 +504,8 @@ struct DSCIOMFBForceKernDiscoveryTests {}/// The three the reference refuses to ship without.- @Test("The required entry points are present and forcible")- func requiredEntryPointsAreForcible() throws {+ @Test+ func `The required entry points are present and forcible`() throws {let pristine = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let resolver = try DSCSymbolResolver(chunks: chunks)@@ -511,16 +515,16 @@ struct DSCIOMFBForceKernDiscoveryTests {for required in DSCIOMFBForceKernPatcher.requiredSuffixes {let entry = try #require(entries.first { $0.suffix == required },- "no entry point discovered for \(required)"+ "no entry point discovered for \(required)",)- let instructions = disassembler.disassemble(- try chunks.bytesAtVMA(entry.publicAddress, length: 16),+ let instructions = try disassembler.disassemble(+ chunks.bytesAtVMA(entry.publicAddress, length: 16),at: entry.publicAddress,- count: 4+ count: 4,)#expect(DSCIOMFBForceKernPatcher.isDispatchTrampoline(instructions),- "\(entry.publicName) is not a thin dispatch trampoline"+ "\(entry.publicName) is not a thin dispatch trampoline",)}}@@ -529,8 +533,8 @@ struct DSCIOMFBForceKernDiscoveryTests {/// reference left four entry points on the virt path on this cache, and so/// must this. A matcher that accepted everything would still pass the byte/// comparison only if it happened to agree — it does not, so pin it.- @Test("Non-trampoline entry points are recognised and left alone")- func nonTrampolinesAreLeftAlone() throws {+ @Test+ func `Non-trampoline entry points are recognised and left alone`() throws {let pristine = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let clone = try ForceKernFixture.cloneCache(named: "shapes")@@ -538,12 +542,12 @@ struct DSCIOMFBForceKernDiscoveryTests {let dry = try DSCIOMFBForceKernPatcher.patch(chunksDirectory: clone,dryRun: true,- log: nil+ log: nil,)#expect(dry.notTrampolines.map(\.entry.publicName).sorted()- == FrozenReference.leftOnVirtPath.sorted()+ == FrozenReference.leftOnVirtPath.sorted(),)#expect(dry.forced.count + dry.notTrampolines.count + dry.alreadyForced.count == dry.sites.count)@@ -553,10 +557,10 @@ struct DSCIOMFBForceKernDiscoveryTests {let chunks = try DSCChunkSet(directory: pristine)let disassembler = ARM64Disassembler()for site in dry.notTrampolines {- let instructions = disassembler.disassemble(- try chunks.bytesAtVMA(site.entry.publicAddress, length: 16),+ let instructions = try disassembler.disassemble(+ chunks.bytesAtVMA(site.entry.publicAddress, length: 16),at: site.entry.publicAddress,- count: 4+ count: 4,)#expect(!DSCIOMFBForceKernPatcher.isDispatchTrampoline(instructions))print("[force-kern] left on virt: \(site.entry.publicName) — \(site.originalDisassembly)")@@ -566,8 +570,8 @@ struct DSCIOMFBForceKernDiscoveryTests {/// Each written site is a 4-byte `b` at the public entry point, aimed at the/// kern sibling — checked from the record the patcher emits, which is what/// the record-comparison harness consumes.- @Test("Every record is a four-byte branch to the paired kern implementation")- func recordsDescribeTheBranches() throws {+ @Test+ func `Every record is a four-byte branch to the paired kern implementation`() throws {_ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)let clone = try ForceKernFixture.cloneCache(named: "records")@@ -576,7 +580,7 @@ struct DSCIOMFBForceKernDiscoveryTests {#expect(outcome.records.count == outcome.writtenSiteCount)let kernAddresses = Dictionary(- uniqueKeysWithValues: FrozenReference.forcedPairs.map { ($0.publicAddress, $0.kernAddress) }+ uniqueKeysWithValues: FrozenReference.forcedPairs.map { ($0.publicAddress, $0.kernAddress) },)let chunks = try DSCChunkSet(directory: clone)let disassembler = ARM64Disassembler()@@ -587,10 +591,10 @@ struct DSCIOMFBForceKernDiscoveryTests {#expect(record.originalBytes != record.patchedBytes)let address = try #require(record.virtualAddress)let instruction = try #require(- disassembler.disassembleOne(- try chunks.bytesAtVMA(address, length: 4),- at: address- )+ try disassembler.disassembleOne(+ chunks.bytesAtVMA(address, length: 4),+ at: address,+ ),)#expect(instruction.mnemonic == "b")// …and it lands on the kern sibling the reference named for this@@ -600,7 +604,7 @@ struct DSCIOMFBForceKernDiscoveryTests {let site = "0x\(String(address, radix: 16))"#expect(instruction.operandString == expected,- "\(site) branches to \(instruction.operandString), reference paired it with \(expected)"+ "\(site) branches to \(instruction.operandString), reference paired it with \(expected)",)}}diff --git a/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift b/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swiftindex 1060b3fd..62e17ee9 100644--- a/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift+++ b/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift@@ -87,7 +87,7 @@ private enum FrozenReference {changedChunks: ["dyld_shared_cache_arm64e.38":"b49bbe7872273242c73973a451d9dac1a7ec803da8efeb5dcd1e04c7b5292f1d",- ]+ ],),0x560: SizeRun(sitesWritten: 1,@@ -95,7 +95,7 @@ private enum FrozenReference {changedChunks: ["dyld_shared_cache_arm64e.38":"72f07ea587a523ed602d30f8f9a3508d291451a75ab90a0c578313d208b8a0e4",- ]+ ],),0x6E0: SizeRun(sitesWritten: 0, wasAlreadyCorrect: true, changedChunks: [:]),]@@ -125,7 +125,9 @@ private enum SwapEndFixture {ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"}- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -155,15 +157,15 @@ private enum SwapEndFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let result = try SwapEndSubprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),arguments: ["-c", "-R"]- + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))+ + (FileManager.default.contentsOfDirectory(atPath: pristine.path)).sorted().map { pristine.appendingPathComponent($0).path }- + [destination.path]+ + [destination.path],)guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }return destination@@ -209,7 +211,7 @@ private enum SwapEndSubprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -253,9 +255,11 @@ private enum CacheComparison {"-s",left.appendingPathComponent(name).path,right.appendingPathComponent(name).path,- ]+ ],)- if result.status != 0 { differing.append(name) }+ if result.status != 0 {+ differing.append(name)+ }}return differing}@@ -277,7 +281,7 @@ private enum SwapEndCallSetup {static func assemble(selector: UInt16 = 5,size: UInt16 = sourceSize,- terminator: Data? = nil+ terminator: Data? = nil,) -> Data? {let branchPC = Int(baseAddress) + 24guard let ldr = ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 0, offset: 0x14),@@ -298,10 +302,9 @@ private enum SwapEndCallSetup {// MARK: - 1 · The anchor, with no cache in sight-@Suitestruct DSCIOMFBSwapEndShapeTests {- @Test("The finder lands on the size move of the external-method call set-up")- func findsTheSizeMove() throws {+ @Test+ func `The finder lands on the size move of the external-method call set-up`() throws {let disassembler = ARM64Disassembler()let code = try #require(SwapEndCallSetup.assemble())let instructions = SwapEndCallSetup.disassemble(code, disassembler)@@ -310,28 +313,28 @@ struct DSCIOMFBSwapEndShapeTests {let site = try #require(DSCIOMFBSwapEndPatcher.findSizeInstruction(in: instructions,- disassembler: disassembler- )+ disassembler: disassembler,+ ),)#expect(site.index == SwapEndCallSetup.sizeIndex)#expect(site.instruction.address- == SwapEndCallSetup.baseAddress + UInt64(SwapEndCallSetup.sizeIndex * 4)+ == SwapEndCallSetup.baseAddress + UInt64(SwapEndCallSetup.sizeIndex * 4),)let decoded = try #require(DSCIOMFBSwapEndPatcher.movRegisterImmediate(site.instruction,- disassembler: disassembler- )+ disassembler: disassembler,+ ),)#expect(decoded.register == DSCIOMFBSwapEndPatcher.sizeRegister)#expect(decoded.immediate == Int64(SwapEndCallSetup.sourceSize))print("[shape] size move at index \(site.index): \(site.instruction)")}- @Test("A different selector is not this call, and is not patched")- func rejectsAnotherSelector() throws {+ @Test+ func `A different selector is not this call, and is not patched`() throws {let disassembler = ARM64Disassembler()// Selector 6 is some other external method of the same userclient; the// size it passes is none of this patcher's business.@@ -340,49 +343,49 @@ struct DSCIOMFBSwapEndShapeTests {#expect(DSCIOMFBSwapEndPatcher.findSizeInstruction(in: instructions,- disassembler: disassembler- ) == nil+ disassembler: disassembler,+ ) == nil,)}- @Test("Without the call itself the shape is not a call set-up")- func rejectsASequenceThatNeverCalls() throws {+ @Test+ func `Without the call itself the shape is not a call set-up`() throws {let disassembler = ARM64Disassembler()let code = try #require(SwapEndCallSetup.assemble(terminator: ARM64.nop))let instructions = SwapEndCallSetup.disassemble(code, disassembler)#expect(DSCIOMFBSwapEndPatcher.findSizeInstruction(in: instructions,- disassembler: disassembler- ) == nil+ disassembler: disassembler,+ ) == nil,)}- @Test("The replacement is the encoder's MOVZ, for every size a base kernel wants")- func replacementComesFromTheEncoder() throws {+ @Test+ func `The replacement is the encoder's MOVZ, for every size a base kernel wants`() throws {// 0x560 is the 26.1 base, 0x588 the 26.4 one; both are passed by// `cfw_install*.sh` / `cfw-kit` today.for size: UInt16 in [0x560, 0x588] {let encoded = try #require(ARM64Encoder.encodeMovzW(rd: 3, imm16: size))#expect(encoded.count == 4)let decoded = try #require(- ARM64Disassembler().disassembleOne(encoded, at: SwapEndCallSetup.baseAddress)+ ARM64Disassembler().disassembleOne(encoded, at: SwapEndCallSetup.baseAddress),)let move = try #require(DSCIOMFBSwapEndPatcher.movRegisterImmediate(decoded,- disassembler: ARM64Disassembler()- )+ disassembler: ARM64Disassembler(),+ ),)#expect(move.register == DSCIOMFBSwapEndPatcher.sizeRegister)#expect(move.immediate == Int64(size))}}- @Test("A size that will not fit a MOVZ immediate is refused, not truncated")- func oversizedTargetIsRefused() throws {+ @Test+ func `A size that will not fit a MOVZ immediate is refused, not truncated`() throws {#expect(throws: PatcherError.self) {- _ = try DSCIOMFBSwapEndPatcher.replacement(forTargetSize: 0x1_0000)+ _ = try DSCIOMFBSwapEndPatcher.replacement(forTargetSize: 0x10000)}// And it is refused before the 6.7 GB cache is opened, so the caller// gets "that size cannot be encoded" rather than whatever the cache@@ -392,9 +395,9 @@ struct DSCIOMFBSwapEndShapeTests {do {_ = try DSCIOMFBSwapEndPatcher.patch(chunksDirectory: URL(fileURLWithPath: "/nonexistent-dyld-cache"),- targetSize: 0x1_0000,+ targetSize: 0x10000,dryRun: true,- log: nil+ log: nil,)} catch {thrown = error@@ -418,15 +421,14 @@ struct DSCIOMFBSwapEndParityTests {static let targetSizes: [UInt32] = [0x588, 0x560, 0x6E0]@Test(- "Swift patches the real cache to the reference's bytes",- arguments: targetSizes+ arguments: targetSizes,)- func matchesTheReferenceByteForByte(targetSize: UInt32) throws {+ func `Swift patches the real cache to the reference's bytes`(targetSize: UInt32) throws {let pristine = try #require(SwapEndFixture.pristine, SwapEndFixture.missing)let suffix = String(targetSize, radix: 16)let reference = try #require(FrozenReference.bySize[targetSize],- "no frozen reference run for this target size"+ "no frozen reference run for this target size",)let swiftClone = try SwapEndFixture.cloneCache(named: "swift_\(suffix)")@@ -435,13 +437,13 @@ struct DSCIOMFBSwapEndParityTests {let mine = try DSCIOMFBSwapEndPatcher.patch(chunksDirectory: swiftClone,targetSize: targetSize,- log: nil+ log: nil,)// Same number of sites, at the same address, from the same source size.#expect(mine.sitesWritten == reference.sitesWritten,- "swift wrote \(mine.sitesWritten) site(s), reference \(reference.sitesWritten)"+ "swift wrote \(mine.sitesWritten) site(s), reference \(reference.sitesWritten)",)#expect(mine.wasAlreadyCorrect == reference.wasAlreadyCorrect)#expect(mine.siteVMA == FrozenReference.siteVMA)@@ -469,12 +471,12 @@ struct DSCIOMFBSwapEndParityTests {+ "(0x\(String(mine.originalSize, radix: 16, uppercase: true)) -> "+ "0x\(String(mine.targetSize, radix: 16, uppercase: true)) at "+ "0x\(String(mine.siteVMA, radix: 16, uppercase: true))); "- + "chunks changed: \(touched) — digests match the reference"+ + "chunks changed: \(touched) — digests match the reference",)}- @Test("A dry run reports the site and leaves every chunk untouched")- func dryRunWritesNothing() throws {+ @Test+ func `A dry run reports the site and leaves every chunk untouched`() throws {let pristine = try #require(SwapEndFixture.pristine, SwapEndFixture.missing)let clone = try SwapEndFixture.cloneCache(named: "dry")defer { SwapEndFixture.discard(clone) }@@ -483,7 +485,7 @@ struct DSCIOMFBSwapEndParityTests {chunksDirectory: clone,targetSize: 0x588,dryRun: true,- log: nil+ log: nil,)#expect(mine.sitesWritten == 0)#expect(mine.reattestation == nil)@@ -495,12 +497,12 @@ struct DSCIOMFBSwapEndParityTests {print("[dry-run] would patch 0x\(String(mine.originalSize, radix: 16, uppercase: true)) "+ "-> 0x588 at 0x\(String(mine.siteVMA, radix: 16, uppercase: true)); "- + "0 chunks changed"+ + "0 chunks changed",)}- @Test("Patching an already-patched cache is a no-op, not a second write")- func secondRunChangesNothing() throws {+ @Test+ func `Patching an already-patched cache is a no-op, not a second write`() throws {try #require(SwapEndFixture.pristine != nil, SwapEndFixture.missing)let clone = try SwapEndFixture.cloneCache(named: "idempotent")let afterFirst = try SwapEndFixture.cloneCache(named: "idempotent_snapshot")@@ -509,7 +511,7 @@ struct DSCIOMFBSwapEndParityTests {let first = try DSCIOMFBSwapEndPatcher.patch(chunksDirectory: clone,targetSize: 0x588,- log: nil+ log: nil,)#expect(first.sitesWritten == 1)#expect(!first.wasAlreadyCorrect)@@ -518,14 +520,14 @@ struct DSCIOMFBSwapEndParityTests {try? FileManager.default.removeItem(at: afterFirst)let copy = try SwapEndSubprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: ["-c", "-R", clone.path, afterFirst.path]+ arguments: ["-c", "-R", clone.path, afterFirst.path],)#expect(copy.status == 0)let second = try DSCIOMFBSwapEndPatcher.patch(chunksDirectory: clone,targetSize: 0x588,- log: nil+ log: nil,)#expect(second.wasAlreadyCorrect)#expect(second.sitesWritten == 0)@@ -544,8 +546,8 @@ struct DSCIOMFBSwapEndParityTests {print("[idempotent] second run wrote 0 sites and changed 0 chunks")}- @Test("The symbol and the site are found without `ipsw` on the patch path")- func resolvesWithoutIpsw() throws {+ @Test+ func `The symbol and the site are found without ipsw on the patch path`() throws {let pristine = try #require(SwapEndFixture.pristine, SwapEndFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let resolver = try DSCSymbolResolver(chunks: chunks)@@ -553,7 +555,7 @@ struct DSCIOMFBSwapEndParityTests {let functionVMA = try resolver.address(of: DSCIOMFBSwapEndPatcher.symbolName,- inImage: DSCIOMFBSwapEndPatcher.imagePath+ inImage: DSCIOMFBSwapEndPatcher.imagePath,)#expect(functionVMA == FrozenReference.functionVMA)@@ -562,23 +564,23 @@ struct DSCIOMFBSwapEndParityTests {in: chunks,at: functionVMA,maximumInstructions: DSCIOMFBSwapEndPatcher.maximumInstructions,- disassembler: disassembler+ disassembler: disassembler,)#expect(!instructions.isEmpty)let site = try #require(DSCIOMFBSwapEndPatcher.findSizeInstruction(in: instructions,- disassembler: disassembler+ disassembler: disassembler,),- "the SwapEnd call set-up was not found in \(DSCIOMFBSwapEndPatcher.symbolName)"+ "the SwapEnd call set-up was not found in \(DSCIOMFBSwapEndPatcher.symbolName)",)// The shape, on the real function: selector, size, two zeros, the call.let selector = try #require(DSCIOMFBSwapEndPatcher.movRegisterImmediate(instructions[site.index - 1],- disassembler: disassembler- )+ disassembler: disassembler,+ ),)#expect(selector.register == "w1")#expect(selector.immediate == DSCIOMFBSwapEndPatcher.selector)@@ -587,8 +589,8 @@ struct DSCIOMFBSwapEndParityTests {let size = try #require(DSCIOMFBSwapEndPatcher.movRegisterImmediate(site.instruction,- disassembler: disassembler- )+ disassembler: disassembler,+ ),)// The reference resolved the same function and landed on the same move.#expect(site.instruction.address == FrozenReference.siteVMA)@@ -597,7 +599,7 @@ struct DSCIOMFBSwapEndParityTests {"[resolve] \(DSCIOMFBSwapEndPatcher.symbolName) @ "+ "0x\(String(functionVMA, radix: 16, uppercase: true)), size move "+ "0x\(String(size.immediate, radix: 16, uppercase: true)) @ "- + "0x\(String(site.instruction.address, radix: 16, uppercase: true))"+ + "0x\(String(site.instruction.address, radix: 16, uppercase: true))",)}}diff --git a/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift b/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swiftindex 4ca2f1e6..e60436ed 100644--- a/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift+++ b/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift@@ -21,8 +21,8 @@// (instant and near-free on APFS) under the system temporary directory, or// under `VPHONE_DSC_SCRATCH` when the caller names one.-@testable import FirmwarePatcherimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -103,7 +103,9 @@ private enum LSDRegFixture {}/// The suite runs unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -137,7 +139,7 @@ private enum LSDRegFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let entries = try FileManager.default.contentsOfDirectory(atPath: pristine.path)@@ -147,9 +149,11 @@ private enum LSDRegFixture {for flags in [["-c", "-R"], ["-R"]] {let result = try Shell.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: flags + entries + [destination.path]+ arguments: flags + entries + [destination.path],)- if result.status == 0 { return destination }+ if result.status == 0 {+ return destination+ }}Issue.record("could not clone the pristine cache into \(destination.path)")throw CocoaError(.fileWriteUnknown)@@ -182,12 +186,14 @@ private enum Shell {static func run(executable: URL,arguments: [String],- currentDirectory: URL? = nil+ currentDirectory: URL? = nil,) throws -> Result {let process = Process()process.executableURL = executableprocess.arguments = arguments- if let currentDirectory { process.currentDirectoryURL = currentDirectory }+ if let currentDirectory {+ process.currentDirectoryURL = currentDirectory+ }let out = Pipe()let err = Pipe()process.standardOutput = out@@ -199,7 +205,7 @@ private enum Shell {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -230,8 +236,8 @@ private enum CacheComparison {/// compared first so a missing or extra chunk is reported as such.static func differences(between lhs: URL, and rhs: URL) throws -> [String] {let manager = FileManager.default- let left = Set(try manager.contentsOfDirectory(atPath: lhs.path))- let right = Set(try manager.contentsOfDirectory(atPath: rhs.path))+ let left = try Set(manager.contentsOfDirectory(atPath: lhs.path))+ let right = try Set(manager.contentsOfDirectory(atPath: rhs.path))var differing = Array(left.symmetricDifference(right)).sorted()for name in left.intersection(right).sorted() {@@ -241,9 +247,11 @@ private enum CacheComparison {"-s",lhs.appendingPathComponent(name).path,rhs.appendingPathComponent(name).path,- ]+ ],)- if result.status != 0 { differing.append(name) }+ if result.status != 0 {+ differing.append(name)+ }}return differing.sorted()}@@ -260,16 +268,16 @@ private enum CacheComparison {@Suite("DSC lsd embedded-registration gate",.enabled(if: LSDRegFixture.runs, LSDRegFixture.missing),- .serialized+ .serialized,)struct DSCLSDEmbeddedRegGateTests {- @Test("the gate is a cbz/cbnz on w0 whose fall-through sets a w register to 1")- func gateShape() throws {+ @Test+ func `the gate is a cbz/cbnz on w0 whose fall-through sets a w register to 1`() throws {let pristine = try #require(LSDRegFixture.pristine, LSDRegFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let located = try #require(try DSCLSDEmbeddedRegPatcher.locateGate(in: chunks),- "the iOS 27 fixture must carry \(DSCLSDEmbeddedRegPatcher.method)"+ "the iOS 27 fixture must carry \(DSCLSDEmbeddedRegPatcher.method)",)#expect(["cbz", "cbnz"].contains(located.gate.mnemonic))@@ -279,7 +287,7 @@ struct DSCLSDEmbeddedRegGateTests {// The gate is inside the disassembly window, by construction.#expect(located.gate.vma- < located.functionVMA + UInt64(DSCLSDEmbeddedRegPatcher.maxInstructions * 4)+ < located.functionVMA + UInt64(DSCLSDEmbeddedRegPatcher.maxInstructions * 4),)// …and it is the exact site the reference Python reported.@@ -289,13 +297,13 @@ struct DSCLSDEmbeddedRegGateTests {#expect(located.gate.resultRegister == FrozenReference.gateResultRegister)}- @Test("the symbol resolves through the cache's own local symbol table")- func symbolIsLocal() throws {+ @Test+ func `the symbol resolves through the cache's own local symbol table`() throws {let pristine = try #require(LSDRegFixture.pristine, LSDRegFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let address = try #require(try chunks.resolveLocalSymbol(DSCLSDEmbeddedRegPatcher.method),- "\(DSCLSDEmbeddedRegPatcher.method) must be in the .symbols table"+ "\(DSCLSDEmbeddedRegPatcher.method) must be in the .symbols table",)#expect(address == FrozenReference.methodVMA)// It has to live in an executable mapping, or it is not the method.@@ -309,17 +317,17 @@ struct DSCLSDEmbeddedRegGateTests {@Suite("DSC lsd embedded-registration parity",.enabled(if: LSDRegFixture.runs, LSDRegFixture.missing),- .serialized+ .serialized,)struct DSCLSDEmbeddedRegParityTests {- @Test("Swift reproduces the reference cache byte for byte, one site")- func byteForByteParity() throws {+ @Test+ func `Swift reproduces the reference cache byte for byte, one site`() throws {let swiftClone = try LSDRegFixture.cloneCache(named: "swift")defer { LSDRegFixture.discard(swiftClone) }let report = try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: swiftClone,- log: nil+ log: nil,)#expect(report.outcome == .patched)#expect(report.sitesWritten == FrozenReference.sitesWritten)@@ -336,8 +344,8 @@ struct DSCLSDEmbeddedRegParityTests {}}- @Test("the recorded write names the chunk, its offset and the gate address")- func recordDescribesTheSite() throws {+ @Test+ func `the recorded write names the chunk, its offset and the gate address`() throws {let clone = try LSDRegFixture.cloneCache(named: "record")defer { LSDRegFixture.discard(clone) }@@ -361,7 +369,7 @@ struct DSCLSDEmbeddedRegParityTests {// The offset has to name the byte that changed, in the file it names.let handle = try FileHandle(- forReadingFrom: clone.appendingPathComponent(record.component)+ forReadingFrom: clone.appendingPathComponent(record.component),)defer { try? handle.close() }try handle.seek(toOffset: UInt64(record.fileOffset))@@ -374,11 +382,11 @@ struct DSCLSDEmbeddedRegParityTests {@Suite("DSC lsd embedded-registration re-runs",.enabled(if: LSDRegFixture.runs, LSDRegFixture.missing),- .serialized+ .serialized,)struct DSCLSDEmbeddedRegRerunTests {- @Test("a second Swift run is idempotent and leaves the bytes alone")- func swiftIsIdempotent() throws {+ @Test+ func `a second Swift run is idempotent and leaves the bytes alone`() throws {let clone = try LSDRegFixture.cloneCache(named: "idempotent")defer { LSDRegFixture.discard(clone) }@@ -398,20 +406,20 @@ struct DSCLSDEmbeddedRegRerunTests {for name in afterFirst {#expect(try Digest.sha256(of: clone.appendingPathComponent(name))- == FrozenReference.changedChunks[name]+ == FrozenReference.changedChunks[name],)}}- @Test("a dry run locates the gate and writes nothing")- func dryRunWritesNothing() throws {+ @Test+ func `a dry run locates the gate and writes nothing`() throws {let clone = try LSDRegFixture.cloneCache(named: "dryrun")defer { LSDRegFixture.discard(clone) }let report = try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: clone,dryRun: true,- log: nil+ log: nil,)#expect(report.outcome == .wouldPatch)#expect(report.sitesWritten == 0)diff --git a/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swift b/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swiftindex 425acdc1..72758932 100644--- a/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swift+++ b/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swift@@ -98,7 +98,9 @@ private enum LockdownFixture {}/// The suite runs unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -127,14 +129,14 @@ private enum LockdownFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let entries = try FileManager.default.contentsOfDirectory(atPath: pristine.path).sorted()let result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),arguments: ["-c", "-R"]+ entries.map { pristine.appendingPathComponent($0).path }- + [destination.path]+ + [destination.path],)guard result.status == 0 else {Issue.record("clone failed: \(result.stderr)")@@ -183,7 +185,7 @@ private enum Subprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -240,11 +242,11 @@ private enum DirectoryComparison {arguments: [lhs.appendingPathComponent(name).path,rhs.appendingPathComponent(name).path,- ]+ ],)if result.status != 0 {differing.append("\(name): \(result.stdout)\(result.stderr)".trimmingCharacters(- in: .whitespacesAndNewlines+ in: .whitespacesAndNewlines,))}}@@ -254,8 +256,8 @@ private enum DirectoryComparison {/// The names of the files in `directory` that differ from `reference`.static func changedNames(in directory: URL, against reference: URL) throws -> [String] {let manager = FileManager.default- let left = Set(try manager.contentsOfDirectory(atPath: reference.path))- let right = Set(try manager.contentsOfDirectory(atPath: directory.path))+ let left = try Set(manager.contentsOfDirectory(atPath: reference.path))+ let right = try Set(manager.contentsOfDirectory(atPath: directory.path))var differing = Array(left.symmetricDifference(right))for name in left.intersection(right) {let result = try Subprocess.run(@@ -264,9 +266,11 @@ private enum DirectoryComparison {"-s",reference.appendingPathComponent(name).path,directory.appendingPathComponent(name).path,- ]+ ],)- if result.status != 0 { differing.append(name) }+ if result.status != 0 {+ differing.append(name)+ }}return differing.sorted()}@@ -279,7 +283,7 @@ private enum DirectoryComparison {for name in names {let result = try Subprocess.run(executable: URL(fileURLWithPath: "/sbin/md5"),- arguments: ["-q", directory.appendingPathComponent(name).path]+ arguments: ["-q", directory.appendingPathComponent(name).path],)digests[name] = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)}@@ -292,8 +296,8 @@ private enum DirectoryComparison {@Suite(.serialized, .enabled(if: LockdownFixture.runs, LockdownFixture.skipReason))struct DSCLockdownModeParityTests {/// The one that matters: the real cache in, the reference's bytes out.- @Test("Swift reproduces the reference's patched cache byte for byte")- func patchedCacheMatchesTheReference() throws {+ @Test+ func `Swift reproduces the reference's patched cache byte for byte`() throws {_ = try #require(LockdownFixture.pristine, LockdownFixture.missing)let swiftClone = try LockdownFixture.cloneCache(named: "swift")@@ -316,8 +320,8 @@ struct DSCLockdownModeParityTests {/// The write has to be covered by exactly one re-attested page, or the/// guest takes a `KERN_PROTECTION_FAILURE` the first time it faults the/// page in. The Python re-attests one slot here; so must this.- @Test("The write is re-attested, and only the page it dirtied")- func reattestationCoversTheWrite() throws {+ @Test+ func `The write is re-attested, and only the page it dirtied`() throws {_ = try #require(LockdownFixture.pristine, LockdownFixture.missing)let clone = try LockdownFixture.cloneCache(named: "reattest")@@ -333,8 +337,8 @@ struct DSCLockdownModeParityTests {/// A second pass over an installed cache is how this patch is actually met/// in the field — `cfw_install` re-runs. It must report a no-op rather than/// raise, and must not move a byte.- @Test("A second run is a no-op on an already-patched cache")- func secondRunIsANoOp() throws {+ @Test+ func `A second run is a no-op on an already-patched cache`() throws {_ = try #require(LockdownFixture.pristine, LockdownFixture.missing)let clone = try LockdownFixture.cloneCache(named: "idempotence")@@ -361,8 +365,8 @@ struct DSCLockdownModeParityTests {/// The reference's `--dry-run` named the gate and changed no chunk. So/// must this one — an install script that asks what would happen must not/// be the thing that makes it happen.- @Test("A dry run names the reference's gate and writes nothing")- func dryRunWritesNothing() throws {+ @Test+ func `A dry run names the reference's gate and writes nothing`() throws {let pristine = try #require(LockdownFixture.pristine, LockdownFixture.missing)let clone = try LockdownFixture.cloneCache(named: "dryrun")@@ -371,7 +375,7 @@ struct DSCLockdownModeParityTests {let outcome = try DSCLockdownModePatcher.patch(chunksDirectory: clone,dryRun: true,- log: nil+ log: nil,)#expect(outcome.sitesWritten == 0)#expect(outcome.sitesFound == 1)@@ -383,15 +387,15 @@ struct DSCLockdownModeParityTests {/// The reveal — symbol, then gate — read off the pristine cache without/// touching it, and checked against the addresses the reference printed.- @Test("Symbol and gate resolve to the reference's addresses")- func revealMatchesTheReference() throws {+ @Test+ func `Symbol and gate resolve to the reference's addresses`() throws {let pristine = try #require(LockdownFixture.pristine, LockdownFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let resolved = try DSCLockdownModePatcher.resolveBlockInvoke(in: chunks)let block = try #require(resolved,- "the cache must carry an os_lockdown_mode_enabled block to compare against"+ "the cache must carry an os_lockdown_mode_enabled block to compare against",)#expect(block.vma == FrozenReference.functionVMA)#expect(block.name == DSCLockdownModePatcher.symbolCandidates.first)@@ -431,7 +435,7 @@ struct DSCLockdownModeGateTests {return Stream(instructions: instructions,gateIndex: gateIndex,- comparisonIndex: gateIndex - 1+ comparisonIndex: gateIndex - 1,)}@@ -449,8 +453,8 @@ struct DSCLockdownModeGateTests {return ARM64.encodeU32(rewritten)}- @Test("The live b.eq gate is found, and it is the one the patch NOPs")- func findsTheLiveGate() throws {+ @Test+ func `The live b.eq gate is found, and it is the one the patch NOPs`() throws {let stream = try realStream()let comparison = stream.instructions[stream.comparisonIndex]#expect(comparison.mnemonic == "cmn")@@ -460,21 +464,21 @@ struct DSCLockdownModeGateTests {#expect(stream.instructions[..<stream.comparisonIndex].contains { $0.mnemonic == "bl" })}- @Test("A cmn with no preceding call is not a gate")- func rejectsComparisonWithoutACall() throws {+ @Test+ func `A cmn with no preceding call is not a gate`() throws {let stream = try realStream()let withoutCalls = stream.instructions.filter { $0.mnemonic != "bl" }#expect(DSCLockdownModePatcher.findErrorGate(withoutCalls) == nil)}- @Test("A cmn with the wrong immediate is not a gate")- func rejectsWrongImmediate() throws {+ @Test+ func `A cmn with the wrong immediate is not a gate`() throws {let stream = try realStream()let comparison = stream.instructions[stream.comparisonIndex]let disassembler = ARM64Disassembler()let mutated = try #require(disassembler.disassembleOne(word(of: comparison, withImmediate: 2),- at: comparison.address+ at: comparison.address,))#expect(mutated.mnemonic == "cmn")#expect(DSCLockdownModePatcher.immediate(of: mutated, at: 1) == 2)@@ -484,20 +488,20 @@ struct DSCLockdownModeGateTests {#expect(DSCLockdownModePatcher.findErrorGate(instructions) == nil)}- @Test("An unrelated instruction in the branch slot is not a gate")- func rejectsUnrelatedBranchSlot() throws {+ @Test+ func `An unrelated instruction in the branch slot is not a gate`() throws {let stream = try realStream()let filler = try #require(stream.instructions.first { $0.mnemonic != "b.eq" && $0.mnemonic != "nop" },- "the block must contain some instruction that is neither b.eq nor nop"+ "the block must contain some instruction that is neither b.eq nor nop",)var instructions = stream.instructionsinstructions[stream.gateIndex] = filler#expect(DSCLockdownModePatcher.findErrorGate(instructions) == nil)}- @Test("A truncated stream that ends on the cmn is not a gate")- func rejectsTruncatedStream() throws {+ @Test+ func `A truncated stream that ends on the cmn is not a gate`() throws {let stream = try realStream()let truncated = Array(stream.instructions[...stream.comparisonIndex])#expect(DSCLockdownModePatcher.findErrorGate(truncated) == nil)@@ -505,8 +509,8 @@ struct DSCLockdownModeGateTests {/// The already-patched shape, read off a cache this code actually patched/// rather than off a synthesised stream.- @Test("A NOPed gate is still recognised, at the same address")- func findsAnAlreadyNOPedGate() throws {+ @Test+ func `A NOPed gate is still recognised, at the same address`() throws {_ = try #require(LockdownFixture.pristine, LockdownFixture.missing)let clone = try LockdownFixture.cloneCache(named: "nopedgate")defer { LockdownFixture.discard(clone) }diff --git a/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swift b/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swiftindex ed09ed74..6f68991a 100644--- a/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swift+++ b/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swift@@ -25,8 +25,8 @@// `ipsws/scratch_dscmaxslide/`, on the same filesystem, so `cp -c` is a// `clonefile` rather than 10 GB of copying.-@testable import FirmwarePatcherimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -64,12 +64,12 @@ private enum FrozenReference {"3d7197cc0714e95c0e49434ab8bbb6311952a96d5b0425b10f87d2cc060c0110",]- /// Re-running the Python over its own output printed `fits: span+maxSlide- /// 0x17D504000 <= region 0x180000000; no change` — the *fits* gate, not the- /// already-zero one — and left the digest above standing. A third run with- /// `--force` skipped that gate and printed `maxSlide already 0; no change`,- /// also writing nothing. A `--dry-run` on a fresh clone printed `would set- /// maxSlide 0x20000000 -> 0x0` and changed no byte.+ // Re-running the Python over its own output printed `fits: span+maxSlide+ // 0x17D504000 <= region 0x180000000; no change` — the *fits* gate, not the+ // already-zero one — and left the digest above standing. A third run with+ // `--force` skipped that gate and printed `maxSlide already 0; no change`,+ // also writing nothing. A `--dry-run` on a fresh clone printed `would set+ // maxSlide 0x20000000 -> 0x0` and changed no byte.// MARK: The synthetic gate cases@@ -89,7 +89,7 @@ private enum FrozenReference {static let overflow = GateCase(inputSHA256: "0eeb86dc953aa43a29df533a0c151cb1d8ce7f322f8fa77232d5c97733984ab3",outputSHA256: "93e9ee632ab259a245f37e224e52e7f5671c8b323d04ba541483335c0d94bc6c",- branch: "overflow"+ branch: "overflow",)/// `writeCache(regionSize: 0x140904000, maxSlide: 0x20000000)`, no flags.@@ -98,7 +98,7 @@ private enum FrozenReference {static let fits = GateCase(inputSHA256: "88c50a6f8304c87bca21e6c01da193d8022673c12d03d4d0dfd52340b3fca718",outputSHA256: "88c50a6f8304c87bca21e6c01da193d8022673c12d03d4d0dfd52340b3fca718",- branch: "fits"+ branch: "fits",)/// The same input as `fits`, with `--force`. Python: `forced: span+maxSlide@@ -107,7 +107,7 @@ private enum FrozenReference {static let forced = GateCase(inputSHA256: "88c50a6f8304c87bca21e6c01da193d8022673c12d03d4d0dfd52340b3fca718",outputSHA256: "73e12cacf1350c07ad38991f4e845e51f64199815061e0ea1889d19f53f4beda",- branch: "forced"+ branch: "forced",)/// `writeCache(regionSize: 0x140904000, maxSlide: 0)` with `--force`.@@ -115,7 +115,7 @@ private enum FrozenReference {static let forcedZero = GateCase(inputSHA256: "73e12cacf1350c07ad38991f4e845e51f64199815061e0ea1889d19f53f4beda",outputSHA256: "73e12cacf1350c07ad38991f4e845e51f64199815061e0ea1889d19f53f4beda",- branch: "maxSlide already 0"+ branch: "maxSlide already 0",)/// `writeCache(regionSize: 0x190000000, maxSlide: 0)`, no flags — a span@@ -124,16 +124,16 @@ private enum FrozenReference {static let overflowWithZeroSlide = GateCase(inputSHA256: "f2543eb53f0f69a25c72045311292c9c428798a53683aeebd5b051509126d4b9",outputSHA256: "f2543eb53f0f69a25c72045311292c9c428798a53683aeebd5b051509126d4b9",- branch: "maxSlide already 0"+ branch: "maxSlide already 0",)- /// The Python's own self-test fixture — a bare 0x100-byte header with no- /// mapping table — is the one input where the two implementations- /// deliberately disagree, so it has no `GateCase` above. The reference- /// patched it (`overflow: … set maxSlide 0x20000000 -> 0x0`, the field- /// reading back as 0 afterwards); the Swift refuses it, because every write- /// here goes through `DSCChunkSet`, which has nothing to address such a- /// file with. See `noMappingTableIsRefused`.+ // The Python's own self-test fixture — a bare 0x100-byte header with no+ // mapping table — is the one input where the two implementations+ // deliberately disagree, so it has no `GateCase` above. The reference+ // patched it (`overflow: … set maxSlide 0x20000000 -> 0x0`, the field+ // reading back as 0 afterwards); the Swift refuses it, because every write+ // here goes through `DSCChunkSet`, which has nothing to address such a+ // file with. See `noMappingTableIsRefused`.}// MARK: - Fixture discovery@@ -161,7 +161,9 @@ private enum MaxSlideFixture {}/// The suites run unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -188,7 +190,7 @@ private enum MaxSlideFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let sources = try FileManager.default.contentsOfDirectory(atPath: pristine.path)@@ -197,14 +199,14 @@ private enum MaxSlideFixture {var result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: ["-c", "-R"] + sources + [destination.path]+ arguments: ["-c", "-R"] + sources + [destination.path],)if result.status != 0 {// A fixture pointed at another volume cannot be cloned. Copying is// slow but correct, and a refusal here would look like a patch bug.result = try Subprocess.run(executable: URL(fileURLWithPath: "/bin/cp"),- arguments: ["-R"] + sources + [destination.path]+ arguments: ["-R"] + sources + [destination.path],)}guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }@@ -219,11 +221,11 @@ private enum MaxSlideFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)try FileManager.default.copyItem(at: pristine.appendingPathComponent(mainChunkName),- to: destination.appendingPathComponent(mainChunkName)+ to: destination.appendingPathComponent(mainChunkName),)return destination}@@ -268,7 +270,7 @@ private enum Subprocess {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -297,7 +299,7 @@ private enum Bytes {static func identical(_ lhs: URL, _ rhs: URL) throws -> Bool {try Subprocess.run(executable: URL(fileURLWithPath: "/usr/bin/cmp"),- arguments: ["-s", lhs.path, rhs.path]+ arguments: ["-s", lhs.path, rhs.path],).status == 0}@@ -314,7 +316,7 @@ private enum Bytes {for name in leftNames {if try identical(lhs.appendingPathComponent(name),- rhs.appendingPathComponent(name)+ rhs.appendingPathComponent(name),) {matched += 1} else {@@ -342,8 +344,8 @@ struct DSCMaxSlideRealCacheTests {/// The gate this cache trips, stated once: 24A435's arm64e cache records a/// 0x17D504000 span and a 0x20000000 slide, which together overrun the/// kernel's 0x180000000 region by 0x1D504000.- @Test("The pristine cache is one that overflows the kernel's shared region")- func pristineCacheOverflowsTheRegion() throws {+ @Test+ func `The pristine cache is one that overflows the kernel's shared region`() throws {let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)let chunks = try DSCChunkSet(directory: pristine)@@ -351,14 +353,14 @@ struct DSCMaxSlideRealCacheTests {let header = try DSCMaxSlidePatcher.readHeader(from: chunks,at: headerVMA,- chunkName: MaxSlideFixture.mainChunkName+ chunkName: MaxSlideFixture.mainChunkName,)#expect(header.sharedRegionStart == chunks.addressRange.lowerBound)#expect(header.maxSlide != 0, "the fixture is already patched; re-extract it")#expect(header.sharedRegionSize + header.maxSlide > DSCMaxSlidePatcher.kernelSharedRegionSize,- "this fixture does not exercise the patch: it fits the region as it stands"+ "this fixture does not exercise the patch: it fits the region as it stands",)// The three numbers the reference read out of this same header.#expect(header.sharedRegionStart == FrozenReference.realStart)@@ -367,7 +369,7 @@ struct DSCMaxSlideRealCacheTests {print("[pristine] start=0x\(String(header.sharedRegionStart, radix: 16, uppercase: true)) "+ "size=0x\(String(header.sharedRegionSize, radix: 16, uppercase: true)) "- + "maxSlide=0x\(String(header.maxSlide, radix: 16, uppercase: true))"+ + "maxSlide=0x\(String(header.maxSlide, radix: 16, uppercase: true))",)}@@ -375,8 +377,8 @@ struct DSCMaxSlideRealCacheTests {/// require the result to be the bytes the reference left behind, over every/// one of the 79 chunks and the symbol side file — not just over the eight/// bytes the patch is about.- @Test("Swift patches the real cache into the reference's bytes")- func realCacheMatchesTheReference() throws {+ @Test+ func `Swift patches the real cache into the reference's bytes`() throws {let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)let swiftSide = try MaxSlideFixture.cloneCache(named: "parity_swift")@@ -387,7 +389,7 @@ struct DSCMaxSlideRealCacheTests {#expect(mine.didWrite)#expect(mine.outcome == .overflow(combined: mine.sharedRegionSize + mine.maxSlide,- region: DSCMaxSlidePatcher.kernelSharedRegionSize+ region: DSCMaxSlidePatcher.kernelSharedRegionSize,))#expect(mine.writtenSpan?.length == 8, "one site, one u64")@@ -418,8 +420,8 @@ struct DSCMaxSlideRealCacheTests {/// "fixes" it: the header page's code slot is left stale on purpose, because/// `maxSlide` is kernel-read cache metadata rather than a `cs_validate`'d/// code page. The code directory must come out of the patch untouched.- @Test("The patch leaves the code directory alone and the header page unattested")- func headerPageIsDeliberatelyNotReattested() throws {+ @Test+ func `The patch leaves the code directory alone and the header page unattested`() throws {let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)let clone = try MaxSlideFixture.cloneMainChunk(named: "noreattest")@@ -429,12 +431,12 @@ struct DSCMaxSlideRealCacheTests {let directory = try #require(try DSCCodeSignature.readCodeDirectory(ofChunk: main),- "the main chunk should carry a code directory"+ "the main chunk should carry a code directory",)let before = try DSCCodeSignature.pageHashes(chunkURL: main,pageIndex: 0,- directory: directory+ directory: directory,)#expect(before.computed == before.stored, "page 0 was not attested before the patch")@@ -445,24 +447,24 @@ struct DSCMaxSlideRealCacheTests {let mineBlob = try Bytes.read(main,offset: UInt64(directory.blobOffset),- length: directory.blobLength+ length: directory.blobLength,)let pristineBlob = try Bytes.read(pristineMain,offset: UInt64(directory.blobOffset),- length: directory.blobLength+ length: directory.blobLength,)#expect(mineBlob == pristineBlob, "the patch rewrote a code slot it must not rewrite")let after = try DSCCodeSignature.pageHashes(chunkURL: main,pageIndex: 0,- directory: directory+ directory: directory,)#expect(after.stored == before.stored)#expect(after.computed != after.stored,- "page 0's slot still matches, so something re-attested it"+ "page 0's slot still matches, so something re-attested it",)print("[no re-attest] page 0 stored \(after.stored.hex.prefix(16))… "+ "computed \(after.computed.hex.prefix(16))… — stale on purpose")@@ -470,8 +472,8 @@ struct DSCMaxSlideRealCacheTests {/// The reference's `--dry-run` printed `would set maxSlide 0x20000000 ->/// 0x0` — one site reported, no byte written. So must this one.- @Test("A dry run reports the reference's site, and writes nothing")- func dryRunReportsTheSiteAndWritesNothing() throws {+ @Test+ func `A dry run reports the reference's site, and writes nothing`() throws {let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)let swiftSide = try MaxSlideFixture.cloneMainChunk(named: "dryrun_swift")@@ -487,7 +489,7 @@ struct DSCMaxSlideRealCacheTests {let untouched = try Bytes.identical(swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),- pristine.appendingPathComponent(MaxSlideFixture.mainChunkName)+ pristine.appendingPathComponent(MaxSlideFixture.mainChunkName),)#expect(untouched, "a dry run wrote to the chunk")}@@ -495,8 +497,8 @@ struct DSCMaxSlideRealCacheTests {/// `8eb6c8b`'s lesson again: a patcher has to recognise its own output. A/// second pass over a clamped cache is a no-op, not an error and not a/// second write.- @Test("A second pass over an already-clamped cache is a no-op")- func secondPassIsANoOp() throws {+ @Test+ func `A second pass over an already-clamped cache is a no-op`() throws {_ = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)let swiftSide = try MaxSlideFixture.cloneMainChunk(named: "idem_swift")@@ -504,7 +506,7 @@ struct DSCMaxSlideRealCacheTests {let first = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide)let afterFirst = try Digest.sha256(- of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName)+ of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),)let mineAgain = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide)@@ -518,7 +520,7 @@ struct DSCMaxSlideRealCacheTests {// second run printed "fits: … no change", not "maxSlide already 0".#expect(mineAgain.outcome == .fits(combined: first.sharedRegionSize,- region: DSCMaxSlidePatcher.kernelSharedRegionSize+ region: DSCMaxSlidePatcher.kernelSharedRegionSize,))// `--force` skips the fits gate, so it is the one path that does reach@@ -530,7 +532,7 @@ struct DSCMaxSlideRealCacheTests {#expect(mineForced.outcome == .alreadyZero)let afterThird = try Digest.sha256(- of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName)+ of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),)#expect(afterThird == afterFirst, "a no-op pass rewrote the chunk")#expect(afterThird == FrozenReference.realChangedChunks[MaxSlideFixture.mainChunkName])@@ -561,23 +563,29 @@ struct DSCMaxSlideGateTests {regionSize: UInt64,maxSlide: UInt64,mappingOffset: Int = 0x238,- magic: String = "dyld_v1 arm64e"+ magic: String = "dyld_v1 arm64e",) throws {try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)var bytes = [UInt8](repeating: 0, count: 0x4000)func put(_ value: UInt64, at offset: Int) {withUnsafeBytes(of: value.littleEndian) { source in- for (index, byte) in source.enumerated() { bytes[offset + index] = byte }+ for (index, byte) in source.enumerated() {+ bytes[offset + index] = byte+ }}}func put32(_ value: UInt32, at offset: Int) {withUnsafeBytes(of: value.littleEndian) { source in- for (index, byte) in source.enumerated() { bytes[offset + index] = byte }+ for (index, byte) in source.enumerated() {+ bytes[offset + index] = byte+ }}}- for (index, byte) in Array(magic.utf8).prefix(16).enumerated() { bytes[index] = byte }+ for (index, byte) in Array(magic.utf8).prefix(16).enumerated() {+ bytes[index] = byte+ }put32(UInt32(mappingOffset), at: 0x10)put32(1, at: 0x14) // mappingCount@@ -593,7 +601,7 @@ struct DSCMaxSlideGateTests {put(maxSlide, at: 0xF0) // maxSlidetry Data(bytes).write(- to: directory.appendingPathComponent(MaxSlideFixture.mainChunkName)+ to: directory.appendingPathComponent(MaxSlideFixture.mainChunkName),)}@@ -614,7 +622,7 @@ struct DSCMaxSlideGateTests {reference: FrozenReference.GateCase,expectedSites: Int,expectedOutcome: DSCMaxSlidePatcher.Outcome,- expectedMaxSlideAfter: UInt64+ expectedMaxSlideAfter: UInt64,) throws {let swiftSide = MaxSlideFixture.scratchRoot.appendingPathComponent("\(name)_swift")defer { MaxSlideFixture.discard(swiftSide) }@@ -624,7 +632,7 @@ struct DSCMaxSlideGateTests {let inputDigest = try Digest.sha256(of: swiftMain)#expect(inputDigest == reference.inputSHA256,- "\(name): this is not the cache the reference saw — \(inputDigest)"+ "\(name): this is not the cache the reference saw — \(inputDigest)",)let mine = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide, force: force)@@ -634,15 +642,15 @@ struct DSCMaxSlideGateTests {let outputDigest = try Digest.sha256(of: swiftMain)#expect(outputDigest == reference.outputSHA256,- "\(name): Swift \(outputDigest), reference \(reference.outputSHA256)"+ "\(name): Swift \(outputDigest), reference \(reference.outputSHA256)",)#expect(try Bytes.maxSlide(of: swiftMain) == expectedMaxSlideAfter)print("[gate \(name)] \(expectedSites) site(s) on the reference's \(reference.branch) "+ "branch; maxSlide now 0x\(String(expectedMaxSlideAfter, radix: 16, uppercase: true))")}- @Test("An overflowing cache is clamped, as the reference clamped it")- func overflowIsClamped() throws {+ @Test+ func `An overflowing cache is clamped, as the reference clamped it`() throws {// iOS 27.0-like: 0x17C830000 + 0x20000000 > 0x180000000.try compare(named: "overflow",@@ -652,14 +660,14 @@ struct DSCMaxSlideGateTests {expectedSites: 1,expectedOutcome: .overflow(combined: 0x1_9C83_0000,- region: DSCMaxSlidePatcher.kernelSharedRegionSize+ region: DSCMaxSlidePatcher.kernelSharedRegionSize,),- expectedMaxSlideAfter: 0+ expectedMaxSlideAfter: 0,)}- @Test("A cache that fits is left alone, as the reference left it")- func fittingCacheIsUntouched() throws {+ @Test+ func `A cache that fits is left alone, as the reference left it`() throws {// 26.4-like: 0x140904000 + 0x20000000 <= 0x180000000.try compare(named: "fits",@@ -669,14 +677,14 @@ struct DSCMaxSlideGateTests {expectedSites: 0,expectedOutcome: .fits(combined: 0x1_6090_4000,- region: DSCMaxSlidePatcher.kernelSharedRegionSize+ region: DSCMaxSlidePatcher.kernelSharedRegionSize,),- expectedMaxSlideAfter: 0x2000_0000+ expectedMaxSlideAfter: 0x2000_0000,)}- @Test("--force clamps a cache that fits, to the reference's bytes")- func forceClampsAFittingCache() throws {+ @Test+ func `--force clamps a cache that fits, to the reference's bytes`() throws {try compare(named: "forced",regionSize: 0x1_4090_4000,@@ -686,14 +694,14 @@ struct DSCMaxSlideGateTests {expectedSites: 1,expectedOutcome: .forced(combined: 0x1_6090_4000,- region: DSCMaxSlidePatcher.kernelSharedRegionSize+ region: DSCMaxSlidePatcher.kernelSharedRegionSize,),- expectedMaxSlideAfter: 0+ expectedMaxSlideAfter: 0,)}- @Test("--force over an already-zero cache is a no-op, as it was for the reference")- func forceOverZeroIsANoOp() throws {+ @Test+ func `--force over an already-zero cache is a no-op, as it was for the reference`() throws {try compare(named: "forced_zero",regionSize: 0x1_4090_4000,@@ -702,7 +710,7 @@ struct DSCMaxSlideGateTests {reference: FrozenReference.forcedZero,expectedSites: 0,expectedOutcome: .alreadyZero,- expectedMaxSlideAfter: 0+ expectedMaxSlideAfter: 0,)}@@ -714,8 +722,8 @@ struct DSCMaxSlideGateTests {/// The span has to exceed the region by itself — a 0x17C830000 span with a/// zero slide *fits*, and takes the fits branch instead, which is what both/// implementations do and what an earlier version of this test got wrong.- @Test("A cache that overruns the region with no slide left is left alone")- func overflowWithZeroSlideIsANoOp() throws {+ @Test+ func `A cache that overruns the region with no slide left is left alone`() throws {try compare(named: "overflow_zero",regionSize: 0x1_9000_0000,@@ -723,14 +731,14 @@ struct DSCMaxSlideGateTests {reference: FrozenReference.overflowWithZeroSlide,expectedSites: 0,expectedOutcome: .alreadyZero,- expectedMaxSlideAfter: 0+ expectedMaxSlideAfter: 0,)}// MARK: - Refusals- @Test("A missing main chunk is a named failure, not a crash")- func missingMainChunkThrows() throws {+ @Test+ func `A missing main chunk is a named failure, not a crash`() throws {let empty = MaxSlideFixture.scratchRoot.appendingPathComponent("empty")try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)defer { MaxSlideFixture.discard(empty) }@@ -743,15 +751,15 @@ struct DSCMaxSlideGateTests {/// The Python checks `hdr[:7] != b"dyld_v1"`; so does this. A `dyld_v2`/// header still parses as a cache far enough to reach the check, which is/// what makes the check worth having.- @Test("A file that is not a dyld_v1 cache is refused")- func wrongMagicIsRefused() throws {+ @Test+ func `A file that is not a dyld_v1 cache is refused`() throws {let directory = MaxSlideFixture.scratchRoot.appendingPathComponent("badmagic")defer { MaxSlideFixture.discard(directory) }try Self.writeCache(into: directory,regionSize: 0x1_7C83_0000,maxSlide: 0x2000_0000,- magic: "dyld_v2 arm64e"+ magic: "dyld_v2 arm64e",)#expect(throws: PatcherError.self) {@@ -764,8 +772,8 @@ struct DSCMaxSlideGateTests {/// means this cache version has no such field. The reference had no/// equivalent gate and would write eight zero bytes into whatever is at/// 0xF0 — here that is a `dyld_cache_mapping_info.fileOffset`.- @Test("A header too short to hold maxSlide is refused, where the reference would write")- func truncatedHeaderIsRefused() throws {+ @Test+ func `A header too short to hold maxSlide is refused, where the reference would write`() throws {let directory = MaxSlideFixture.scratchRoot.appendingPathComponent("shortheader")defer { MaxSlideFixture.discard(directory) }// Mapping table at 0xC0: the header struct then ends at 0xC0, well@@ -775,7 +783,7 @@ struct DSCMaxSlideGateTests {into: directory,regionSize: 0x1_7C83_0000,maxSlide: 0x2000_0000,- mappingOffset: 0xC0+ mappingOffset: 0xC0,)#expect(throws: PatcherError.self) {@@ -786,14 +794,14 @@ struct DSCMaxSlideGateTests {/// The corroboration check: a header whose `sharedRegionStart` is not the/// cache's lowest mapped address is not laid out the way these offsets/// assume, so the write is refused rather than aimed at an unknown field.- @Test("A header that disagrees with the mapping table is refused")- func headerDisagreeingWithMappingsIsRefused() throws {+ @Test+ func `A header that disagrees with the mapping table is refused`() throws {let directory = MaxSlideFixture.scratchRoot.appendingPathComponent("mismatch")defer { MaxSlideFixture.discard(directory) }try Self.writeCache(into: directory,regionSize: 0x1_7C83_0000,- maxSlide: 0x2000_0000+ maxSlide: 0x2000_0000,)// Move sharedRegionStart away from the mapping's address.let main = directory.appendingPathComponent(MaxSlideFixture.mainChunkName)@@ -815,31 +823,35 @@ struct DSCMaxSlideGateTests {/// it, because every write here goes through `DSCChunkSet`, which has/// nothing to address such a file with. A documented divergence, and a/// strictly safer one — the input is not a shared cache.- @Test("A header with no mapping table is refused, where the reference patched it")- func noMappingTableIsRefused() throws {+ @Test+ func `A header with no mapping table is refused, where the reference patched it`() throws {let swiftSide = MaxSlideFixture.scratchRoot.appendingPathComponent("headeronly_swift")defer { MaxSlideFixture.discard(swiftSide) }try FileManager.default.createDirectory(at: swiftSide, withIntermediateDirectories: true)var bytes = [UInt8](repeating: 0, count: 0x100)- for (index, byte) in Array("dyld_v1 arm64e".utf8).enumerated() { bytes[index] = byte }+ for (index, byte) in Array("dyld_v1 arm64e".utf8).enumerated() {+ bytes[index] = byte+ }func put(_ value: UInt64, at offset: Int) {withUnsafeBytes(of: value.littleEndian) { source in- for (index, byte) in source.enumerated() { bytes[offset + index] = byte }+ for (index, byte) in source.enumerated() {+ bytes[offset + index] = byte+ }}}put(Self.mappingAddress, at: 0xE0)put(0x1_7C83_0000, at: 0xE8)put(0x2000_0000, at: 0xF0)try Data(bytes).write(- to: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName)+ to: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),)#expect(throws: DSCError.self) {_ = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide, verbose: false)}let untouchedSlide = try Bytes.maxSlide(- of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName)+ of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),)#expect(untouchedSlide == 0x2000_0000, "the refusal still wrote")}diff --git a/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift b/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swiftindex abe46d8c..c03ff2c2 100644--- a/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift+++ b/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift@@ -20,9 +20,9 @@// `cp -c` — APFS `clonefile`, so instant and near-free — under the system// temporary directory, or `VPHONE_DSC_SCRATCH` when it is set.-@testable import FirmwarePatcherimport Capstoneimport CryptoKit+@testable import FirmwarePatcherimport Foundationimport Testing@@ -103,7 +103,9 @@ private enum LWCRFixture {}/// The suites run unless the cache is absent *and* the caller opted out.- static var runs: Bool { pristine != nil || !isOptional }+ static var runs: Bool {+ pristine != nil || !isOptional+ }static let missing: Comment = """the real 24A435 arm64e shared cache is required — put it at \@@ -138,14 +140,14 @@ private enum LWCRFixture {try? FileManager.default.removeItem(at: destination)try FileManager.default.createDirectory(at: destination,- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let entries = try FileManager.default.contentsOfDirectory(atPath: pristine.path).sorted()let result = try Shell.run(executable: URL(fileURLWithPath: "/bin/cp"),arguments: ["-c", "-R"]+ entries.map { pristine.appendingPathComponent($0).path }- + [destination.path]+ + [destination.path],)guard result.status == 0 else {Issue.record("cp -c failed: \(result.stderr)")@@ -172,8 +174,8 @@ private enum LWCRFixture {/// Returns the names of files that differ, plus the names present in one/// directory and not the other. Empty means the two trees are identical.static func differences(between left: URL, and right: URL) throws -> [String] {- let leftNames = Set(try FileManager.default.contentsOfDirectory(atPath: left.path))- let rightNames = Set(try FileManager.default.contentsOfDirectory(atPath: right.path))+ let leftNames = try Set(FileManager.default.contentsOfDirectory(atPath: left.path))+ let rightNames = try Set(FileManager.default.contentsOfDirectory(atPath: right.path))var differing = Array(leftNames.symmetricDifference(rightNames))for name in leftNames.intersection(rightNames).sorted() {@@ -183,9 +185,11 @@ private enum LWCRFixture {// to compare them is not a thing this test can afford.let result = try Shell.run(executable: URL(fileURLWithPath: "/usr/bin/cmp"),- arguments: ["-s", a.path, b.path]+ arguments: ["-s", a.path, b.path],)- if result.status != 0 { differing.append(name) }+ if result.status != 0 {+ differing.append(name)+ }}return differing.sorted()}@@ -252,7 +256,7 @@ private enum Shell {return Result(status: process.terminationStatus,stdout: String(decoding: outData, as: UTF8.self),- stderr: String(decoding: errData, as: UTF8.self)+ stderr: String(decoding: errData, as: UTF8.self),)}}@@ -261,8 +265,8 @@ private enum Shell {@Suite(.serialized, .enabled(if: LWCRFixture.runs, LWCRFixture.skipReason))struct DSCXPCLWCRParityTests {- @Test("Swift patches the reference's three sites, to the reference's bytes")- func patchedCloneMatchesTheReference() throws {+ @Test+ func `Swift patches the reference's three sites, to the reference's bytes`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let swiftClone = try LWCRFixture.cloneCache(named: "swift")@@ -278,8 +282,8 @@ struct DSCXPCLWCRParityTests {try Digest.expectMatchesReference(swiftClone)}- @Test("The replacement words are exactly cset w0,eq / nop / nop")- func replacementWordsComeFromTheEncoders() throws {+ @Test+ func `The replacement words are exactly cset w0,eq / nop / nop`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let clone = try LWCRFixture.cloneCache(named: "words")defer { LWCRFixture.discard(clone) }@@ -303,8 +307,8 @@ struct DSCXPCLWCRParityTests {#expect(addresses[2] == addresses[1] + 4)}- @Test("A dry run reports the same three sites and writes nothing")- func dryRunWritesNothing() throws {+ @Test+ func `A dry run reports the same three sites and writes nothing`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let clone = try LWCRFixture.cloneCache(named: "dry")@@ -320,8 +324,8 @@ struct DSCXPCLWCRParityTests {#expect(changed.isEmpty, "a dry run modified \(changed)")}- @Test("Re-running over a patched cache is a no-op")- func secondRunIsANoOp() throws {+ @Test+ func `Re-running over a patched cache is a no-op`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let swiftClone = try LWCRFixture.cloneCache(named: "swift_twice")@@ -339,8 +343,8 @@ struct DSCXPCLWCRParityTests {try Digest.expectMatchesReference(swiftClone)}- @Test("Every page the writes dirtied is re-attested")- func patchedPagesAreAttested() throws {+ @Test+ func `Every page the writes dirtied is re-attested`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let clone = try LWCRFixture.cloneCache(named: "attest")defer { LWCRFixture.discard(clone) }@@ -357,14 +361,14 @@ struct DSCXPCLWCRParityTests {#expect(again.skipped.isEmpty)}- @Test("A missing local symbol table is not the same answer as a missing symbol")- func missingSymbolTableThrows() throws {+ @Test+ func `A missing local symbol table is not the same answer as a missing symbol`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let clone = try LWCRFixture.cloneCache(named: "nosymbols")defer { LWCRFixture.discard(clone) }try FileManager.default.removeItem(- at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols")+ at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols"),)#expect(throws: DSCError.self) {try DSCXPCLWCRPatcher.apply(directory: clone, dryRun: true, log: nil)@@ -390,19 +394,19 @@ struct DSCXPCLWCRShapeTests {return try DSCXPCLWCRPatcher.disassembleFunction(in: chunks,at: vma,- disassembler: ARM64Disassembler()+ disassembler: ARM64Disassembler(),)}- @Test("The symbol resolves under its mangled spelling, at a function prologue")- func symbolResolvesToAFunctionStart() throws {+ @Test+ func `The symbol resolves under its mangled spelling, at a function prologue`() throws {let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)let chunks = try DSCChunkSet(directory: pristine)let mangledAddress = try chunks.resolveLocalSymbol("__xpc_token_satisfies_lwcr")let mangled = try #require(mangledAddress,- "the double-underscore spelling is the one Mach-O stores"+ "the double-underscore spelling is the one Mach-O stores",)// The reference resolved the same symbol to the same address.#expect(mangled == FrozenReference.functionVMA)@@ -414,21 +418,21 @@ struct DSCXPCLWCRShapeTests {let stream = try DSCXPCLWCRPatcher.disassembleFunction(in: chunks,at: mangled,- disassembler: ARM64Disassembler()+ disassembler: ARM64Disassembler(),)#expect(stream.first?.mnemonic == "pacibsp")#expect(stream.last?.mnemonic == "retab")#expect(stream.count < DSCXPCLWCRPatcher.maxInstructions)}- @Test("On a pristine stream the idiom matches and the patched shape does not")- func pristineStreamMatchesTheIdiomOnly() throws {+ @Test+ func `On a pristine stream the idiom matches and the patched shape does not`() throws {let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)let disassembler = ARM64Disassembler()let stream = try functionStream(in: pristine)let site = try #require(- DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler)+ DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler),)#expect(site.cset.mnemonic == "cset")#expect(site.cset.aarch64?.conditionCode == AArch64CC_NE)@@ -448,14 +452,14 @@ struct DSCXPCLWCRShapeTests {#expect(DSCXPCLWCRPatcher.register(site.eor, 1, disassembler) == "w0")#expect(DSCXPCLWCRPatcher.register(site.eor, 2, disassembler)- == DSCXPCLWCRPatcher.register(site.cset, 0, disassembler)+ == DSCXPCLWCRPatcher.register(site.cset, 0, disassembler),)#expect(DSCXPCLWCRPatcher.findPatchedShape(in: stream, disassembler: disassembler) == nil)}- @Test("On a patched stream the patched shape matches and the idiom does not")- func patchedStreamMatchesThePatchedShapeOnly() throws {+ @Test+ func `On a patched stream the patched shape matches and the idiom does not`() throws {_ = try #require(LWCRFixture.pristine, LWCRFixture.missing)let clone = try LWCRFixture.cloneCache(named: "shape")defer { LWCRFixture.discard(clone) }@@ -468,20 +472,20 @@ struct DSCXPCLWCRShapeTests {#expect(DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler) == nil)let already = try #require(- DSCXPCLWCRPatcher.findPatchedShape(in: stream, disassembler: disassembler)+ DSCXPCLWCRPatcher.findPatchedShape(in: stream, disassembler: disassembler),)#expect(already.mnemonic == "cset")#expect(already.aarch64?.conditionCode == AArch64CC_EQ)#expect(already.address == outcome.records[0].virtualAddress)}- @Test("Neither detector matches a stream that stops before the check")- func aTruncatedStreamMatchesNothing() throws {+ @Test+ func `Neither detector matches a stream that stops before the check`() throws {let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)let disassembler = ARM64Disassembler()let stream = try functionStream(in: pristine)let site = try #require(- DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler)+ DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler),)let csetIndex = try #require(stream.firstIndex { $0.address == site.cset.address })@@ -496,13 +500,13 @@ struct DSCXPCLWCRShapeTests {#expect(DSCXPCLWCRPatcher.findPatchedShape(in: [], disassembler: disassembler) == nil)}- @Test("The idiom needs the cset that feeds the xor, not just any cset")- func aStrandedXorDoesNotMatch() throws {+ @Test+ func `The idiom needs the cset that feeds the xor, not just any cset`() throws {let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)let disassembler = ARM64Disassembler()let stream = try functionStream(in: pristine)let site = try #require(- DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler)+ DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler),)let csetIndex = try #require(stream.firstIndex { $0.address == site.cset.address })@@ -512,7 +516,7 @@ struct DSCXPCLWCRShapeTests {var withoutCset = streamwithoutCset.remove(at: csetIndex)#expect(- DSCXPCLWCRPatcher.findConsistencyCheck(in: withoutCset, disassembler: disassembler) == nil+ DSCXPCLWCRPatcher.findConsistencyCheck(in: withoutCset, disassembler: disassembler) == nil,)}}diff --git a/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift b/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swiftindex 992b1f5e..637ab1cd 100644--- a/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift+++ b/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift@@ -1,6 +1,6 @@+@testable import FirmwarePatcherimport Foundationimport Testing-@testable import FirmwarePatcher/// Identity selection for the hybrid manifest.///@@ -22,7 +22,7 @@ struct FirmwareManifestSelectionTests {static func identity(deviceClass: String,variant: String = "Customer Erase Install (IPSW)",- llbPath: String? = nil+ llbPath: String? = nil,) -> PlistDict {var manifest = PlistDict()if let llbPath {@@ -39,59 +39,59 @@ struct FirmwareManifestSelectionTests {// MARK: - isResearch- @Test("a four-part LLB filename with RESEARCH in field 3 marks a research identity")- func researchFromLLBPath() {+ @Test+ func `a four-part LLB filename with RESEARCH in field 3 marks a research identity`() {// Firmware/all_flash/LLB.vresearch101.RESEARCH.im4p -> 4 dot-separated// parts, and the third says RESEARCH.let bi = Self.identity(deviceClass: "vresearch101ap",- llbPath: "Firmware/all_flash/LLB.vresearch101.RESEARCH.im4p"+ llbPath: "Firmware/all_flash/LLB.vresearch101.RESEARCH.im4p",)#expect(FirmwareManifest.isResearch(bi))}- @Test("the same filename shape with RELEASE does not")- func releaseFromLLBPath() {+ @Test+ func `the same filename shape with RELEASE does not`() {let bi = Self.identity(deviceClass: "vresearch101ap",- llbPath: "Firmware/all_flash/LLB.vresearch101.RELEASE.im4p"+ llbPath: "Firmware/all_flash/LLB.vresearch101.RELEASE.im4p",)#expect(!FirmwareManifest.isResearch(bi))}- @Test("with no usable path, the Variant string decides")- func researchFromVariant() {+ @Test+ func `with no usable path, the Variant string decides`() {#expect(FirmwareManifest.isResearch(- Self.identity(deviceClass: "vresearch101ap", variant: "Research Erase Install (IPSW)")+ Self.identity(deviceClass: "vresearch101ap", variant: "Research Erase Install (IPSW)"),))#expect(!FirmwareManifest.isResearch(- Self.identity(deviceClass: "vresearch101ap", variant: "Customer Erase Install (IPSW)")+ Self.identity(deviceClass: "vresearch101ap", variant: "Customer Erase Install (IPSW)"),))}- @Test("the Variant check is case-insensitive")- func researchVariantIsCaseInsensitive() {+ @Test+ func `the Variant check is case-insensitive`() {#expect(FirmwareManifest.isResearch(- Self.identity(deviceClass: "vresearch101ap", variant: "RESEARCH Erase Install")+ Self.identity(deviceClass: "vresearch101ap", variant: "RESEARCH Erase Install"),))}- @Test("a filename that is not four parts falls through to the Variant")- func nonFourPartPathFallsThrough() {+ @Test+ func `a filename that is not four parts falls through to the Variant`() {// "LLB.vresearch101.im4p" is three parts: no RESEARCH field to read,// so the decision has to come from Variant instead of defaulting.let bi = Self.identity(deviceClass: "vresearch101ap",variant: "Research Erase Install (IPSW)",- llbPath: "Firmware/all_flash/LLB.vresearch101.im4p"+ llbPath: "Firmware/all_flash/LLB.vresearch101.im4p",)#expect(FirmwareManifest.isResearch(bi))}// MARK: - findCloudOS- @Test("picks the first release and the first research for a device class")- func findsBothIdentities() throws {+ @Test+ func `picks the first release and the first research for a device class`() throws {let identities = [Self.identity(deviceClass: "j226cap"),Self.identity(deviceClass: "vphone600ap"),@@ -100,22 +100,22 @@ struct FirmwareManifestSelectionTests {Self.identity(deviceClass: "vresearch101ap", variant: "Research Erase Install"),]let (release, research) = try FirmwareManifest.findCloudOS(- identities, deviceClass: "vresearch101ap"+ identities, deviceClass: "vresearch101ap",)#expect(release == 2)- #expect(research == 3) // the first research one, not the last+ #expect(research == 3) // the first research one, not the last}- @Test("a device class with no research identity is an error, not a silent fallback")- func missingResearchThrows() {+ @Test+ func `a device class with no research identity is an error, not a silent fallback`() {let identities = [Self.identity(deviceClass: "vresearch101ap")]#expect(throws: (any Error).self) {try FirmwareManifest.findCloudOS(identities, deviceClass: "vresearch101ap")}}- @Test("an unknown device class is an error")- func missingDeviceClassThrows() {+ @Test+ func `an unknown device class is an error`() {let identities = [Self.identity(deviceClass: "j226cap")]#expect(throws: (any Error).self) {try FirmwareManifest.findCloudOS(identities, deviceClass: "vphone600ap")@@ -124,8 +124,8 @@ struct FirmwareManifestSelectionTests {// MARK: - findIPhoneErase- @Test("erase is the first identity that is not research, upgrade or recovery")- func findsEraseIdentity() throws {+ @Test+ func `erase is the first identity that is not research, upgrade or recovery`() throws {let identities = [Self.identity(deviceClass: "d47ap", variant: "Customer Upgrade Install (IPSW)"),Self.identity(deviceClass: "d47ap", variant: "Research Erase Install (IPSW)"),@@ -135,8 +135,8 @@ struct FirmwareManifestSelectionTests {#expect(try FirmwareManifest.findIPhoneErase(identities) == 3)}- @Test("the erase match is case-insensitive")- func eraseMatchIsCaseInsensitive() throws {+ @Test+ func `the erase match is case-insensitive`() throws {let identities = [Self.identity(deviceClass: "d47ap", variant: "Customer UPGRADE Install"),Self.identity(deviceClass: "d47ap", variant: "Customer Erase Install"),@@ -144,8 +144,8 @@ struct FirmwareManifestSelectionTests {#expect(try FirmwareManifest.findIPhoneErase(identities) == 1)}- @Test("an iPhone manifest with no erase identity is an error")- func missingEraseThrows() {+ @Test+ func `an iPhone manifest with no erase identity is an error`() {let identities = [Self.identity(deviceClass: "d47ap", variant: "Customer Upgrade Install (IPSW)"),]diff --git a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swiftindex d7561e70..6c310715 100644--- a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift+++ b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift@@ -37,49 +37,49 @@ struct ARM64ConstantTests {#expect(insn?.mnemonic == "pacibsp" || insn?.mnemonic == "hint")}- @Test func movX0_0() {+ @Test func `mov X 0 0`() {let insn = disasm.disassembleOne(ARM64.movX0_0, at: 0)#expect(insn != nil)#expect(insn?.mnemonic == "mov" || insn?.mnemonic == "movz")}- @Test func movX0_1() {+ @Test func `mov X 0 1`() {let insn = disasm.disassembleOne(ARM64.movX0_1, at: 0)#expect(insn != nil)#expect(insn?.mnemonic == "mov" || insn?.mnemonic == "movz")}- @Test func movW0_0() {+ @Test func `mov W 0 0`() {let insn = disasm.disassembleOne(ARM64.movW0_0, at: 0)#expect(insn != nil)#expect(insn?.mnemonic == "mov" || insn?.mnemonic == "movz")}- @Test func movW0_1() {+ @Test func `mov W 0 1`() {let insn = disasm.disassembleOne(ARM64.movW0_1, at: 0)#expect(insn != nil)#expect(insn?.mnemonic == "mov" || insn?.mnemonic == "movz")}- @Test func cmpW0W0() {+ @Test func `cmp W 0 W 0`() {verifyConstant(ARM64.cmpW0W0, expectedMnemonic: "cmp")}- @Test func cmpX0X0() {+ @Test func `cmp X 0 X 0`() {verifyConstant(ARM64.cmpX0X0, expectedMnemonic: "cmp")}- @Test func movX0X20() {+ @Test func `mov X 0 X 20`() {let insn = disasm.disassembleOne(ARM64.movX0X20, at: 0)#expect(insn != nil)#expect(insn?.mnemonic == "mov" || insn?.mnemonic == "orr")}- @Test func strbW0X20_30() {+ @Test func `strb W 0 X 20 30`() {verifyConstant(ARM64.strbW0X20_30, expectedMnemonic: "strb")}- @Test func movW0_0xA1() {+ @Test func `mov W 0 0 x A 1`() {let insn = disasm.disassembleOne(ARM64.movW0_0xA1, at: 0)#expect(insn != nil)#expect(insn?.mnemonic == "mov" || insn?.mnemonic == "movz")@@ -89,7 +89,7 @@ struct ARM64ConstantTests {struct ARM64EncoderTests {let disasm = ARM64Disassembler()- @Test func encodeBForward() throws {+ @Test func `encode B forward`() throws {// B from 0x1000 to 0x2000 (forward 0x1000 bytes)let data = ARM64Encoder.encodeB(from: 0x1000, to: 0x2000)#expect(data != nil)@@ -97,7 +97,7 @@ struct ARM64EncoderTests {#expect(insn?.mnemonic == "b")}- @Test func encodeBBackward() throws {+ @Test func `encode B backward`() throws {// B from 0x2000 to 0x1000 (backward 0x1000 bytes)let data = ARM64Encoder.encodeB(from: 0x2000, to: 0x1000)#expect(data != nil)@@ -105,14 +105,14 @@ struct ARM64EncoderTests {#expect(insn?.mnemonic == "b")}- @Test func encodeBLForward() throws {+ @Test func `encode BL forward`() throws {let data = ARM64Encoder.encodeBL(from: 0x1000, to: 0x2000)#expect(data != nil)let insn = try disasm.disassembleOne(#require(data), at: 0x1000)#expect(insn?.mnemonic == "bl")}- @Test func decodeBranchTarget() throws {+ @Test func `decode branch target`() throws {// Encode a B, then decode and verify the target matcheslet from: UInt64 = 0x10000let to: UInt64 = 0x20000@@ -122,27 +122,27 @@ struct ARM64EncoderTests {#expect(decoded == to)}- @Test func encodeBOutOfRange() {+ @Test func `encode B out of range`() {// Try to encode a branch that's too far (> 128MB)let data = ARM64Encoder.encodeB(from: 0, to: 0x1000_0000)#expect(data == nil)}- @Test func encodeADRP() throws {+ @Test func `encode ADRP`() throws {let data = ARM64Encoder.encodeADRP(rd: 0, pc: 0x1000, target: 0x2000)#expect(data != nil)let insn = try disasm.disassembleOne(#require(data), at: 0x1000)#expect(insn?.mnemonic == "adrp")}- @Test func encodeAddImm12() throws {+ @Test func `encode add imm 12`() throws {let data = ARM64Encoder.encodeAddImm12(rd: 0, rn: 0, imm12: 0x100)#expect(data != nil)let insn = try disasm.disassembleOne(#require(data), at: 0)#expect(insn?.mnemonic == "add")}- @Test func encodeMovXFromZR() {+ @Test func `encode mov X from ZR`() {// `mov x8, xzr` — the mac_mount state-clear encoding (ORR X8, XZR, XZR).let bytes = ARM64Encoder.encodeMovX(rd: 8, rm: 31)let insn = disasm.disassembleOne(bytes, at: 0)@@ -152,16 +152,17 @@ struct ARM64EncoderTests {#expect(bytes == withUnsafeBytes(of: UInt32(0xAA1F_03E8).littleEndian) { Data($0) })}- @Test func encodeMovXIsRegisterMove() {+ @Test func `encode mov X is register move`() {// `mov x0, x20` matches the project's preverified ARM64.movX0X20 constant.#expect(ARM64Encoder.encodeMovX(rd: 0, rm: 20) == ARM64.movX0X20)}- @Test func encodeTestBitBranchRoundTrips() throws {+ @Test func `encode test bit branch round trips`() throws {// The vm_map_delete --frida patch retargets `tbz/tbnz w8,#9` to bit 13// (current-protection.X → max_protection.X), preserving sense and target.let tbz = try #require(ARM64Encoder.encodeTestBitBranch(- nonzero: false, register: 8, bit: 13, from: 0x1000, to: 0x1020))+ nonzero: false, register: 8, bit: 13, from: 0x1000, to: 0x1020,+ ))let tbzI = try #require(disasm.disassembleOne(tbz, at: 0x1000))#expect(tbzI.mnemonic == "tbz")#expect(tbzI.operandString.contains("w8"))@@ -169,7 +170,8 @@ struct ARM64EncoderTests {#expect(tbzI.operandString.contains("0x1020"))let tbnz = try #require(ARM64Encoder.encodeTestBitBranch(- nonzero: true, register: 8, bit: 13, from: 0x2000, to: 0x1f00))+ nonzero: true, register: 8, bit: 13, from: 0x2000, to: 0x1F00,+ ))let tbnzI = try #require(disasm.disassembleOne(tbnz, at: 0x2000))#expect(tbnzI.mnemonic == "tbnz")#expect(tbnzI.operandString.contains("#0xd"))@@ -181,7 +183,7 @@ struct ARM64EncoderTests {#expect(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: 13, from: 0, to: 0x8000) == nil)}- @Test func encodeMovzWClearsTSSFCheckEntitlement() throws {+ @Test func `encode movz W clears TSSF check entitlement`() throws {// The thread_set_state --frida patch rewrites `mov w6, #0x201`// (TSSF_TRANSLATE_TO_USER | TSSF_CHECK_ENTITLEMENT) to `mov w6, #0x1`,// clearing only the entitlement bit while preserving user translation.@@ -205,7 +207,7 @@ struct ARM64InstTests {return disasm.disassembleOne(data, at: 0)?.mnemonic}- @Test func fieldAccessors() {+ @Test func `field accessors`() {// ldr x1, [x0, #0x3e0] → Rt=1, Rn=0let ldr: UInt32 = 0xF941_F001#expect(ARM64Inst.rd(ldr) == 1)@@ -229,14 +231,14 @@ struct ARM64InstTests {#expect(!ARM64Inst.isADRP(0xF941_F001)) // an ldr is not adrp}- @Test func ldrImm64() {+ @Test func `ldr imm 64`() {let w: UInt32 = 0xF941_F001 // ldr x1, [x0, #0x3e0]#expect(mnemonic(of: w) == "ldr")#expect(ARM64Inst.isLDRImm64(w))#expect(!ARM64Inst.isLDRImm64(0x9000_0000))}- @Test func cmpReg64() {+ @Test func `cmp reg 64`() {let w: UInt32 = 0xEB01_001F // cmp x0, x1#expect(mnemonic(of: w) == "cmp")#expect(ARM64Inst.isCMPReg64(w))@@ -245,14 +247,14 @@ struct ARM64InstTests {#expect(!ARM64Inst.isCMPReg64(0x5100_0462)) // sub-imm is not cmp-reg}- @Test func subImm32() {+ @Test func `sub imm 32`() {let w: UInt32 = 0x5100_0462 // sub w2, w3, #1#expect(mnemonic(of: w) == "sub")#expect(ARM64Inst.isSUBImm32(w))#expect(!ARM64Inst.isSUBImm32(0x5280_02C0)) // movz is not sub}- @Test func movzW() {+ @Test func `movz W`() {let w: UInt32 = 0x5280_02C0 // movz w0, #0x16let m = mnemonic(of: w)#expect(m == "mov" || m == "movz")@@ -261,14 +263,14 @@ struct ARM64InstTests {#expect(!ARM64Inst.isMOVZW(0xF941_F001))}- @Test func andRegW() {+ @Test func `and reg W`() {let w: UInt32 = 0x0A05_0083 // and w3, w4, w5#expect(mnemonic(of: w) == "and")#expect(ARM64Inst.isANDRegW(w))#expect(!ARM64Inst.isANDRegW(0x5280_02C0))}- @Test func lsrImm7W() {+ @Test func `lsr imm 7 W`() {let w: UInt32 = 0x5307_7C20 // lsr w0, w1, #7let m = mnemonic(of: w)#expect(m == "lsr" || m == "ubfm")@@ -276,16 +278,16 @@ struct ARM64InstTests {#expect(!ARM64Inst.isLSRImm7W(0x0A05_0083))}- @Test func branchPredicates() {- let bl = ARM64Encoder.encodeBL(from: 0x1000, to: 0x2000)!- .withUnsafeBytes { $0.load(as: UInt32.self) }+ @Test func `branch predicates`() throws {+ let bl = try #require(ARM64Encoder.encodeBL(from: 0x1000, to: 0x2000)?+ .withUnsafeBytes { $0.load(as: UInt32.self) })#expect(ARM64Inst.isBL(bl))// b.eq vs b.ne (cond field)#expect(ARM64Inst.isBEQ(0x5400_0020)) // b.eq #4#expect(!ARM64Inst.isBEQ(0x5400_0021)) // b.ne #4}- @Test func compareAndBranch() {+ @Test func `compare and branch`() {#expect(ARM64Inst.isCBZW(0x3400_0020)) // cbz w0, #4#expect(!ARM64Inst.isCBZW(0x3500_0020)) // that is cbnz#expect(ARM64Inst.isCBNZW(0x3500_0020))@@ -297,14 +299,14 @@ struct ARM64InstTests {}struct BinaryBufferTests {- @Test func readWriteU32() {+ @Test func `read write U 32`() {let data = Data(repeating: 0, count: 16)let buf = BinaryBuffer(data)buf.writeU32(at: 4, value: 0xDEAD_BEEF)#expect(buf.readU32(at: 4) == 0xDEAD_BEEF)}- @Test func findString() {+ @Test func `find string`() {let testStr = "Hello, World!\0Extra"let data = Data(testStr.utf8)let buf = BinaryBuffer(data)@@ -312,7 +314,7 @@ struct BinaryBufferTests {#expect(offset == 0)}- @Test func findAll() {+ @Test func `find all`() {var data = Data(repeating: 0, count: 32)// Write NOP at offset 8 and 20let nop = ARM64.nop@@ -325,7 +327,7 @@ struct BinaryBufferTests {#expect(offsets.contains(20))}- @Test func readUnalignedValues() {+ @Test func `read unaligned values`() {let data = Data([0xFF, 0x78, 0x56, 0x34, 0x12, 0xF0, 0xDE, 0xBC, 0x9A])let buf = BinaryBuffer(data)#expect(buf.readU32(at: 1) == 0x1234_5678)@@ -356,19 +358,21 @@ final class BytePatchPatcher: Patcher {fileOffset: offset,originalBytes: Data([data[offset]]),patchedBytes: Data([byte]),- description: id+ description: id,),]}- func apply() throws -> Int { 1 }+ func apply() throws -> Int {+ 1+ }}struct FirmwarePipelineDataFlowTests {- @Test func chainedPatchersReceivePreviousPatchedBytes() throws {+ @Test func `chained patchers receive previous patched bytes`() throws {let pipeline = FirmwarePipeline(vmDirectory: URL(fileURLWithPath: NSTemporaryDirectory()),- verbose: false+ verbose: false,)var secondInput = Data()@@ -383,7 +387,7 @@ struct FirmwarePipelineDataFlowTests {secondInput = datareturn BytePatchPatcher(data: data, offset: 1, byte: 0xBB, id: "second")},- ]+ ],)#expect(secondInput == Data([0xAA, 0x00]))@@ -393,7 +397,7 @@ struct FirmwarePipelineDataFlowTests {}struct IBootPatcherIdempotencyTests {- @Test func serialLabelsPatchTwoBannerRunsWhenLabelAbsent() {+ @Test func `serial labels patch two banner runs when label absent`() {let banner = String(repeating: "=", count: 32)let payload = Data("prefix \(banner) middle \(banner) suffix".utf8)let patcher = IBootPatcher(data: payload, mode: .ibss, verbose: false)@@ -406,7 +410,7 @@ struct IBootPatcherIdempotencyTests {})}- @Test func serialLabelsSkipWhenLabelAlreadyPresent() {+ @Test func `serial labels skip when label already present`() {let payload = Data("Loaded iBSS\0 middle Loaded iBSS\0 suffix".utf8)let patcher = IBootPatcher(data: payload, mode: .ibss, verbose: false)@@ -415,7 +419,7 @@ struct IBootPatcherIdempotencyTests {#expect(patcher.patches.isEmpty)}- @Test func serialLabelsDoNotSkipForUnrelatedSingleLabel() {+ @Test func `serial labels do not skip for unrelated single label`() {let banner = String(repeating: "=", count: 32)let payload = Data("Loaded iBSS\0 prefix \(banner) middle \(banner) suffix".utf8)let patcher = IBootPatcher(data: payload, mode: .ibss, verbose: false)@@ -427,7 +431,7 @@ struct IBootPatcherIdempotencyTests {}struct IM4PPayloadParityTests {- @Test func ibssIM4PPayloadMatchesRawAndJBPatcherFindsNoncePatch() throws {+ @Test func `ibss IM 4 P payload matches raw and JB patcher finds nonce patch`() throws {let baseDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()@@ -436,7 +440,7 @@ struct IM4PPayloadParityTests {let rawIBSS = try Data(contentsOf: baseDir.appendingPathComponent("raw_payloads/ibss.bin"))let (im4pPayload, _) = try IM4PHandler.load(- contentsOf: baseDir.appendingPathComponent("Firmware/dfu/iBSS.vresearch101.RELEASE.im4p")+ contentsOf: baseDir.appendingPathComponent("Firmware/dfu/iBSS.vresearch101.RELEASE.im4p"),)#expect(im4pPayload == rawIBSS)@@ -446,7 +450,7 @@ struct IM4PPayloadParityTests {#expect(records.count == 1)}- @Test func savingIBSSIM4PRoundTripsPayload() throws {+ @Test func `saving IBSSIM 4 P round trips payload`() throws {let baseDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()@@ -466,10 +470,10 @@ struct IM4PPayloadParityTests {let (roundTripPayload, _) = try IM4PHandler.load(contentsOf: tempURL)#expect(roundTripPayload == payload)- #expect((try Data(contentsOf: tempURL)).count > originalFile.count)+ #expect(try (Data(contentsOf: tempURL)).count > originalFile.count)}- @Test func savingTXMIM4PPreservesPAYPTrailer() throws {+ @Test func `saving TXMIM 4 P preserves PAYP trailer`() throws {let baseDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()@@ -497,7 +501,7 @@ struct IM4PPayloadParityTests {}struct FirmwarePipelineTests {- @Test func findFileSupportsGlobPatterns() throws {+ @Test func `find file supports glob patterns`() throws {let fm = FileManager.defaultlet tempDir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)@@ -519,7 +523,7 @@ struct FirmwarePipelineTests {}struct FridaGatingTests {- @Test func cloudOSVersionGate() {+ @Test func `cloud OS version gate`() {// Frida kernel patches apply on cloudOS 26.4+ only.#expect(FirmwarePipeline.productVersionAtLeast("26.4", 26, 4))#expect(FirmwarePipeline.productVersionAtLeast("26.5", 26, 4))diff --git a/tests/FirmwarePatcherTests/MachOParserBoundsTests.swift b/tests/FirmwarePatcherTests/MachOParserBoundsTests.swiftindex ac1ce53a..416413c4 100644--- a/tests/FirmwarePatcherTests/MachOParserBoundsTests.swift+++ b/tests/FirmwarePatcherTests/MachOParserBoundsTests.swift@@ -39,7 +39,7 @@ struct MachOParserBoundsTests {vmAddr: UInt64,vmSize: UInt64,nsects: UInt32,- cmdsize: UInt32+ cmdsize: UInt32,) -> Data {var data = Data()func append32(_ value: UInt32) {@@ -66,16 +66,16 @@ struct MachOParserBoundsTests {// MARK: - Positive control- // Without this, "returns nothing" would be indistinguishable from a guard- // that rejects everything.- @Test func aWellFormedSegmentStillParses() {+ /// Without this, "returns nothing" would be indistinguishable from a guard+ /// that rejects everything.+ @Test func `a well formed segment still parses`() {var image = Self.header(ncmds: 1, sizeofcmds: 72)image.append(Self.segment(name: "__TEXT",vmAddr: 0x1_0000_0000,vmSize: 0x4000,nsects: 0,- cmdsize: 72+ cmdsize: 72,))let segments = MachOParser.parseSegments(from: image)@@ -87,9 +87,9 @@ struct MachOParserBoundsTests {// MARK: - Truncation- // The original repro: `head -c 64 ipsws/ref_extract/macho_pristine/seputil`.- // Header says 23 commands in 2312 bytes; the file holds 64.- @Test func aTruncatedLoadCommandTableYieldsNothingInsteadOfTrapping() {+ /// The original repro: `head -c 64 ipsws/ref_extract/macho_pristine/seputil`.+ /// Header says 23 commands in 2312 bytes; the file holds 64.+ @Test func `a truncated load command table yields nothing instead of trapping`() {var image = Self.header(ncmds: 23, sizeofcmds: 2312)image.append(Data(repeating: 0, count: 32)) // half of one LC_SEGMENT_64#expect(image.count == 64)@@ -100,16 +100,16 @@ struct MachOParserBoundsTests {#expect(MachOParser.findSymbol(containing: "anything", in: image) == nil)}- // A command whose body is one byte short of fitting is still a command the- // walk must not enter — the last field read lives at the very end of it.- @Test func aSegmentOneByteShortOfFittingIsNotParsed() {+ /// A command whose body is one byte short of fitting is still a command the+ /// walk must not enter — the last field read lives at the very end of it.+ @Test func `a segment one byte short of fitting is not parsed`() {var image = Self.header(ncmds: 1, sizeofcmds: 72)image.append(Self.segment(name: "__TEXT",vmAddr: 0x1_0000_0000,vmSize: 0x4000,nsects: 0,- cmdsize: 72+ cmdsize: 72,))image.removeLast()@@ -118,9 +118,9 @@ struct MachOParserBoundsTests {// MARK: - Malformed sizes- // `cmdsize == 0` used to advance the cursor by zero, re-reading the same- // command `ncmds` times. Bounded, but it is not a table worth trusting.- @Test func aZeroSizedCommandStopsTheWalk() {+ /// `cmdsize == 0` used to advance the cursor by zero, re-reading the same+ /// command `ncmds` times. Bounded, but it is not a table worth trusting.+ @Test func `a zero sized command stops the walk`() {var image = Self.header(ncmds: 4, sizeofcmds: 32)var zero = Data()withUnsafeBytes(of: UInt32(0x19).littleEndian) { zero.append(contentsOf: $0) }@@ -131,16 +131,16 @@ struct MachOParserBoundsTests {#expect(MachOParser.parseSegments(from: image).isEmpty)}- // `nsects` is inside the command but the section table it describes is not:- // the command declares one section and then stops at the fixed 72 bytes.- @Test func aSectionTableOutsideItsCommandIsNotRead() {+ /// `nsects` is inside the command but the section table it describes is not:+ /// the command declares one section and then stops at the fixed 72 bytes.+ @Test func `a section table outside its command is not read`() {var image = Self.header(ncmds: 1, sizeofcmds: 72)image.append(Self.segment(name: "__TEXT",vmAddr: 0x1_0000_0000,vmSize: 0x4000,nsects: 1, // claims a section_64 that cmdsize leaves no room for- cmdsize: 72+ cmdsize: 72,))image.append(Data(repeating: 0xFF, count: 80)) // trailing bytes, not ours to read@@ -152,7 +152,7 @@ struct MachOParserBoundsTests {// MARK: - Not a Mach-O at all- @Test func nonMachOInputIsRejectedWithoutReading() {+ @Test func `non mach O input is rejected without reading`() {let text = Data("this is not a mach-o, not even a little bit of one".utf8)#expect(MachOParser.parseSegments(from: text).isEmpty)#expect(MachOParser.parseSections(from: text).isEmpty)diff --git a/tests/FirmwarePatcherTests/PatchComparisonTests.swift b/tests/FirmwarePatcherTests/PatchComparisonTests.swiftindex 2dbb206d..f0ae5d43 100644--- a/tests/FirmwarePatcherTests/PatchComparisonTests.swift+++ b/tests/FirmwarePatcherTests/PatchComparisonTests.swift@@ -24,7 +24,7 @@ import Testing/// True when the unreproducible Python reference records are present.private var hasReferencePatches: Bool {FileManager.default.fileExists(- atPath: baseDir.appendingPathComponent("reference_patches").path+ atPath: baseDir.appendingPathComponent("reference_patches").path,)}@@ -70,7 +70,7 @@ private func loadReference(_ name: String) throws -> [ReferencePatch] {private func comparePatchRecords(swift swiftPatches: [PatchRecord],reference refPatches: [ReferencePatch],- component: String+ component: String,) {// Sort both by file_offset for stable comparisonlet sortedSwift = swiftPatches.sorted { $0.fileOffset < $1.fileOffset }@@ -121,7 +121,7 @@ private func comparePatchRecords(@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct AVPBooterComparisonTests {- @Test func compareAVPBooter() throws {+ @Test func `compare AVP booter`() throws {let data = try loadRawPayload("avpbooter.bin")let patcher = AVPBooterPatcher(data: data, verbose: false)let swiftPatches = try patcher.findAll()@@ -134,7 +134,7 @@ struct AVPBooterComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct IBSSComparisonTests {- @Test func compareIBSS() throws {+ @Test func `compare IBSS`() throws {let data = try loadRawPayload("ibss.bin")let patcher = IBootPatcher(data: data, mode: .ibss, verbose: false)let swiftPatches = try patcher.findAll()@@ -145,7 +145,7 @@ struct IBSSComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct IBECComparisonTests {- @Test func compareIBEC() throws {+ @Test func `compare IBEC`() throws {let data = try loadRawPayload("ibec.bin")let patcher = IBootPatcher(data: data, mode: .ibec, verbose: false)let swiftPatches = try patcher.findAll()@@ -156,7 +156,7 @@ struct IBECComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct LLBComparisonTests {- @Test func compareLLB() throws {+ @Test func `compare LLB`() throws {let data = try loadRawPayload("llb.bin")let patcher = IBootPatcher(data: data, mode: .llb, verbose: false)let swiftPatches = try patcher.findAll()@@ -169,7 +169,7 @@ struct LLBComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct TXMComparisonTests {- @Test func compareTXM() throws {+ @Test func `compare TXM`() throws {let data = try loadRawPayload("txm.bin")let patcher = TXMPatcher(data: data, verbose: false)let swiftPatches = try patcher.findAll()@@ -180,7 +180,7 @@ struct TXMComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct TXMDevComparisonTests {- @Test func compareTXMDev() throws {+ @Test func `compare TXM dev`() throws {let url = baseDir.appendingPathComponent("reference_patches/txm_dev.json")let jsonData = try Data(contentsOf: url)let ref = try JSONDecoder().decode(TXMDevReference.self, from: jsonData)@@ -199,7 +199,7 @@ struct TXMDevComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct KernelcacheComparisonTests {- @Test func compareKernelcache() throws {+ @Test func `compare kernelcache`() throws {let data = try loadRawPayload("kernelcache.bin")let patcher = KernelPatcher(data: data, verbose: false)let swiftPatches = try patcher.findAll()@@ -212,7 +212,7 @@ struct KernelcacheComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct IBSSJBComparisonTests {- @Test func compareIBSSJB() throws {+ @Test func `compare IBSSJB`() throws {let data = try loadRawPayload("ibss.bin")let patcher = IBootJBPatcher(data: data, mode: .ibss, verbose: false)// IBootJBPatcher only adds JB-specific patches on top of base@@ -226,7 +226,7 @@ struct IBSSJBComparisonTests {@Suite(.enabled(if: hasReferencePatches, referenceMissing))struct KernelcacheJBComparisonTests {- @Test func compareKernelcacheJB() throws {+ @Test func `compare kernelcache JB`() throws {let data = try loadRawPayload("kernelcache.bin")let patcher = KernelJBPatcher(data: data, verbose: false)let swiftPatches = try patcher.findAll()diff --git a/tests/FirmwarePatcherTests/VerboseJBDebug.swift b/tests/FirmwarePatcherTests/VerboseJBDebug.swiftindex d9245835..b4039bf9 100644--- a/tests/FirmwarePatcherTests/VerboseJBDebug.swift+++ b/tests/FirmwarePatcherTests/VerboseJBDebug.swift@@ -3,7 +3,7 @@ import Foundationimport Testingstruct VerboseJBDebug {- @Test func debugFailingPatches() throws {+ @Test func `debug failing patches`() throws {let baseDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()diff --git a/tests/VPhoneArchiveTests/BundleTransferTests.swift b/tests/VPhoneArchiveTests/BundleTransferTests.swiftindex 3bfd8b93..472de401 100644--- a/tests/VPhoneArchiveTests/BundleTransferTests.swift+++ b/tests/VPhoneArchiveTests/BundleTransferTests.swift@@ -32,7 +32,7 @@ struct BundleTransferTests {private func makeBundle(_ name: String,cpuCount: UInt = 2,- in library: VPhoneLibrary+ in library: VPhoneLibrary,) throws -> VPhoneBundle {let rom = try fakeROM(); let seprom = try fakeROM()defer {@@ -46,9 +46,9 @@ struct BundleTransferTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: library+ in: library,)}@@ -58,7 +58,7 @@ struct BundleTransferTests {// MARK: - Round trip- @Test func exportThenImportRoundTrips() throws {+ @Test func `export then import round trips`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -79,7 +79,7 @@ struct BundleTransferTests {#expect(try lib2.bundle(named: "copy").manifest.cpuCount == 8)}- @Test func importRejectsExistingName() throws {+ @Test func `import rejects existing name`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -92,7 +92,7 @@ struct BundleTransferTests {}}- @Test func importWithRenameDoesNotClobberArchivedNameCollision() throws {+ @Test func `import with rename does not clobber archived name collision`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -110,12 +110,12 @@ struct BundleTransferTests {let imported = try VPhoneBundleTransfer.importArchive(from: archive, name: "renamed", in: lib)#expect(imported.name == "renamed")#expect(imported.manifest.cpuCount == 4)- #expect(try lib.bundle(named: "orig").manifest.cpuCount == 16) // untouched+ #expect(try lib.bundle(named: "orig").manifest.cpuCount == 16) // untouched}// MARK: - Exclusions- @Test func exportExcludesRestoreDirByDefault() throws {+ @Test func `export excludes restore dir by default`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -130,7 +130,7 @@ struct BundleTransferTests {#expect(!members.contains { $0.contains("iPhone_Restore") })}- @Test func exportIncludesRestoreDirWhenAsked() throws {+ @Test func `export includes restore dir when asked`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -145,7 +145,7 @@ struct BundleTransferTests {#expect(members.contains("orig/iPhone_Restore/marker"))}- @Test func exportExcludesRegenerableStagingFiles() throws {+ @Test func `export excludes regenerable staging files`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -173,7 +173,7 @@ struct BundleTransferTests {// MARK: - Malformed input- @Test func importRejectsMultiTopLevelArchive() throws {+ @Test func `import rejects multi top level archive`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }// An archive with TWO top-level dirs is not a single bundle → badArchive.@@ -187,11 +187,12 @@ struct BundleTransferTests {#expect(throws: VPhoneBundleTransferError.self) {_ = try VPhoneBundleTransfer.importArchive(- from: archive, name: nil, in: VPhoneLibrary(root: root.appendingPathComponent("library")))+ from: archive, name: nil, in: VPhoneLibrary(root: root.appendingPathComponent("library")),+ )}}- @Test func importRejectsInvalidManifestWithoutReservingName() throws {+ @Test func `import rejects invalid manifest without reserving name`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let fm = FileManager.default@@ -205,7 +206,8 @@ struct BundleTransferTests {func pack() throws {try? fm.removeItem(at: archive)try VPhoneArchiveWriter.create(- archive: archive, from: bundleDir, topLevel: "original", compression: .gzip(level: 1))+ archive: archive, from: bundleDir, topLevel: "original", compression: .gzip(level: 1),+ )}try pack()#expect(throws: VPhoneManifestError.self) {@@ -215,7 +217,8 @@ struct BundleTransferTests {#expect(try fm.contentsOfDirectory(atPath: lib.root.path).isEmpty)let manifest = VPhoneVirtualMachineManifest(- cpuCount: 2, memorySize: 2048 * 1024 * 1024, romImages: nil)+ cpuCount: 2, memorySize: 2048 * 1024 * 1024, romImages: nil,+ )try manifest.write(to: config)try pack()let imported = try VPhoneBundleTransfer.importArchive(from: archive, name: nil, in: lib)@@ -229,7 +232,7 @@ struct BundleTransferTests {private static let xzMagic: [UInt8] = [0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]private func magic(_ url: URL, _ n: Int) throws -> [UInt8] {- Array(try Data(contentsOf: url).prefix(n))+ try Array(Data(contentsOf: url).prefix(n))}/// Takes a body rather than returning the pair, because it makes two@@ -244,7 +247,7 @@ struct BundleTransferTests {/// was the one place that could not.private func withExportAndImport(_ compression: VPhoneBundleTransfer.ExportCompression?,- _ body: (_ archive: URL, _ imported: VPhoneBundle) throws -> Void+ _ body: (_ archive: URL, _ imported: VPhoneBundle) throws -> Void,) throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }@@ -257,7 +260,7 @@ struct BundleTransferTests {to: archive,includeIPSW: false,compression: compression,- in: lib+ in: lib,)} else {try VPhoneBundleTransfer.export(bundleNamed: "orig", to: archive, includeIPSW: false, in: lib)@@ -265,14 +268,15 @@ struct BundleTransferTests {let dstRoot = try makeRoot()defer { try? FileManager.default.removeItem(at: dstRoot) }let imported = try VPhoneBundleTransfer.importArchive(- from: archive, name: "copy", in: VPhoneLibrary(root: dstRoot))+ from: archive, name: "copy", in: VPhoneLibrary(root: dstRoot),+ )try body(archive, imported)}- // The `try` is hoisted out of `#expect` in these three: inside a throwing- // closure the macro's expansion does not carry the throw out, so- // `#expect(try magic(...))` is "errors thrown from here are not handled".- @Test func exportDefaultsToFastZstd() throws {+ /// The `try` is hoisted out of `#expect` in these three: inside a throwing+ /// closure the macro's expansion does not carry the throw out, so+ /// `#expect(try magic(...))` is "errors thrown from here are not handled".+ @Test func `export defaults to fast zstd`() throws {try withExportAndImport(nil) { archive, imported inlet magic = try magic(archive, 4)#expect(magic == Self.zstdMagic)@@ -280,7 +284,7 @@ struct BundleTransferTests {}}- @Test func exportFastProducesZstdAndRoundTrips() throws {+ @Test func `export fast produces zstd and round trips`() throws {try withExportAndImport(.fast) { archive, imported inlet magic = try magic(archive, 4)#expect(magic == Self.zstdMagic)@@ -288,7 +292,7 @@ struct BundleTransferTests {}}- @Test func exportMaxProducesXzAndRoundTrips() throws {+ @Test func `export max produces xz and round trips`() throws {try withExportAndImport(.max) { archive, imported inlet magic = try magic(archive, 6)#expect(magic == Self.xzMagic)@@ -299,14 +303,14 @@ struct BundleTransferTests {/// Replaces the old `compressionPresetTarArgs`, which pinned the same/// contract as `tar` flag strings. The levels are not tuning: `.tzst` and/// `.txz` files produced at these settings are already in circulation.- @Test func compressionPresetsPinLevelsAndExtensions() {+ @Test func `compression presets pin levels and extensions`() {#expect(VPhoneBundleTransfer.ExportCompression.fast.archiveCompression == .zstd(level: 3))#expect(VPhoneBundleTransfer.ExportCompression.max.archiveCompression == .xz(level: 9))#expect(VPhoneBundleTransfer.ExportCompression.fast.fileExtension == "tzst")#expect(VPhoneBundleTransfer.ExportCompression.max.fileExtension == "txz")}- @Test func exportToDirectoryAutoNamesWithExtension() throws {+ @Test func `export to directory auto names with extension`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -318,7 +322,7 @@ struct BundleTransferTests {bundleNamed: "orig",to: outDir,includeIPSW: false,- in: lib+ in: lib,)#expect(zstdOut == outDir.appendingPathComponent("orig.tzst"))#expect(FileManager.default.fileExists(atPath: zstdOut.path))@@ -327,7 +331,7 @@ struct BundleTransferTests {to: outDir,includeIPSW: false,compression: .max,- in: lib+ in: lib,)#expect(xzOut == outDir.appendingPathComponent("orig.txz"))#expect(FileManager.default.fileExists(atPath: xzOut.path))@@ -335,11 +339,13 @@ struct BundleTransferTests {// MARK: - Progress- @Test func exportAndImportReportProgress() throws {+ @Test func `export and import report progress`() throws {final class Collector {private(set) var dones: [Int64] = []private(set) var total: Int64 = 0- func add(_ done: Int64, _ total: Int64) { dones.append(done); self.total = total }+ func add(_ done: Int64, _ total: Int64) {+ dones.append(done); self.total = total+ }}let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }@@ -352,9 +358,9 @@ struct BundleTransferTests {exp.add($0, $1)}#expect(!exp.dones.isEmpty)- #expect(exp.total > 0) // bundle logical size- #expect(exp.dones.last! > 0)- #expect(exp.dones == exp.dones.sorted()) // monotonically non-decreasing+ #expect(exp.total > 0) // bundle logical size+ #expect(try #require(exp.dones.last) > 0)+ #expect(exp.dones == exp.dones.sorted()) // monotonically non-decreasing// A bar that only moved once per member would sit at zero for the whole// export: Disk.img is one entry and everything else is tiny.#expect(exp.dones.count > 1)@@ -363,14 +369,15 @@ struct BundleTransferTests {let dstRoot = try makeRoot()defer { try? FileManager.default.removeItem(at: dstRoot) }_ = try VPhoneBundleTransfer.importArchive(- from: archive, name: "copy", in: VPhoneLibrary(root: dstRoot)) {+ from: archive, name: "copy", in: VPhoneLibrary(root: dstRoot),+ ) {imp.add($0, $1)}let archiveSize = try Data(contentsOf: archive).count#expect(!imp.dones.isEmpty)- #expect(imp.total == Int64(archiveSize)) // total == compressed file size+ #expect(imp.total == Int64(archiveSize)) // total == compressed file size#expect(imp.dones == imp.dones.sorted())- #expect(imp.dones.last! == Int64(archiveSize)) // whole archive accounted for+ #expect(imp.dones.last == Int64(archiveSize)) // whole archive accounted for// That last one cannot fail on its own: `importArchive` reports// `(total, total)` unconditionally once extraction returns, precisely@@ -389,7 +396,7 @@ struct BundleTransferTests {/// many names it has — the writer's link resolver turns the later names/// into size-0 references. Counting each name's size instead put the total/// permanently above the packed bytes, so the bar could not reach 100%.- @Test func exportProgressTotalCountsAHardlinkedFileOnce() throws {+ @Test func `export progress total counts A hardlinked file once`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -401,13 +408,16 @@ struct BundleTransferTests {try Data(repeating: 0x7A, count: 100 * 1024).write(to: payload)for alias in ["linked_b.bin", "linked_c.bin"] {try FileManager.default.linkItem(- at: payload, to: bundle.url.appendingPathComponent(alias))+ at: payload, to: bundle.url.appendingPathComponent(alias),+ )}final class Collector {private(set) var done: Int64 = 0private(set) var total: Int64 = 0- func add(_ done: Int64, _ total: Int64) { self.done = done; self.total = total }+ func add(_ done: Int64, _ total: Int64) {+ self.done = done; self.total = total+ }}let progress = Collector()let archive = root.appendingPathComponent("orig.tzst")@@ -430,7 +440,7 @@ struct BundleTransferTests {/// an entry for that directory itself — what `tar -C <library> <name>`/// produced. `importArchive` requires it, and so does every archive already/// written by an older copy of this program.- @Test func exportCarriesOneTopLevelBundleDirectory() throws {+ @Test func `export carries one top level bundle directory`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -454,7 +464,7 @@ struct BundleTransferTests {/// PATH — which is the whole point of the migration. The compressor is/// detected either way; `research/host/archive_extraction_contracts.md` records/// the .tzst and .txz runs.- @Test func importReadsArchiveWrittenByTheOldTarPipeline() throws {+ @Test func `import reads archive written by the old tar pipeline`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -471,7 +481,8 @@ struct BundleTransferTests {let dstRoot = try makeRoot()defer { try? FileManager.default.removeItem(at: dstRoot) }let imported = try VPhoneBundleTransfer.importArchive(- from: archive, name: "fromlegacy", in: VPhoneLibrary(root: dstRoot))+ from: archive, name: "fromlegacy", in: VPhoneLibrary(root: dstRoot),+ )#expect(imported.name == "fromlegacy")#expect(imported.manifest.cpuCount == 6)#expect(FileManager.default.fileExists(atPath: imported.url.appendingPathComponent("Disk.img").path))@@ -480,7 +491,7 @@ struct BundleTransferTests {/// And the other direction: what this writes is an ordinary tar. Checked/// after `decompress`, so the check does not need a `zstd(1)` either; the/// zstd stream itself is pinned by the magic-byte tests above.- @Test func systemTarReadsWhatExportWrites() throws {+ @Test func `system tar reads what export writes`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)diff --git a/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift b/tests/VPhoneArchiveTests/ExtractPermissionsTests.swiftindex 91746f63..0c188b19 100644--- a/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift+++ b/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift@@ -48,19 +48,22 @@ struct ExtractPermissionsTests {try fm.createDirectory(at: source, withIntermediateDirectories: true)try Data("#!/bin/sh\n".utf8).write(to: source.appendingPathComponent(setuidFile))try fm.createDirectory(- at: source.appendingPathComponent(wideDirectory), withIntermediateDirectories: true)+ at: source.appendingPathComponent(wideDirectory), withIntermediateDirectories: true,+ )try Data("owo\n".utf8).write(to: source.appendingPathComponent(worldWritableFile))// chmod after the writes: creating a file resets its mode.for (name, mode) in archivedModes {try fm.setAttributes([.posixPermissions: NSNumber(value: mode)],- ofItemAtPath: source.appendingPathComponent(name).path)+ ofItemAtPath: source.appendingPathComponent(name).path,+ )}// A setuid bit that the filesystem refused would make every// assertion below vacuously true.try #require(- self.mode(of: source.appendingPathComponent(setuidFile)) == 0o4755,- "the test filesystem would not keep a setuid bit")+ mode(of: source.appendingPathComponent(setuidFile)) == 0o4755,+ "the test filesystem would not keep a setuid bit",+ )// Uncompressed, so /usr/bin/tar can read it without a filter// helper on PATH.@@ -82,7 +85,9 @@ struct ExtractPermissionsTests {}func cleanUp() {- for url in [source, archive] { try? FileManager.default.removeItem(at: url) }+ for url in [source, archive] {+ try? FileManager.default.removeItem(at: url)+ }}}@@ -95,7 +100,7 @@ struct ExtractPermissionsTests {/// umask; with it, the archive's mode is written exactly. Anything that/// sets it on the host preset — including "tidying up" the conditional —/// fails here.- @Test func hostPresetNeverRestoresSetuid() {+ @Test func `host preset never restores setuid`() {let host = VPhoneArchiveExtractOptions.intoHostDirectory#expect(!host.exactPermissions)#expect(host.extractFlags & Int32(ARCHIVE_EXTRACT_PERM) == 0)@@ -109,7 +114,7 @@ struct ExtractPermissionsTests {/// The default is the safe one, so an option set built by hand — or a/// preset someone copies — does not acquire `-p` by omission.- @Test func exactPermissionsIsOptIn() {+ @Test func `exact permissions is opt in`() {#expect(!VPhoneArchiveExtractOptions(ownership: .currentUser).exactPermissions)#expect(!VPhoneArchiveExtractOptions(ownership: .preserveNumeric).exactPermissions)}@@ -122,7 +127,7 @@ struct ExtractPermissionsTests {/// Comparing against `tar` rather than against literals keeps this true/// whatever umask the test runs under — and `tar -xf` is precisely what/// `vm import` used to run, so agreement with it *is* the contract.- @Test func hostExtractionMatchesPlainSystemTar() throws {+ @Test func `host extraction matches plain system tar`() throws {let fixture = try Fixture.make()defer { fixture.cleanUp() }let fm = FileManager.default@@ -131,13 +136,17 @@ struct ExtractPermissionsTests {let theirs = Fixture.scratch("perm-tar")try fm.createDirectory(at: ours, withIntermediateDirectories: true)try fm.createDirectory(at: theirs, withIntermediateDirectories: true)- defer { for url in [ours, theirs] { try? fm.removeItem(at: url) } }+ defer { for url in [ours, theirs] {+ try? fm.removeItem(at: url)+ } }try VPhoneArchiveExtractor.extract(- fixture.archive, into: ours, options: .intoHostDirectory)+ fixture.archive, into: ours, options: .intoHostDirectory,+ )let untarred = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/bin/tar"),- ["-xf", fixture.archive.path, "-C", theirs.path])+ ["-xf", fixture.archive.path, "-C", theirs.path],+ )try #require(untarred.succeeded, "system tar could not unpack the fixture: \(untarred.stderr)")for name in Fixture.archivedModes.keys.sorted() {@@ -152,7 +161,7 @@ struct ExtractPermissionsTests {/// archive may be setuid, setgid or sticky. Run as root — `vm import`/// under sudo — restoring the archive's mode would give a setuid-root/// binary out of an untrusted file.- @Test func hostExtractionStripsSetuidSetgidAndSticky() throws {+ @Test func `host extraction strips setuid setgid and sticky`() throws {let fixture = try Fixture.make()defer { fixture.cleanUp() }let fm = FileManager.default@@ -161,7 +170,8 @@ struct ExtractPermissionsTests {defer { try? fm.removeItem(at: destination) }try VPhoneArchiveExtractor.extract(- fixture.archive, into: destination, options: .intoHostDirectory)+ fixture.archive, into: destination, options: .intoHostDirectory,+ )for name in Fixture.archivedModes.keys.sorted() {let mode = try #require(Fixture.mode(of: destination.appendingPathComponent(name)))@@ -175,7 +185,7 @@ struct ExtractPermissionsTests {/// being root: with `-p` the setuid bit survives. (Ownership cannot —/// `ARCHIVE_EXTRACT_OWNER` needs root — but the mode does, because the/// file already belongs to whoever is running.)- @Test func guestPresetKeepsExactModes() throws {+ @Test func `guest preset keeps exact modes`() throws {let fixture = try Fixture.make()defer { fixture.cleanUp() }let fm = FileManager.default@@ -193,7 +203,8 @@ struct ExtractPermissionsTests {for (name, archived) in Fixture.archivedModes.sorted(by: { $0.key < $1.key }) {#expect(Fixture.mode(of: destination.appendingPathComponent(name)) == archived,- "\(name) did not come back with the mode the archive stores")+ "\(name) did not come back with the mode the archive stores",+ )}}}diff --git a/tests/VPhoneArchiveTests/IPSWCacheTests.swift b/tests/VPhoneArchiveTests/IPSWCacheTests.swiftindex fae176f5..f800d21e 100644--- a/tests/VPhoneArchiveTests/IPSWCacheTests.swift+++ b/tests/VPhoneArchiveTests/IPSWCacheTests.swift@@ -6,13 +6,18 @@ private final class IPSWStubProtocol: URLProtocol {nonisolated(unsafe) static var payload = Data()nonisolated(unsafe) static var status = 200- override class func canInit(with request: URLRequest) -> Bool { true }- override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }+ override class func canInit(with _: URLRequest) -> Bool {+ true+ }++ override class func canonicalRequest(for request: URLRequest) -> URLRequest {+ request+ }override func startLoading() {let response = HTTPURLResponse(url: request.url!, statusCode: Self.status, httpVersion: "HTTP/1.1",- headerFields: ["Content-Length": String(Self.payload.count)]+ headerFields: ["Content-Length": String(Self.payload.count)],)!client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)client?.urlProtocol(self, didLoad: Self.payload)@@ -31,7 +36,7 @@ struct IPSWCacheTests {"ProductVersion": "26.6.2", "ProductBuildVersion": "23G90",]let data = try PropertyListSerialization.data(- fromPropertyList: manifest, format: .xml, options: 0+ fromPropertyList: manifest, format: .xml, options: 0,)try data.write(to: files.appendingPathComponent("BuildManifest.plist"))let archive = root.appendingPathComponent("input.ipsw")@@ -39,13 +44,13 @@ struct IPSWCacheTests {return archive}- @Test func localSourceReadsManifestWithoutCopying() async throws {+ @Test func `local source reads manifest without copying`() async throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: root) }let source = try fixture(in: root)let result = try await VPhoneIPSWCache.resolve(- source.path, in: root.appendingPathComponent("cache")+ source.path, in: root.appendingPathComponent("cache"),)#expect(result.file == source)#expect(result.version == "26.6.2")@@ -53,7 +58,7 @@ struct IPSWCacheTests {#expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("cache").path))}- @Test func downloadReplacesInvalidCacheOnlyAfterValidation() async throws {+ @Test func `download replaces invalid cache only after validation`() async throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: root) }@@ -65,14 +70,14 @@ struct IPSWCacheTests {let session = URLSession(configuration: configuration)defer { session.invalidateAndCancel() }- let url = URL(string: "https://example.invalid/input.ipsw")!+ let url = try #require(URL(string: "https://example.invalid/input.ipsw"))let cacheDir = root.appendingPathComponent("cache")try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true)let cached = cacheDir.appendingPathComponent(VPhoneIPSWCache.cacheName(for: url))try Data("damaged".utf8).write(to: cached)let result = try await VPhoneIPSWCache.resolve(- url.absoluteString, in: cacheDir, session: session+ url.absoluteString, in: cacheDir, session: session,)#expect(result.file == cached)#expect(result.build == "23G90")@@ -80,12 +85,12 @@ struct IPSWCacheTests {IPSWStubProtocol.status = 503let reused = try await VPhoneIPSWCache.resolve(- url.absoluteString, in: cacheDir, session: session+ url.absoluteString, in: cacheDir, session: session,)#expect(reused.file == cached)}- @Test func failedDownloadLeavesNoReusableCache() async throws {+ @Test func `failed download leaves no reusable cache`() async throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: root) }@@ -96,13 +101,13 @@ struct IPSWCacheTests {let session = URLSession(configuration: configuration)defer { session.invalidateAndCancel() }- let url = URL(string: "https://example.invalid/input.ipsw")!+ let url = try #require(URL(string: "https://example.invalid/input.ipsw"))let cacheDir = root.appendingPathComponent("cache")await #expect(throws: VPhoneIPSWCache.Error.self) {try await VPhoneIPSWCache.resolve(url.absoluteString, in: cacheDir, session: session)}#expect(!FileManager.default.fileExists(- atPath: cacheDir.appendingPathComponent(VPhoneIPSWCache.cacheName(for: url)).path+ atPath: cacheDir.appendingPathComponent(VPhoneIPSWCache.cacheName(for: url)).path,))}}diff --git a/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift b/tests/VPhoneArchiveTests/NoOverwriteDirTests.swiftindex 1dfe7864..19367b19 100644--- a/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift+++ b/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift@@ -29,7 +29,7 @@ struct NoOverwriteDirTests {try Data("from archive\n".utf8).write(to: dir.appendingPathComponent("inside.txt"))try Data("beside\n".utf8).write(to: staging.appendingPathComponent("beside.txt"))try FileManager.default.setAttributes(- [.posixPermissions: NSNumber(value: directoryMode)], ofItemAtPath: dir.path+ [.posixPermissions: NSNumber(value: directoryMode)], ofItemAtPath: dir.path,)let archive = FileManager.default.temporaryDirectory@@ -74,8 +74,8 @@ struct NoOverwriteDirTests {// MARK: - The behaviour that matters- @Test("an existing directory keeps its own permissions")- func existingDirectoryKeepsItsMode() throws {+ @Test+ func `an existing directory keeps its own permissions`() throws {let archive = try Self.makeFixture(directoryMode: 0o777)let destination = try Self.makeDestination()defer {@@ -88,17 +88,18 @@ struct NoOverwriteDirTests {let existing = destination.appendingPathComponent("dir")try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: true)try FileManager.default.setAttributes(- [.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: existing.path+ [.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: existing.path,)try VPhoneArchiveExtractor.extract(- archive, into: destination, options: Self.installOptions(noOverwriteDir: true))+ archive, into: destination, options: Self.installOptions(noOverwriteDir: true),+ )#expect(try Self.mode(of: existing) == 0o700)}- @Test("without the flag, the archive's permissions win — the behaviour we must not have")- func defaultOverwritesTheMode() throws {+ @Test+ func `without the flag, the archive's permissions win — the behaviour we must not have`() throws {let archive = try Self.makeFixture(directoryMode: 0o777)let destination = try Self.makeDestination()defer {@@ -109,11 +110,12 @@ struct NoOverwriteDirTests {let existing = destination.appendingPathComponent("dir")try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: true)try FileManager.default.setAttributes(- [.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: existing.path+ [.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: existing.path,)try VPhoneArchiveExtractor.extract(- archive, into: destination, options: Self.installOptions(noOverwriteDir: false))+ archive, into: destination, options: Self.installOptions(noOverwriteDir: false),+ )// `man 3 archive_write_disk`: "existing directories will have their// permissions updated". Confirmed — 0700 in, 0777 out. This is@@ -126,8 +128,8 @@ struct NoOverwriteDirTests {#expect(try Self.mode(of: existing) == 0o777)}- @Test("skipping a directory header still writes the files under it")- func filesUnderASkippedDirectoryAreStillWritten() throws {+ @Test+ func `skipping a directory header still writes the files under it`() throws {let archive = try Self.makeFixture()let destination = try Self.makeDestination()defer {@@ -139,7 +141,8 @@ struct NoOverwriteDirTests {try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: true)try VPhoneArchiveExtractor.extract(- archive, into: destination, options: Self.installOptions(noOverwriteDir: true))+ archive, into: destination, options: Self.installOptions(noOverwriteDir: true),+ )// This is the difference from ARCHIVE_EXTRACT_NO_OVERWRITE, which// would have skipped the whole subtree.@@ -148,8 +151,8 @@ struct NoOverwriteDirTests {#expect(try String(contentsOf: inside, encoding: .utf8) == "from archive\n")}- @Test("an existing regular file is still replaced")- func existingFilesAreStillOverwritten() throws {+ @Test+ func `an existing regular file is still replaced`() throws {let archive = try Self.makeFixture()let destination = try Self.makeDestination()defer {@@ -161,15 +164,16 @@ struct NoOverwriteDirTests {try Data("stale\n".utf8).write(to: beside)try VPhoneArchiveExtractor.extract(- archive, into: destination, options: Self.installOptions(noOverwriteDir: true))+ archive, into: destination, options: Self.installOptions(noOverwriteDir: true),+ )// The other half of why ARCHIVE_EXTRACT_NO_OVERWRITE is not a// substitute: it would have left "stale" in place.#expect(try String(contentsOf: beside, encoding: .utf8) == "beside\n")}- @Test("a directory that does not exist yet is created normally")- func newDirectoriesAreUnaffected() throws {+ @Test+ func `a directory that does not exist yet is created normally`() throws {let archive = try Self.makeFixture(directoryMode: 0o755)let destination = try Self.makeDestination()defer {@@ -178,15 +182,16 @@ struct NoOverwriteDirTests {}try VPhoneArchiveExtractor.extract(- archive, into: destination, options: Self.installOptions(noOverwriteDir: true))+ archive, into: destination, options: Self.installOptions(noOverwriteDir: true),+ )let dir = destination.appendingPathComponent("dir")#expect(FileManager.default.fileExists(atPath: dir.path))#expect(try Self.mode(of: dir) == 0o755)}- @Test("a symlink standing where a directory would go is replaced, not followed")- func symlinkIsNotFollowed() throws {+ @Test+ func `a symlink standing where a directory would go is replaced, not followed`() throws {let archive = try Self.makeFixture()let destination = try Self.makeDestination()defer {@@ -199,11 +204,12 @@ struct NoOverwriteDirTests {let elsewhere = destination.appendingPathComponent("elsewhere")try FileManager.default.createDirectory(at: elsewhere, withIntermediateDirectories: true)try FileManager.default.createSymbolicLink(- at: destination.appendingPathComponent("dir"), withDestinationURL: elsewhere+ at: destination.appendingPathComponent("dir"), withDestinationURL: elsewhere,)try VPhoneArchiveExtractor.extract(- archive, into: destination, options: Self.installOptions(noOverwriteDir: true))+ archive, into: destination, options: Self.installOptions(noOverwriteDir: true),+ )// Two things have to hold, and both do.//@@ -217,10 +223,10 @@ struct NoOverwriteDirTests {#expect(lstat(destination.appendingPathComponent("dir").path, &info) == 0)#expect((info.st_mode & S_IFMT) == S_IFDIR)#expect(!FileManager.default.fileExists(- atPath: elsewhere.appendingPathComponent("inside.txt").path+ atPath: elsewhere.appendingPathComponent("inside.txt").path,))#expect(FileManager.default.fileExists(- atPath: destination.appendingPathComponent("dir/inside.txt").path+ atPath: destination.appendingPathComponent("dir/inside.txt").path,))}}diff --git a/tests/VPhoneArchiveTests/RoundTripTests.swift b/tests/VPhoneArchiveTests/RoundTripTests.swiftindex 6d493a23..194d92e6 100644--- a/tests/VPhoneArchiveTests/RoundTripTests.swift+++ b/tests/VPhoneArchiveTests/RoundTripTests.swift@@ -16,7 +16,7 @@ struct RoundTripTests {try Data(repeating: 0x5A, count: 300_000).write(to: nested.appendingPathComponent("big.bin"))try FileManager.default.createSymbolicLink(atPath: root.appendingPathComponent("link").path,- withDestinationPath: "top.txt"+ withDestinationPath: "top.txt",)try Data("skip me\n".utf8).write(to: root.appendingPathComponent("excluded.log"))return root@@ -28,15 +28,14 @@ struct RoundTripTests {}@Test(- "tar round trip preserves contents, nesting and symlinks",arguments: [VPhoneArchiveCompression.none,.zstd(level: 3),.xz(level: 1),.gzip(level: 1),- ]+ ],)- func roundTrip(compression: VPhoneArchiveCompression) throws {+ func `tar round trip preserves contents, nesting and symlinks`(compression: VPhoneArchiveCompression) throws {let source = try Self.makeTree()let archive = Self.scratch("arc").appendingPathExtension(compression.tarExtension)let destination = Self.scratch("out")@@ -49,14 +48,14 @@ struct RoundTripTests {try VPhoneArchiveWriter.create(archive: archive, from: source, compression: compression)try VPhoneArchiveExtractor.extract(- archive, into: destination, options: .intoHostDirectory+ archive, into: destination, options: .intoHostDirectory,)#expect(try String(- contentsOf: destination.appendingPathComponent("top.txt"), encoding: .utf8+ contentsOf: destination.appendingPathComponent("top.txt"), encoding: .utf8,) == "hello\n")#expect(try Data(- contentsOf: destination.appendingPathComponent("a/b/big.bin")+ contentsOf: destination.appendingPathComponent("a/b/big.bin"),).count == 300_000)// The symlink has to come back as a symlink, not as a copy of its@@ -69,13 +68,15 @@ struct RoundTripTests {#expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == "top.txt")}- @Test("the compressor actually ran")- func compressionIsApplied() throws {+ @Test+ func `the compressor actually ran`() throws {let source = try Self.makeTree()let plain = Self.scratch("plain").appendingPathExtension("tar")let compressed = Self.scratch("zstd").appendingPathExtension("tzst")defer {- for url in [source, plain, compressed] { try? FileManager.default.removeItem(at: url) }+ for url in [source, plain, compressed] {+ try? FileManager.default.removeItem(at: url)+ }}try VPhoneArchiveWriter.create(archive: plain, from: source)@@ -90,12 +91,14 @@ struct RoundTripTests {#expect(described.filter == "zstd")}- @Test("member paths are relative, even when the source is reached through a symlink")- func memberPathsAreRelative() throws {+ @Test+ func `member paths are relative, even when the source is reached through a symlink`() throws {let source = try Self.makeTree()let archive = Self.scratch("rel").appendingPathExtension("tar")defer {- for url in [source, archive] { try? FileManager.default.removeItem(at: url) }+ for url in [source, archive] {+ try? FileManager.default.removeItem(at: url)+ }}try VPhoneArchiveWriter.create(archive: archive, from: source)@@ -125,8 +128,8 @@ struct RoundTripTests {}}- @Test("hardlinks survive as hardlinks")- func hardlinksArePreserved() throws {+ @Test+ func `hardlinks survive as hardlinks`() throws {let source = try Self.makeTree()let archive = Self.scratch("hl").appendingPathExtension("tar")let destination = Self.scratch("hlout")@@ -139,7 +142,7 @@ struct RoundTripTests {try FileManager.default.linkItem(at: source.appendingPathComponent("top.txt"),- to: source.appendingPathComponent("same.txt")+ to: source.appendingPathComponent("same.txt"),)try VPhoneArchiveWriter.create(archive: archive, from: source)@@ -158,8 +161,8 @@ struct RoundTripTests {#expect(first.st_nlink == 2)}- @Test("a tree fingerprint notices what diff -r would miss")- func fingerprintDetectsMetadataDifferences() throws {+ @Test+ func `a tree fingerprint notices what diff -r would miss`() throws {let a = Self.scratch("fpa")let b = Self.scratch("fpb")// The same mtime on both, because two files written a moment apart@@ -170,14 +173,16 @@ struct RoundTripTests {try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)try Data("same\n".utf8).write(to: url.appendingPathComponent("f.txt"))try FileManager.default.setAttributes(- [.modificationDate: when], ofItemAtPath: url.appendingPathComponent("f.txt").path+ [.modificationDate: when], ofItemAtPath: url.appendingPathComponent("f.txt").path,)try FileManager.default.setAttributes(- [.modificationDate: when], ofItemAtPath: url.path+ [.modificationDate: when], ofItemAtPath: url.path,)}defer {- for url in [a, b] { try? FileManager.default.removeItem(at: url) }+ for url in [a, b] {+ try? FileManager.default.removeItem(at: url)+ }}#expect(try VPhoneTreeFingerprint.capture(a)@@ -186,7 +191,7 @@ struct RoundTripTests {// Identical contents, different mode — `diff -r` says nothing.try FileManager.default.setAttributes([.posixPermissions: NSNumber(value: 0o600)],- ofItemAtPath: b.appendingPathComponent("f.txt").path+ ofItemAtPath: b.appendingPathComponent("f.txt").path,)let differences = try VPhoneTreeFingerprint.capture(a).differences(from: VPhoneTreeFingerprint.capture(b))@@ -194,12 +199,14 @@ struct RoundTripTests {#expect(differences[0].contains("mode"))}- @Test("exclusions are applied")- func exclusions() throws {+ @Test+ func `exclusions are applied`() throws {let source = try Self.makeTree()let archive = Self.scratch("exc").appendingPathExtension("tar")defer {- for url in [source, archive] { try? FileManager.default.removeItem(at: url) }+ for url in [source, archive] {+ try? FileManager.default.removeItem(at: url)+ }}try VPhoneArchiveWriter.create(archive: archive, from: source, excluding: ["*.log"])@@ -208,8 +215,8 @@ struct RoundTripTests {#expect(paths.contains("top.txt"))}- @Test("packing does not modify the tree it reads")- func packingLeavesTheSourceAlone() throws {+ @Test+ func `packing does not modify the tree it reads`() throws {// libarchive's read_disk defaults to ARCHIVE_READDISK_MAC_COPYFILE,// which packs each file's AppleDouble form through a temp file made// from a *relative* mkstemp template — and the tree walker chdir's@@ -221,7 +228,9 @@ struct RoundTripTests {let source = try Self.makeTree()let archive = Self.scratch("untouched").appendingPathExtension("tar")defer {- for url in [source, archive] { try? FileManager.default.removeItem(at: url) }+ for url in [source, archive] {+ try? FileManager.default.removeItem(at: url)+ }}let when = Date(timeIntervalSince1970: 1_700_000_000)@@ -239,12 +248,14 @@ struct RoundTripTests {}}- @Test("a single member can be read without unpacking")- func readMember() throws {+ @Test+ func `a single member can be read without unpacking`() throws {let source = try Self.makeTree()let archive = Self.scratch("member").appendingPathExtension("tar")defer {- for url in [source, archive] { try? FileManager.default.removeItem(at: url) }+ for url in [source, archive] {+ try? FileManager.default.removeItem(at: url)+ }}try VPhoneArchiveWriter.create(archive: archive, from: source)@@ -256,8 +267,8 @@ struct RoundTripTests {}}- @Test("decompress unwraps a single stream without unpacking it")- func decompress() throws {+ @Test+ func `decompress unwraps a single stream without unpacking it`() throws {// What `zstd -d -f bootstrap.tar.zst -o bootstrap.tar` does: the input// is one compressed file and the output is the tar, still packed.let source = try Self.makeTree()@@ -280,7 +291,7 @@ struct RoundTripTests {defer { try? FileManager.default.removeItem(at: staging) }try FileManager.default.copyItem(at: tar, to: staging.appendingPathComponent("inner.tar"))try VPhoneArchiveWriter.create(- archive: compressed, from: staging, compression: .zstd(level: 3)+ archive: compressed, from: staging, compression: .zstd(level: 3),)// What decompress gives back is the tar.zst's single stream, which@@ -292,11 +303,11 @@ struct RoundTripTests {// And it is still an archive, not a decompressed blob: the inner tar// comes out byte-identical to the one that went in.#expect(try VPhoneArchiveReader.readMember("inner.tar", from: restored)- == Data(contentsOf: tar))+ == Data(contentsOf: tar))}- @Test("a member that escapes the destination is refused")- func pathEscapeIsRefused() throws {+ @Test+ func `a member that escapes the destination is refused`() throws {// Hand-built, because the writer will not produce one.let staging = Self.scratch("evil")try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)@@ -315,11 +326,11 @@ struct RoundTripTests {#expect(throws: VPhoneArchiveError.self) {try VPhoneArchiveExtractor.extract(- archive, into: destination, options: .intoHostDirectory+ archive, into: destination, options: .intoHostDirectory,)}#expect(!FileManager.default.fileExists(- atPath: destination.deletingLastPathComponent().appendingPathComponent("escaped").path+ atPath: destination.deletingLastPathComponent().appendingPathComponent("escaped").path,))}@@ -328,13 +339,21 @@ struct RoundTripTests {/// to be recomputed or libarchive rejects the entry before we see it.private func rewriteFirstMemberName(of archive: URL, to name: String) throws {var bytes = try [UInt8](Data(contentsOf: archive))- for i in 0..<100 { bytes[i] = 0 }- for (i, byte) in Array(name.utf8).enumerated() { bytes[i] = byte }+ for i in 0 ..< 100 {+ bytes[i] = 0+ }+ for (i, byte) in Array(name.utf8).enumerated() {+ bytes[i] = byte+ }- for i in 148..<156 { bytes[i] = UInt8(ascii: " ") } // checksum field reads as spaces- let sum = (0..<512).reduce(0) { $0 + Int(bytes[$1]) }+ for i in 148 ..< 156 {+ bytes[i] = UInt8(ascii: " ")+ } // checksum field reads as spaces+ let sum = (0 ..< 512).reduce(0) { $0 + Int(bytes[$1]) }let octal = String(format: "%06o", sum)- for (i, byte) in Array(octal.utf8).enumerated() { bytes[148 + i] = byte }+ for (i, byte) in Array(octal.utf8).enumerated() {+ bytes[148 + i] = byte+ }bytes[154] = 0bytes[155] = UInt8(ascii: " ")diff --git a/tests/VPhoneCoreTests/APFSSnapshotTests.swift b/tests/VPhoneCoreTests/APFSSnapshotTests.swiftindex df146f8b..f4f14022 100644--- a/tests/VPhoneCoreTests/APFSSnapshotTests.swift+++ b/tests/VPhoneCoreTests/APFSSnapshotTests.swift@@ -19,12 +19,18 @@ struct APFSSnapshotTests {/// A 4 KiB block carrying `payload` at `offset`, with a correct checksum.static func makeValidBlock(payload: [UInt8], at offset: Int, filler: UInt8 = 0x41) -> [UInt8] {var block = [UInt8](repeating: filler, count: VPhoneAPFSSnapshot.blockSize)- for k in 0..<8 { block[k] = 0 }- for (k, byte) in payload.enumerated() { block[offset + k] = byte }+ for k in 0 ..< 8 {+ block[k] = 0+ }+ for (k, byte) in payload.enumerated() {+ block[offset + k] = byte+ }let sum = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }withUnsafeBytes(of: sum.littleEndian) { bytes in- for (k, byte) in bytes.enumerated() { block[k] = byte }+ for (k, byte) in bytes.enumerated() {+ block[k] = byte+ }}return block}@@ -33,7 +39,7 @@ struct APFSSnapshotTests {VPhoneAPFSSnapshot.oldPrefix + Array(hash.utf8)}- static let validHash = String(repeating: "ab12cd34", count: 8) // 64 hex chars+ static let validHash = String(repeating: "ab12cd34", count: 8) // 64 hex charsstatic func write(_ bytes: [UInt8]) throws -> URL {let url = FileManager.default.temporaryDirectory@@ -44,29 +50,31 @@ struct APFSSnapshotTests {// MARK: - Checksum- @Test("fletcher64 round-trips: a block we stamp verifies")- func checksumVerifies() {+ @Test+ func `fletcher64 round-trips: a block we stamp verifies`() {let block = Self.makeValidBlock(payload: Self.snapshotName(hash: Self.validHash), at: 100)let stored = block.withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) }let computed = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }#expect(stored == computed)}- @Test("fletcher64 uses modulus 0xFFFFFFFF, not 2^32")- func checksumModulus() {+ @Test+ func `fletcher64 uses modulus 0xFFFFFFFF, not 2^32`() {// A block of all-0xFF words is the case where the two moduli diverge:// with 2^32 the sums wrap to 0, with 0xFFFFFFFF they do not. Getting// this "right" in the arithmetic sense would make every checksum wrong.var block = [UInt8](repeating: 0xFF, count: VPhoneAPFSSnapshot.blockSize)- for k in 0..<8 { block[k] = 0 }+ for k in 0 ..< 8 {+ block[k] = 0+ }let sum = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }#expect(sum != 0)}// MARK: - Scan- @Test("finds a snapshot record in a valid block")- func findsRecord() throws {+ @Test+ func `finds a snapshot record in a valid block`() {let block = Self.makeValidBlock(payload: Self.snapshotName(hash: Self.validHash), at: 100)let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }@@ -77,38 +85,46 @@ struct APFSSnapshotTests {#expect(report.snapshotName == "com.apple.os.update-" + Self.validHash)}- @Test("ignores a hit in a block that does not checksum")- func ignoresNonMetadataBlock() throws {+ @Test+ func `ignores a hit in a block that does not checksum`() {// This is the case that matters: the same string is baked into binaries// sitting on the volume. Those are file data, so the block they live in// is not an APFS object and must never be rewritten.var block = Self.makeValidBlock(payload: Self.snapshotName(hash: Self.validHash), at: 100)- block[9] ^= 0xFF // corrupt a byte the checksum covers+ block[9] ^= 0xFF // corrupt a byte the checksum coverslet report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }#expect(report.isEmpty)}- @Test("ignores a prefix not followed by 64 hex characters")- func ignoresNonHexSuffix() throws {- let notAHash = String(repeating: "zz", count: 32) // 64 chars, not hex+ @Test+ func `ignores a prefix not followed by 64 hex characters`() {+ let notAHash = String(repeating: "zz", count: 32) // 64 chars, not hexlet block = Self.makeValidBlock(payload: Self.snapshotName(hash: notAHash), at: 100)let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }#expect(report.isEmpty)}- @Test("finds both records when they share one block")- func findsTwoRecordsInOneBlock() throws {+ @Test+ func `finds both records when they share one block`() {// The real layout: snap_metadata value and snap_name key, normally in// the same leaf node.var block = [UInt8](repeating: 0x41, count: VPhoneAPFSSnapshot.blockSize)- for k in 0..<8 { block[k] = 0 }+ for k in 0 ..< 8 {+ block[k] = 0+ }let name = Self.snapshotName(hash: Self.validHash)- for (k, byte) in name.enumerated() { block[200 + k] = byte }- for (k, byte) in name.enumerated() { block[1200 + k] = byte }+ for (k, byte) in name.enumerated() {+ block[200 + k] = byte+ }+ for (k, byte) in name.enumerated() {+ block[1200 + k] = byte+ }let sum = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }withUnsafeBytes(of: sum.littleEndian) { bytes in- for (k, byte) in bytes.enumerated() { block[k] = byte }+ for (k, byte) in bytes.enumerated() {+ block[k] = byte+ }}let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }@@ -117,8 +133,8 @@ struct APFSSnapshotTests {#expect(report.blocks[0].offsetsInBlock == [200, 1200])}- @Test("reports blocks in ascending order")- func blocksAreOrdered() throws {+ @Test+ func `reports blocks in ascending order`() {let name = Self.snapshotName(hash: Self.validHash)let first = Self.makeValidBlock(payload: name, at: 100)let second = Self.makeValidBlock(payload: name, at: 300, filler: 0x42)@@ -129,8 +145,8 @@ struct APFSSnapshotTests {// MARK: - Rename- @Test("renames every record and leaves the block verifying")- func renameKeepsBlockValid() throws {+ @Test+ func `renames every record and leaves the block verifying`() throws {let name = Self.snapshotName(hash: Self.validHash)let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))defer { try? FileManager.default.removeItem(at: url) }@@ -138,7 +154,7 @@ struct APFSSnapshotTests {try VPhoneAPFSSnapshot.rename(imageAt: url, log: { _ in })let after = try [UInt8](Data(contentsOf: url))- let renamed = String(decoding: after[100..<120], as: UTF8.self)+ let renamed = String(decoding: after[100 ..< 120], as: UTF8.self)#expect(renamed == VPhoneAPFSSnapshot.defaultNewPrefix)// The point of fixing the checksum: the block still reads as an APFS@@ -148,8 +164,8 @@ struct APFSSnapshotTests {#expect(stored == computed)}- @Test("renames snapshot records on both sides of a 64 MiB scan window")- func renameAcrossWindows() throws {+ @Test+ func `renames snapshot records on both sides of a 64 MiB scan window`() throws {let name = Self.snapshotName(hash: Self.validHash)let first = Self.makeValidBlock(payload: name, at: 100)let second = Self.makeValidBlock(payload: name, at: 200)@@ -168,15 +184,15 @@ struct APFSSnapshotTests {try check.seek(toOffset: 64 * 1024 * 1024)let secondAfter = try #require(try check.read(upToCount: VPhoneAPFSSnapshot.blockSize))for (block, offset) in [(firstAfter, 100), (secondAfter, 200)] {- #expect(String(decoding: block[offset..<offset + 20], as: UTF8.self)+ #expect(String(decoding: block[offset ..< offset + 20], as: UTF8.self)== VPhoneAPFSSnapshot.defaultNewPrefix)#expect(block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }== block.withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) })}}- @Test("rename is idempotent: a second pass finds nothing")- func renameIsIdempotent() throws {+ @Test+ func `rename is idempotent: a second pass finds nothing`() throws {let name = Self.snapshotName(hash: Self.validHash)let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))defer { try? FileManager.default.removeItem(at: url) }@@ -186,8 +202,8 @@ struct APFSSnapshotTests {#expect(second.isEmpty)}- @Test("dry run changes nothing")- func dryRunIsReadOnly() throws {+ @Test+ func `dry run changes nothing`() throws {let name = Self.snapshotName(hash: Self.validHash)let original = Self.makeValidBlock(payload: name, at: 100)let url = try Self.write(original)@@ -198,8 +214,8 @@ struct APFSSnapshotTests {#expect(try [UInt8](Data(contentsOf: url)) == original)}- @Test("a differently sized prefix is refused")- func rejectsWrongLengthPrefix() throws {+ @Test+ func `a differently sized prefix is refused`() throws {let name = Self.snapshotName(hash: Self.validHash)let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))defer { try? FileManager.default.removeItem(at: url) }@@ -211,8 +227,8 @@ struct APFSSnapshotTests {}}- @Test("log lines match the Python the port replaces")- func logLinesAreUnchanged() throws {+ @Test+ func `log lines match the Python the port replaces`() throws {let name = Self.snapshotName(hash: Self.validHash)let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))defer { try? FileManager.default.removeItem(at: url) }@@ -227,8 +243,8 @@ struct APFSSnapshotTests {])}- @Test("says so when there is nothing to rename")- func reportsNothingFound() throws {+ @Test+ func `says so when there is nothing to rename`() throws {let url = try Self.write([UInt8](repeating: 0x41, count: VPhoneAPFSSnapshot.blockSize))defer { try? FileManager.default.removeItem(at: url) }diff --git a/tests/VPhoneCoreTests/BundleOpsTests.swift b/tests/VPhoneCoreTests/BundleOpsTests.swiftindex 7280cbd6..199cac37 100644--- a/tests/VPhoneCoreTests/BundleOpsTests.swift+++ b/tests/VPhoneCoreTests/BundleOpsTests.swift@@ -1,6 +1,6 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCore/// Creating, editing, renaming and cloning a bundle. Export and import moved to/// `VPhoneArchiveTests/BundleTransferTests` with the implementation, which needs@@ -18,7 +18,7 @@ struct BundleOpsTests {return f}- @Test func createsBundleWithSparseDiskAndManifest() throws {+ @Test func `creates bundle with sparse disk and manifest`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -30,22 +30,22 @@ struct BundleOpsTests {memoryMB: 8192,diskSizeGB: 64,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,)let bundle = try VPhoneBundleOps.create(spec, in: VPhoneLibrary(root: root))#expect(bundle.manifest.cpuCount == 8)#expect(bundle.manifest.memorySize == 8192 * 1024 * 1024)let disk = bundle.url.appendingPathComponent("Disk.img")- let size = (try FileManager.default.attributesOfItem(atPath: disk.path)[.size] as? NSNumber)?.int64Value+ let size = try (FileManager.default.attributesOfItem(atPath: disk.path)[.size] as? NSNumber)?.int64Value#expect(size == Int64(64 * 1024 * 1024 * 1024))#expect(FileManager.default.fileExists(atPath: bundle.url.appendingPathComponent("SEPStorage").path))#expect(- FileManager.default.fileExists(atPath: bundle.url.appendingPathComponent("AVPBooter.vresearch1.bin").path)+ FileManager.default.fileExists(atPath: bundle.url.appendingPathComponent("AVPBooter.vresearch1.bin").path),)}- @Test func rejectsDuplicateName() throws {+ @Test func `rejects duplicate name`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -56,7 +56,7 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,)_ = try VPhoneBundleOps.create(spec, in: VPhoneLibrary(root: root))#expect(throws: VPhoneLibraryError.self) {@@ -64,7 +64,7 @@ struct BundleOpsTests {}}- @Test func rejectsInvalidNames() throws {+ @Test func `rejects invalid names`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -79,15 +79,15 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)}}}- @Test func rollsBackPartialBundleOnFailure() throws {+ @Test func `rolls back partial bundle on failure`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let lib = VPhoneLibrary(root: root)@@ -102,16 +102,16 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: missingRom,- sepromSource: missingRom+ sepromSource: missingRom,),- in: lib+ in: lib,)}// The half-built directory must be removed so the name is reusable.#expect(!FileManager.default.fileExists(atPath: lib.url(forName: "partial").path))}- @Test func updateConfigPersistsFields() throws {+ @Test func `update config persists fields`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -124,9 +124,9 @@ struct BundleOpsTests {memoryMB: 8192,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)let updated = try VPhoneBundleOps.updateConfig(bundleNamed: "cfg", in: lib, cpuCount: 4, memoryMB: nil)@@ -139,7 +139,7 @@ struct BundleOpsTests {#expect(updated.manifest.networkConfig.mode == .nat)}- @Test func updateConfigPersistsNetwork() throws {+ @Test func `update config persists network`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -152,9 +152,9 @@ struct BundleOpsTests {memoryMB: 8192,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)let updated = try VPhoneBundleOps.updateConfig(@@ -162,7 +162,7 @@ struct BundleOpsTests {in: lib,cpuCount: nil,memoryMB: nil,- networkMode: .off+ networkMode: .off,)#expect(updated.manifest.networkConfig.mode == .off)// Persisted across a fresh load, and cpu/memory untouched.@@ -171,7 +171,7 @@ struct BundleOpsTests {#expect(reloaded.cpuCount == 8)}- @Test func updateConfigRejectsBadNetwork() throws {+ @Test func `update config rejects bad network`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -184,9 +184,9 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)#expect(throws: VPhoneNetworkingError.hostOnlyUnsupported) {@@ -195,14 +195,14 @@ struct BundleOpsTests {in: lib,cpuCount: nil,memoryMB: nil,- networkMode: .hostOnly+ networkMode: .hostOnly,)}// A rejected edit must not have mutated the on-disk manifest.#expect(try lib.bundle(named: "bad").manifest.networkConfig.mode == .nat)}- @Test func renameThenDelete() throws {+ @Test func `rename then delete`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -215,9 +215,9 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)let renamed = try VPhoneBundleOps.rename(bundleNamed: "old", to: "shiny", in: lib)@@ -228,7 +228,7 @@ struct BundleOpsTests {#expect(try lib.bundles().isEmpty)}- @Test func renameRejectsExistingTarget() throws {+ @Test func `rename rejects existing target`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -242,9 +242,9 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)}#expect(throws: VPhoneLibraryError.alreadyExists(name: "b")) {@@ -252,7 +252,7 @@ struct BundleOpsTests {}}- @Test func cloneCopiesBundleAndResetsIdentity() throws {+ @Test func `clone copies bundle and resets identity`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -265,9 +265,9 @@ struct BundleOpsTests {memoryMB: 4096,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)// Simulate a booted/restored VM: identity artifacts present + non-empty machineIdentifier.let fm = FileManager.default@@ -292,7 +292,7 @@ struct BundleOpsTests {#expect(try lib.bundle(named: "src").manifest.machineIdentifier == Data([9, 9]))}- @Test func cloneRejectsExistingTarget() throws {+ @Test func `clone rejects existing target`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }let rom = try fakeROM(); let seprom = try fakeROM()@@ -306,9 +306,9 @@ struct BundleOpsTests {memoryMB: 2048,diskSizeGB: 1,romSource: rom,- sepromSource: seprom+ sepromSource: seprom,),- in: lib+ in: lib,)}#expect(throws: VPhoneLibraryError.alreadyExists(name: "b")) {diff --git a/tests/VPhoneCoreTests/BundleReportTests.swift b/tests/VPhoneCoreTests/BundleReportTests.swiftindex 4cbb84eb..01d92407 100644--- a/tests/VPhoneCoreTests/BundleReportTests.swift+++ b/tests/VPhoneCoreTests/BundleReportTests.swift@@ -1,13 +1,13 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct BundleReportTests {- @Test func mapsManifestFields() throws {+ @Test func `maps manifest fields`() {let manifest = VPhoneVirtualMachineManifest(cpuCount: 6,memorySize: 4 * 1024 * 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)let bundle = VPhoneBundle(url: URL(fileURLWithPath: "/tmp/myvm"), manifest: manifest)@@ -18,31 +18,31 @@ struct BundleReportTests {#expect(report.network.mode == .nat)}- @Test func carriesNetworkConfig() throws {+ @Test func `carries network config`() throws {let net = VPhoneVirtualMachineManifest.NetworkConfig(mode: .bridged,macAddress: "00:11:22:33:44:55",- bridgeInterface: "en0"+ bridgeInterface: "en0",)let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 2 * 1024 * 1024 * 1024,networkConfig: net,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)let report = VPhoneBundleReport(bundle: VPhoneBundle(url: URL(fileURLWithPath: "/tmp/b"), manifest: manifest))#expect(report.network.mode == .bridged)#expect(report.network.bridgeInterface == "en0")- let back = try JSONDecoder().decode(VPhoneBundleReport.self, from: try JSONEncoder().encode(report))+ let back = try JSONDecoder().decode(VPhoneBundleReport.self, from: JSONEncoder().encode(report))#expect(back.network == net)}- @Test func encodesToJSON() throws {+ @Test func `encodes to JSON`() throws {let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 2 * 1024 * 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)let report = VPhoneBundleReport(bundle: VPhoneBundle(url: URL(fileURLWithPath: "/tmp/x"), manifest: manifest))let data = try JSONEncoder().encode(report)diff --git a/tests/VPhoneCoreTests/CreateOrchestratorTests.swift b/tests/VPhoneCoreTests/CreateOrchestratorTests.swiftindex b8088e38..7b3204d7 100644--- a/tests/VPhoneCoreTests/CreateOrchestratorTests.swift+++ b/tests/VPhoneCoreTests/CreateOrchestratorTests.swift@@ -1,10 +1,10 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCore-// Tests for `VPhoneBootPatterns` — the pure, device-independent pieces of the-// native `vm create` pipeline (`VPhoneCreateOrchestrator`, executable target).-// The orchestrator's live stages (DFU/restore/CFW/boot check) require a VM.+/// Tests for `VPhoneBootPatterns` — the pure, device-independent pieces of the+/// native `vm create` pipeline (`VPhoneCreateOrchestrator`, executable target).+/// The orchestrator's live stages (DFU/restore/CFW/boot check) require a VM.struct CreateOrchestratorTests {// MARK: - first-boot panic markers@@ -13,41 +13,41 @@ struct CreateOrchestratorTests {return re.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)) != nil}- @Test func panicRegexMatchesKernelPanicLine() throws {+ @Test func `panic regex matches kernel panic line`() throws {#expect(try matches(VPhoneBootPatterns.panicRegex, "panic(cpu 0 caller 0xfffffff01234): test panic"))}- @Test func panicRegexMatchesStackshotSucceeded() throws {+ @Test func `panic regex matches stackshot succeeded`() throws {#expect(try matches(VPhoneBootPatterns.panicRegex, "stackshot succeeded"))}- @Test func panicRegexDoesNotMatchOrdinaryLogLine() throws {+ @Test func `panic regex does not match ordinary log line`() throws {#expect(try !matches(VPhoneBootPatterns.panicRegex, "vphoned: connected, awaiting handshake"))}// MARK: - normalizeECID (port of setup_machine.sh's normalize_ecid)- @Test func normalizeECIDStripsPrefixAndPads() {+ @Test func `normalize ECID strips prefix and pads`() {#expect(VPhoneBootPatterns.normalizeECID("0xabc") == "0000000000000ABC")}- @Test func normalizeECIDPassesThroughSixteenHexDigits() {+ @Test func `normalize ECID passes through sixteen hex digits`() {#expect(VPhoneBootPatterns.normalizeECID("0011223344556677") == "0011223344556677")}- @Test func normalizeECIDUppercasesLowerHex() {+ @Test func `normalize ECID uppercases lower hex`() {#expect(VPhoneBootPatterns.normalizeECID("0xdeadbeef") == "00000000DEADBEEF")}- @Test func normalizeECIDRejectsNonHex() {+ @Test func `normalize ECID rejects non hex`() {#expect(VPhoneBootPatterns.normalizeECID("zzzz") == nil)}- @Test func normalizeECIDRejectsOverlongInput() {- #expect(VPhoneBootPatterns.normalizeECID("00112233445566778") == nil) // 17 hex chars+ @Test func `normalize ECID rejects overlong input`() {+ #expect(VPhoneBootPatterns.normalizeECID("00112233445566778") == nil) // 17 hex chars}- @Test func normalizeECIDRejectsEmptyInput() {+ @Test func `normalize ECID rejects empty input`() {#expect(VPhoneBootPatterns.normalizeECID("") == nil)#expect(VPhoneBootPatterns.normalizeECID("0x") == nil)}@@ -55,5 +55,4 @@ struct CreateOrchestratorTests {// The three parseHVVmmPresent cases that were here tested a string parse of// `sysctl -n kern.hv_vmm_present`. The nested-host check reads the int// through `sysctlbyname` now, so the parse — and its tests — are gone.-}diff --git a/tests/VPhoneCoreTests/FirmwareCatalogReportTests.swift b/tests/VPhoneCoreTests/FirmwareCatalogReportTests.swiftindex 9a19cd68..0a4562c6 100644--- a/tests/VPhoneCoreTests/FirmwareCatalogReportTests.swift+++ b/tests/VPhoneCoreTests/FirmwareCatalogReportTests.swift@@ -1,9 +1,9 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct FirmwareCatalogReportTests {- @Test func mapsEveryPairing() throws {+ @Test func `maps every pairing`() {let report = VPhoneFirmwareCatalog.report#expect(report.device == VPhoneFirmwareCatalog.device)#expect(report.pairings.count == VPhoneFirmwareCatalog.pairings.count)@@ -16,9 +16,9 @@ struct FirmwareCatalogReportTests {}}- @Test func roundTripsJSON() throws {+ @Test func `round trips JSON`() throws {let report = VPhoneFirmwareCatalog.report- let back = try JSONDecoder().decode(VPhoneFirmwareCatalogReport.self, from: try JSONEncoder().encode(report))+ let back = try JSONDecoder().decode(VPhoneFirmwareCatalogReport.self, from: JSONEncoder().encode(report))#expect(back == report)}}diff --git a/tests/VPhoneCoreTests/FirmwareMatrixTests.swift b/tests/VPhoneCoreTests/FirmwareMatrixTests.swiftindex 8a234801..e66bbaf5 100644--- a/tests/VPhoneCoreTests/FirmwareMatrixTests.swift+++ b/tests/VPhoneCoreTests/FirmwareMatrixTests.swift@@ -29,9 +29,9 @@// numbers before text instead of crashing; `nonNumericComponentsStillOrder`// below pins that choice down.-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCore// MARK: - Frozen fixture@@ -164,39 +164,39 @@ private enum Golden {// MARK: - Byte-for-byte equivalence with the Pythonstruct FirmwareMatrixGoldenTests {- @Test func listingMatchesPythonPlain() {+ @Test func `listing matches python plain`() {let out = VPhoneFirmwareMatrix.listing(device: Fixture.d, readme: Fixture.readme,- downloadURLs: Fixture.urls, style: Fixture.plain+ downloadURLs: Fixture.urls, style: Fixture.plain,)#expect(out == .matrix(Golden.listPlain))}- @Test func listingMatchesPythonColored() {+ @Test func `listing matches python colored`() {let out = VPhoneFirmwareMatrix.listing(device: Fixture.d, readme: Fixture.readme,- downloadURLs: Fixture.urls, style: Fixture.colored+ downloadURLs: Fixture.urls, style: Fixture.colored,)#expect(out == .matrix(Golden.listColored))}- @Test func ambiguousVersionMatchesPython() {+ @Test func `ambiguous version matches python`() {for (style, golden) in [(Fixture.plain, Golden.ambiguousPlain),(Fixture.colored, Golden.ambiguousColored),] {let out = VPhoneFirmwareMatrix.selection(device: Fixture.d, version: "27.0", build: "",- readme: Fixture.readme, downloadURLs: Fixture.urls, style: style+ readme: Fixture.readme, downloadURLs: Fixture.urls, style: style,)#expect(out == .ambiguous(golden))}}- @Test func resolvedSelectorMatchesPython() {+ @Test func `resolved selector matches python`() {let out = VPhoneFirmwareMatrix.selection(device: Fixture.d, version: "26.3", build: "",- readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.colored+ readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.colored,)guard case let .selected(release, support) = out else {Issue.record("expected a selection, got \(out)")@@ -211,7 +211,7 @@ struct FirmwareMatrixGoldenTests {// Only a hit has a line; the failure cases have nothing to hand back.#expect(VPhoneFirmwareMatrix.selection(device: Fixture.d, version: "99.9", build: "",- readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.plain+ readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.plain,).resolvedLine == nil)}@@ -220,23 +220,23 @@ struct FirmwareMatrixGoldenTests {("", "99Z99", "Unsupported: no downloadable IPSW matched device=iPhone17,3 build=99Z99\n"),("99.9", "99Z99", "Unsupported: no downloadable IPSW matched device=iPhone17,3 version=99.9 build=99Z99\n"),])- func missMatchesPython(version: String, build: String, expected: String) {+ func `miss matches python`(version: String, build: String, expected: String) {let out = VPhoneFirmwareMatrix.selection(device: Fixture.d, version: version, build: build,- readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.plain+ readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.plain,)#expect(out == .unmatched(expected))let colored = VPhoneFirmwareMatrix.selection(device: Fixture.d, version: version, build: build,- readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.colored+ readme: Fixture.readme, downloadURLs: Fixture.urls, style: Fixture.colored,)#expect(colored == .unmatched("\u{1B}[31mUnsupported\u{1B}[0m" + expected.dropFirst("Unsupported".count)))}- @Test func emptyDownloadListIsAnError() {+ @Test func `empty download list is an error`() {let out = VPhoneFirmwareMatrix.listing(device: "iPhone99,9", readme: Fixture.readme,- downloadURLs: Fixture.urls, style: Fixture.colored+ downloadURLs: Fixture.urls, style: Fixture.colored,)// Plain even in colour, exactly as the Python printed it.#expect(out == .nothingDownloadable("No downloadable IPSWs found for iPhone99,9\n"))@@ -246,7 +246,7 @@ struct FirmwareMatrixGoldenTests {// MARK: - Parsingstruct FirmwareMatrixParsingTests {- @Test func readsOnlyTheTestedEnvironmentsSectionAndOnlyThisDevice() {+ @Test func `reads only the tested environments section and only this device`() {let tested = VPhoneFirmwareMatrix.testedBuilds(readme: Fixture.readme, device: Fixture.d)#expect(tested.count == 7)#expect(tested.contains(VPhoneFirmwareBuildID(version: "26.3.1", build: "23D8133")))@@ -258,11 +258,11 @@ struct FirmwareMatrixParsingTests {#expect(!tested.contains(VPhoneFirmwareBuildID(version: "26.1", build: "23B85")))}- @Test func aMissingReadmeMeansNothingIsTested() {+ @Test func `a missing readme means nothing is tested`() {#expect(VPhoneFirmwareMatrix.testedBuilds(readme: nil, device: Fixture.d).isEmpty)let out = VPhoneFirmwareMatrix.listing(device: Fixture.d, readme: nil,- downloadURLs: Fixture.urls, style: Fixture.plain+ downloadURLs: Fixture.urls, style: Fixture.plain,)guard case let .matrix(text) = out else {Issue.record("expected a matrix")@@ -272,7 +272,7 @@ struct FirmwareMatrixParsingTests {#expect(text.components(separatedBy: "Not Tested").count == 1 + 9 + 1)}- @Test func rejectsLookalikeURLs() {+ @Test func `rejects lookalike UR ls`() {let found = VPhoneFirmwareMatrix.releases(downloadURLs: Fixture.urls, device: Fixture.d)// 9 real lines, 1 exact duplicate dropped, 3 lookalikes rejected.#expect(found.count == 9)@@ -281,7 +281,7 @@ struct FirmwareMatrixParsingTests {#expect(!found.contains { $0.build == "23B85" })}- @Test func toleratesSurroundingWhitespaceAndBlankLines() {+ @Test func `tolerates surrounding whitespace and blank lines`() {let urls = "\n \(Fixture.url263) \n\n"let found = VPhoneFirmwareMatrix.releases(downloadURLs: urls, device: Fixture.d)#expect(found.count == 1)@@ -289,10 +289,10 @@ struct FirmwareMatrixParsingTests {#expect(found.first?.url == Fixture.url263)}- @Test func parsesTheRepositoryCompatibilityGuide() throws {- let tested = VPhoneFirmwareMatrix.testedBuilds(- readme: try RealData.repositoryCompatibilityGuide(),- device: Fixture.d+ @Test func `parses the repository compatibility guide`() throws {+ let tested = try VPhoneFirmwareMatrix.testedBuilds(+ readme: RealData.repositoryCompatibilityGuide(),+ device: Fixture.d,)#expect(tested.count == 2)#expect(tested.contains(VPhoneFirmwareBuildID(version: "26.6.2", build: "23G90")))@@ -363,7 +363,7 @@ private enum RealData {/// The same table, read by splitting on `|` and `_` instead of by regex.static func testedBuildsByColumnSplitting(in readme: String,- deviceSuffix: String+ deviceSuffix: String,) -> Set<VPhoneFirmwareBuildID> {// A different way to find the section too: cut the document at its `## `// headings rather than scanning line by line for them.@@ -387,7 +387,7 @@ private enum RealData {}struct FirmwareMatrixRealDataTests {- @Test func theCompatibilityParserAgreesWithAnIndependentColumnSplitter() throws {+ @Test func `the compatibility parser agrees with an independent column splitter`() throws {let readme = try RealData.repositoryCompatibilityGuide()let byRegex = VPhoneFirmwareMatrix.testedBuilds(readme: readme, device: Fixture.d)let bySplitting = RealData.testedBuildsByColumnSplitting(in: readme, deviceSuffix: "17,3")@@ -395,10 +395,10 @@ struct FirmwareMatrixRealDataTests {#expect(byRegex == bySplitting)}- @Test func aLiveDownloadCaptureParsesWholeAndJoinsAgainstTheGuide() throws {+ @Test func `a live download capture parses whole and joins against the guide`() throws {let releases = VPhoneFirmwareMatrix.releases(downloadURLs: RealData.liveURLs,- device: Fixture.d+ device: Fixture.d,)// Every line of the capture is a restore image for this device, so the// URL parser has to claim all 31 — a silent drop is the failure mode@@ -407,7 +407,7 @@ struct FirmwareMatrixRealDataTests {#expect(releases.count == 31)#expect(Set(releases.map(\.build)).count == 31)- let tested = VPhoneFirmwareMatrix.testedBuilds(readme: try RealData.repositoryCompatibilityGuide(), device: Fixture.d)+ let tested = try VPhoneFirmwareMatrix.testedBuilds(readme: RealData.repositoryCompatibilityGuide(), device: Fixture.d)var supported = 0, notTested = 0for release in releases {let id = VPhoneFirmwareBuildID(version: release.version, build: release.build)@@ -430,10 +430,10 @@ struct FirmwareMatrixRealDataTests {/// Apple serves one build per version, so `--list` over live data is fully/// ordered by version alone. This is the property the shell's `sorted(…,/// reverse=True)` was there to produce.- @Test func theLiveCaptureListsNewestFirst() {+ @Test func `the live capture lists newest first`() {let out = VPhoneFirmwareMatrix.listing(device: Fixture.d, readme: nil,- downloadURLs: RealData.liveURLs, style: Fixture.plain+ downloadURLs: RealData.liveURLs, style: Fixture.plain,)guard case let .matrix(text) = out else {Issue.record("expected a matrix")@@ -461,7 +461,7 @@ struct FirmwareMatrixOrderingTests {VPhoneFirmwareRelease(version: version, build: build, url: "/\(version)_\(build)")}- @Test func sortsVersionsNewestFirstWithNumericComponents() {+ @Test func `sorts versions newest first with numeric components`() {// Lexically "18.6.2" > "26.0" and "26.4.1" > "26.4"; numerically neither.let sorted = [release("26.4", "a"), release("18.6.2", "a"), release("26.4.1", "a"),@@ -470,7 +470,7 @@ struct FirmwareMatrixOrderingTests {#expect(sorted.map(\.version) == ["27.0", "26.10", "26.4.1", "26.4", "26.0", "18.6.2"])}- @Test func sortsBuildsByCodePointDescending() {+ @Test func `sorts builds by code point descending`() {// 24A435 vs 24A5430a is the case that separates a string sort from a// "looks numeric" one: '4' < '5' at index 3, so 24A5430a wins.let sorted = [@@ -479,12 +479,12 @@ struct FirmwareMatrixOrderingTests {#expect(sorted.map(\.build) == ["24A5430a", "24A5390f", "24A435"])}- @Test func aShorterVersionSortsBelowItsOwnPrefixExtension() {+ @Test func `a shorter version sorts below its own prefix extension`() {#expect(VPhoneFirmwareMatrix.isNewer(release("26.4.1", "a"), than: release("26.4", "a")))#expect(!VPhoneFirmwareMatrix.isNewer(release("26.4", "a"), than: release("26.4.1", "a")))}- @Test func nonNumericComponentsStillOrder() {+ @Test func `non numeric components still order`() {#expect(VPhoneFirmwareMatrix.versionKey("26.beta") == [.number(26), .text("beta")])#expect(VPhoneFirmwareMatrix.versionKey("") == [.text("")])#expect(VPhoneFirmwareMatrix.VersionPart.number(9) < .text("0"))@@ -494,14 +494,14 @@ struct FirmwareMatrixOrderingTests {// MARK: - Column paddingstruct FirmwareMatrixPaddingTests {- @Test func leftJustifyingNeverTruncates() {+ @Test func `left justifying never truncates`() {// `String.padding(toLength:)` would cut this to 12 and lose the build.#expect(VPhoneFirmwareMatrix.leftJustified("27.0.1.2.3.4.5", 12) == "27.0.1.2.3.4.5")#expect(VPhoneFirmwareMatrix.leftJustified("26.3", 12) == "26.3 ")#expect(VPhoneFirmwareMatrix.leftJustified("", 3) == " ")}- @Test func paddingGoesInsideTheColourEscape() {+ @Test func `padding goes inside the colour escape`() {// Outside the escape the text would be the same width on screen but a// different byte string, and every golden above would break.#expect(Fixture.colored.render(.supported, width: 11) == "\u{1B}[32mSupported \u{1B}[0m")@@ -509,10 +509,10 @@ struct FirmwareMatrixPaddingTests {#expect(Fixture.plain.render(.supported, width: 11) == "Supported ")}- @Test func anOverlongVersionStillLeavesOneSpaceBeforeTheNextColumn() {+ @Test func `an overlong version still leaves one space before the next column`() {let urls = "/iPhone17,3_26.4.10.20.30_23E246_Restore.ipsw"let out = VPhoneFirmwareMatrix.listing(- device: Fixture.d, readme: nil, downloadURLs: urls, style: Fixture.plain+ device: Fixture.d, readme: nil, downloadURLs: urls, style: Fixture.plain,)guard case let .matrix(text) = out else {Issue.record("expected a matrix")@@ -529,11 +529,15 @@ struct FirmwareMatrixColorPolicyTests {/// descriptors, so `isatty` is answering for real here.private func withTTY<T>(_ body: (Int32) throws -> T) rethrows -> T {let fd = posix_openpt(O_RDWR | O_NOCTTY)- defer { if fd >= 0 { close(fd) } }+ defer {+ if fd >= 0 {+ close(fd)+ }+ }return try body(fd)}- @Test func honoursNoColorClicolorForceAndIsattyPerStream() throws {+ @Test func `honours no color clicolor force and isatty per stream`() throws {let pipe = Pipe()let pipeFD = pipe.fileHandleForWriting.fileDescriptortry withTTY { ttyFD in@@ -571,7 +575,7 @@ struct FirmwareMatrixColorPolicyTests {struct FirmwareMatrixCommandLineTests {private func capture(- _ body: (FileHandle, FileHandle) -> Int32+ _ body: (FileHandle, FileHandle) -> Int32,) -> (code: Int32, out: String, err: String) {let outPipe = Pipe(), errPipe = Pipe()let code = body(outPipe.fileHandleForWriting, errPipe.fileHandleForWriting)@@ -582,12 +586,12 @@ struct FirmwareMatrixCommandLineTests {return (code, out, err)}- @Test func listGoesToStdoutAndExitsZero() {+ @Test func `list goes to stdout and exits zero`() {let r = Fixture.withReadmeFile { path incapture { out, err inVPhoneFirmwareMatrixCommandLine.list(device: Fixture.d, readmePath: path, downloadURLs: Fixture.urls,- environment: [:], stdout: out, stderr: err+ environment: [:], stdout: out, stderr: err,)}}@@ -596,12 +600,12 @@ struct FirmwareMatrixCommandLineTests {#expect(r.err.isEmpty)}- @Test func anEmptyDeviceListGoesToStderrAndExitsOne() {+ @Test func `an empty device list goes to stderr and exits one`() {let r = Fixture.withReadmeFile { path incapture { out, err inVPhoneFirmwareMatrixCommandLine.list(device: "iPhone99,9", readmePath: path, downloadURLs: Fixture.urls,- environment: [:], stdout: out, stderr: err+ environment: [:], stdout: out, stderr: err,)}}@@ -610,12 +614,12 @@ struct FirmwareMatrixCommandLineTests {#expect(r.err == "No downloadable IPSWs found for iPhone99,9\n")}- @Test func aResolvedSelectorGoesToStdoutAndExitsZero() {+ @Test func `a resolved selector goes to stdout and exits zero`() {let r = Fixture.withReadmeFile { path incapture { out, err inVPhoneFirmwareMatrixCommandLine.resolve(device: Fixture.d, version: "26.3", build: "", readmePath: path,- downloadURLs: Fixture.urls, environment: [:], stdout: out, stderr: err+ downloadURLs: Fixture.urls, environment: [:], stdout: out, stderr: err,)}}@@ -626,12 +630,12 @@ struct FirmwareMatrixCommandLineTests {/// 2, not 1. `fw_prepare.sh` forwards this status verbatim so a caller can/// tell "pick a build" from "there is no such firmware".- @Test func anAmbiguousVersionGoesToStderrAndExitsTwo() {+ @Test func `an ambiguous version goes to stderr and exits two`() {let r = Fixture.withReadmeFile { path incapture { out, err inVPhoneFirmwareMatrixCommandLine.resolve(device: Fixture.d, version: "27.0", build: "", readmePath: path,- downloadURLs: Fixture.urls, environment: [:], stdout: out, stderr: err+ downloadURLs: Fixture.urls, environment: [:], stdout: out, stderr: err,)}}@@ -640,13 +644,13 @@ struct FirmwareMatrixCommandLineTests {#expect(r.err == Golden.ambiguousPlain)}- @Test func aMissGoesToStderrAndExitsOne() {+ @Test func `a miss goes to stderr and exits one`() {let r = Fixture.withReadmeFile { path incapture { out, err inVPhoneFirmwareMatrixCommandLine.resolve(device: Fixture.d, version: "99.9", build: "", readmePath: path,downloadURLs: Fixture.urls, environment: [:],- stdout: out, stderr: err+ stdout: out, stderr: err,)}}@@ -655,11 +659,11 @@ struct FirmwareMatrixCommandLineTests {#expect(r.err == "Unsupported: no downloadable IPSW matched device=iPhone17,3 version=99.9\n")}- @Test func anUnreadableReadmePathIsNotAnError() {+ @Test func `an unreadable readme path is not an error`() {let r = capture { out, err inVPhoneFirmwareMatrixCommandLine.list(device: Fixture.d, readmePath: "/nonexistent/README.md",- downloadURLs: Fixture.urls, environment: [:], stdout: out, stderr: err+ downloadURLs: Fixture.urls, environment: [:], stdout: out, stderr: err,)}#expect(r.code == 0)@@ -670,7 +674,7 @@ struct FirmwareMatrixCommandLineTests {/// The half that is easy to get wrong: each command styles the stream it/// writes to, not the process. `list` writes its table to stdout, so a/// terminal on stderr must not colour it.- @Test func listStylesStdoutNotStderr() throws {+ @Test func `list styles stdout not stderr`() throws {let fd = posix_openpt(O_RDWR | O_NOCTTY)try #require(fd >= 0)defer { close(fd) }@@ -679,7 +683,7 @@ struct FirmwareMatrixCommandLineTests {let code = Fixture.withReadmeFile { path inVPhoneFirmwareMatrixCommandLine.list(device: Fixture.d, readmePath: path, downloadURLs: Fixture.urls,- environment: [:], stdout: outPipe.fileHandleForWriting, stderr: tty+ environment: [:], stdout: outPipe.fileHandleForWriting, stderr: tty,)}try outPipe.fileHandleForWriting.close()@@ -692,7 +696,7 @@ struct FirmwareMatrixCommandLineTests {/// And the mirror image: the selector's failures are stderr's, so a/// terminal on stdout must not colour them. This is the case that keeps/// escapes out of `selection="$(resolve_selector_from_downloads …)"`.- @Test func resolveStylesStderrNotStdout() throws {+ @Test func `resolve styles stderr not stdout`() throws {let fd = posix_openpt(O_RDWR | O_NOCTTY)try #require(fd >= 0)defer { close(fd) }@@ -702,7 +706,7 @@ struct FirmwareMatrixCommandLineTests {VPhoneFirmwareMatrixCommandLine.resolve(device: Fixture.d, version: "99.9", build: "", readmePath: path,downloadURLs: Fixture.urls, environment: [:],- stdout: tty, stderr: errPipe.fileHandleForWriting+ stdout: tty, stderr: errPipe.fileHandleForWriting,)}try errPipe.fileHandleForWriting.close()diff --git a/tests/VPhoneCoreTests/FirmwarePickerTests.swift b/tests/VPhoneCoreTests/FirmwarePickerTests.swiftindex 40a9e4e9..c2cc3bcb 100644--- a/tests/VPhoneCoreTests/FirmwarePickerTests.swift+++ b/tests/VPhoneCoreTests/FirmwarePickerTests.swift@@ -1,5 +1,5 @@-@testable import VPhoneCoreimport Testing+@testable import VPhoneCorestruct FirmwarePickerTests {/// A scripted stdin: pops one line per `read()` call.@@ -10,11 +10,11 @@ struct FirmwarePickerTests {// MARK: - Catalog integrity- @Test func catalogHasTwentyFivePairings() {+ @Test func `catalog has twenty five pairings`() {#expect(VPhoneFirmwareCatalog.pairings.count == 25)}- @Test func everyPairingIsPopulated() {+ @Test func `every pairing is populated`() {for p in VPhoneFirmwareCatalog.pairings {#expect(!p.iosName.isEmpty)#expect(p.iosURL.hasPrefix("https://"))@@ -24,51 +24,51 @@ struct FirmwarePickerTests {}}- @Test func cloudOSOptionsAreDistinctInFirstSeenOrder() {+ @Test func `cloud OS options are distinct in first seen order`() {let opts = VPhoneFirmwareCatalog.cloudOSOptions#expect(opts.map(\.name) == ["cloudOS 26.1", "cloudOS 26.2", "cloudOS 26.3", "cloudOS 26.4"])- #expect(Set(opts.map(\.url)).count == opts.count) // no dup URLs+ #expect(Set(opts.map(\.url)).count == opts.count) // no dup URLs}// MARK: - Passthrough- @Test func bothProvidedPassesThrough() throws {+ @Test func `both provided passes through`() throws {let out = try VPhoneFirmwarePicker.resolve(iphone: "a.ipsw",cloudos: "b.dmg",isInteractive: true,read: { nil },- write: { _ in }+ write: { _ in },)#expect(out == VPhoneFirmwareSources(iphoneSource: "a.ipsw", cloudosSource: "b.dmg"))}- @Test func nonInteractivePassesThroughEvenWhenIncomplete() throws {+ @Test func `non interactive passes through even when incomplete`() throws {let out = try VPhoneFirmwarePicker.resolve(iphone: nil,cloudos: nil,isInteractive: false,read: { nil },- write: { _ in }+ write: { _ in },)#expect(out == VPhoneFirmwareSources(iphoneSource: nil, cloudosSource: nil))}- @Test func emptyStringsTreatedAsUnset() throws {+ @Test func `empty strings treated as unset`() throws {// Non-interactive + empty → passthrough as nil (no prompt), not "".let out = try VPhoneFirmwarePicker.resolve(iphone: "",cloudos: "",isInteractive: false,read: { nil },- write: { _ in }+ write: { _ in },)#expect(out == VPhoneFirmwareSources(iphoneSource: nil, cloudosSource: nil))}// MARK: - Prompt: neither provided- @Test func neitherProvidedPicksFullPairing() throws {+ @Test func `neither provided picks full pairing`() throws {// "1" → first pairing (iOS 18.6.2 → cloudOS 26.1).let first = VPhoneFirmwareCatalog.pairings[0]let out = try VPhoneFirmwarePicker.resolve(@@ -76,13 +76,13 @@ struct FirmwarePickerTests {cloudos: nil,isInteractive: true,read: reader(["1"]),- write: { _ in }+ write: { _ in },)#expect(out == VPhoneFirmwareSources(iphoneSource: first.iosURL, cloudosSource: first.cloudosURL))}- @Test func neitherProvidedResolvesBothFromChosenPairing() throws {- let idx = 8 // iOS 26.4 (menu number 9), paired with cloudOS 26.4+ @Test func `neither provided resolves both from chosen pairing`() throws {+ let idx = 8 // iOS 26.4 (menu number 9), paired with cloudOS 26.4let p = VPhoneFirmwareCatalog.pairings[idx]#expect(p.iosName == "iOS 26.4")let out = try VPhoneFirmwarePicker.resolve(@@ -90,7 +90,7 @@ struct FirmwarePickerTests {cloudos: nil,isInteractive: true,read: reader([String(idx + 1)]),- write: { _ in }+ write: { _ in },)#expect(out.iphoneSource == p.iosURL)#expect(out.cloudosSource == p.cloudosURL)@@ -98,7 +98,7 @@ struct FirmwarePickerTests {// MARK: - Prompt: only one side missing- @Test func iPhoneProvidedPromptsForCloudOSOnly() throws {+ @Test func `i phone provided prompts for cloud OS only`() throws {// cloudOS menu: [1]26.1 [2]26.2 [3]26.3 [4]26.4 → pick 4.let opts = VPhoneFirmwareCatalog.cloudOSOptionslet out = try VPhoneFirmwarePicker.resolve(@@ -106,36 +106,36 @@ struct FirmwarePickerTests {cloudos: nil,isInteractive: true,read: reader(["4"]),- write: { _ in }+ write: { _ in },)- #expect(out.iphoneSource == "custom.ipsw") // untouched- #expect(out.cloudosSource == opts[3].url) // chosen cloudOS 26.4+ #expect(out.iphoneSource == "custom.ipsw") // untouched+ #expect(out.cloudosSource == opts[3].url) // chosen cloudOS 26.4}- @Test func cloudOSProvidedPromptsForIPhoneOnly() throws {- let p = VPhoneFirmwareCatalog.pairings[3] // iOS 26.1 (menu 4)+ @Test func `cloud OS provided prompts for I phone only`() throws {+ let p = VPhoneFirmwareCatalog.pairings[3] // iOS 26.1 (menu 4)#expect(p.iosName == "iOS 26.1")let out = try VPhoneFirmwarePicker.resolve(iphone: nil,cloudos: "custom.dmg",isInteractive: true,read: reader(["4"]),- write: { _ in }+ write: { _ in },)- #expect(out.iphoneSource == p.iosURL) // chosen iPhone build- #expect(out.cloudosSource == "custom.dmg") // untouched+ #expect(out.iphoneSource == p.iosURL) // chosen iPhone build+ #expect(out.cloudosSource == "custom.dmg") // untouched}// MARK: - Menu formatting- @Test func pairingMenuIsColumnAligned() throws {+ @Test func `pairing menu is column aligned`() throws {var lines: [String] = []_ = try VPhoneFirmwarePicker.resolve(iphone: nil,cloudos: nil,isInteractive: true,read: reader(["1"]),- write: { lines.append($0) }+ write: { lines.append($0) },)let menu = lines.filter { $0.hasPrefix(" [") }#expect(menu.count == 25)@@ -149,31 +149,31 @@ struct FirmwarePickerTests {// MARK: - Retry / abort semantics- @Test func retriesThenSucceeds() throws {+ @Test func `retries then succeeds`() throws {let first = VPhoneFirmwareCatalog.pairings[0]let out = try VPhoneFirmwarePicker.resolve(iphone: nil,cloudos: nil,isInteractive: true,read: reader(["", "999", "garbage", "1"]),- write: { _ in }+ write: { _ in },)#expect(out.iphoneSource == first.iosURL)}- @Test func eofAborts() {+ @Test func `eof aborts`() {#expect(throws: VPhoneFirmwarePickerError.aborted) {_ = try VPhoneFirmwarePicker.resolve(iphone: nil,cloudos: nil,isInteractive: true,read: { nil },- write: { _ in }+ write: { _ in },)}}- @Test func tooManyInvalidThrows() {+ @Test func `too many invalid throws`() {#expect(throws: VPhoneFirmwarePickerError.invalidSelection) {_ = try VPhoneFirmwarePicker.resolve(iphone: nil,@@ -181,7 +181,7 @@ struct FirmwarePickerTests {isInteractive: true,maxRetries: 2,read: reader(["x", "y", "z"]),- write: { _ in }+ write: { _ in },)}}diff --git a/tests/VPhoneCoreTests/LaunchLayoutTests.swift b/tests/VPhoneCoreTests/LaunchLayoutTests.swiftindex 06d88fb4..812e2926 100644--- a/tests/VPhoneCoreTests/LaunchLayoutTests.swift+++ b/tests/VPhoneCoreTests/LaunchLayoutTests.swift@@ -1,24 +1,24 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct LaunchLayoutTests {- @Test func delegatesToResources() {+ @Test func `delegates to resources`() {let resources = VPhoneResources(base: URL(fileURLWithPath: "/proj"))let layout = VPhoneLaunchLayout(resources: resources)#expect(layout.vphoned.path == resources.vphoned.path)}- @Test func parsesLsofPIDs() {+ @Test func `parses lsof PI ds`() {#expect(VPhoneLsof.parsePIDs("123\n456\n123\n\n \nnotapid\n789\n") == [123, 456, 789])#expect(VPhoneLsof.parsePIDs("") == [])}- @Test func stageVphonedCopiesWhenSourceExists() throws {+ @Test func `stage vphoned copies when source exists`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root.appendingPathComponent(".build"),- withIntermediateDirectories: true+ withIntermediateDirectories: true,)defer { try? FileManager.default.removeItem(at: root) }try Data([1, 2, 3]).write(to: root.appendingPathComponent(".build/vphoned.signed"))@@ -28,7 +28,7 @@ struct LaunchLayoutTests {let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)let bundle = VPhoneBundle(url: bundleDir, manifest: manifest)@@ -39,7 +39,7 @@ struct LaunchLayoutTests {#expect(try layout.stageVphoned(into: bundle) == false)}- @Test func stageVphonedFailsWhenSourceAbsent() throws {+ @Test func `stage vphoned fails when source absent`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: root) }@@ -49,7 +49,7 @@ struct LaunchLayoutTests {let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)let bundle = VPhoneBundle(url: bundleDir, manifest: manifest)@@ -57,14 +57,15 @@ struct LaunchLayoutTests {try VPhoneLaunchLayout(projectRoot: root).stageVphoned(into: bundle)}#expect(!FileManager.default.fileExists(- atPath: bundleDir.appendingPathComponent(".vphoned.signed").path))+ atPath: bundleDir.appendingPathComponent(".vphoned.signed").path,+ ))}- @Test func stageVphonedOverwritesStaleDestination() throws {+ @Test func `stage vphoned overwrites stale destination`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root.appendingPathComponent(".build"),- withIntermediateDirectories: true+ withIntermediateDirectories: true,)defer { try? FileManager.default.removeItem(at: root) }try Data([9, 9, 9, 9]).write(to: root.appendingPathComponent(".build/vphoned.signed"))@@ -76,7 +77,7 @@ struct LaunchLayoutTests {let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)let bundle = VPhoneBundle(url: bundleDir, manifest: manifest)diff --git a/tests/VPhoneCoreTests/LibraryTests.swift b/tests/VPhoneCoreTests/LibraryTests.swiftindex ac26ebb0..16339d44 100644--- a/tests/VPhoneCoreTests/LibraryTests.swift+++ b/tests/VPhoneCoreTests/LibraryTests.swift@@ -1,6 +1,6 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCore// Serialized: defaultRootHonorsEnvOverride / defaultRootIsShellSafe mutate the// process-global VPHONE_LIBRARY_ROOT; run in parallel they race (a set/unset@@ -19,12 +19,12 @@ struct LibraryTests {let manifest = VPhoneVirtualMachineManifest(cpuCount: 8,memorySize: 8 * 1024 * 1024 * 1024,- romImages: .init(avpBooter: "AVPBooter.vresearch1.bin", avpSEPBooter: "AVPSEPBooter.vresearch1.bin")+ romImages: .init(avpBooter: "AVPBooter.vresearch1.bin", avpSEPBooter: "AVPSEPBooter.vresearch1.bin"),)try manifest.write(to: dir.appendingPathComponent("config.plist"))}- @Test func scansOnlyDirsWithManifest() throws {+ @Test func `scans only dirs with manifest`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }try writeBundle("alpha", in: root)@@ -32,14 +32,14 @@ struct LibraryTests {// A stray dir without config.plist must be ignored.try FileManager.default.createDirectory(at: root.appendingPathComponent("junk"),- withIntermediateDirectories: true+ withIntermediateDirectories: true,)let names = try VPhoneLibrary(root: root).bundles().map(\.name)#expect(names == ["alpha", "beta"])}- @Test func bundleNamedThrowsWhenMissing() throws {+ @Test func `bundle named throws when missing`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }#expect(throws: VPhoneLibraryError.self) {@@ -47,19 +47,19 @@ struct LibraryTests {}}- // These three go through `ProcessEnvironment` rather than calling `setenv`- // and `unsetenv` directly. `.serialized` on this suite orders these tests- // against each other, but `ResourcesTests` drives the same two variables- // from its own serialized suite, and nothing ordered the two suites — so- // the bare `unsetenv` that used to open `defaultRootIsShellSafe` could- // clear `VPHONE_ROOT` in the middle of a ResourcesTests assertion.- @Test func defaultRootHonorsEnvOverride() {+ /// These three go through `ProcessEnvironment` rather than calling `setenv`+ /// and `unsetenv` directly. `.serialized` on this suite orders these tests+ /// against each other, but `ResourcesTests` drives the same two variables+ /// from its own serialized suite, and nothing ordered the two suites — so+ /// the bare `unsetenv` that used to open `defaultRootIsShellSafe` could+ /// clear `VPHONE_ROOT` in the middle of a ResourcesTests assertion.+ @Test func `default root honors env override`() {ProcessEnvironment.withOverrides(["VPHONE_LIBRARY_ROOT": "/tmp/vphone-test-root"]) {#expect(VPhoneLibrary.defaultRoot().path == "/tmp/vphone-test-root")}}- @Test func defaultRootHonorsVPHONERoot() {+ @Test func `default root honors VPHONE root`() {ProcessEnvironment.withOverrides(["VPHONE_LIBRARY_ROOT": nil,"VPHONE_ROOT": "/tmp/vphone-test-root",@@ -68,7 +68,7 @@ struct LibraryTests {}}- @Test func defaultRootIsShellSafe() {+ @Test func `default root is shell safe`() {// The default root feeds the shell/make firmware pipeline; a space in it// (e.g. "Application Support") breaks unquoted expansion. Must stay space-free.ProcessEnvironment.withOverrides([@@ -79,7 +79,7 @@ struct LibraryTests {}}- @Test func scanReportsCorruptBundlesInsteadOfDropping() throws {+ @Test func `scan reports corrupt bundles instead of dropping`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }try writeBundle("good", in: root)diff --git a/tests/VPhoneCoreTests/ManagedProcessTests.swift b/tests/VPhoneCoreTests/ManagedProcessTests.swiftindex be94c2d1..3156f808 100644--- a/tests/VPhoneCoreTests/ManagedProcessTests.swift+++ b/tests/VPhoneCoreTests/ManagedProcessTests.swift@@ -1,14 +1,14 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct ManagedProcessTests {- @Test func waitsForOutputMatch() throws {+ @Test func `waits for output match`() throws {// Emit a line after a short delay, then sleep; the matcher should catch it.let p = VPhoneManagedProcess(URL(fileURLWithPath: "/bin/sh"),["-c", "sleep 0.2; echo READY-NOW; sleep 2"],- echo: false+ echo: false,)try p.start()let r = p.waitForOutput(matching: "READY-NOW", timeout: 5)@@ -16,14 +16,14 @@ struct ManagedProcessTests {p.terminate()}- @Test func reportsExitBeforeMatch() throws {+ @Test func `reports exit before match`() throws {let p = VPhoneManagedProcess(URL(fileURLWithPath: "/bin/sh"), ["-c", "echo nope; exit 3"], echo: false)try p.start()let r = p.waitForOutput(matching: "WILL-NOT-APPEAR", timeout: 5)#expect(r == .exited(3))}- @Test func timesOutWhenNoMatch() throws {+ @Test func `times out when no match`() throws {let p = VPhoneManagedProcess(URL(fileURLWithPath: "/bin/sh"), ["-c", "sleep 3"], echo: false)try p.start()let r = p.waitForOutput(matching: "NEVER", timeout: 0.5)@@ -31,7 +31,7 @@ struct ManagedProcessTests {p.terminate()}- @Test func sendWritesToStdinAndDrivesTheChild() throws {+ @Test func `send writes to stdin and drives the child`() throws {// Child echoes a marker only after it reads a line from stdin.let p = VPhoneManagedProcess(URL(fileURLWithPath: "/bin/sh"), ["-c", "read line; echo GOT:$line"], echo: false)try p.start()@@ -41,17 +41,17 @@ struct ManagedProcessTests {#expect(p.waitUntilExit() == 0)}- @Test func terminateForceKillsAResistantChild() throws {+ @Test func `terminate force kills A resistant child`() throws {// Child IGNORES SIGINT and SIGTERM, so terminate() must escalate to SIGKILL// and waitUntilExit() must return (not hang).let p = VPhoneManagedProcess(URL(fileURLWithPath: "/bin/sh"),["-c", "trap '' INT TERM; while :; do sleep 1; done"],- echo: false+ echo: false,)try p.start()- _ = p.waitForOutput(matching: "NEVER", timeout: 0.4) // let it install the traps+ _ = p.waitForOutput(matching: "NEVER", timeout: 0.4) // let it install the trapsp.terminate()- #expect(p.waitUntilExit() != 0) // SIGKILL → nonzero/signal status, and it RETURNED+ #expect(p.waitUntilExit() != 0) // SIGKILL → nonzero/signal status, and it RETURNED}}diff --git a/tests/VPhoneCoreTests/ManifestTests.swift b/tests/VPhoneCoreTests/ManifestTests.swiftindex bf6ed25b..aa37e962 100644--- a/tests/VPhoneCoreTests/ManifestTests.swift+++ b/tests/VPhoneCoreTests/ManifestTests.swift@@ -1,17 +1,17 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct ManifestTests {private func sampleManifest() -> VPhoneVirtualMachineManifest {VPhoneVirtualMachineManifest(cpuCount: 8,memorySize: 8 * 1024 * 1024 * 1024,- romImages: .init(avpBooter: "AVPBooter.vresearch1.bin", avpSEPBooter: "AVPSEPBooter.vresearch1.bin")+ romImages: .init(avpBooter: "AVPBooter.vresearch1.bin", avpSEPBooter: "AVPSEPBooter.vresearch1.bin"),)}- @Test func roundTripsThroughPlist() throws {+ @Test func `round trips through plist`() throws {let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)@@ -26,7 +26,7 @@ struct ManifestTests {#expect(loaded.romImages?.avpBooter == "AVPBooter.vresearch1.bin")}- @Test func updatingReplacesOnlyGivenFields() {+ @Test func `updating replaces only given fields`() {let updated = sampleManifest().updating(cpuCount: 4, memorySize: nil)#expect(updated.cpuCount == 4)#expect(updated.memorySize == 8 * 1024 * 1024 * 1024)@@ -34,7 +34,7 @@ struct ManifestTests {#expect(updated.networkConfig.mode == .nat)}- @Test func networkConfigRoundTripsThroughPlist() throws {+ @Test func `network config round trips through plist`() throws {let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)@@ -49,18 +49,18 @@ struct ManifestTests {#expect(loaded.networkConfig.bridgeInterface == "en0")}- // Manifests written before bridgeInterface existed omit that key; they must- // still decode, with bridgeInterface defaulting to nil.- @Test func decodesManifestWithoutBridgeInterfaceKey() throws {+ /// Manifests written before bridgeInterface existed omit that key; they must+ /// still decode, with bridgeInterface defaulting to nil.+ @Test func `decodes manifest without bridge interface key`() throws {let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: dir) }let url = dir.appendingPathComponent("config.plist")- try sampleManifest().write(to: url) // default network → bridgeInterface nil+ try sampleManifest().write(to: url) // default network → bridgeInterface nillet text = try String(contentsOf: url, encoding: .utf8)- #expect(!text.contains("bridgeInterface")) // nil optional is omitted from the plist+ #expect(!text.contains("bridgeInterface")) // nil optional is omitted from the plistlet loaded = try VPhoneVirtualMachineManifest.load(from: url)#expect(loaded.networkConfig.bridgeInterface == nil)diff --git a/tests/VPhoneCoreTests/NetworkingTests.swift b/tests/VPhoneCoreTests/NetworkingTests.swiftindex d8223272..5874d0d1 100644--- a/tests/VPhoneCoreTests/NetworkingTests.swift+++ b/tests/VPhoneCoreTests/NetworkingTests.swift@@ -1,38 +1,38 @@-@testable import VPhoneCoreimport Foundationimport Testingimport Virtualization+@testable import VPhoneCorestruct NetworkingTests {typealias NetworkConfig = VPhoneVirtualMachineManifest.NetworkConfig- @Test func mergeSetsMode() throws {+ @Test func `merge sets mode`() throws {let out = try VPhoneNetworking.merge(into: .default, mode: .off, bridgeInterface: nil)#expect(out.mode == .off)#expect(out.bridgeInterface == nil)}- @Test func mergeWithoutModePreservesCurrent() throws {+ @Test func `merge without mode preserves current`() throws {let current = NetworkConfig(mode: .off, macAddress: "")let out = try VPhoneNetworking.merge(into: current, mode: nil, bridgeInterface: nil)#expect(out.mode == .off)}- @Test func mergeRejectsHostOnly() {+ @Test func `merge rejects host only`() {#expect(throws: VPhoneNetworkingError.hostOnlyUnsupported) {_ = try VPhoneNetworking.merge(into: .default, mode: .hostOnly, bridgeInterface: nil)}}- @Test func mergeRejectsBridgeInterfaceWithoutBridgedMode() {+ @Test func `merge rejects bridge interface without bridged mode`() {#expect(throws: VPhoneNetworkingError.bridgeInterfaceWithoutBridgedMode) {_ = try VPhoneNetworking.merge(into: .default, mode: .nat, bridgeInterface: "en0")}}- // The test binary is unsigned, so no interfaces are available for bridging:- // selecting bridged must fail loudly rather than silently produce a dead NIC.- @Test func bridgedWithoutAvailableInterfacesThrows() {+ /// The test binary is unsigned, so no interfaces are available for bridging:+ /// selecting bridged must fail loudly rather than silently produce a dead NIC.+ @Test func `bridged without available interfaces throws`() {guard VPhoneNetworking.availableBridgeInterfaces().isEmpty else { return }#expect(throws: VPhoneNetworkingError.self) {_ = try VPhoneNetworking.merge(into: .default, mode: .bridged, bridgeInterface: nil)@@ -42,12 +42,12 @@ struct NetworkingTests {}}- @Test func makeNetworkDeviceOffIsNil() throws {+ @Test func `make network device off is nil`() throws {let dev = try VPhoneNetworking.makeNetworkDevice(NetworkConfig(mode: .off, macAddress: ""))#expect(dev == nil)}- @Test func makeNetworkDeviceNATHasAttachment() throws {+ @Test func `make network device NAT has attachment`() throws {let dev = try VPhoneNetworking.makeNetworkDevice(NetworkConfig(mode: .nat, macAddress: ""))#expect(dev != nil)#expect(dev?.attachment is VZNATNetworkDeviceAttachment)diff --git a/tests/VPhoneCoreTests/NewVMManifestTests.swift b/tests/VPhoneCoreTests/NewVMManifestTests.swiftindex 800d8c8b..056d2e8d 100644--- a/tests/VPhoneCoreTests/NewVMManifestTests.swift+++ b/tests/VPhoneCoreTests/NewVMManifestTests.swift@@ -14,8 +14,8 @@ import Testing/// result of that comparison, so it cannot drift once the Python is gone.@Suite("Fresh VM manifest")struct NewVMManifestTests {- @Test("defaults match the Python's")- func defaults() {+ @Test+ func `defaults match the Python's`() {let m = VPhoneVirtualMachineManifest.newVM()#expect(m.platformType == .vresearch101)@@ -33,31 +33,31 @@ struct NewVMManifestTests {#expect(m.networkConfig.mode == .nat)}- @Test("machineIdentifier starts empty, for first boot to fill in")- func machineIdentifierIsEmpty() {+ @Test+ func `machineIdentifier starts empty, for first boot to fill in`() {#expect(VPhoneVirtualMachineManifest.newVM().machineIdentifier.isEmpty)}- @Test("macAddress starts empty so the framework assigns one")- func macAddressIsEmpty() {+ @Test+ func `macAddress starts empty so the framework assigns one`() {// Not cosmetic: forcing a MAC here breaks guest networking.#expect(VPhoneVirtualMachineManifest.newVM().networkConfig.macAddress.isEmpty)}- @Test("memory is MB in, bytes out")- func memoryConversion() {+ @Test+ func `memory is MB in, bytes out`() {#expect(VPhoneVirtualMachineManifest.newVM(memoryMB: 4096).memorySize == 4_294_967_296)}- @Test("platformFusing is absent unless asked for")- func platformFusingOmitted() throws {+ @Test+ func `platformFusing is absent unless asked for`() throws {let url = FileManager.default.temporaryDirectory.appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")defer { try? FileManager.default.removeItem(at: url) }try VPhoneVirtualMachineManifest.newVM().write(to: url)let parsed = try PropertyListSerialization.propertyList(- from: Data(contentsOf: url), format: nil+ from: Data(contentsOf: url), format: nil,) as? [String: Any]// Absent, not null: the host OS decides when the key is missing.@@ -65,29 +65,29 @@ struct NewVMManifestTests {#expect(parsed?["bridgeInterface"] == nil)}- @Test("platformFusing is written when asked for")- func platformFusingWritten() throws {+ @Test+ func `platformFusing is written when asked for`() throws {let url = FileManager.default.temporaryDirectory.appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")defer { try? FileManager.default.removeItem(at: url) }try VPhoneVirtualMachineManifest.newVM(platformFusing: .dev).write(to: url)let parsed = try PropertyListSerialization.propertyList(- from: Data(contentsOf: url), format: nil+ from: Data(contentsOf: url), format: nil,) as? [String: Any]#expect(parsed?["platformFusing"] as? String == "dev")}- @Test("the exact key set the Python wrote")- func keySet() throws {+ @Test+ func `the exact key set the Python wrote`() throws {let url = FileManager.default.temporaryDirectory.appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")defer { try? FileManager.default.removeItem(at: url) }try VPhoneVirtualMachineManifest.newVM().write(to: url)let parsed = try #require(PropertyListSerialization.propertyList(- from: Data(contentsOf: url), format: nil+ from: Data(contentsOf: url), format: nil,) as? [String: Any])#expect(parsed.keys.sorted() == [@@ -97,8 +97,8 @@ struct NewVMManifestTests {])}- @Test("what is written can be read back")- func roundTrips() throws {+ @Test+ func `what is written can be read back`() throws {let url = FileManager.default.temporaryDirectory.appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")defer { try? FileManager.default.removeItem(at: url) }@@ -113,15 +113,15 @@ struct NewVMManifestTests {#expect(read.networkConfig.mode == .nat)}- @Test("cpuCount stays an integer, not a string")- func typesAreNotCoerced() throws {+ @Test+ func `cpuCount stays an integer, not a string`() throws {let url = FileManager.default.temporaryDirectory.appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")defer { try? FileManager.default.removeItem(at: url) }try VPhoneVirtualMachineManifest.newVM().write(to: url)let parsed = try #require(PropertyListSerialization.propertyList(- from: Data(contentsOf: url), format: nil+ from: Data(contentsOf: url), format: nil,) as? [String: Any])// A number that becomes "8" parses fine and fails much later.diff --git a/tests/VPhoneCoreTests/PCCGPUDriverTests.swift b/tests/VPhoneCoreTests/PCCGPUDriverTests.swiftindex 92fe3b08..d6c1cc78 100644--- a/tests/VPhoneCoreTests/PCCGPUDriverTests.swift+++ b/tests/VPhoneCoreTests/PCCGPUDriverTests.swift@@ -1,9 +1,9 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct PCCGPUDriverTests {- @Test func selectsVphone600OSImage() throws {+ @Test func `selects vphone 600 OS image`() throws {let directory = FileManager.default.temporaryDirectory.appendingPathComponent("pcc-gpu-test-\(UUID().uuidString)")try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)@@ -14,7 +14,7 @@ struct PCCGPUDriverTests {identity(device: "vphone600ap", os: "PCC-OS.dmg.aea"),]let manifest = try PropertyListSerialization.data(- fromPropertyList: ["BuildIdentities": identities], format: .binary, options: 0+ fromPropertyList: ["BuildIdentities": identities], format: .binary, options: 0,)try manifest.write(to: directory.appendingPathComponent("BuildManifest.plist"))@@ -24,14 +24,14 @@ struct PCCGPUDriverTests {== directory.appending(path: ".pcc-gpu/AppleParavirtGPUMetalIOGPUFamily.bundle"))}- @Test func refusesPathOutsidePCCDirectory() throws {+ @Test func `refuses path outside PCC directory`() throws {let directory = FileManager.default.temporaryDirectory.appendingPathComponent("pcc-gpu-test-\(UUID().uuidString)")try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: directory) }let manifest = try PropertyListSerialization.data(fromPropertyList: ["BuildIdentities": [identity(device: "vphone600ap", os: "../outside.dmg")]],- format: .binary, options: 0+ format: .binary, options: 0,)try manifest.write(to: directory.appendingPathComponent("BuildManifest.plist"))diff --git a/tests/VPhoneCoreTests/PlistEquivalence.swift b/tests/VPhoneCoreTests/PlistEquivalence.swiftindex 8ade1204..257f5534 100644--- a/tests/VPhoneCoreTests/PlistEquivalence.swift+++ b/tests/VPhoneCoreTests/PlistEquivalence.swift@@ -28,13 +28,15 @@ enum PlistEquivalence {let path: Stringlet detail: String- var description: String { "\(path.isEmpty ? "<root>" : path): \(detail)" }+ var description: String {+ "\(path.isEmpty ? "<root>" : path): \(detail)"+ }}static func differences(between lhs: Any,and rhs: Any,- at path: String = ""+ at path: String = "",) -> [Difference] {// Dictionaries: compare key sets first so a missing key is reported as// a missing key, not as a mismatch at some deeper path.@@ -51,7 +53,7 @@ enum PlistEquivalence {for key in Set(l.keys).intersection(r.keys).sorted() {found += differences(between: l[key]!, and: r[key]!,- at: path.isEmpty ? key : "\(path).\(key)"+ at: path.isEmpty ? key : "\(path).\(key)",)}return found@@ -61,7 +63,7 @@ enum PlistEquivalence {guard l.count == r.count else {return [Difference(path: path, detail: "\(l.count) elements on the left, \(r.count) on the right")]}- return (0..<l.count).flatMap {+ return (0 ..< l.count).flatMap {differences(between: l[$0], and: r[$0], at: "\(path)[\($0)]")}}@@ -75,7 +77,7 @@ enum PlistEquivalence {if lIsBool != rIsBool {return [Difference(path: path,- detail: "one is a boolean and the other is a number (\(l) vs \(r))"+ detail: "one is a boolean and the other is a number (\(l) vs \(r))",)]}return l == r ? [] : [Difference(path: path, detail: "\(l) vs \(r)")]@@ -86,10 +88,12 @@ enum PlistEquivalence {}if let l = lhs as? Data, let r = rhs as? Data {- if l == r { return [] }+ if l == r {+ return []+ }return [Difference(path: path,- detail: "data differs (\(l.count) vs \(r.count) bytes)"+ detail: "data differs (\(l.count) vs \(r.count) bytes)",)]}@@ -99,17 +103,17 @@ enum PlistEquivalence {return [Difference(path: path,- detail: "different types: \(type(of: lhs)) vs \(type(of: rhs))"+ detail: "different types: \(type(of: lhs)) vs \(type(of: rhs))",)]}/// Parse two plist files and report every semantic difference.static func differences(betweenFileAt lhs: URL, andFileAt rhs: URL) throws -> [Difference] {let left = try PropertyListSerialization.propertyList(- from: Data(contentsOf: lhs), format: nil+ from: Data(contentsOf: lhs), format: nil,)let right = try PropertyListSerialization.propertyList(- from: Data(contentsOf: rhs), format: nil+ from: Data(contentsOf: rhs), format: nil,)return differences(between: left, and: right)}diff --git a/tests/VPhoneCoreTests/ProcessEnvironment.swift b/tests/VPhoneCoreTests/ProcessEnvironment.swiftindex ba54130e..1c95849e 100644--- a/tests/VPhoneCoreTests/ProcessEnvironment.swift+++ b/tests/VPhoneCoreTests/ProcessEnvironment.swift@@ -25,7 +25,7 @@ enum ProcessEnvironment {/// `nil` value unsets.static func withOverrides(_ overrides: [String: String?],- _ body: () throws -> Void+ _ body: () throws -> Void,) rethrows {lock.lock()defer { lock.unlock() }@@ -33,9 +33,13 @@ enum ProcessEnvironment {let previous = overrides.keys.reduce(into: [String: String?]()) { saved, key insaved[key] = ProcessInfo.processInfo.environment[key]}- defer { for (key, value) in previous { apply(key, value) } }+ defer { for (key, value) in previous {+ apply(key, value)+ } }- for (key, value) in overrides { apply(key, value) }+ for (key, value) in overrides {+ apply(key, value)+ }try body()}@@ -48,6 +52,10 @@ enum ProcessEnvironment {}private static func apply(_ key: String, _ value: String?) {- if let value { setenv(key, value, 1) } else { unsetenv(key) }+ if let value {+ setenv(key, value, 1)+ } else {+ unsetenv(key)+ }}}diff --git a/tests/VPhoneCoreTests/ProcessRunnerTests.swift b/tests/VPhoneCoreTests/ProcessRunnerTests.swiftindex 3b54fd7f..70ed576d 100644--- a/tests/VPhoneCoreTests/ProcessRunnerTests.swift+++ b/tests/VPhoneCoreTests/ProcessRunnerTests.swift@@ -1,55 +1,58 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct ProcessRunnerTests {- @Test func capturesStdoutAndZeroExit() throws {+ @Test func `captures stdout and zero exit`() throws {let r = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/bin/echo"), ["hello", "world"])#expect(r.exitCode == 0)#expect(r.succeeded)#expect(r.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "hello world")}- @Test func capturesNonzeroExit() throws {+ @Test func `captures nonzero exit`() throws {// `/usr/bin/false` exits 1 with no output.let r = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/bin/false"), [])#expect(r.exitCode == 1)#expect(!r.succeeded)}- @Test func passesCwd() throws {+ @Test func `passes cwd`() throws {let r = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/bin/pwd"),[],- cwd: URL(fileURLWithPath: "/tmp")+ cwd: URL(fileURLWithPath: "/tmp"),)// /tmp is a symlink to /private/tmp on macOS; accept either.let out = r.stdout.trimmingCharacters(in: .whitespacesAndNewlines)#expect(out == "/tmp" || out == "/private/tmp")}- @Test func drainsBothPipesConcurrentlyWithoutDeadlock() throws {+ @Test func `drains both pipes concurrently without deadlock`() throws {// Child writes 100 KB to stderr BEFORE any stdout; a sequential// "read stdout fully first" drain would deadlock at the ~64 KB stderr// pipe buffer. Concurrent draining must complete without hanging.let r = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/bin/sh"),- ["-c", "yes E | head -c 100000 1>&2; yes X | head -c 100000"])+ ["-c", "yes E | head -c 100000 1>&2; yes X | head -c 100000"],+ )#expect(r.exitCode == 0)- #expect(r.stdout.utf8.count == 100000)- #expect(r.stderr.utf8.count == 100000)+ #expect(r.stdout.utf8.count == 100_000)+ #expect(r.stderr.utf8.count == 100_000)}- @Test func runStreamingReturnsExitCode() throws {+ @Test func `run streaming returns exit code`() throws {#expect(try VPhoneProcessRunner.runStreaming(URL(fileURLWithPath: "/usr/bin/true"), []) == 0)#expect(try VPhoneProcessRunner.runStreaming(URL(fileURLWithPath: "/usr/bin/false"), []) == 1)}- @Test func runStreamingEchoFalseStillReturnsExitCode() throws {+ @Test func `run streaming echo false still returns exit code`() throws {// Child writes to stdout but echo:false discards it; exit code still propagates.#expect(try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/bin/sh"), ["-c", "echo noise; exit 0"], echo: false) == 0)+ URL(fileURLWithPath: "/bin/sh"), ["-c", "echo noise; exit 0"], echo: false,+ ) == 0)#expect(try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/bin/sh"), ["-c", "echo noise >&2; exit 7"], echo: false) == 7)+ URL(fileURLWithPath: "/bin/sh"), ["-c", "echo noise >&2; exit 7"], echo: false,+ ) == 7)}}diff --git a/tests/VPhoneCoreTests/ResourcesTests.swift b/tests/VPhoneCoreTests/ResourcesTests.swiftindex 81f69dc9..1979cfac 100644--- a/tests/VPhoneCoreTests/ResourcesTests.swift+++ b/tests/VPhoneCoreTests/ResourcesTests.swift@@ -1,6 +1,6 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCore/// `.serialized` because several of these set and unset `VPHONE_ROOT`, and the/// environment is process-global: run in parallel, one test's@@ -14,22 +14,22 @@ import Testing/// which is the lock that actually spans them.@Suite(.serialized)struct ResourcesTests {- @Test func bundledLayoutResolvesToContentsResources() {+ @Test func `bundled layout resolves to contents resources`() {let exe = "/Applications/vphone-cli.app/Contents/MacOS/vphone-cli"let r = VPhoneResources.resolve(executablePath: exe)#expect(r.base.path == "/Applications/vphone-cli.app/Contents/Resources")}- @Test func devLayoutWalksUpToProjectRoot() throws {+ @Test func `dev layout walks up to project root`() throws {// Fake a dev tree: <root>/.build/release/vphone-cli with a <root>/scripts dir.let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root.appendingPathComponent(".build/release"),- withIntermediateDirectories: true+ withIntermediateDirectories: true,)try FileManager.default.createDirectory(at: root.appendingPathComponent("scripts"),- withIntermediateDirectories: true+ withIntermediateDirectories: true,)defer { try? FileManager.default.removeItem(at: root) }let exe = root.appendingPathComponent(".build/release/vphone-cli").path@@ -37,7 +37,7 @@ struct ResourcesTests {#expect(r.base.path == root.resolvingSymlinksInPath().path)}- @Test func cacheDirsAreHomeRelative() {+ @Test func `cache dirs are home relative`() {// The VPHONE_ROOT override would relocate the cache; assert the default// with the variable held clear, rather than bailing out when some other// suite happens to have set it — that skip was the old way of living@@ -47,7 +47,7 @@ struct ResourcesTests {}}- @Test func userDataRootHonorsVPHONERoot() {+ @Test func `user data root honors VPHONE root`() {ProcessEnvironment.withOverrides(["VPHONE_ROOT": "/tmp/vphone-test-root"]) {let r = VPhoneResources(base: URL(fileURLWithPath: "/x"))#expect(VPhoneResources.userDataRoot().path == "/tmp/vphone-test-root")@@ -61,7 +61,7 @@ struct ResourcesTests {/// interpreter. That claim is what the deleted venv tests used to guard/// from the other side, so assert it directly: every URL this type hands/// out is rooted in `base` or in the user data root.- @Test func everyResourceIsRootedInTheBaseOrTheDataRoot() {+ @Test func `every resource is rooted in the base or the data root`() {ProcessEnvironment.withOverrides(["VPHONE_ROOT": "/tmp/vphone-test-root"]) {let base = URL(fileURLWithPath: "/x")let r = VPhoneResources(base: base)@@ -80,7 +80,7 @@ struct ResourcesTests {/// A companion binary is found beside the running image, never on `PATH` —/// the property that made the interpreter ladder removable.- @Test func siblingExecutableSitsBesideTheRunningImage() {+ @Test func `sibling executable sits beside the running image`() {let me = VPhoneResources.runningExecutable()let sibling = VPhoneResources.siblingExecutable("vphone-vm")#expect(sibling.deletingLastPathComponent().path == me.deletingLastPathComponent().path)diff --git a/tests/VPhoneCoreTests/RestoreInfoTests.swift b/tests/VPhoneCoreTests/RestoreInfoTests.swiftindex 07f22b99..bbd5e6d7 100644--- a/tests/VPhoneCoreTests/RestoreInfoTests.swift+++ b/tests/VPhoneCoreTests/RestoreInfoTests.swift@@ -1,6 +1,6 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct RestoreInfoTests {private func makeBundle() throws -> VPhoneBundle {@@ -9,7 +9,7 @@ struct RestoreInfoTests {let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)return VPhoneBundle(url: root, manifest: manifest)}@@ -21,14 +21,18 @@ struct RestoreInfoTests {iosVersion: String?,iosBuild: String?,cloudVersion: String?,- cloudBuild: String?+ cloudBuild: String?,) throws {let dir = bundle.url.appendingPathComponent("iPhone17,3_27.0_24A5390f_Restore")try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)func write(_ name: String, _ version: String?, _ build: String?) throws {var dict: [String: Any] = [:]- if let version { dict["ProductVersion"] = version }- if let build { dict["ProductBuildVersion"] = build }+ if let version {+ dict["ProductVersion"] = version+ }+ if let build {+ dict["ProductBuildVersion"] = build+ }let data = try PropertyListSerialization.data(fromPropertyList: dict, format: .xml, options: 0)try data.write(to: dir.appendingPathComponent(name))}@@ -36,7 +40,7 @@ struct RestoreInfoTests {try write("BuildManifest.plist", cloudVersion, cloudBuild)}- @Test func derivesBothVersionsFromPlists() throws {+ @Test func `derives both versions from plists`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try makeRestoreDir(@@ -44,20 +48,20 @@ struct RestoreInfoTests {iosVersion: "27.0",iosBuild: "24A5390f",cloudVersion: "26.4",- cloudBuild: "23E5207q"+ cloudBuild: "23E5207q",)let info = VPhoneRestoreInfo.derive(fromBundle: b)#expect(info?.ios == .init(version: "27.0", build: "24A5390f"))#expect(info?.cloudOS == .init(version: "26.4", build: "23E5207q"))}- @Test func deriveNilWhenNoRestoreDir() throws {+ @Test func `derive nil when no restore dir`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }#expect(VPhoneRestoreInfo.derive(fromBundle: b) == nil)}- @Test func deriveNilWhenVersionKeyMissing() throws {+ @Test func `derive nil when version key missing`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try makeRestoreDir(@@ -65,23 +69,23 @@ struct RestoreInfoTests {iosVersion: "27.0",iosBuild: "24A5390f",cloudVersion: nil,- cloudBuild: "23E5207q"+ cloudBuild: "23E5207q",)#expect(VPhoneRestoreInfo.derive(fromBundle: b) == nil)}- @Test func writeThenLoadRoundTrips() throws {+ @Test func `write then load round trips`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }let info = VPhoneRestoreInfo(ios: .init(version: "18.6.2", build: "22G100"),- cloudOS: .init(version: "26.1", build: "23B85")+ cloudOS: .init(version: "26.1", build: "23B85"),)try info.write(toBundle: b)#expect(VPhoneRestoreInfo.load(fromBundle: b) == info)}- @Test func loadFallsBackToDeriveWhenNoJSON() throws {+ @Test func `load falls back to derive when no JSON`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try makeRestoreDir(@@ -89,7 +93,7 @@ struct RestoreInfoTests {iosVersion: "27.0",iosBuild: "24A5390f",cloudVersion: "26.4",- cloudBuild: "23E5207q"+ cloudBuild: "23E5207q",)// No restore-info.json written — load() must derive from the plists.let info = VPhoneRestoreInfo.load(fromBundle: b)@@ -97,7 +101,7 @@ struct RestoreInfoTests {#expect(info?.cloudOS.version == "26.4")}- @Test func bundleReportCarriesRestoreInfo() throws {+ @Test func `bundle report carries restore info`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try makeRestoreDir(@@ -105,26 +109,26 @@ struct RestoreInfoTests {iosVersion: "27.0",iosBuild: "24A5390f",cloudVersion: "26.4",- cloudBuild: "23E5207q"+ cloudBuild: "23E5207q",)let report = VPhoneBundleReport(bundle: b)#expect(report.restoreInfo?.ios.build == "24A5390f")#expect(report.restoreInfo?.cloudOS.build == "23E5207q")}- @Test func deviceForVariant() {+ @Test func `device for variant`() {#expect(VPhoneRestoreInfo.device(forVariant: "exp") == "iPhone17,3")for v in ["regular", "dev", "jb"] {#expect(VPhoneRestoreInfo.device(forVariant: v) == "iPhone99,11")}}- @Test func recordVariantMergesIntoVersions() throws {+ @Test func `record variant merges into versions`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try VPhoneRestoreInfo(ios: .init(version: "18.6.2", build: "22G100"),- cloudOS: .init(version: "26.1", build: "23B85")+ cloudOS: .init(version: "26.1", build: "23B85"),).write(toBundle: b)let merged = try VPhoneRestoreInfo.recordVariant("exp", toBundle: b)@@ -137,20 +141,20 @@ struct RestoreInfoTests {#expect(loaded?.device == "iPhone17,3")}- @Test func recordVariantNilWithoutVersions() throws {+ @Test func `record variant nil without versions`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }#expect(try VPhoneRestoreInfo.recordVariant("jb", toBundle: b) == nil)}- @Test func normalBootRejectsAnExplicitOldVariantButDFUStillParses() throws {+ @Test func `normal boot rejects an explicit old variant but DFU still parses`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try b.manifest.write(to: b.configURL)try VPhoneRestoreInfo(ios: .init(version: "26.6.2", build: "23G90"),cloudOS: .init(version: "26.4", build: "23E5207q"),- variant: "exp"+ variant: "exp",).write(toBundle: b)do {@@ -162,7 +166,7 @@ struct RestoreInfoTests {_ = try VPhoneBootCLI.parseAsRoot(["--config", b.configURL.path, "--dfu"])}- @Test func bundleReportCarriesUDID() throws {+ @Test func `bundle report carries UDID`() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }try "UDID=AAAABBBB-1122334455667788\n"@@ -173,7 +177,7 @@ struct RestoreInfoTests {/// The snapshot lives at the bundle root, so `vm export` must not strip it:/// it is matched by neither the `*_Restore*` exclude nor any regenerable-/// artifact pattern. Guards against a future exclude edit dropping it.- @Test func notExcludedFromExport() throws {+ @Test func `not excluded from export`() {let name = VPhoneRestoreInfo.fileName#expect(fnmatch("*_Restore*", name, 0) != 0)for pattern in VPhoneBundleOps.exportExcludePatterns {diff --git a/tests/VPhoneCoreTests/RestoreOpsTests.swift b/tests/VPhoneCoreTests/RestoreOpsTests.swiftindex defa727f..76f605b2 100644--- a/tests/VPhoneCoreTests/RestoreOpsTests.swift+++ b/tests/VPhoneCoreTests/RestoreOpsTests.swift@@ -1,6 +1,6 @@-@testable import VPhoneCoreimport Foundationimport Testing+@testable import VPhoneCorestruct RestoreOpsTests {private func bundle(in root: URL) throws -> VPhoneBundle {@@ -8,19 +8,19 @@ struct RestoreOpsTests {let manifest = VPhoneVirtualMachineManifest(cpuCount: 2,memorySize: 1024 * 1024,- romImages: .init(avpBooter: "a", avpSEPBooter: "b")+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),)return VPhoneBundle(url: root, manifest: manifest)}- @Test func resolveECIDPrefersExplicit() throws {+ @Test func `resolve ECID prefers explicit`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: root) }let b = try bundle(in: root)#expect(VPhoneRestoreOps.resolveECID(explicit: "0xABCD", bundle: b) == "0xABCD")}- @Test func resolveECIDFromPredictionFile() throws {+ @Test func `resolve ECID from prediction file`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: root) }let b = try bundle(in: root)@@ -29,14 +29,14 @@ struct RestoreOpsTests {#expect(VPhoneRestoreOps.resolveECID(explicit: nil, bundle: b) == "1122334455667788")}- @Test func resolveECIDNilWhenMissing() throws {+ @Test func `resolve ECID nil when missing`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: root) }let b = try bundle(in: root)#expect(VPhoneRestoreOps.resolveECID(explicit: nil, bundle: b) == nil)}- @Test func resolveUDIDFromPredictionFile() throws {+ @Test func `resolve UDID from prediction file`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: root) }let b = try bundle(in: root)@@ -45,14 +45,14 @@ struct RestoreOpsTests {#expect(VPhoneRestoreOps.resolveUDID(bundle: b) == "AAAABBBB-1122334455667788")}- @Test func resolveUDIDNilWhenMissing() throws {+ @Test func `resolve UDID nil when missing`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: root) }let b = try bundle(in: root)#expect(VPhoneRestoreOps.resolveUDID(bundle: b) == nil)}- @Test func isAEAEncryptedDetectsMagic() throws {+ @Test func `is AEA encrypted detects magic`() throws {let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: dir) }diff --git a/tests/VPhoneCoreTests/VMPickerTests.swift b/tests/VPhoneCoreTests/VMPickerTests.swiftindex f0c971c4..fc42ca8d 100644--- a/tests/VPhoneCoreTests/VMPickerTests.swift+++ b/tests/VPhoneCoreTests/VMPickerTests.swift@@ -1,5 +1,5 @@-@testable import VPhoneCoreimport Testing+@testable import VPhoneCorestruct VMPickerTests {/// A scripted stdin: pops one line per `read()` call.@@ -8,19 +8,19 @@ struct VMPickerTests {return { defer { i += 1 }; return i < lines.count ? lines[i] : nil }}- @Test func returnsProvidedNameUnchanged() throws {+ @Test func `returns provided name unchanged`() throws {let out = try VPhoneVMPicker.resolve(provided: "myvm",names: ["a", "b"],libraryRoot: "/r",isInteractive: true,read: { nil },- write: { _ in }+ write: { _ in },)- #expect(out == "myvm") // no prompt when a name is supplied+ #expect(out == "myvm") // no prompt when a name is supplied}- @Test func nonInteractiveWithoutNameThrows() {+ @Test func `non interactive without name throws`() {#expect(throws: VPhoneVMPickerError.notInteractive) {_ = try VPhoneVMPicker.resolve(provided: nil,@@ -28,12 +28,12 @@ struct VMPickerTests {libraryRoot: "/r",isInteractive: false,read: { nil },- write: { _ in }+ write: { _ in },)}}- @Test func emptyLibraryThrows() {+ @Test func `empty library throws`() {#expect(throws: VPhoneVMPickerError.emptyLibrary(root: "/r")) {_ = try VPhoneVMPicker.resolve(provided: nil,@@ -41,36 +41,36 @@ struct VMPickerTests {libraryRoot: "/r",isInteractive: true,read: { nil },- write: { _ in }+ write: { _ in },)}}- @Test func selectsByIndex() throws {+ @Test func `selects by index`() throws {let out = try VPhoneVMPicker.resolve(provided: nil,names: ["alpha", "beta", "gamma"],libraryRoot: "/r",isInteractive: true,read: reader(["2"]),- write: { _ in }+ write: { _ in },)#expect(out == "beta")}- @Test func selectsByExactName() throws {+ @Test func `selects by exact name`() throws {let out = try VPhoneVMPicker.resolve(provided: nil,names: ["alpha", "beta"],libraryRoot: "/r",isInteractive: true,read: reader(["alpha"]),- write: { _ in }+ write: { _ in },)#expect(out == "alpha")}- @Test func retriesThenSucceeds() throws {+ @Test func `retries then succeeds`() throws {// blank, out-of-range, bad-name, then a good index.let out = try VPhoneVMPicker.resolve(provided: nil,@@ -78,12 +78,12 @@ struct VMPickerTests {libraryRoot: "/r",isInteractive: true,read: reader(["", "9", "nope", "1"]),- write: { _ in }+ write: { _ in },)#expect(out == "alpha")}- @Test func eofAborts() {+ @Test func `eof aborts`() {#expect(throws: VPhoneVMPickerError.aborted) {_ = try VPhoneVMPicker.resolve(provided: nil,@@ -91,12 +91,12 @@ struct VMPickerTests {libraryRoot: "/r",isInteractive: true,read: { nil },- write: { _ in }+ write: { _ in },)}}- @Test func tooManyInvalidThrows() {+ @Test func `too many invalid throws`() {#expect(throws: VPhoneVMPickerError.invalidSelection) {_ = try VPhoneVMPicker.resolve(provided: nil,@@ -105,7 +105,7 @@ struct VMPickerTests {isInteractive: true,maxRetries: 2,read: reader(["x", "y", "z"]),- write: { _ in }+ write: { _ in },)}}diff --git a/tests/VPhoneCoreTests/VerbosityTests.swift b/tests/VPhoneCoreTests/VerbosityTests.swiftindex 7ec58b1d..fce1b029 100644--- a/tests/VPhoneCoreTests/VerbosityTests.swift+++ b/tests/VPhoneCoreTests/VerbosityTests.swift@@ -1,17 +1,17 @@-@testable import VPhoneCoreimport Testing+@testable import VPhoneCorestruct VerbosityTests {- @Test func countClampsToRange() {+ @Test func `count clamps to range`() {#expect(VPhoneVerbosity(count: 0) == .quiet)#expect(VPhoneVerbosity(count: 1) == .info)#expect(VPhoneVerbosity(count: 2) == .debug)#expect(VPhoneVerbosity(count: 3) == .trace)- #expect(VPhoneVerbosity(count: 9) == .trace) // clamp up- #expect(VPhoneVerbosity(count: -4) == .quiet) // clamp down+ #expect(VPhoneVerbosity(count: 9) == .trace) // clamp up+ #expect(VPhoneVerbosity(count: -4) == .quiet) // clamp down}- @Test func gatesAreMonotonic() {+ @Test func `gates are monotonic`() {#expect(VPhoneVerbosity.quiet.showsToolDetail == false)#expect(VPhoneVerbosity.info.showsToolDetail == true)#expect(VPhoneVerbosity.debug.tracesInternals == false)diff --git a/tests/VPhoneRestoreTests/RestoreEventTests.swift b/tests/VPhoneRestoreTests/RestoreEventTests.swiftindex 7e018570..2e4764b4 100644--- a/tests/VPhoneRestoreTests/RestoreEventTests.swift+++ b/tests/VPhoneRestoreTests/RestoreEventTests.swift@@ -8,7 +8,7 @@ import Testingstruct RestoreEventTests {// MARK: - Log levels- @Test func levelsMatchIdevicerestoresEnum() {+ @Test func `levels match idevicerestores enum`() {// src/log.h: LL_ERROR = 0 … LL_DEBUG = 5. Lower is more severe.#expect(VPhoneRestoreLogLevel.error.rawValue == 0)#expect(VPhoneRestoreLogLevel.warning.rawValue == 1)@@ -18,7 +18,7 @@ struct RestoreEventTests {#expect(VPhoneRestoreLogLevel.debug.rawValue == 5)}- @Test func severityOrdersTheOtherWayRound() {+ @Test func `severity orders the other way round`() {#expect(VPhoneRestoreLogLevel.error < VPhoneRestoreLogLevel.info)#expect(VPhoneRestoreLogLevel.info < VPhoneRestoreLogLevel.debug)// Which is what the console sink's `messageLevel <= level` relies on:@@ -28,13 +28,13 @@ struct RestoreEventTests {}@Test(arguments: [Int32(-1), 6, 99])- func anUnknownLevelBecomesInfo(_ raw: Int32) {+ func `an unknown level becomes info`(_ raw: Int32) {// Rather than dropping the line, which is the one outcome nobody can// debug.#expect(VPhoneRestoreLogLevel(clamping: raw) == .info)}- @Test func aKnownLevelSurvivesClamping() {+ @Test func `a known level survives clamping`() {for level in VPhoneRestoreLogLevel.allCases {#expect(VPhoneRestoreLogLevel(clamping: level.rawValue) == level)}@@ -42,7 +42,7 @@ struct RestoreEventTests {// MARK: - Steps- @Test func stepsCarryTheCSideNames() {+ @Test func `steps carry the C side names`() {// vphone_restore_step_name(), so a renumbered RESTORE_STEP_* shows up// here rather than in a user's log.#expect(VPhoneRestoreStep.detect.name == "detect")@@ -55,15 +55,15 @@ struct RestoreEventTests {#expect(VPhoneRestoreStep.uploadImage.name == "upload image")}- @Test func theStepsAreNumberedZeroUpwards() {+ @Test func `the steps are numbered zero upwards`() {let ordered: [VPhoneRestoreStep] = [.detect, .prepare, .uploadFilesystem, .verifyFilesystem,.flashFirmware, .flashBaseband, .flashFUD, .uploadImage,]- #expect(ordered.map(\.rawValue) == Array(Int32(0)...Int32(7)))+ #expect(ordered.map(\.rawValue) == Array(Int32(0) ... Int32(7)))}- @Test func anUnknownStepStillRoundTrips() {+ @Test func `an unknown step still round trips`() {let step = VPhoneRestoreStep(rawValue: 42)#expect(step.rawValue == 42)#expect(step.name == "unknown")@@ -71,7 +71,7 @@ struct RestoreEventTests {// MARK: - Recovery modes- @Test func onlyTheFourRecoveryProductIDsCountAsRecovery() {+ @Test func `only the four recovery product I ds count as recovery`() {// pymobiledevice3's `Mode.is_recovery`: everything that is not WTF and// not DFU. The probe's --is-recovery filter is this predicate.#expect(VPhoneRecoveryMode.recovery1.isRecovery)@@ -85,7 +85,7 @@ struct RestoreEventTests {#expect(!VPhoneRecoveryMode.portDFU.isRecovery)}- @Test func modesMatchLibirecoverysProductIDs() {+ @Test func `modes match libirecoverys product I ds`() {#expect(VPhoneRecoveryMode.recovery1.rawValue == 0x1280)#expect(VPhoneRecoveryMode.recovery4.rawValue == 0x1283)#expect(VPhoneRecoveryMode.wtf.rawValue == 0x1222)@@ -93,13 +93,13 @@ struct RestoreEventTests {#expect(VPhoneRecoveryMode.portDFU.rawValue == 0xF014)}- @Test func anUnknownModeIsReportableAndNotRecovery() {+ @Test func `an unknown mode is reportable and not recovery`() {let mode = VPhoneRecoveryMode(rawValue: 0x1234)#expect(!mode.isRecovery)#expect(mode.description == "mode 0x1234")}- @Test func modesDescribeThemselves() {+ @Test func `modes describe themselves`() {#expect(VPhoneRecoveryMode.recovery3.description == "recovery")#expect(VPhoneRecoveryMode.dfu.description == "DFU")#expect(VPhoneRecoveryMode.portDFU.description == "port DFU")@@ -107,7 +107,7 @@ struct RestoreEventTests {// MARK: - Timeout message- @Test func aProbeWithAPastDeadlineGivesUpWithoutHanging() {+ @Test func `a probe with A past deadline gives up without hanging`() {// Python's `while time.monotonic() < deadline` never ran the body when// the timeout was zero, and neither does this — which is what makes it// safe for `vm create` to call it ninety times in a row.@@ -124,14 +124,14 @@ struct RestoreEventTests {}}- @Test func theTimeoutMessageIsThePythonsWordForWord() {+ @Test func `the timeout message is the pythons word for word`() {let error = VPhoneRestoreBackendError.recoveryProbeTimedOut(mode: "dfu/recovery")#expect("\(error)" == "Timed out waiting for dfu/recovery endpoint")}// MARK: - Error messages- @Test func theRestoreTreeMessagesAreThePythonsWordForWord() {+ @Test func `the restore tree messages are the pythons word for word`() {let none = VPhoneRestoreBackendError.noRestoreDirectory(URL(fileURLWithPath: "/tmp/vm"))#expect("\(none)" == "No iPhone*_Restore directory found in /tmp/vm")let several = VPhoneRestoreBackendError.multipleRestoreDirectories(["a", "b"])diff --git a/tests/VPhoneRestoreTests/RestoreIdentityTests.swift b/tests/VPhoneRestoreTests/RestoreIdentityTests.swiftindex cbeaf9d4..332b2ab3 100644--- a/tests/VPhoneRestoreTests/RestoreIdentityTests.swift+++ b/tests/VPhoneRestoreTests/RestoreIdentityTests.swift@@ -9,7 +9,7 @@ import Testingstruct RestoreIdentityTests {// MARK: - Accepted- @Test func absentECIDIsNotAnError() throws {+ @Test func `absent ECID is not an error`() throws {let fromNil = try VPhoneRestoreIdentity.parseECID(nil)#expect(fromNil == nil)// Python's `if not value: return None` — "" is falsy, so it is "unset",@@ -27,18 +27,18 @@ struct RestoreIdentityTests {("0", UInt64(0)),("ffffffffffffffff", UInt64.max),])- func hexWithOrWithoutPrefix(_ input: String, _ expected: UInt64) throws {+ func `hex with or without prefix`(_ input: String, _ expected: UInt64) throws {let parsed = try VPhoneRestoreIdentity.parseECID(input)#expect(parsed == expected)}- @Test func formatsAsSixteenUppercaseHexDigits() {+ @Test func `formats as sixteen uppercase hex digits`() {#expect(VPhoneRestoreIdentity.formatECID(0x1234) == "0000000000001234")#expect(VPhoneRestoreIdentity.formatECID(0xAABB_CCDD_EEFF_0011) == "AABBCCDDEEFF0011")#expect(VPhoneRestoreIdentity.formatECID(0) == "0000000000000000")}- @Test func roundTripsThroughTheFormattedForm() throws {+ @Test func `round trips through the formatted form`() throws {let original: UInt64 = 0x0000_0001_1A2B_3C4Dlet reparsed = try VPhoneRestoreIdentity.parseECID(VPhoneRestoreIdentity.formatECID(original))#expect(reparsed == original)@@ -47,14 +47,14 @@ struct RestoreIdentityTests {// MARK: - Rejected@Test(arguments: [" ", "\t", "0x", "0X", " 0x "])- func presentButWithoutDigits(_ input: String) {+ func `present but without digits`(_ input: String) {#expect(throws: VPhoneRestoreBackendError.ecidEmpty) {try VPhoneRestoreIdentity.parseECID(input)}}@Test(arguments: ["ghij", "12 34", "0x12g", "-1", "12.34", "0x0x12", "1234"])- func nonHexIsRejectedAndReportedAsTyped(_ input: String) {+ func `non hex is rejected and reported as typed`(_ input: String) {// The payload is the ORIGINAL string, not the lower-cased,// prefix-stripped one — Python's `f"Invalid ECID: {value}"`.#expect(throws: VPhoneRestoreBackendError.ecidInvalid(input)) {@@ -62,7 +62,7 @@ struct RestoreIdentityTests {}}- @Test func seventeenHexDigitsDoNotFitAnECID() {+ @Test func `seventeen hex digits do not fit an ECID`() {// Python's ints are unbounded, so this is the one rejection the bridge// adds. Truncating silently would target a different device.#expect(throws: VPhoneRestoreBackendError.ecidTooLarge("00000000000000001")) {@@ -73,14 +73,14 @@ struct RestoreIdentityTests {}}- @Test func invalidECIDCarriesThePythonMessage() {+ @Test func `invalid ECID carries the python message`() {#expect("\(VPhoneRestoreBackendError.ecidEmpty)" == "ECID is empty")#expect("\(VPhoneRestoreBackendError.ecidInvalid("zz"))" == "Invalid ECID: zz")}// MARK: - UDID- @Test func udidIsTrimmedAndUpperCased() {+ @Test func `udid is trimmed and upper cased`() {// Not cosmetic: usbmuxd and udid-prediction.txt both report upper-case// hex, so a lower-case --udid would match nothing.#expect(VPhoneRestoreIdentity.normalizeUDID(" abcdef01-0001020304050607 ")@@ -89,7 +89,7 @@ struct RestoreIdentityTests {== "ABCDEF01-0001020304050607")}- @Test func absentOrEmptyUDIDMeansMatchAnyDevice() {+ @Test func `absent or empty UDID means match any device`() {#expect(VPhoneRestoreIdentity.normalizeUDID(nil) == nil)// Python kept "" and every call site then treated it as falsy; nil says// the same thing once, where it cannot be got wrong.diff --git a/tests/VPhoneRestoreTests/RestoreLayoutTests.swift b/tests/VPhoneRestoreTests/RestoreLayoutTests.swiftindex be4c34d7..0480e982 100644--- a/tests/VPhoneRestoreTests/RestoreLayoutTests.swift+++ b/tests/VPhoneRestoreTests/RestoreLayoutTests.swift@@ -21,13 +21,13 @@ struct RestoreLayoutTests {private func makeDirectory(_ name: String, in root: URL) throws {try FileManager.default.createDirectory(at: root.appendingPathComponent(name, isDirectory: true),- withIntermediateDirectories: true+ withIntermediateDirectories: true,)}// MARK: - Restore directory- @Test func findsTheOneRestoreTree() throws {+ @Test func `finds the one restore tree`() throws {try withTemporaryDirectory { root intry makeDirectory("iPhone17,3_Restore", in: root)try makeDirectory("cfw_input", in: root)@@ -36,7 +36,7 @@ struct RestoreLayoutTests {}}- @Test func noRestoreTreeIsAnError() throws {+ @Test func `no restore tree is an error`() throws {try withTemporaryDirectory { root intry makeDirectory("cfw_input", in: root)#expect(throws: VPhoneRestoreBackendError.noRestoreDirectory(root)) {@@ -45,7 +45,7 @@ struct RestoreLayoutTests {}}- @Test func missingBundleDirectoryIsTheSameError() throws {+ @Test func `missing bundle directory is the same error`() throws {// contentsOfDirectory fails rather than returning nothing; the caller// should still hear "no restore tree", not a Cocoa error.let absent = FileManager.default.temporaryDirectory@@ -55,7 +55,7 @@ struct RestoreLayoutTests {}}- @Test func twoRestoreTreesAreAnErrorNamingBoth() throws {+ @Test func `two restore trees are an error naming both`() throws {try withTemporaryDirectory { root intry makeDirectory("iPhone17,3_Restore", in: root)try makeDirectory("iPhone16,1_Restore", in: root)@@ -67,7 +67,7 @@ struct RestoreLayoutTests {}}- @Test func threeRestoreTreesAreStillAnError() throws {+ @Test func `three restore trees are still an error`() throws {try withTemporaryDirectory { root intry makeDirectory("iPhone17,3_Restore", in: root)try makeDirectory("iPhone16,1_Restore", in: root)@@ -80,7 +80,7 @@ struct RestoreLayoutTests {}}- @Test func aFileWithTheRightNameIsNotARestoreTree() throws {+ @Test func `a file with the right name is not A restore tree`() throws {try withTemporaryDirectory { root in// Python's `if p.is_dir()`. A stray file would otherwise be handed// to idevicerestore as a restore directory.@@ -92,7 +92,7 @@ struct RestoreLayoutTests {}}- @Test func theGlobStarMayMatchNothing() throws {+ @Test func `the glob star may match nothing`() throws {try withTemporaryDirectory { root in// "iPhone*_Restore" with an empty star. `hasPrefix` + `hasSuffix`// has to accept it, and the two literals cannot overlap, so it does.@@ -103,7 +103,7 @@ struct RestoreLayoutTests {}@Test(arguments: ["iPhone17,3", "iPhone", "17,3_Restore", "Restore", "iphone17,3_restore"])- func neighbouringNamesAreNotRestoreTrees(_ name: String) throws {+ func `neighbouring names are not restore trees`(_ name: String) throws {try withTemporaryDirectory { root intry makeDirectory(name, in: root)let names = try VPhoneRestoreLayout.restoreDirectoryNames(in: root)@@ -111,14 +111,14 @@ struct RestoreLayoutTests {}}- @Test func aSymlinkToADirectoryCounts() throws {+ @Test func `a symlink to A directory counts`() throws {try withTemporaryDirectory { root in// Python's glob + `p.is_dir()` follows symlinks, and a bundle that// points at a shared firmware tree is a reasonable thing to build.try makeDirectory("real_tree", in: root)try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("iPhone17,3_Restore"),- withDestinationURL: root.appendingPathComponent("real_tree")+ withDestinationURL: root.appendingPathComponent("real_tree"),)let found = try VPhoneRestoreLayout.findRestoreDirectory(in: root)#expect(found.lastPathComponent == "iPhone17,3_Restore")@@ -127,7 +127,7 @@ struct RestoreLayoutTests {// MARK: - SHSH filename- @Test func shshIsNamedAfterTheECIDInSixteenHexDigits() {+ @Test func `shsh is named after the ECID in sixteen hex digits`() {let root = URL(fileURLWithPath: "/tmp/vm")#expect(VPhoneRestoreLayout.shshOutput(vmDir: root, ecid: 0x0000_0001_1A2B_3C4D).path== "/tmp/vm/000000011A2B3C4D.shsh")@@ -135,17 +135,17 @@ struct RestoreLayoutTests {== "/tmp/vm/0000000000000001.shsh")}- @Test func shshFallsBackToAutoWithoutAnECID() {+ @Test func `shsh falls back to auto without an ECID`() {let root = URL(fileURLWithPath: "/tmp/vm")#expect(VPhoneRestoreLayout.shshOutput(vmDir: root, ecid: nil).path == "/tmp/vm/auto.shsh")}- @Test func theDerivedNameIsTheOneOfflineRestoresLookFor() throws {+ @Test func `the derived name is the one offline restores look for`() {// `vphone-cli restore --offline` takes the first *.shsh in the bundle.// Whatever else changes, the extension has to stay.let derived = VPhoneRestoreLayout.shshOutput(vmDir: URL(fileURLWithPath: "/tmp/vm"),- ecid: 0xAABB+ ecid: 0xAABB,)#expect(derived.pathExtension == "shsh")#expect(derived.deletingPathExtension().lastPathComponent == "000000000000AABB")diff --git a/tests/VPhoneRestoreTests/RestoreOptionsTests.swift b/tests/VPhoneRestoreTests/RestoreOptionsTests.swiftindex d4b6efea..c8c31754 100644--- a/tests/VPhoneRestoreTests/RestoreOptionsTests.swift+++ b/tests/VPhoneRestoreTests/RestoreOptionsTests.swift@@ -40,14 +40,14 @@ struct RestoreOptionsTests {debugLevel: c.debug_level,hasLogCallback: c.log_cb != nil,hasProgressCallback: c.progress_cb != nil,- hasContext: c.context != nil+ hasContext: c.context != nil,)}}// MARK: - Mapping- @Test func everyFieldReachesTheCStruct() {+ @Test func `every field reaches the C struct`() {let options = VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),cacheDirectory: URL(fileURLWithPath: "/tmp/cache"),@@ -57,7 +57,7 @@ struct RestoreOptionsTests {ticketPath: URL(fileURLWithPath: "/tmp/vm/000000011A2B3C4D.shsh"),shshOnly: false,keepPers: true,- debugLevel: 2+ debugLevel: 2,)let c = snapshot(options)#expect(c.restoreDir == "/tmp/vm/iPhone17,3_Restore")@@ -71,11 +71,11 @@ struct RestoreOptionsTests {#expect(c.debugLevel == 2)}- @Test func absentOptionalsBecomeNullNotEmptyStrings() {+ @Test func `absent optionals become null not empty strings`() {// A `udid` of "" is a device whose UDID is the empty string, which// matches nothing; NULL is "whichever device is attached".let options = VPhoneRestoreOptions(- restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore")+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),)let c = snapshot(options)#expect(c.cacheDir == nil)@@ -83,11 +83,11 @@ struct RestoreOptionsTests {#expect(c.ticketPath == nil)}- @Test func defaultsAreAnOnlineEraseRestore() {+ @Test func `defaults are an online erase restore`() {// Which is what `restore-update` did with no flags: Behavior.Erase,// a ticket from Apple, no debug logging.let c = snapshot(VPhoneRestoreOptions(- restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore")+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),))#expect(c.erase)#expect(c.ecid == 0)@@ -97,70 +97,70 @@ struct RestoreOptionsTests {#expect(c.ticketPath == nil)}- @Test func updateInPlaceClearsErase() {+ @Test func `update in place clears erase`() {// pymobiledevice3's Behavior.Update, the bridge's `--no-erase`.let c = snapshot(VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),- erase: false+ erase: false,))#expect(!c.erase)}- @Test func eraseAndShshOnlyAreIndependent() {+ @Test func `erase and shsh only are independent`() {// The SHSH fetch asks for an ERASE ticket and stops before the device;// both bits are set, and swapping them would fetch the wrong blob.let c = snapshot(VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),erase: true,- shshOnly: true+ shshOnly: true,))#expect(c.erase)#expect(c.shshOnly)}- @Test func callbackFieldsAreLeftForTheRunner() {+ @Test func `callback fields are left for the runner`() {// `withCOptions` maps the data only; `VPhoneRestoreRunner` installs the// function pointers and the context on its own copy.let c = snapshot(VPhoneRestoreOptions(- restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore")+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),))#expect(!c.hasLogCallback)#expect(!c.hasProgressCallback)#expect(!c.hasContext)}- @Test func pathsAreTakenFromTheURLNotItsDescription() {+ @Test func `paths are taken from the URL not its description`() {// A URL's description is "file:///…"; its `path` is what a C API wants.let c = snapshot(VPhoneRestoreOptions(- restoreDirectory: URL(fileURLWithPath: "/tmp/a space/iPhone17,3_Restore")+ restoreDirectory: URL(fileURLWithPath: "/tmp/a space/iPhone17,3_Restore"),))#expect(c.restoreDir == "/tmp/a space/iPhone17,3_Restore")}// MARK: - Storage lifetime- @Test func eachCallGetsItsOwnStorage() {+ @Test func `each call gets its own storage`() {// `withCOptions` frees its strings on the way out, so two snapshots// taken separately must not alias — a stale pointer here would be a// use-after-free inside idevicerestore.let first = snapshot(VPhoneRestoreOptions(- restoreDirectory: URL(fileURLWithPath: "/tmp/one/iPhone17,3_Restore")+ restoreDirectory: URL(fileURLWithPath: "/tmp/one/iPhone17,3_Restore"),))let second = snapshot(VPhoneRestoreOptions(- restoreDirectory: URL(fileURLWithPath: "/tmp/two/iPhone17,3_Restore")+ restoreDirectory: URL(fileURLWithPath: "/tmp/two/iPhone17,3_Restore"),))#expect(first.restoreDir == "/tmp/one/iPhone17,3_Restore")#expect(second.restoreDir == "/tmp/two/iPhone17,3_Restore")}- @Test func nestedCallsDoNotClobberEachOther() {+ @Test func `nested calls do not clobber each other`() {let outer = VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/outer"))let inner = VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/inner"))let pair = outer.withCOptions { outerC ininner.withCOptions { innerC in(outerC.restore_dir.map { String(cString: $0) },- innerC.restore_dir.map { String(cString: $0) }+ innerC.restore_dir.map { String(cString: $0) },)}}diff --git a/tests/VPhoneRestoreTests/RestoreRunnerTests.swift b/tests/VPhoneRestoreTests/RestoreRunnerTests.swiftindex 9807bd5d..30336836 100644--- a/tests/VPhoneRestoreTests/RestoreRunnerTests.swift+++ b/tests/VPhoneRestoreTests/RestoreRunnerTests.swift@@ -37,7 +37,9 @@ struct RestoreRunnerTests {lock.lock()defer { lock.unlock() }return events.compactMap { event in- if case let .log(_, message) = event { return message }+ if case let .log(_, message) = event {+ return message+ }return nil}}@@ -46,7 +48,9 @@ struct RestoreRunnerTests {lock.lock()defer { lock.unlock() }return events.compactMap { event in- if case let .log(level, message) = event, level == .error { return message }+ if case let .log(level, message) = event, level == .error {+ return message+ }return nil}}@@ -62,14 +66,14 @@ struct RestoreRunnerTests {// MARK: - Restore directory- @Test func anAbsentRestoreDirectoryIsRejectedAndReported() throws {+ @Test func `an absent restore directory is rejected and reported`() throws {let absent = URL(fileURLWithPath: "/nonexistent/vphone/iPhone17,3_Restore")let collector = Collector()#expect(throws: VPhoneRestoreBackendError.restoreDirectoryUnusable(absent)) {try VPhoneRestoreRunner.run(VPhoneRestoreOptions(restoreDirectory: absent),- onEvent: { collector.record($0) }+ onEvent: { collector.record($0) },)}@@ -80,7 +84,7 @@ struct RestoreRunnerTests {#expect(errors.contains { $0.contains("/nonexistent/vphone/iPhone17,3_Restore") })}- @Test func aFileIsNotARestoreDirectory() throws {+ @Test func `a file is not A restore directory`() throws {try withTemporaryDirectory { root in// This build has no libzip, so a .ipsw is refused here by name// rather than failing four layers down in src/ipsw.c.@@ -91,7 +95,7 @@ struct RestoreRunnerTests {#expect(throws: VPhoneRestoreBackendError.restoreDirectoryUnusable(archive)) {try VPhoneRestoreRunner.run(VPhoneRestoreOptions(restoreDirectory: archive),- onEvent: { collector.record($0) }+ onEvent: { collector.record($0) },)}#expect(collector.errorMessages.contains { $0.contains("not a directory") })@@ -100,7 +104,7 @@ struct RestoreRunnerTests {// MARK: - Ticket- @Test func anOfflineTicketThatIsNotAPlistIsRejected() throws {+ @Test func `an offline ticket that is not A plist is rejected`() throws {try withTemporaryDirectory { root in// A real directory, so the run gets past the restore-dir checks and// into the offline-ticket loader — still without a device, because@@ -114,14 +118,14 @@ struct RestoreRunnerTests {#expect(throws: VPhoneRestoreBackendError.ticketUnreadable(ticket)) {try VPhoneRestoreRunner.run(VPhoneRestoreOptions(restoreDirectory: restoreDirectory, ticketPath: ticket),- onEvent: { collector.record($0) }+ onEvent: { collector.record($0) },)}#expect(collector.errorMessages.contains { $0.contains(ticket.path) })}}- @Test func aRunWithoutACallbackIsStillSafe() throws {+ @Test func `a run without A callback is still safe`() throws {// The default handler discards, and the C side takes NULL for the// context it never uses. Nothing here may dereference it anyway.let absent = URL(fileURLWithPath: "/nonexistent/vphone/iPhone17,3_Restore")@@ -132,7 +136,7 @@ struct RestoreRunnerTests {// MARK: - The facade- @Test func fetchingASHSHStopsAtTheMissingRestoreTree() throws {+ @Test func `fetching ASHSH stops at the missing restore tree`() throws {// `VPhoneRestoreBridge` finds the restore tree BEFORE it starts a run,// so an empty bundle never reaches idevicerestore at all.try withTemporaryDirectory { root in@@ -142,7 +146,7 @@ struct RestoreRunnerTests {}}- @Test func restoringStopsAtTheMissingRestoreTree() throws {+ @Test func `restoring stops at the missing restore tree`() throws {try withTemporaryDirectory { root in#expect(throws: VPhoneRestoreBackendError.noRestoreDirectory(root)) {try VPhoneRestoreBridge.restore(@@ -150,13 +154,13 @@ struct RestoreRunnerTests {ecid: nil,udid: nil,erase: true,- ticketPath: nil+ ticketPath: nil,)}}}- @Test func theCachedSHSHNoticeIsPrintedBeforeTheRestoreStarts() throws {+ @Test func `the cached SHSH notice is printed before the restore starts`() throws {try withTemporaryDirectory { root in// Python printed "[+] Using cached SHSH: …" the moment it loaded// the blob. Users grep for that line, so it has to survive — and it@@ -174,7 +178,7 @@ struct RestoreRunnerTests {udid: nil,erase: true,ticketPath: ticket,- onEvent: { collector.record($0) }+ onEvent: { collector.record($0) },)}#expect(collector.messages.contains("[+] Using cached SHSH: \(ticket.path)"))diff --git a/tests/VPhoneRestoreTests/RestoreTicketTests.swift b/tests/VPhoneRestoreTests/RestoreTicketTests.swiftindex ae08e852..b6f740a4 100644--- a/tests/VPhoneRestoreTests/RestoreTicketTests.swift+++ b/tests/VPhoneRestoreTests/RestoreTicketTests.swift@@ -1,7 +1,7 @@import Foundationimport Testing-import zlib@testable import VPhoneRestore+import zlib/// Turning what idevicerestore's `-t/--shsh` wrote into what this project has/// always kept beside a VM: a gzipped binary plist under@@ -36,7 +36,7 @@ struct RestoreTicketTests {8,Z_DEFAULT_STRATEGY,zlibVersion(),- Int32(MemoryLayout<z_stream>.size)+ Int32(MemoryLayout<z_stream>.size),)try #require(started == Z_OK)defer { deflateEnd(&stream) }@@ -54,9 +54,15 @@ struct RestoreTicketTests {return deflate(&stream, Z_FINISH)}let produced = chunk.count - Int(stream.avail_out)- if produced > 0 { output.append(contentsOf: chunk[0..<produced]) }- if status == Z_STREAM_END { break }- if status != Z_OK { break }+ if produced > 0 {+ output.append(contentsOf: chunk[0 ..< produced])+ }+ if status == Z_STREAM_END {+ break+ }+ if status != Z_OK {+ break+ }}}return output@@ -71,7 +77,7 @@ struct RestoreTicketTests {("1-iPhone17,3-26.0.shsh", UInt64(1)),("18446744073709551615-iPhone17,3-26.0.shsh", UInt64.max),])- func readsTheDecimalECIDOffTheFilename(_ name: String, _ expected: UInt64) {+ func `reads the decimal ECID off the filename`(_ name: String, _ expected: UInt64) {// idevicerestore prints client->ecid in DECIMAL there, and it is the// ECID the device reported — which is how a fetch with no --ecid still// produces a named .shsh, exactly as Python's@@ -80,18 +86,18 @@ struct RestoreTicketTests {}@Test(arguments: ["shsh", "-iPhone17,3-26.0.shsh", "auto.shsh", "iPhone17,3-26.0.shsh", ""])- func aFilenameWithoutALeadingECIDGivesNothing(_ name: String) {+ func `a filename without A leading ECID gives nothing`(_ name: String) {#expect(VPhoneRestoreTicket.ecid(fromSHSHFilename: name) == nil)}- @Test func anECIDTooLargeForSixtyFourBitsGivesNothing() {+ @Test func `an ECID too large for sixty four bits gives nothing`() {// Rather than wrapping into some other device's identifier.#expect(VPhoneRestoreTicket.ecid(fromSHSHFilename: "99999999999999999999-x-y.shsh") == nil)}// MARK: - Magic- @Test func recognisesTheGzipMagic() {+ @Test func `recognises the gzip magic`() {#expect(VPhoneRestoreTicket.isGzipped(Data([0x1F, 0x8B, 0x08, 0x00])))#expect(!VPhoneRestoreTicket.isGzipped(Data("<?xml".utf8)))#expect(!VPhoneRestoreTicket.isGzipped(Data("bplist00".utf8)))@@ -101,7 +107,7 @@ struct RestoreTicketTests {// MARK: - Decompression- @Test func inflatesWhatGzipWrote() throws {+ @Test func `inflates what gzip wrote`() throws {let original = Data("the quick brown fox, repeated: \(String(repeating: "ab", count: 5000))".utf8)let compressed = try gzip(original)#expect(VPhoneRestoreTicket.isGzipped(compressed))@@ -109,23 +115,25 @@ struct RestoreTicketTests {#expect(inflated == original)}- @Test func inflatesAcrossTheOutputChunkBoundary() throws {+ @Test func `inflates across the output chunk boundary`() throws {// The inflate loop refills a 64 KiB buffer; a blob bigger than that is// the case that finds an off-by-one in the refill.var original = Data()- for index in 0..<400_000 { original.append(UInt8(index % 251)) }- let inflated = try #require(VPhoneRestoreTicket.gunzip(try gzip(original)))+ for index in 0 ..< 400_000 {+ original.append(UInt8(index % 251))+ }+ let inflated = try #require(try VPhoneRestoreTicket.gunzip(gzip(original)))#expect(inflated.count == original.count)#expect(inflated == original)}- @Test func refusesGarbageRatherThanLoopingOnIt() {+ @Test func `refuses garbage rather than looping on it`() {#expect(VPhoneRestoreTicket.gunzip(Data([0x1F, 0x8B, 0x00, 0x01, 0x02, 0x03])) == nil)#expect(VPhoneRestoreTicket.gunzip(Data()) == nil)#expect(VPhoneRestoreTicket.gunzip(Data("not compressed at all".utf8)) == nil)}- @Test func refusesATruncatedStream() throws {+ @Test func `refuses A truncated stream`() throws {let compressed = try gzip(Data(repeating: 0x5A, count: 100_000))let truncated = compressed.prefix(compressed.count / 2)#expect(VPhoneRestoreTicket.gunzip(Data(truncated)) == nil)@@ -133,7 +141,7 @@ struct RestoreTicketTests {// MARK: - Reading a .shsh- @Test func readsTheGzippedBinaryPlistIdevicerestoreWrites() throws {+ @Test func `reads the gzipped binary plist idevicerestore writes`() throws {let binary = try plist(tssResponse, format: .binary)let onDisk = try gzip(binary)let recovered = try VPhoneRestoreTicket.plistData(of: onDisk, at: anyPath)@@ -144,7 +152,7 @@ struct RestoreTicketTests {#expect((parsed as? [String: Any])?["ApImg4Ticket"] is Data)}- @Test func readsThePlainXMLPlistThePythonBridgeWrote() throws {+ @Test func `reads the plain XML plist the python bridge wrote`() throws {// plistlib.dump defaults to XML, so every .shsh already sitting in a// bundle is this shape.let xml = try plist(tssResponse, format: .xml)@@ -152,19 +160,19 @@ struct RestoreTicketTests {#expect(recovered == xml)}- @Test func readsABareBinaryPlist() throws {+ @Test func `reads A bare binary plist`() throws {let binary = try plist(tssResponse, format: .binary)let recovered = try VPhoneRestoreTicket.plistData(of: binary, at: anyPath)#expect(recovered == binary)}- @Test func rejectsSomethingThatIsNotAPlist() {+ @Test func `rejects something that is not A plist`() {#expect(throws: VPhoneRestoreBackendError.shshMalformed(anyPath)) {try VPhoneRestoreTicket.plistData(of: Data("just some bytes".utf8), at: anyPath)}}- @Test func rejectsAPlistThatIsNotADictionary() throws {+ @Test func `rejects A plist that is not A dictionary`() throws {// A TSS response is a dict with an entry per component. An array here// means the wrong file, and hearing that now beats hearing it from a// device that rejects every component it is sent.@@ -174,14 +182,14 @@ struct RestoreTicketTests {}}- @Test func rejectsAGzipStreamOfSomethingThatIsNotAPlist() throws {+ @Test func `rejects A gzip stream of something that is not A plist`() throws {let compressed = try gzip(Data("hello, not a plist".utf8))#expect(throws: VPhoneRestoreBackendError.shshMalformed(anyPath)) {try VPhoneRestoreTicket.plistData(of: compressed, at: anyPath)}}- @Test func reportsADamagedGzipSeparatelyFromADamagedPlist() {+ @Test func `reports A damaged gzip separately from A damaged plist`() {// Different fixes: one is a corrupt file, the other is the wrong file.#expect(throws: VPhoneRestoreBackendError.shshNotDecompressible(anyPath)) {try VPhoneRestoreTicket.plistData(of: Data([0x1F, 0x8B, 0x08, 0xFF, 0x00]), at: anyPath)diff --git a/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift b/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swiftindex ad5a3647..cb1a15bd 100644--- a/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift+++ b/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift@@ -17,8 +17,8 @@ struct VPhoneSignEntitlementsTests {////// The seeded fixtures carry the interesting cases: a long sandbox profile/// in a `<data>`, arrays, and the integers.- @Test("dump matches ldid -e byte for byte")- func dumpMatchesLdid() throws {+ @Test+ func `dump matches ldid -e byte for byte`() throws {let corpus = try VPhoneSignFixtures.fixtures#expect(corpus.count >= 12, "only \(corpus.count) fixtures: too few to say anything")var withEntitlements = 0@@ -26,18 +26,20 @@ struct VPhoneSignEntitlementsTests {let name = source.lastPathComponentlet ours = try VPhoneSigner.entitlements(ofFileAt: source).reduce(Data(), +)try VPhoneSignFixtures.expect("\(name).dump", matches: ours)- if !ours.isEmpty { withEntitlements += 1 }+ if !ours.isEmpty {+ withEntitlements += 1+ }}#expect(withEntitlements >= 7, "only \(withEntitlements) fixtures had entitlements to print")}- @Test("a file this signed reads back the entitlements it was given")- func roundTrip() throws {+ @Test+ func `a file this signed reads back the entitlements it was given`() throws {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let plist = VPhoneSignParityTests.sampleEntitlementslet file = try VPhoneSignFixtures.sign(- try VPhoneSignFixtures.url("hello-arm64"), in: directory, entitlements: plist+ VPhoneSignFixtures.url("hello-arm64"), in: directory, entitlements: plist,)let read = try VPhoneSigner.entitlements(ofFileAt: file)@@ -54,8 +56,8 @@ struct VPhoneSignEntitlementsTests {// MARK: - What the writer must agree with libplist about- @Test("the XML writer keeps the order libplist keeps, not Foundation's")- func keepsInsertionOrder() throws {+ @Test+ func `the XML writer keeps the order libplist keeps, not Foundation's`() throws {// "b" before "a": Foundation would sort them, libplist would not, and// the bytes are hashed into the signaturelet plist = Data("""@@ -72,14 +74,14 @@ struct VPhoneSignEntitlementsTests {""".utf8)let entitlements = try VPhoneSignEntitlements(xml: plist)- let written = String(decoding: try entitlements.xml(), as: UTF8.self)+ let written = try String(decoding: entitlements.xml(), as: UTF8.self)let zeta = try #require(written.range(of: "zeta"))let alpha = try #require(written.range(of: "alpha"))#expect(zeta.lowerBound < alpha.lowerBound, "the keys were sorted")}- @Test("a merge replaces a key where it stands and appends a new one")- func mergeKeepsPositions() throws {+ @Test+ func `a merge replaces a key where it stands and appends a new one`() throws {var base = try VPhoneSignEntitlements(xml: Data("""<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>@@ -87,7 +89,7 @@ struct VPhoneSignEntitlementsTests {\t<key>second</key><true/></dict></plist>""".utf8))- base.merge(try VPhoneSignEntitlements(xml: Data("""+ try base.merge(VPhoneSignEntitlements(xml: Data("""<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>\t<key>first</key><string>new</string>@@ -101,8 +103,8 @@ struct VPhoneSignEntitlementsTests {/// The executable segment flags ldid derives. Getting these wrong is/// silent: the binary signs, and then the guest refuses to debug it or/// lets it do something it should not.- @Test("executable segment flags follow the entitlements")- func executableSegmentFlags() throws {+ @Test+ func `executable segment flags follow the entitlements`() throws {let entitlements = try VPhoneSignEntitlements(xml: Data("""<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>@@ -136,7 +138,6 @@ struct VPhoneSignEntitlementsTests {/// asserted present, since a signature that wrote neither would have/// nothing to disagree about.@Test(- "every <integer> ldid takes is carried the way ldid carries it",arguments: ["0", // 020100 — the one that broke spindump"-1", // 0208ffffffffffffffff, the same bits as 2^64-1@@ -158,9 +159,9 @@ struct VPhoneSignEntitlementsTests {"9223372036854775808", // above Int64.max: libplist prints it unsigned"18446744073709551615", // UInt64.max" 42 ", // libplist skips the space around it- ]+ ],)- func integerSpellingsMatchLdid(_ spelling: String) throws {+ func `every <integer> ldid takes is carried the way ldid carries it`(_ spelling: String) throws {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }@@ -171,10 +172,10 @@ struct VPhoneSignEntitlementsTests {// `binary` is the identifier these rows were frozen under; see the// regeneration note in VPhoneSignFixtureslet ours = try VPhoneSignFixtures.sign(- try VPhoneSignFixtures.url("hello-arm64"),+ VPhoneSignFixtures.url("hello-arm64"),in: directory,identifier: "binary",- entitlements: plist+ entitlements: plist,)try VPhoneSignFixtures.expect("integer.\(spelling)", matches: Data(contentsOf: ours))@@ -182,7 +183,7 @@ struct VPhoneSignEntitlementsTests {for slot in [UInt32(5), 7] {#expect(slice[slot] != nil,- "<integer>\(spelling)</integer> slice \(index): no slot \(slot)"+ "<integer>\(spelling)</integer> slice \(index): no slot \(slot)",)}}@@ -200,10 +201,9 @@ struct VPhoneSignEntitlementsTests {/// observation for the same reason every other row is — running ldid to/// re-confirm it would put the dependency back.@Test(- "what ldid's DER has no room for is refused, as ldid refuses it",- arguments: ["<date>2020-01-01T00:00:00Z</date>", "<real>1.5</real>"]+ arguments: ["<date>2020-01-01T00:00:00Z</date>", "<real>1.5</real>"],)- func refusesWhatItCannotCarry(_ value: String) throws {+ func `what ldid's DER has no room for is refused, as ldid refuses it`(_ value: String) throws {let plist = Data("""<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>k</key>\(value)</dict></plist>@@ -227,7 +227,6 @@ struct VPhoneSignEntitlementsTests {/// No claim about the installed ldid is made here: it accepts these/// today. That is the point of refusing them.@Test(- "an <integer> the two libplists disagree about is refused",arguments: ["42abc", // released reads 42; master stops on the trailing text"abc", // released reads 0@@ -237,9 +236,9 @@ struct VPhoneSignEntitlementsTests {"-18446744073709551615", // released wraps it; master calls it out of range"0x", // a hex prefix with no digits: released reads the 0 and stops"--1", // the one both agree on and this refuses anyway; see integer(_:)- ]+ ],)- func refusesWhatTwoLibplistsReadDifferently(_ spelling: String) throws {+ func `an <integer> the two libplists disagree about is refused`(_ spelling: String) throws {let plist = Data("""<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>k</key><integer>\(spelling)</integer></dict></plist>@@ -249,10 +248,10 @@ struct VPhoneSignEntitlementsTests {}}- @Test("a binary plist is refused rather than read as XML")- func refusesABinaryPlist() throws {+ @Test+ func `a binary plist is refused rather than read as XML`() throws {let binary = try PropertyListSerialization.data(- fromPropertyList: ["k": true], format: .binary, options: 0+ fromPropertyList: ["k": true], format: .binary, options: 0,)#expect(throws: VPhoneSignError.self) {_ = try VPhoneSignEntitlements(xml: binary)diff --git a/tests/VPhoneSignTests/VPhoneSignFixtures.swift b/tests/VPhoneSignTests/VPhoneSignFixtures.swiftindex d0cda5ac..f003f559 100644--- a/tests/VPhoneSignTests/VPhoneSignFixtures.swift+++ b/tests/VPhoneSignTests/VPhoneSignFixtures.swift@@ -135,7 +135,7 @@ enum VPhoneSignFixtures {let url = root.appendingPathComponent(name)try #require(FileManager.default.fileExists(atPath: url.path),- "fixture \"\(name)\" is missing from \(root.path); the corpus is committed, not built"+ "fixture \"\(name)\" is missing from \(root.path); the corpus is committed, not built",)return url}@@ -154,12 +154,12 @@ enum VPhoneSignFixtures {static func expect(_ key: String,matches data: Data,- sourceLocation: SourceLocation = #_sourceLocation+ sourceLocation: SourceLocation = #_sourceLocation,) throws {let frozen = try #require(expected[key],"no frozen digest for \"\(key)\" — a typo, or a row the table never had",- sourceLocation: sourceLocation+ sourceLocation: sourceLocation,)let ours = digest(data)#expect(@@ -169,7 +169,7 @@ enum VPhoneSignFixtures {ldid \(frozen)ours \(ours)""",- sourceLocation: sourceLocation+ sourceLocation: sourceLocation,)}@@ -177,19 +177,21 @@ enum VPhoneSignFixtures {static func expect(length key: String,is length: Int,- sourceLocation: SourceLocation = #_sourceLocation+ sourceLocation: SourceLocation = #_sourceLocation,) throws {let frozen = try #require(expectedLengths[key],"no frozen length for \"\(key)\"",- sourceLocation: sourceLocation+ sourceLocation: sourceLocation,)#expect(length == frozen, "\(key): ldid \(frozen) bytes, ours \(length)", sourceLocation: sourceLocation)}/// Whether the table has a row at all, for the cases that assert a blob is/// present exactly when ldid wrote one.- static func isFrozen(_ key: String) -> Bool { expected[key] != nil }+ static func isFrozen(_ key: String) -> Bool {+ expected[key] != nil+ }// MARK: - Working files@@ -253,7 +255,7 @@ enum VPhoneSignFixtures {entitlements: Data? = nil,mergesExisting: Bool = false,style: VPhoneSignOptions.Style = .ldid,- identity: (any VPhoneSigningIdentity)? = nil+ identity: (any VPhoneSigningIdentity)? = nil,) throws -> URL {let name = fixture.lastPathComponentlet file = try copy(fixture, into: directory, as: name)@@ -262,7 +264,7 @@ enum VPhoneSignFixtures {entitlements: entitlements,mergesExisting: mergesExisting,style: style,- identity: identity+ identity: identity,))return file}diff --git a/tests/VPhoneSignTests/VPhoneSignParityTests.swift b/tests/VPhoneSignTests/VPhoneSignParityTests.swiftindex f9db1dcb..5f9d3a0a 100644--- a/tests/VPhoneSignTests/VPhoneSignParityTests.swift+++ b/tests/VPhoneSignTests/VPhoneSignParityTests.swift@@ -20,14 +20,14 @@ import Testingstruct VPhoneSignParityTests {// MARK: - Ad-hoc, which is nearly every call- @Test("ldid -S")- func adHoc() throws {+ @Test+ func `ldid -S`() throws {let corpus = try VPhoneSignFixtures.fixtures// a corpus that shrank to nothing would make every one of these pass#expect(corpus.count >= 12, "only \(corpus.count) fixtures: too few to say anything")#expect(corpus.contains { (try? Data(contentsOf: $0).prefix(4)) == Data([0xCA, 0xFE, 0xBA, 0xBE]) },- "no fat binary in the corpus"+ "no fat binary in the corpus",)for source in corpus {let directory = try VPhoneSignFixtures.temporaryDirectory()@@ -41,8 +41,8 @@ struct VPhoneSignParityTests {// MARK: - Entitlements- @Test("ldid -S<entitlements>")- func entitlements() throws {+ @Test+ func `ldid -S<entitlements>`() throws {let corpus = try VPhoneSignFixtures.fixtures#expect(corpus.count >= 12, "only \(corpus.count) fixtures: too few to say anything")for source in corpus {@@ -51,7 +51,7 @@ struct VPhoneSignParityTests {let name = source.lastPathComponentlet ours = try VPhoneSignFixtures.sign(- source, in: directory, entitlements: Self.sampleEntitlements+ source, in: directory, entitlements: Self.sampleEntitlements,)try VPhoneSignFixtures.expect("\(name).entitlements", matches: Data(contentsOf: ours))}@@ -64,8 +64,8 @@ struct VPhoneSignParityTests {/// nothing anybody here composed. The five `hello-*` files carry none,/// which is the other half of the claim: over them the merge has to be a/// no-op and land exactly where `ldid -S<ent>` lands.- @Test("ldid -S<entitlements> -M over a seeded signature")- func merged() throws {+ @Test+ func `ldid -S<entitlements> -M over a seeded signature`() throws {let corpus = try VPhoneSignFixtures.fixtures#expect(corpus.count >= 12, "only \(corpus.count) fixtures: too few to say anything")var seeded = 0@@ -78,7 +78,7 @@ struct VPhoneSignParityTests {}let ours = try VPhoneSignFixtures.sign(- source, in: directory, entitlements: Self.sampleEntitlements, mergesExisting: true+ source, in: directory, entitlements: Self.sampleEntitlements, mergesExisting: true,)try VPhoneSignFixtures.expect("\(name).mergeSample", matches: Data(contentsOf: ours))}@@ -101,8 +101,8 @@ struct VPhoneSignParityTests {/// `seeded-promotedcontentd` a value above `Int32.max`,/// `seeded-runningboardd` two different ones and/// `seeded-sysdiagnose_helper` six.- @Test("ldid -S -M over a binary's own entitlements, which is what cfw_install calls")- func mergedWithoutAFile() throws {+ @Test+ func `ldid -S -M over a binary's own entitlements, which is what cfw_install calls`() throws {let corpus = try VPhoneSignFixtures.fixtures#expect(corpus.count >= 12, "only \(corpus.count) fixtures: too few to say anything")var merged = 0@@ -111,7 +111,9 @@ struct VPhoneSignParityTests {defer { try? FileManager.default.removeItem(at: directory) }let name = source.lastPathComponentlet carries = try VPhoneSigner.entitlements(ofFileAt: source).contains { !$0.isEmpty }- if carries { merged += 1 }+ if carries {+ merged += 1+ }let ours = try VPhoneSignFixtures.sign(source, in: directory, mergesExisting: true)try VPhoneSignFixtures.expect("\(name).mergeOwn", matches: Data(contentsOf: ours))@@ -123,7 +125,7 @@ struct VPhoneSignParityTests {#expect(VPhoneSignFixtures.expected["\(name).mergeOwn"]!= VPhoneSignFixtures.expected["\(name).adhoc"],- "\(name): ldid's -S -M and its -S agree, so the merge carried nothing"+ "\(name): ldid's -S -M and its -S agree, so the merge carried nothing",)}}@@ -140,8 +142,8 @@ struct VPhoneSignParityTests {/// corpus; what this adds is the guard that every one of the seven really/// did arrive with a list, and that merging over it is not the same as/// replacing it.- @Test("ldid -S<entitlements> -M over a binary's own entitlements")- func mergedOverOwnEntitlements() throws {+ @Test+ func `ldid -S<entitlements> -M over a binary's own entitlements`() throws {let seeded = try VPhoneSignFixtures.seeded// Without this the loop body can never run and the test passes having// compared nothing. Its sibling `mergedWithoutAFile` carries the same@@ -153,11 +155,11 @@ struct VPhoneSignParityTests {let name = source.lastPathComponent#expect(try VPhoneSigner.entitlements(ofFileAt: source).contains { !$0.isEmpty },- "\(name) carries no entitlements, so there is nothing here to merge over"+ "\(name) carries no entitlements, so there is nothing here to merge over",)let ours = try VPhoneSignFixtures.sign(- source, in: directory, entitlements: Self.sampleEntitlements, mergesExisting: true+ source, in: directory, entitlements: Self.sampleEntitlements, mergesExisting: true,)try VPhoneSignFixtures.expect("\(name).mergeSample", matches: Data(contentsOf: ours))@@ -165,7 +167,7 @@ struct VPhoneSignParityTests {#expect(VPhoneSignFixtures.expected["\(name).mergeSample"]!= VPhoneSignFixtures.expected["\(name).entitlements"],- "\(name): ldid's -S<ent> -M and its -S<ent> agree, so the merge dropped the existing list"+ "\(name): ldid's -S<ent> -M and its -S<ent> agree, so the merge dropped the existing list",)}}@@ -173,8 +175,8 @@ struct VPhoneSignParityTests {/// `-I`, which a handful of call sites use to sign under an Apple/// identifier (`com.apple.seputil` and friends) rather than the file's/// name.- @Test("ldid -I<identifier>")- func explicitIdentifier() throws {+ @Test+ func `ldid -I<identifier>`() throws {let corpus = try VPhoneSignFixtures.fixtures#expect(corpus.count >= 12, "only \(corpus.count) fixtures: too few to say anything")for source in corpus {@@ -196,15 +198,15 @@ struct VPhoneSignParityTests {/// production logic — `options.identifier ?? url.lastPathComponent` —/// covered by nothing, so it is covered here, and structurally: the name/// is read back out of the CodeDirectory rather than compared to a digest.- @Test("an unset identifier defaults to the file's name, as ldid does")- func identifierDefaultsToTheFileName() throws {+ @Test+ func `an unset identifier defaults to the file's name, as ldid does`() throws {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }// deliberately not the fixture's name: the claim is that the signer// reads the name off the file it was handedlet name = "named-for-this-test"let file = try VPhoneSignFixtures.copy(- try VPhoneSignFixtures.url("hello-arm64"), into: directory, as: name+ VPhoneSignFixtures.url("hello-arm64"), into: directory, as: name,)try VPhoneSigner.sign(fileAt: file)@@ -218,8 +220,8 @@ struct VPhoneSignParityTests {/// Signing twice must land on the same bytes, or a rebuild of the CFW/// would produce a different image every time.- @Test("signing an already-signed file is idempotent")- func idempotent() throws {+ @Test+ func `signing an already-signed file is idempotent`() throws {for source in try VPhoneSignFixtures.fixtures {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }diff --git a/tests/VPhoneSignTests/VPhoneSignStyleTests.swift b/tests/VPhoneSignTests/VPhoneSignStyleTests.swiftindex 54bac78c..1f45d2e3 100644--- a/tests/VPhoneSignTests/VPhoneSignStyleTests.swift+++ b/tests/VPhoneSignTests/VPhoneSignStyleTests.swift@@ -10,8 +10,8 @@ struct VPhoneSignStyleTests {/// CMS blob — and rejects this signer's `.ldid` output for the same two/// reasons, which is the point. `.appleAdHoc` is the shape it accepts,/// kept for anything that has to satisfy the host rather than the guest.- @Test("the Apple ad-hoc style passes codesign --verify")- func appleAdHocVerifies() throws {+ @Test+ func `the Apple ad-hoc style passes codesign --verify`() throws {let codesign = URL(fileURLWithPath: "/usr/bin/codesign")for source in try VPhoneSignFixtures.fixtures {let directory = try VPhoneSignFixtures.temporaryDirectory()@@ -25,12 +25,12 @@ struct VPhoneSignStyleTests {}}- @Test("the Apple ad-hoc style sets the flag and writes the empty wrapper")- func appleAdHocShape() throws {+ @Test+ func `the Apple ad-hoc style sets the flag and writes the empty wrapper`() throws {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let file = try VPhoneSignFixtures.sign(- try VPhoneSignFixtures.url("hello-arm64"), in: directory, style: .appleAdHoc+ VPhoneSignFixtures.url("hello-arm64"), in: directory, style: .appleAdHoc,)for slice in try VPhoneSignBlobs(fileAt: file).slices {@@ -48,8 +48,8 @@ struct VPhoneSignStyleTests {// MARK: - Refusing rather than corrupting- @Test("a file that is not a Mach-O is refused")- func refusesSomethingElse() throws {+ @Test+ func `a file that is not a Mach-O is refused`() throws {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }let file = directory.appendingPathComponent("script.sh")@@ -61,8 +61,8 @@ struct VPhoneSignStyleTests {#expect(try Data(contentsOf: file) == Data("#!/bin/sh\necho hello\n".utf8))}- @Test("a truncated Mach-O is refused rather than signed over garbage")- func refusesATruncatedMachO() throws {+ @Test+ func `a truncated Mach-O is refused rather than signed over garbage`() throws {let whole = try Data(contentsOf: VPhoneSignFixtures.url("hello-arm64"))#expect(throws: VPhoneSignError.self) {_ = try VPhoneSigner.sign(whole.prefix(whole.count / 3), options: .init(identifier: "x"))@@ -72,8 +72,8 @@ struct VPhoneSignStyleTests {/// A Java class file opens with the four bytes of a fat Mach-O. Reading/// the next two as an architecture count is how a signer ends up writing/// over something it does not understand.- @Test("something that only starts like a fat Mach-O is refused")- func refusesAJavaClass() throws {+ @Test+ func `something that only starts like a fat Mach-O is refused`() throws {var file = Data([0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x41])file.append(Data(count: 512))#expect(throws: VPhoneSignError.self) {@@ -87,8 +87,8 @@ struct VPhoneSignStyleTests {/// slice on a guess is worse than saying so — and this is the rule that/// took the old corpus of fat system binaries out of this suite, so it is/// worth one test of its own.- @Test("an x86_64 slice is refused rather than signed on a guess")- func refusesAnX86Slice() throws {+ @Test+ func `an x86_64 slice is refused rather than signed on a guess`() throws {// MH_MAGIC_64, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL, MH_EXECUTE,// then ncmds/sizeofcmds/flags/reserved, all zerovar header = Data()@@ -104,8 +104,8 @@ struct VPhoneSignStyleTests {/// parent's indices. Every offset in the signer counts from the start of/// the file, so a slice that starts anywhere else has to be handled/// before the first byte is read.- @Test("a Data slice that does not start at zero signs the same as a copy")- func signsANonZeroBasedSlice() throws {+ @Test+ func `a Data slice that does not start at zero signs the same as a copy`() throws {let whole = try Data(contentsOf: VPhoneSignFixtures.url("hello-arm64"))let padded = Data(count: 7) + wholelet slice = padded[7...]@@ -118,14 +118,14 @@ struct VPhoneSignStyleTests {/// Signing a read-only file is the normal case, not the exception:/// everything unpacked out of an IPSW is mode 444, and the whole CFW/// pipeline signs those in place.- @Test("a read-only file is signed and keeps its mode")- func signsAReadOnlyFile() throws {+ @Test+ func `a read-only file is signed and keeps its mode`() throws {let directory = try VPhoneSignFixtures.temporaryDirectory()defer { try? FileManager.default.removeItem(at: directory) }// not through the shared helper: the mode has to be set between the// copy and the signaturelet file = try VPhoneSignFixtures.copy(- try VPhoneSignFixtures.url("hello-arm64"), into: directory, as: "binary"+ VPhoneSignFixtures.url("hello-arm64"), into: directory, as: "binary",)try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: file.path)