Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Format sources with swiftformat for Swift 6.2

Lakrb4f00fce42e4
diff --git a/Research/Guest/SettingsRows/CachePatch/main.swift b/Research/Guest/SettingsRows/CachePatch/main.swift
index 47ceb53e..13540a6a 100644
--- a/Research/Guest/SettingsRows/CachePatch/main.swift
+++ b/Research/Guest/SettingsRows/CachePatch/main.swift
@@ -1,40 +1,56 @@
-import Foundation
import CryptoKit
+import Foundation
import VPhonePatchKit
-struct Failure: Error {let message:String}
-func require(_ ok:Bool,_ message:String)throws{if !ok{throw Failure(message:message)}}
-func hash(_ d:Data)->String{SHA256.hash(data:d).map{String(format:"%02x",$0)}.joined()}
-func hex(_ s:String)->Data {Data(stride(from:0,to:s.count,by:2).map{let i=s.index(s.startIndex,offsetBy:$0);return UInt8(s[i..<s.index(i,offsetBy:2)],radix:16)!})}
+
+struct Failure: Error { let message: String }
+func require(_ ok: Bool, _ message: String) throws {
+ if !ok {
+ throw Failure(message: message)
+ }
+}
+
+func hash(_ d: Data) -> String {
+ SHA256.hash(data: d).map { String(format: "%02x", $0) }.joined()
+}
+
+func hex(_ s: String) -> Data {
+ Data(stride(from: 0, to: s.count, by: 2).map { let i = s.index(s.startIndex, offsetBy: $0); return UInt8(s[i ..< s.index(i, offsetBy: 2)], radix: 16)! })
+}
+
do {
- let args=CommandLine.arguments
- try require(args.count==5,"usage: tool original-chunk extracted-image discovery-manifest output-directory")
- let source=URL(fileURLWithPath:args[1]), fixture=try Data(contentsOf:URL(fileURLWithPath:args[2]))
- let manifest=try JSONSerialization.jsonObject(with:Data(contentsOf:URL(fileURLWithPath:args[3]))) as! [String:Any]
- try require(hash(fixture)==manifest["inputSHA256"] as? String,"extracted fixture hash mismatch")
- let changes=manifest["changes"] as! [[String:Any]]
- try require(changes.count==1 && changes[0]["provider"] as? String == "SoftwareUpdateListItemProvider","unexpected discovery manifest")
- let c=changes[0],va=UInt64((c["va"] as! String).dropFirst(2),radix:16)!,fo=c["fileOffset"] as! Int
- let before=hex(c["before"] as! String),after=hex(c["after"] as! String)
- try require(before.count==4 && ARM64Encoder.encodeB(from:Int(va),to:Int(va+4))==after,"invalid replacement")
- let original=try Data(contentsOf:source)
- let dir=URL(fileURLWithPath:args[4]),out=dir.appendingPathComponent("dyld_shared_cache_arm64e.36")
- try require(!FileManager.default.fileExists(atPath:out.path),"output exists")
- try FileManager.default.copyItem(at:source,to:out)
- let chunks=try DyldSharedCacheChunkSet(directory:dir,captureUndo:true)
- try require(try chunks.readAtVMA(va,length:4)==before,"cache site mismatch")
- try require(fo>=128 && fo+132<=fixture.count,"fixture bounds")
- try require(try chunks.readAtVMA(va-128,length:260)==fixture.subdata(in:(fo-128)..<(fo+132)),"surrounding code differs from reviewed image")
- try chunks.write(at:va,after)
- let report=try DyldSharedCacheCodeSignature.reattestRecordedWrites(in:chunks)
- try require(report.skipped.isEmpty,"signature pages skipped")
- if let undo=chunks.takeUndoLog(){try JSONEncoder().encode(undo).write(to:dir.appendingPathComponent("software-update-undo.json"),options:.withoutOverwriting)}
- let patched=try Data(contentsOf:out)
- let (url,range)=try chunks.fileRange(of:DyldSharedCacheWriteSpan(vma:va,length:4))
- guard let cd=try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk:url) else{throw Failure(message:"no code directory")}
- let page=range.lowerBound/cd.pageSize,slot=cd.slotOffset(forPage:page)
- try require(Data(SHA256.hash(data:patched.subdata(in:page*cd.pageSize..<(page+1)*cd.pageSize)))==patched.subdata(in:slot..<slot+32),"hash validation failed")
- try require(original.count==patched.count,"size changed")
- var count=0
- for i in original.indices where original[i] != patched[i] {try require(range.contains(i)||(slot..<slot+32).contains(i),"unexpected changed byte"); count+=1}
- print("sourceSHA256=\(hash(original)) outputSHA256=\(hash(patched)) changedBytes=\(count) site=\(range) page=\(page) hashSlot=\(slot)")
-} catch {fputs("ERROR: \(error)\n",stderr);exit(1)}
+ let args = CommandLine.arguments
+ try require(args.count == 5, "usage: tool original-chunk extracted-image discovery-manifest output-directory")
+ let source = URL(fileURLWithPath: args[1]), fixture = try Data(contentsOf: URL(fileURLWithPath: args[2]))
+ let manifest = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: args[3]))) as! [String: Any]
+ try require(hash(fixture) == manifest["inputSHA256"] as? String, "extracted fixture hash mismatch")
+ let changes = manifest["changes"] as! [[String: Any]]
+ try require(changes.count == 1 && changes[0]["provider"] as? String == "SoftwareUpdateListItemProvider", "unexpected discovery manifest")
+ let c = changes[0], va = UInt64((c["va"] as! String).dropFirst(2), radix: 16)!, fo = c["fileOffset"] as! Int
+ let before = hex(c["before"] as! String), after = hex(c["after"] as! String)
+ try require(before.count == 4 && ARM64Encoder.encodeB(from: Int(va), to: Int(va + 4)) == after, "invalid replacement")
+ let original = try Data(contentsOf: source)
+ let dir = URL(fileURLWithPath: args[4]), out = dir.appendingPathComponent("dyld_shared_cache_arm64e.36")
+ try require(!FileManager.default.fileExists(atPath: out.path), "output exists")
+ try FileManager.default.copyItem(at: source, to: out)
+ let chunks = try DyldSharedCacheChunkSet(directory: dir, captureUndo: true)
+ try require(chunks.readAtVMA(va, length: 4) == before, "cache site mismatch")
+ try require(fo >= 128 && fo + 132 <= fixture.count, "fixture bounds")
+ try require(chunks.readAtVMA(va - 128, length: 260) == fixture.subdata(in: (fo - 128) ..< (fo + 132)), "surrounding code differs from reviewed image")
+ try chunks.write(at: va, after)
+ let report = try DyldSharedCacheCodeSignature.reattestRecordedWrites(in: chunks)
+ try require(report.skipped.isEmpty, "signature pages skipped")
+ if let undo = chunks.takeUndoLog() {
+ try JSONEncoder().encode(undo).write(to: dir.appendingPathComponent("software-update-undo.json"), options: .withoutOverwriting)
+ }
+ let patched = try Data(contentsOf: out)
+ let (url, range) = try chunks.fileRange(of: DyldSharedCacheWriteSpan(vma: va, length: 4))
+ guard let cd = try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: url) else { throw Failure(message: "no code directory") }
+ let page = range.lowerBound / cd.pageSize, slot = cd.slotOffset(forPage: page)
+ try require(Data(SHA256.hash(data: patched.subdata(in: page * cd.pageSize ..< (page + 1) * cd.pageSize))) == patched.subdata(in: slot ..< slot + 32), "hash validation failed")
+ try require(original.count == patched.count, "size changed")
+ var count = 0
+ for i in original.indices where original[i] != patched[i] {
+ try require(range.contains(i) || (slot ..< slot + 32).contains(i), "unexpected changed byte"); count += 1
+ }
+ print("sourceSHA256=\(hash(original)) outputSHA256=\(hash(patched)) changedBytes=\(count) site=\(range) page=\(page) hashSlot=\(slot)")
+} catch { fputs("ERROR: \(error)\n", stderr); exit(1) }
diff --git a/Research/Guest/SettingsRows/GameCenterStandalonePatch.swift b/Research/Guest/SettingsRows/GameCenterStandalonePatch.swift
index 1559a2f7..ee05d34b 100644
--- a/Research/Guest/SettingsRows/GameCenterStandalonePatch.swift
+++ b/Research/Guest/SettingsRows/GameCenterStandalonePatch.swift
@@ -1,123 +1,172 @@
import Foundation
+
struct InvalidImage: Error, CustomStringConvertible { let description: String }
struct Image {
- let data: Data
- struct Segment { let va: UInt64; let size: UInt64; let file: Int }
- struct Section { let name: String; let va: UInt64; let size: Int; let file: Int }
- var segments: [Segment] = []
- var sections: [Section] = []
- var starts: Set<UInt64> = []
- func check(_ p:Int,_ n:Int) throws { guard p>=0,n>=0,p<=data.count,n<=data.count-p else {throw InvalidImage(description:"out of bounds \(p), \(n)")} }
- func word(_ p:Int) throws -> UInt32 {try check(p,4);return data.withUnsafeBytes{UInt32(littleEndian:$0.loadUnaligned(fromByteOffset:p,as:UInt32.self))}}
- func quad(_ p:Int) throws -> UInt64 {try check(p,8);return data.withUnsafeBytes{UInt64(littleEndian:$0.loadUnaligned(fromByteOffset:p,as:UInt64.self))}}
- func name(_ p:Int,_ max:Int=512) throws -> String {try check(p,1);let end=min(data.count,p+max);guard let z=data[p..<end].firstIndex(of:0) else {throw InvalidImage(description:"unterminated string")};return String(decoding:data[p..<z],as:UTF8.self)}
- func offset(_ va:UInt64) throws -> Int {guard let s=segments.first(where:{va >= $0.va && va-$0.va < $0.size}) else {throw InvalidImage(description:"unmapped VA")};let p=s.file+Int(va-s.va);try check(p,1);return p}
- func relative(_ va:UInt64) throws -> UInt64 {let delta=Int64(Int32(bitPattern:try word(offset(va))));let value=Int64(va)+delta;guard value>=0 else{throw InvalidImage(description:"negative address")};return UInt64(value)}
- init(_ data:Data) throws {
- self.data=data
- guard try word(0)==0xfeedfacf,try word(4)==0x0100000c else{throw InvalidImage(description:"expected ARM64 Mach-O")}
- let end=32+Int(try word(20));try check(32,end-32)
- var p=32; var fs:(Int,Int)?
- for _ in 0..<(try word(16)) {
- let cmd=try word(p), n=Int(try word(p+4));guard n>=8,p+n<=end else{throw InvalidImage(description:"bad load command")}
- if cmd==0x19 {
- guard n>=72 else{throw InvalidImage(description:"short segment")}
- let count=Int(try word(p+64));guard count<=(n-72)/80 else{throw InvalidImage(description:"short sections")}
- let file=Int(try quad(p+40)),size=try quad(p+48);try check(file,Int(size))
- segments.append(Segment(va:try quad(p+24),size:size,file:file))
- for i in 0..<count {let s=p+72+i*80;sections.append(Section(name:String(decoding:data[s..<s+16].prefix(while:{$0 != 0}),as:UTF8.self),va:try quad(s+32),size:Int(try quad(s+40)),file:Int(try word(s+48))))}
- }
- if cmd==0x26 {guard n>=16 else{throw InvalidImage(description:"short function starts")};fs=(Int(try word(p+8)),Int(try word(p+12)))}
- p+=n
- }
- if let (at,size)=fs,let text=sections.first(where:{$0.name=="__text"}),let base=segments.first(where:{text.va >= $0.va && text.va-$0.va < $0.size})?.va {
- try check(at,size); var cur=at;var va=base
- while cur<at+size {var value:UInt64=0;var shift=0;var byte:UInt8
- repeat {guard cur<at+size,shift<63 else{throw InvalidImage(description:"bad ULEB")};byte=data[cur];cur+=1;value|=UInt64(byte&127)<<shift;shift+=7} while byte&128 != 0
- if value==0{break};va+=value;starts.insert(va)
- }
- }
- }
- func resolve() throws {
- guard let proto=sections.first(where:{$0.name=="__swift5_proto"}) else{throw InvalidImage(description:"no conformances")}
- for i in stride(from:0,to:proto.size,by:4) {
- let c=try relative(proto.va+UInt64(i));let cp=try offset(c);let flags=try word(cp+12)
- // Only non-generic direct nominal references without conditional trailing records.
- guard (flags>>3)&7==0,flags&0xff00==0,flags&0x10000 != 0 else{continue}
- let type=try relative(c+4),tp=try offset(type);guard try word(tp)&0x80==0 else{continue}
- let typeName=try name(offset(relative(type+8)));guard typeName.contains("Provider") else{continue}
- let count=Int(try word(cp+16));guard count<=64 else{throw InvalidImage(description:"invalid witness count")}
- try check(cp+20,count*8)
- var functions:[String]=[]
- for slot in 0..<count {let impl=try relative(c+UInt64(24+slot*8));if starts.contains(impl){functions.append(String(format:"%d:0x%llx",slot,impl))}}
- print(typeName,functions.joined(separator:" "))
- }
- }
+ let data: Data
+ struct Segment { let va: UInt64; let size: UInt64; let file: Int }
+ struct Section { let name: String; let va: UInt64; let size: Int; let file: Int }
+ var segments: [Segment] = []
+ var sections: [Section] = []
+ var starts: Set<UInt64> = []
+ func check(_ p: Int, _ n: Int) throws {
+ guard p >= 0, n >= 0, p <= data.count, n <= data.count - p else { throw InvalidImage(description: "out of bounds \(p), \(n)") }
+ }
+
+ func word(_ p: Int) throws -> UInt32 {
+ try check(p, 4); return data.withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt32.self)) }
+ }
+
+ func quad(_ p: Int) throws -> UInt64 {
+ try check(p, 8); return data.withUnsafeBytes { UInt64(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt64.self)) }
+ }
+
+ func name(_ p: Int, _ max: Int = 512) throws -> String {
+ try check(p, 1); let end = min(data.count, p + max); guard let z = data[p ..< end].firstIndex(of: 0) else { throw InvalidImage(description: "unterminated string") }; return String(decoding: data[p ..< z], as: UTF8.self)
+ }
+
+ func offset(_ va: UInt64) throws -> Int {
+ guard let s = segments.first(where: { va >= $0.va && va - $0.va < $0.size }) else { throw InvalidImage(description: "unmapped VA") }; let p = s.file + Int(va - s.va); try check(p, 1); return p
+ }
+
+ func relative(_ va: UInt64) throws -> UInt64 {
+ let delta = try Int64(Int32(bitPattern: word(offset(va)))); let value = Int64(va) + delta; guard value >= 0 else { throw InvalidImage(description: "negative address") }; return UInt64(value)
+ }
+
+ init(_ data: Data) throws {
+ self.data = data
+ guard try word(0) == 0xFEED_FACF, try word(4) == 0x0100_000C else { throw InvalidImage(description: "expected ARM64 Mach-O") }
+ let end = try 32 + Int(word(20)); try check(32, end - 32)
+ var p = 32; var fs: (Int, Int)?
+ for _ in try 0 ..< word(16) {
+ let cmd = try word(p), n = try Int(word(p + 4)); guard n >= 8, p + n <= end else { throw InvalidImage(description: "bad load command") }
+ if cmd == 0x19 {
+ guard n >= 72 else { throw InvalidImage(description: "short segment") }
+ let count = try Int(word(p + 64)); guard count <= (n - 72) / 80 else { throw InvalidImage(description: "short sections") }
+ let file = try Int(quad(p + 40)), size = try quad(p + 48); try check(file, Int(size))
+ try segments.append(Segment(va: quad(p + 24), size: size, file: file))
+ for i in 0 ..< count {
+ let s = p + 72 + i * 80; try sections.append(Section(name: String(decoding: data[s ..< s + 16].prefix(while: { $0 != 0 }), as: UTF8.self), va: quad(s + 32), size: Int(quad(s + 40)), file: Int(word(s + 48))))
+ }
+ }
+ if cmd == 0x26 {
+ guard n >= 16 else { throw InvalidImage(description: "short function starts") }; fs = try (Int(word(p + 8)), Int(word(p + 12)))
+ }
+ p += n
+ }
+ if let (at, size) = fs, let text = sections.first(where: { $0.name == "__text" }), let base = segments.first(where: { text.va >= $0.va && text.va - $0.va < $0.size })?.va {
+ try check(at, size); var cur = at; var va = base
+ while cur < at + size {
+ var value: UInt64 = 0; var shift = 0; var byte: UInt8
+ repeat {
+ guard cur < at + size, shift < 63 else { throw InvalidImage(description: "bad ULEB") }; byte = data[cur]; cur += 1; value |= UInt64(byte & 127) << shift; shift += 7
+ } while byte & 128 != 0
+ if value == 0 {
+ break
+ }; va += value; starts.insert(va)
+ }
+ }
+ }
+
+ func resolve() throws {
+ guard let proto = sections.first(where: { $0.name == "__swift5_proto" }) else { throw InvalidImage(description: "no conformances") }
+ for i in stride(from: 0, to: proto.size, by: 4) {
+ let c = try relative(proto.va + UInt64(i)); let cp = try offset(c); let flags = try word(cp + 12)
+ // Only non-generic direct nominal references without conditional trailing records.
+ guard (flags >> 3) & 7 == 0, flags & 0xFF00 == 0, flags & 0x10000 != 0 else { continue }
+ let type = try relative(c + 4), tp = try offset(type); guard try word(tp) & 0x80 == 0 else { continue }
+ let typeName = try name(offset(relative(type + 8))); guard typeName.contains("Provider") else { continue }
+ let count = try Int(word(cp + 16)); guard count <= 64 else { throw InvalidImage(description: "invalid witness count") }
+ try check(cp + 20, count * 8)
+ var functions: [String] = []
+ for slot in 0 ..< count {
+ let impl = try relative(c + UInt64(24 + slot * 8)); if starts.contains(impl) {
+ functions.append(String(format: "%d:0x%llx", slot, impl))
+ }
+ }
+ print(typeName, functions.joined(separator: " "))
+ }
+ }
}
-import VPhonePatchKit
import CryptoKit
-guard CommandLine.arguments.count == 3 else {fputs("usage: gamecenter-patch input output\n",stderr);exit(1)}
-let input=try Data(contentsOf:URL(fileURLWithPath:CommandLine.arguments[1]))
-let digest=SHA256.hash(data:input).map{String(format:"%02x",$0)}.joined()
-guard digest == "e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3" else {fputs("unreviewed input hash\n",stderr);exit(1)}
-let image=try Image(input)
+import VPhonePatchKit
+
+guard CommandLine.arguments.count == 3 else { fputs("usage: gamecenter-patch input output\n", stderr); exit(1) }
+let input = try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1]))
+let digest = SHA256.hash(data: input).map { String(format: "%02x", $0) }.joined()
+guard digest == "e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3" else { fputs("unreviewed input hash\n", stderr); exit(1) }
+let image = try Image(input)
// Resolve the named import through LC_SYMTAB, LC_DYSYMTAB and pointer sections.
// No exported r2 JSON or absolute GOT address is part of the patch input.
-var sym:(Int,Int,Int,Int)?
-var indirect:(Int,Int)?
-var pointerSections:[(UInt64,Int,Int)]=[]
-var command=32
-for _ in 0..<(try image.word(16)) {
- let kind=try image.word(command),size=Int(try image.word(command+4))
- if kind==2 {try image.check(command,24);sym=(Int(try image.word(command+8)),Int(try image.word(command+12)),Int(try image.word(command+16)),Int(try image.word(command+20)))}
- if kind==0xb {try image.check(command,80);indirect=(Int(try image.word(command+56)),Int(try image.word(command+60)))}
- if kind==0x19 {
- let count=Int(try image.word(command+64))
- for i in 0..<count {let section=command+72+i*80;let flags=try image.word(section+64)&0xff
- if flags==6 || flags==7 {pointerSections.append((try image.quad(section+32),Int(try image.quad(section+40))/8,Int(try image.word(section+68))))}
- }
- }
- command+=size
+var sym: (Int, Int, Int, Int)?
+var indirect: (Int, Int)?
+var pointerSections: [(UInt64, Int, Int)] = []
+var command = 32
+for _ in try 0 ..< (image.word(16)) {
+ let kind = try image.word(command), size = try Int(image.word(command + 4))
+ if kind == 2 {
+ try image.check(command, 24); sym = try (Int(image.word(command + 8)), Int(image.word(command + 12)), Int(image.word(command + 16)), Int(image.word(command + 20)))
+ }
+ if kind == 0xB {
+ try image.check(command, 80); indirect = try (Int(image.word(command + 56)), Int(image.word(command + 60)))
+ }
+ if kind == 0x19 {
+ let count = try Int(image.word(command + 64))
+ for i in 0 ..< count {
+ let section = command + 72 + i * 80; let flags = try image.word(section + 64) & 0xFF
+ if flags == 6 || flags == 7 {
+ try pointerSections.append((image.quad(section + 32), Int(image.quad(section + 40)) / 8, Int(image.word(section + 68))))
+ }
+ }
+ }
+ command += size
}
-guard let (symbols,symbolCount,strings,stringSize)=sym,let (indirectOffset,indirectCount)=indirect else {fputs("missing symbol tables\n",stderr);exit(1)}
-try image.check(symbols,symbolCount*16);try image.check(strings,stringSize);try image.check(indirectOffset,indirectCount*4)
-var targets:[UInt64]=[]
-for (base,count,first) in pointerSections {
- guard first<=indirectCount,count<=indirectCount-first else{throw InvalidImage(description:"indirect section out of bounds")}
- for slot in 0..<count {
- let symbol=try image.word(indirectOffset+(first+slot)*4)
- if symbol&0xc0000000 != 0 {continue}
- guard symbol<symbolCount else{throw InvalidImage(description:"bad symbol index")}
- let nameOffset=Int(try image.word(symbols+Int(symbol)*16))
- guard nameOffset<stringSize else{throw InvalidImage(description:"bad symbol name offset")}
- if try image.name(strings+nameOffset,stringSize-nameOffset)=="_MCFeatureGameCenterAllowed" {targets.append(base+UInt64(slot*8))}
- }
+
+guard let (symbols, symbolCount, strings, stringSize) = sym, let (indirectOffset, indirectCount) = indirect else { fputs("missing symbol tables\n", stderr); exit(1) }
+try image.check(symbols, symbolCount * 16); try image.check(strings, stringSize); try image.check(indirectOffset, indirectCount * 4)
+var targets: [UInt64] = []
+for (base, count, first) in pointerSections {
+ guard first <= indirectCount, count <= indirectCount - first else { throw InvalidImage(description: "indirect section out of bounds") }
+ for slot in 0 ..< count {
+ let symbol = try image.word(indirectOffset + (first + slot) * 4)
+ if symbol & 0xC000_0000 != 0 {
+ continue
+ }
+ guard symbol < symbolCount else { throw InvalidImage(description: "bad symbol index") }
+ let nameOffset = try Int(image.word(symbols + Int(symbol) * 16))
+ guard nameOffset < stringSize else { throw InvalidImage(description: "bad symbol name offset") }
+ if try image.name(strings + nameOffset, stringSize - nameOffset) == "_MCFeatureGameCenterAllowed" {
+ targets.append(base + UInt64(slot * 8))
+ }
+ }
}
-guard targets.count==1 else {fputs("ambiguous named import\n",stderr);exit(1)}
-let got=targets[0]
-print("resolved MCFeatureGameCenterAllowed GOT",String(format:"0x%llx",got))
-let text=image.sections.first{$0.name=="__text"}!
-let decoder=ARM64Disassembler()
-let code=decoder.disassemble(Data(image.data[text.file..<text.file+text.size]),at:text.va)
-var candidates:[(Int,Int,UInt32)]=[]
-for i in 8..<code.count {
- let a=code[i-1],l=code[i]
- guard a.mnemonic=="adrp",l.mnemonic=="ldr",let ao=a.detail?.operands,let lo=l.detail?.operands,ao.count==2,lo.count==2,ao[1].type == .immediate,lo[1].type == .memory,ao[0].reg==lo[1].mem.base,UInt64(ao[1].imm)+UInt64(lo[1].mem.disp)==got else{continue}
- let tag=code[i-4],call=code[i-3],store=code[i-7],arg0=code[i-6]
- guard tag.mnemonic=="mov",let t=tag.detail?.operands,t.count==2,t[0].reg == .w(2),t[1].imm==8,call.mnemonic=="bl",store.mnemonic=="strb",let so=store.detail?.operands,so.count==2,so[1].type == .memory,so[1].mem.disp==0,arg0.mnemonic=="mov",let args=arg0.detail?.operands,args.count==2,args[0].reg == .x(0),args[1].reg==so[1].mem.base else{continue}
- guard let rn=(0..<31).first(where:{so[1].mem.base == .x($0)}) else{continue}
- candidates.append((i-7,i-4,UInt32(rn)))
+
+guard targets.count == 1 else { fputs("ambiguous named import\n", stderr); exit(1) }
+let got = targets[0]
+print("resolved MCFeatureGameCenterAllowed GOT", String(format: "0x%llx", got))
+let text = image.sections.first { $0.name == "__text" }!
+let decoder = ARM64Disassembler()
+let code = decoder.disassemble(Data(image.data[text.file ..< text.file + text.size]), at: text.va)
+var candidates: [(Int, Int, UInt32)] = []
+for i in 8 ..< code.count {
+ let a = code[i - 1], l = code[i]
+ guard a.mnemonic == "adrp", l.mnemonic == "ldr", let ao = a.detail?.operands, let lo = l.detail?.operands, ao.count == 2, lo.count == 2, ao[1].type == .immediate, lo[1].type == .memory, ao[0].reg == lo[1].mem.base, UInt64(ao[1].imm) + UInt64(lo[1].mem.disp) == got else { continue }
+ let tag = code[i - 4], call = code[i - 3], store = code[i - 7], arg0 = code[i - 6]
+ guard tag.mnemonic == "mov", let t = tag.detail?.operands, t.count == 2, t[0].reg == .w(2), t[1].imm == 8, call.mnemonic == "bl", store.mnemonic == "strb", let so = store.detail?.operands, so.count == 2, so[1].type == .memory, so[1].mem.disp == 0, arg0.mnemonic == "mov", let args = arg0.detail?.operands, args.count == 2, args[0].reg == .x(0), args[1].reg == so[1].mem.base else { continue }
+ guard let rn = (0 ..< 31).first(where: { so[1].mem.base == .x($0) }) else { continue }
+ candidates.append((i - 7, i - 4, UInt32(rn)))
}
-guard candidates.count==1 else{fatalError("expected one construction block, got \(candidates.count)")}
-let (s,t,rn)=candidates[0]
-let changes=[(code[s],ARM64Encoder.encodeStrXUnsignedOffset(rt:31,rn:rn,offset:0)!), (code[t],ARM64Encoder.encodeMovzW(rd:2,imm16:2)!)]
-var out=image.data
-for (before,bytes) in changes {
- let after=decoder.disassembleOne(bytes,at:before.address)!
- print("REVIEW",before.description,"->",after.description)
- let off=try image.offset(before.address);out.replaceSubrange(off..<off+4,with:bytes)
+
+guard candidates.count == 1 else { fatalError("expected one construction block, got \(candidates.count)") }
+let (s, t, rn) = candidates[0]
+let changes = [(code[s], ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: rn, offset: 0)!), (code[t], ARM64Encoder.encodeMovzW(rd: 2, imm16: 2)!)]
+var out = image.data
+for (before, bytes) in changes {
+ let after = decoder.disassembleOne(bytes, at: before.address)!
+ print("REVIEW", before.description, "->", after.description)
+ let off = try image.offset(before.address); out.replaceSubrange(off ..< off + 4, with: bytes)
}
+
// Experimental copy only; no signing, guest writes or installer integration.
-try out.write(to:URL(fileURLWithPath:CommandLine.arguments[2]),options:.withoutOverwriting)
-print("sha256",SHA256.hash(data:out).map{String(format:"%02x",$0)}.joined())
+try out.write(to: URL(fileURLWithPath: CommandLine.arguments[2]), options: .withoutOverwriting)
+print("sha256", SHA256.hash(data: out).map { String(format: "%02x", $0) }.joined())
diff --git a/Research/Guest/SettingsRows/ReviewedProviderPatch.swift b/Research/Guest/SettingsRows/ReviewedProviderPatch.swift
index 66407fae..eb0ef7ec 100644
--- a/Research/Guest/SettingsRows/ReviewedProviderPatch.swift
+++ b/Research/Guest/SettingsRows/ReviewedProviderPatch.swift
@@ -1,138 +1,176 @@
-import Foundation
import CryptoKit
+import Foundation
+
struct InvalidImage: Error, CustomStringConvertible { let description: String }
struct Image {
- let data: Data
- struct Segment { let va: UInt64; let size: UInt64; let file: Int }
- struct Section { let name: String; let va: UInt64; let size: Int; let file: Int }
- var segments: [Segment] = []
- var sections: [Section] = []
- var starts: Set<UInt64> = []
- func check(_ p:Int,_ n:Int) throws { guard p>=0,n>=0,p<=data.count,n<=data.count-p else {throw InvalidImage(description:"out of bounds \(p), \(n)")} }
- func word(_ p:Int) throws -> UInt32 {try check(p,4);return data.withUnsafeBytes{UInt32(littleEndian:$0.loadUnaligned(fromByteOffset:p,as:UInt32.self))}}
- func quad(_ p:Int) throws -> UInt64 {try check(p,8);return data.withUnsafeBytes{UInt64(littleEndian:$0.loadUnaligned(fromByteOffset:p,as:UInt64.self))}}
- func name(_ p:Int,_ max:Int=512) throws -> String {try check(p,1);let end=min(data.count,p+max);guard let z=data[p..<end].firstIndex(of:0) else {throw InvalidImage(description:"unterminated string")};return String(decoding:data[p..<z],as:UTF8.self)}
- func offset(_ va:UInt64) throws -> Int {guard let s=segments.first(where:{va >= $0.va && va-$0.va < $0.size}) else {throw InvalidImage(description:"unmapped VA")};let p=s.file+Int(va-s.va);try check(p,1);return p}
- func relative(_ va:UInt64) throws -> UInt64 {let delta=Int64(Int32(bitPattern:try word(offset(va))));let value=Int64(va)+delta;guard value>=0 else{throw InvalidImage(description:"negative address")};return UInt64(value)}
- init(_ data:Data) throws {
- self.data=data
- guard try word(0)==0xfeedfacf,try word(4)==0x0100000c else{throw InvalidImage(description:"expected ARM64 Mach-O")}
- let end=32+Int(try word(20));try check(32,end-32)
- var p=32; var fs:(Int,Int)?
- for _ in 0..<(try word(16)) {
- let cmd=try word(p), n=Int(try word(p+4));guard n>=8,p+n<=end else{throw InvalidImage(description:"bad load command")}
- if cmd==0x19 {
- guard n>=72 else{throw InvalidImage(description:"short segment")}
- let count=Int(try word(p+64));guard count<=(n-72)/80 else{throw InvalidImage(description:"short sections")}
- let file=Int(try quad(p+40)),size=try quad(p+48);try check(file,Int(size))
- segments.append(Segment(va:try quad(p+24),size:size,file:file))
- for i in 0..<count {let s=p+72+i*80;sections.append(Section(name:String(decoding:data[s..<s+16].prefix(while:{$0 != 0}),as:UTF8.self),va:try quad(s+32),size:Int(try quad(s+40)),file:Int(try word(s+48))))}
- }
- if cmd==0x26 {guard n>=16 else{throw InvalidImage(description:"short function starts")};fs=(Int(try word(p+8)),Int(try word(p+12)))}
- p+=n
- }
- if let (at,size)=fs,let text=sections.first(where:{$0.name=="__text"}),let base=segments.first(where:{text.va >= $0.va && text.va-$0.va < $0.size})?.va {
- try check(at,size); var cur=at;var va=base
- while cur<at+size {var value:UInt64=0;var shift=0;var byte:UInt8
- repeat {guard cur<at+size,shift<63 else{throw InvalidImage(description:"bad ULEB")};byte=data[cur];cur+=1;value|=UInt64(byte&127)<<shift;shift+=7} while byte&128 != 0
- if value==0{break};va+=value;starts.insert(va)
- }
- }
- }
- func resolve() throws {
- guard let proto=sections.first(where:{$0.name=="__swift5_proto"}) else{throw InvalidImage(description:"no conformances")}
- for i in stride(from:0,to:proto.size,by:4) {
- let c=try relative(proto.va+UInt64(i));let cp=try offset(c);let flags=try word(cp+12)
- // Only non-generic direct nominal references without conditional trailing records.
- guard (flags>>3)&7==0,flags&0xff00==0,flags&0x10000 != 0 else{continue}
- let type=try relative(c+4),tp=try offset(type);guard try word(tp)&0x80==0 else{continue}
- let typeName=try name(offset(relative(type+8)));guard typeName.contains("Provider") else{continue}
- let count=Int(try word(cp+16));guard count<=64 else{throw InvalidImage(description:"invalid witness count")}
- try check(cp+20,count*8)
- var functions:[String]=[]
- for slot in 0..<count {let impl=try relative(c+UInt64(24+slot*8));if starts.contains(impl){functions.append(String(format:"%d:0x%llx",slot,impl))}}
- print(typeName,functions.joined(separator:" "))
- }
- }
+ let data: Data
+ struct Segment { let va: UInt64; let size: UInt64; let file: Int }
+ struct Section { let name: String; let va: UInt64; let size: Int; let file: Int }
+ var segments: [Segment] = []
+ var sections: [Section] = []
+ var starts: Set<UInt64> = []
+ func check(_ p: Int, _ n: Int) throws {
+ guard p >= 0, n >= 0, p <= data.count, n <= data.count - p else { throw InvalidImage(description: "out of bounds \(p), \(n)") }
+ }
+
+ func word(_ p: Int) throws -> UInt32 {
+ try check(p, 4); return data.withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt32.self)) }
+ }
+
+ func quad(_ p: Int) throws -> UInt64 {
+ try check(p, 8); return data.withUnsafeBytes { UInt64(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt64.self)) }
+ }
+
+ func name(_ p: Int, _ max: Int = 512) throws -> String {
+ try check(p, 1); let end = min(data.count, p + max); guard let z = data[p ..< end].firstIndex(of: 0) else { throw InvalidImage(description: "unterminated string") }; return String(decoding: data[p ..< z], as: UTF8.self)
+ }
+
+ func offset(_ va: UInt64) throws -> Int {
+ guard let s = segments.first(where: { va >= $0.va && va - $0.va < $0.size }) else { throw InvalidImage(description: "unmapped VA") }; let p = s.file + Int(va - s.va); try check(p, 1); return p
+ }
+
+ func relative(_ va: UInt64) throws -> UInt64 {
+ let delta = try Int64(Int32(bitPattern: word(offset(va)))); let value = Int64(va) + delta; guard value >= 0 else { throw InvalidImage(description: "negative address") }; return UInt64(value)
+ }
+
+ init(_ data: Data) throws {
+ self.data = data
+ guard try word(0) == 0xFEED_FACF, try word(4) == 0x0100_000C else { throw InvalidImage(description: "expected ARM64 Mach-O") }
+ let end = try 32 + Int(word(20)); try check(32, end - 32)
+ var p = 32; var fs: (Int, Int)?
+ for _ in try 0 ..< word(16) {
+ let cmd = try word(p), n = try Int(word(p + 4)); guard n >= 8, p + n <= end else { throw InvalidImage(description: "bad load command") }
+ if cmd == 0x19 {
+ guard n >= 72 else { throw InvalidImage(description: "short segment") }
+ let count = try Int(word(p + 64)); guard count <= (n - 72) / 80 else { throw InvalidImage(description: "short sections") }
+ let file = try Int(quad(p + 40)), size = try quad(p + 48); try check(file, Int(size))
+ try segments.append(Segment(va: quad(p + 24), size: size, file: file))
+ for i in 0 ..< count {
+ let s = p + 72 + i * 80; try sections.append(Section(name: String(decoding: data[s ..< s + 16].prefix(while: { $0 != 0 }), as: UTF8.self), va: quad(s + 32), size: Int(quad(s + 40)), file: Int(word(s + 48))))
+ }
+ }
+ if cmd == 0x26 {
+ guard n >= 16 else { throw InvalidImage(description: "short function starts") }; fs = try (Int(word(p + 8)), Int(word(p + 12)))
+ }
+ p += n
+ }
+ if let (at, size) = fs, let text = sections.first(where: { $0.name == "__text" }), let base = segments.first(where: { text.va >= $0.va && text.va - $0.va < $0.size })?.va {
+ try check(at, size); var cur = at; var va = base
+ while cur < at + size {
+ var value: UInt64 = 0; var shift = 0; var byte: UInt8
+ repeat {
+ guard cur < at + size, shift < 63 else { throw InvalidImage(description: "bad ULEB") }; byte = data[cur]; cur += 1; value |= UInt64(byte & 127) << shift; shift += 7
+ } while byte & 128 != 0
+ if value == 0 {
+ break
+ }; va += value; starts.insert(va)
+ }
+ }
+ }
+
+ func resolve() throws {
+ guard let proto = sections.first(where: { $0.name == "__swift5_proto" }) else { throw InvalidImage(description: "no conformances") }
+ for i in stride(from: 0, to: proto.size, by: 4) {
+ let c = try relative(proto.va + UInt64(i)); let cp = try offset(c); let flags = try word(cp + 12)
+ // Only non-generic direct nominal references without conditional trailing records.
+ guard (flags >> 3) & 7 == 0, flags & 0xFF00 == 0, flags & 0x10000 != 0 else { continue }
+ let type = try relative(c + 4), tp = try offset(type); guard try word(tp) & 0x80 == 0 else { continue }
+ let typeName = try name(offset(relative(type + 8))); guard typeName.contains("Provider") else { continue }
+ let count = try Int(word(cp + 16)); guard count <= 64 else { throw InvalidImage(description: "invalid witness count") }
+ try check(cp + 20, count * 8)
+ var functions: [String] = []
+ for slot in 0 ..< count {
+ let impl = try relative(c + UInt64(24 + slot * 8)); if starts.contains(impl) {
+ functions.append(String(format: "%d:0x%llx", slot, impl))
+ }
+ }
+ print(typeName, functions.joined(separator: " "))
+ }
+ }
}
import VPhonePatchKit
-let decoder=ARM64Disassembler()
-func instructions(_ image:Image,_ va:UInt64) throws -> [ARM64Instruction] {
- let end=image.starts.filter{$0>va}.min() ?? va
- guard end>va,end-va<20000 else{return []}
- let off=try image.offset(va);try image.check(off,Int(end-va))
- return decoder.disassemble(Data(image.data[off..<off+Int(end-va)]),at:va)
+
+let decoder = ARM64Disassembler()
+func instructions(_ image: Image, _ va: UInt64) throws -> [ARM64Instruction] {
+ let end = image.starts.filter { $0 > va }.min() ?? va
+ guard end > va, end - va < 20000 else { return [] }
+ let off = try image.offset(va); try image.check(off, Int(end - va))
+ return decoder.disassemble(Data(image.data[off ..< off + Int(end - va)]), at: va)
}
+
do {
- guard CommandLine.arguments.count>1 else{throw InvalidImage(description:"input path required")}
- let path=CommandLine.arguments[1]
- let input=try Data(contentsOf:URL(fileURLWithPath:path))
- let inputHash=SHA256.hash(data:input).map{String(format:"%02x",$0)}.joined()
- let reviewedInputs:Set<String>=["e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3","e43fa27956007aef6180570b242e3b08bb2030841121d13ac8671ec9f8480dd1"]
- guard reviewedInputs.contains(inputHash) else{throw InvalidImage(description:"unreviewed input hash; parsing and output refused")}
- let image=try Image(input)
- guard let proto=image.sections.first(where:{$0.name=="__swift5_proto"}) else{throw InvalidImage(description:"missing conformance section")}
- var sites:[String:[(UInt64,Data)]]=[:]
- let wanted:Set<String>=["PrimaryAppleAccountListItemProvider","iCloudListItemProvider","WalletAndApplePayOrPaymentAndContactlessListItemProvider","SoftwareUpdateListItemProvider"]
- for i in stride(from:0,to:proto.size,by:4) {
- let c=try image.relative(proto.va+UInt64(i));let cp=try image.offset(c);let flags=try image.word(cp+12)
- guard (flags>>3)&7==0,flags&0xff00==0,flags&0x10000 != 0 else{continue}
- let t=try image.relative(c+4);let name=try image.name(image.offset(image.relative(t+8)));guard wanted.contains(name) else{continue}
- let n=Int(try image.word(cp+16));guard n<=64 else{throw InvalidImage(description:"witness overflow")}
- for slot in 0..<n {
- let impl=try image.relative(c+UInt64(24+slot*8));guard image.starts.contains(impl) else{continue}
- let wrapper=try instructions(image,impl)
- for call in wrapper where call.mnemonic=="bl" {
- guard let op=call.detail?.operands.first,op.type == .immediate,op.imm>0,image.starts.contains(UInt64(op.imm)) else{continue}
- let body=try instructions(image,UInt64(op.imm))
- for k in 1..<body.count {
- let prev=body[k-1],branch=body[k]
- guard prev.mnemonic=="cmp",let ops=prev.detail?.operands,ops.count==2,ops[0].type == .register,ops[0].reg == .w(0),ops[1].type == .immediate,ops[1].imm==1,branch.mnemonic=="b.ne" else{continue}
- guard k>=2,body[k-2].mnemonic=="blraa",
- let dest=branch.detail?.operands.first,dest.type == .immediate,
- dest.imm>Int64(branch.address),let end=body.firstIndex(where:{$0.address==UInt64(dest.imm)}),
- end>k,end-k<=40 else {continue}
- let fallthroughBlock=Array(body[(k+1)..<end].prefix(while:{$0.mnemonic != "b" && !$0.isReturn}))
- guard fallthroughBlock.contains(where:{$0.mnemonic=="bl"}),
- k+1+fallthroughBlock.count < end,body[k+1+fallthroughBlock.count].mnemonic=="b" else {
- print("REJECT",name,branch.description,"no cleanup call before merge")
- continue
- }
- guard let replacement=ARM64Encoder.encodeB(from:Int(branch.address),to:Int(branch.address+4)),
- let decoded=decoder.disassembleOne(replacement,at:branch.address),decoded.mnemonic=="b",
- decoded.detail?.operands.first?.imm==Int64(branch.address+4) else {throw InvalidImage(description:"encoder round trip failed")}
- sites[name,default:[]].append((branch.address,replacement))
- print(name,"witness",String(format:"0x%llx",impl),"body",String(format:"0x%llx",UInt64(op.imm)),"CANDIDATE",branch.description)
- for x in body[k..<min(k+9,body.count)] {print(" ",x.description)}
+ guard CommandLine.arguments.count > 1 else { throw InvalidImage(description: "input path required") }
+ let path = CommandLine.arguments[1]
+ let input = try Data(contentsOf: URL(fileURLWithPath: path))
+ let inputHash = SHA256.hash(data: input).map { String(format: "%02x", $0) }.joined()
+ let reviewedInputs: Set = ["e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3", "e43fa27956007aef6180570b242e3b08bb2030841121d13ac8671ec9f8480dd1"]
+ guard reviewedInputs.contains(inputHash) else { throw InvalidImage(description: "unreviewed input hash; parsing and output refused") }
+ let image = try Image(input)
+ guard let proto = image.sections.first(where: { $0.name == "__swift5_proto" }) else { throw InvalidImage(description: "missing conformance section") }
+ var sites: [String: [(UInt64, Data)]] = [:]
+ let wanted: Set = ["PrimaryAppleAccountListItemProvider", "iCloudListItemProvider", "WalletAndApplePayOrPaymentAndContactlessListItemProvider", "SoftwareUpdateListItemProvider"]
+ for i in stride(from: 0, to: proto.size, by: 4) {
+ let c = try image.relative(proto.va + UInt64(i)); let cp = try image.offset(c); let flags = try image.word(cp + 12)
+ guard (flags >> 3) & 7 == 0, flags & 0xFF00 == 0, flags & 0x10000 != 0 else { continue }
+ let t = try image.relative(c + 4); let name = try image.name(image.offset(image.relative(t + 8))); guard wanted.contains(name) else { continue }
+ let n = try Int(image.word(cp + 16)); guard n <= 64 else { throw InvalidImage(description: "witness overflow") }
+ for slot in 0 ..< n {
+ let impl = try image.relative(c + UInt64(24 + slot * 8)); guard image.starts.contains(impl) else { continue }
+ let wrapper = try instructions(image, impl)
+ for call in wrapper where call.mnemonic == "bl" {
+ guard let op = call.detail?.operands.first, op.type == .immediate, op.imm > 0, image.starts.contains(UInt64(op.imm)) else { continue }
+ let body = try instructions(image, UInt64(op.imm))
+ for k in 1 ..< body.count {
+ let prev = body[k - 1], branch = body[k]
+ guard prev.mnemonic == "cmp", let ops = prev.detail?.operands, ops.count == 2, ops[0].type == .register, ops[0].reg == .w(0), ops[1].type == .immediate, ops[1].imm == 1, branch.mnemonic == "b.ne" else { continue }
+ guard k >= 2, body[k - 2].mnemonic == "blraa",
+ let dest = branch.detail?.operands.first, dest.type == .immediate,
+ dest.imm > Int64(branch.address), let end = body.firstIndex(where: { $0.address == UInt64(dest.imm) }),
+ end > k, end - k <= 40 else { continue }
+ let fallthroughBlock = Array(body[(k + 1) ..< end].prefix(while: { $0.mnemonic != "b" && !$0.isReturn }))
+ guard fallthroughBlock.contains(where: { $0.mnemonic == "bl" }),
+ k + 1 + fallthroughBlock.count < end, body[k + 1 + fallthroughBlock.count].mnemonic == "b"
+ else {
+ print("REJECT", name, branch.description, "no cleanup call before merge")
+ continue
+ }
+ guard let replacement = ARM64Encoder.encodeB(from: Int(branch.address), to: Int(branch.address + 4)),
+ let decoded = decoder.disassembleOne(replacement, at: branch.address), decoded.mnemonic == "b",
+ decoded.detail?.operands.first?.imm == Int64(branch.address + 4) else { throw InvalidImage(description: "encoder round trip failed") }
+ sites[name, default: []].append((branch.address, replacement))
+ print(name, "witness", String(format: "0x%llx", impl), "body", String(format: "0x%llx", UInt64(op.imm)), "CANDIDATE", branch.description)
+ for x in body[k ..< min(k + 9, body.count)] {
+ print(" ", x.description)
+ }
+ }
+ }
+ }
+ }
+ for (name, matches) in sites.sorted(by: { $0.key < $1.key }) {
+ guard matches.count == 1 else { throw InvalidImage(description: "ambiguous sites for \(name)") }
+ print("UNIQUE STRUCTURAL CANDIDATE", name, String(format: "0x%llx", matches[0].0), "replacement", matches[0].1.map { String(format: "%02x", $0) }.joined())
+ }
+ if let outIndex = CommandLine.arguments.firstIndex(of: "--output") {
+ guard outIndex + 1 < CommandLine.arguments.count else { throw InvalidImage(description: "--output requires path") }
+ let out = CommandLine.arguments[outIndex + 1]
+ guard !FileManager.default.fileExists(atPath: out),!FileManager.default.fileExists(atPath: out + ".json") else { throw InvalidImage(description: "output already exists") }
+ guard let selectIndex = CommandLine.arguments.firstIndex(of: "--providers"), selectIndex + 1 < CommandLine.arguments.count else { throw InvalidImage(description: "explicit --providers required") }
+ let selected = Set(CommandLine.arguments[selectIndex + 1].split(separator: ",").map(String.init))
+ guard !selected.isEmpty, selected.isSubset(of: wanted) else { throw InvalidImage(description: "unknown provider") }
+ let hash = SHA256.hash(data: image.data).map { String(format: "%02x", $0) }.joined()
+ let known: Set = ["e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3", "e43fa27956007aef6180570b242e3b08bb2030841121d13ac8671ec9f8480dd1"]
+ guard known.contains(hash) else { throw InvalidImage(description: "unreviewed input hash; no output written") }
+ var output = image.data; var changes: [[String: Any]] = []
+ for name in selected.sorted() {
+ guard let matches = sites[name], matches.count == 1 else { throw InvalidImage(description: "missing or ambiguous provider \(name)") }
+ let (va, replacement) = matches[0]; let off = try image.offset(va)
+ changes.append(["provider": name, "va": String(format: "0x%llx", va), "fileOffset": off, "before": output[off ..< off + 4].map { String(format: "%02x", $0) }.joined(), "after": replacement.map { String(format: "%02x", $0) }.joined()])
+ output.replaceSubrange(off ..< off + 4, with: replacement)
+ }
+ let manifest: [String: Any] = ["status": "EXPERIMENTAL_NOT_DEPLOYMENT_APPROVED", "inputSHA256": hash, "outputSHA256": SHA256.hash(data: output).map { String(format: "%02x", $0) }.joined(), "changes": changes, "signature": "invalidated; not re-signed", "limitations": "Game Center unsupported. Extracted cache dylib is analysis-only. Runtime semantics and rollback unverified."]
+ try output.write(to: URL(fileURLWithPath: out), options: .withoutOverwriting)
+ try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys]).write(to: URL(fileURLWithPath: out + ".json"), options: .withoutOverwriting)
+ print("EXPERIMENTAL COPY", out)
}
- }
- }
- }
- for (name,matches) in sites.sorted(by:{$0.key<$1.key}) {
- guard matches.count==1 else {throw InvalidImage(description:"ambiguous sites for \(name)")}
- print("UNIQUE STRUCTURAL CANDIDATE",name,String(format:"0x%llx",matches[0].0),"replacement",matches[0].1.map{String(format:"%02x",$0)}.joined())
- }
- if let outIndex=CommandLine.arguments.firstIndex(of:"--output") {
- guard outIndex+1<CommandLine.arguments.count else {throw InvalidImage(description:"--output requires path")}
- let out=CommandLine.arguments[outIndex+1]
- guard !FileManager.default.fileExists(atPath:out),!FileManager.default.fileExists(atPath:out+".json") else{throw InvalidImage(description:"output already exists")}
- guard let selectIndex=CommandLine.arguments.firstIndex(of:"--providers"),selectIndex+1<CommandLine.arguments.count else{throw InvalidImage(description:"explicit --providers required")}
- let selected=Set(CommandLine.arguments[selectIndex+1].split(separator:",").map(String.init))
- guard !selected.isEmpty,selected.isSubset(of:wanted) else{throw InvalidImage(description:"unknown provider")}
- let hash=SHA256.hash(data:image.data).map{String(format:"%02x",$0)}.joined()
- let known:Set<String>=["e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3","e43fa27956007aef6180570b242e3b08bb2030841121d13ac8671ec9f8480dd1"]
- guard known.contains(hash) else{throw InvalidImage(description:"unreviewed input hash; no output written")}
- var output=image.data;var changes:[[String:Any]]=[]
- for name in selected.sorted() {
- guard let matches=sites[name],matches.count==1 else{throw InvalidImage(description:"missing or ambiguous provider \(name)")}
- let (va,replacement)=matches[0];let off=try image.offset(va)
- changes.append(["provider":name,"va":String(format:"0x%llx",va),"fileOffset":off,"before":output[off..<off+4].map{String(format:"%02x",$0)}.joined(),"after":replacement.map{String(format:"%02x",$0)}.joined()])
- output.replaceSubrange(off..<off+4,with:replacement)
- }
- let manifest:[String:Any]=["status":"EXPERIMENTAL_NOT_DEPLOYMENT_APPROVED","inputSHA256":hash,"outputSHA256":SHA256.hash(data:output).map{String(format:"%02x",$0)}.joined(),"changes":changes,"signature":"invalidated; not re-signed","limitations":"Game Center unsupported. Extracted cache dylib is analysis-only. Runtime semantics and rollback unverified."]
- try output.write(to:URL(fileURLWithPath:out),options:.withoutOverwriting)
- try JSONSerialization.data(withJSONObject:manifest,options:[.prettyPrinted,.sortedKeys]).write(to:URL(fileURLWithPath:out+".json"),options:.withoutOverwriting)
- print("EXPERIMENTAL COPY",out)
- }
-} catch {fputs("ERROR: \(error)\n",stderr);exit(1)}
+} catch { fputs("ERROR: \(error)\n", stderr); exit(1) }
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 053ee113..a18c3437 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -491,7 +491,7 @@ enum GuestAPI {
/// identifier. `setup.settle` counts this list, not icli's `count`, which
/// was one higher than `apps.list` on an iOS 27 guest.
static func listedApps() throws -> [[String: Any]] {
- (try listApps()["apps"] as? [[String: Any]] ?? []).filter {
+ try (listApps()["apps"] as? [[String: Any]] ?? []).filter {
!(($0["bundle_id"] as? String) ?? "").isEmpty
}
}
diff --git a/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift b/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift
index abbc25d7..4fd25695 100644
--- a/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift
+++ b/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift
@@ -80,8 +80,8 @@ enum GuestFirstBootSettle {
let counts = window.map(\.appCount)
if counts.contains(where: { $0 == nil }) {
reasons.append("app count unavailable")
- } else if Set(counts.compactMap { $0 }).count > 1 {
- let values = counts.compactMap { $0 }.map(String.init).joined(separator: " → ")
+ } else if Set(counts.compactMap(\.self)).count > 1 {
+ let values = counts.compactMap(\.self).map(String.init).joined(separator: " → ")
reasons.append("app count changed: \(values)")
}
}
diff --git a/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swift b/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swift
index 6d23cbf8..a4a69aeb 100644
--- a/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swift
+++ b/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swift
@@ -93,7 +93,9 @@ enum GuestSnapshotPolicy {
}
}
- var retryable: Bool { self == .busy }
+ var retryable: Bool {
+ self == .busy
+ }
}
static func message(_ failure: Failure, errno code: Int32, operation: String) -> String {
diff --git a/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swift b/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swift
index f044c478..7f677def 100644
--- a/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swift
+++ b/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swift
@@ -110,8 +110,13 @@ struct GuestSystemAppLocation: Equatable {
let containerUUID: String
let appDirectoryName: String
- var containerPath: String { GuestSystemAppPolicy.containersRoot + "/" + containerUUID }
- var appPath: String { containerPath + "/" + appDirectoryName }
+ var containerPath: String {
+ GuestSystemAppPolicy.containersRoot + "/" + containerUUID
+ }
+
+ var appPath: String {
+ containerPath + "/" + appDirectoryName
+ }
/// Accepts the path LaunchServices reports, with or without the
/// `/private` prefix and with a trailing slash. Anything else, a `.` or
diff --git a/VPhoneDaemon/Tests/SystemMaintenanceTests.swift b/VPhoneDaemon/Tests/SystemMaintenanceTests.swift
index c6983ec6..cdc364b8 100644
--- a/VPhoneDaemon/Tests/SystemMaintenanceTests.swift
+++ b/VPhoneDaemon/Tests/SystemMaintenanceTests.swift
@@ -260,13 +260,13 @@ enum SystemMaintenanceTests {
return (try? JSONSerialization.data(withJSONObject: copy)) ?? Data()
}
check(throwsError { _ = try GuestSystemAppManifest.decode(tampered("container_uuid", "../../../System"),
- expectedBundleID: "com.apple.findmy") },
+ expectedBundleID: "com.apple.findmy") },
"tampered UUID refused")
check(throwsError { _ = try GuestSystemAppManifest.decode(tampered("app", "../../Applications/X.app"),
- expectedBundleID: "com.apple.findmy") },
+ expectedBundleID: "com.apple.findmy") },
"tampered app refused")
check(throwsError { _ = try GuestSystemAppManifest.decode(tampered("version", 2),
- expectedBundleID: "com.apple.findmy") },
+ expectedBundleID: "com.apple.findmy") },
"unknown version refused")
check(throwsError {
_ = try GuestSystemAppManifest.decode(tampered("bundle_id", "com.example.app"), expectedBundleID: "com.example.app")
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareLocationdCohorting.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareLocationdCohorting.swift
index 269affc7..4b7e0553 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareLocationdCohorting.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareLocationdCohorting.swift
@@ -16,7 +16,7 @@ public enum CustomFirmwareLocationdCohorting {
let input = try Data(contentsOf: url)
var format = PropertyListSerialization.PropertyListFormat.xml
guard var root = try PropertyListSerialization.propertyList(
- from: input, options: [], format: &format
+ from: input, options: [], format: &format,
) as? [String: Any],
var feature = root[Self.feature] as? [String: Any]
else {
@@ -28,12 +28,16 @@ public enum CustomFirmwareLocationdCohorting {
else {
throw PatcherError.invalidFormat("CLAutoCohort.Enabled is not a boolean: \(url.path)")
}
- if !number.boolValue { return false }
+ if !number.boolValue {
+ return false
+ }
}
feature["Enabled"] = false
root[Self.feature] = feature
let output = try PropertyListSerialization.data(fromPropertyList: root, format: format, options: 0)
- if !dryRun { try output.write(to: url, options: .atomic) }
+ if !dryRun {
+ try output.write(to: url, options: .atomic)
+ }
return true
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/SettingsRows/CustomFirmwareSettingsRows.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/SettingsRows/CustomFirmwareSettingsRows.swift
index def971c0..e7959075 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/SettingsRows/CustomFirmwareSettingsRows.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/SettingsRows/CustomFirmwareSettingsRows.swift
@@ -7,354 +7,380 @@ import VPhonePatchKit
/// Input is deliberately restricted to the reviewed original; apply to the installer's
/// pristine backup. Signing, deployment, patch selection and receipts belong to the caller.
public enum CustomFirmwareSettingsRows {
- public struct Edit: Sendable {
- public let identifier: String
- public let address: UInt64
- public let fileOffset: Int
- public let before: Data
- public let after: Data
- }
- public struct Result: Sendable {
- public let data: Data
- public let edits: [Edit]
- }
- private static let rootProviders = [
- "PrimaryAppleAccountListItemProvider", "iCloudListItemProvider",
- "WalletAndApplePayOrPaymentAndContactlessListItemProvider",
- ]
- public static func patchPreferences(_ original: Data) throws -> Result {
- let digest = SHA256.hash(data: original).map { String(format: "%02x", $0) }.joined()
- guard digest == "e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3" else {
- throw InvalidImage(
- description: "unreviewed Preferences input; use the pristine reviewed backup")
+ public struct Edit: Sendable {
+ public let identifier: String
+ public let address: UInt64
+ public let fileOffset: Int
+ public let before: Data
+ public let after: Data
}
- let image = try Image(original)
- var edits = try providerEdits(image)
- edits += try gameCenterEdits(image)
- edits.sort { $0.fileOffset < $1.fileOffset }
- guard edits.count == 5 else {
- throw InvalidImage(description: "expected five instructions for four root rows")
- }
- var output = original
- var lastEnd = 0
- for edit in edits {
- guard edit.fileOffset >= lastEnd, edit.after.count == 4, edit.before.count == 4 else {
- throw InvalidImage(description: "overlapping or malformed edits")
- }
- try image.check(edit.fileOffset, 4)
- guard output.subdata(in: edit.fileOffset..<edit.fileOffset + 4) == edit.before else {
- throw InvalidImage(description: "preimage changed")
- }
- output.replaceSubrange(edit.fileOffset..<edit.fileOffset + 4, with: edit.after)
- lastEnd = edit.fileOffset + 4
- }
- return Result(data: output, edits: edits)
- }
- private static func makeEdit(_ image: Image, _ name: String, _ va: UInt64, _ bytes: Data) throws
- -> Edit
- {
- let offset = try image.offset(va)
- try image.check(offset, 4)
- return Edit(
- identifier: name, address: va, fileOffset: offset,
- before: image.data.subdata(in: offset..<offset + 4), after: bytes)
- }
- private struct InvalidImage: Error, CustomStringConvertible { let description: String }
- private struct Image {
- let data: Data
- struct Segment {
- let va: UInt64
- let size: UInt64
- let file: Int
- }
- struct Section {
- let name: String
- let va: UInt64
- let size: Int
- let file: Int
- }
- var segments: [Segment] = []
- var sections: [Section] = []
- var starts: Set<UInt64> = []
- func check(_ p: Int, _ n: Int) throws {
- guard p >= 0, n >= 0, p <= data.count, n <= data.count - p else {
- throw InvalidImage(description: "out of bounds \(p), \(n)")
- }
- }
- func word(_ p: Int) throws -> UInt32 {
- try check(p, 4)
- return data.withUnsafeBytes {
- UInt32(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt32.self))
- }
- }
- func quad(_ p: Int) throws -> UInt64 {
- try check(p, 8)
- return data.withUnsafeBytes {
- UInt64(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt64.self))
- }
- }
- func name(_ p: Int, _ max: Int = 512) throws -> String {
- try check(p, 1)
- let end = min(data.count, p + max)
- guard let z = data[p..<end].firstIndex(of: 0) else {
- throw InvalidImage(description: "unterminated string")
- }
- return String(decoding: data[p..<z], as: UTF8.self)
- }
- func offset(_ va: UInt64) throws -> Int {
- guard let s = segments.first(where: { va >= $0.va && va - $0.va < $0.size }) else {
- throw InvalidImage(description: "unmapped VA")
- }
- let p = s.file + Int(va - s.va)
- try check(p, 1)
- return p
- }
- func relative(_ va: UInt64) throws -> UInt64 {
- let delta = Int64(Int32(bitPattern: try word(offset(va))))
- let value = Int64(va) + delta
- guard value >= 0 else { throw InvalidImage(description: "negative address") }
- return UInt64(value)
+
+ public struct Result: Sendable {
+ public let data: Data
+ public let edits: [Edit]
}
- init(_ data: Data) throws {
- self.data = data
- guard try word(0) == 0xfeed_facf, try word(4) == 0x0100_000c else {
- throw InvalidImage(description: "expected ARM64 Mach-O")
- }
- let end = 32 + Int(try word(20))
- try check(32, end - 32)
- var p = 32
- var fs: (Int, Int)?
- for _ in 0..<(try word(16)) {
- let cmd = try word(p)
- let n = Int(try word(p + 4))
- guard n >= 8, p + n <= end else { throw InvalidImage(description: "bad load command") }
- if cmd == 0x19 {
- guard n >= 72 else { throw InvalidImage(description: "short segment") }
- let count = Int(try word(p + 64))
- guard count <= (n - 72) / 80 else { throw InvalidImage(description: "short sections") }
- let file = Int(try quad(p + 40))
- let size = try quad(p + 48)
- try check(file, Int(size))
- segments.append(Segment(va: try quad(p + 24), size: size, file: file))
- for i in 0..<count {
- let s = p + 72 + i * 80
- sections.append(
- Section(
- name: String(decoding: data[s..<s + 16].prefix(while: { $0 != 0 }), as: UTF8.self),
- va: try quad(s + 32), size: Int(try quad(s + 40)), file: Int(try word(s + 48))))
- }
+
+ private static let rootProviders = [
+ "PrimaryAppleAccountListItemProvider", "iCloudListItemProvider",
+ "WalletAndApplePayOrPaymentAndContactlessListItemProvider",
+ ]
+ public static func patchPreferences(_ original: Data) throws -> Result {
+ let digest = SHA256.hash(data: original).map { String(format: "%02x", $0) }.joined()
+ guard digest == "e59851f14f29409590a6de76ca2fe9b9912341aee526a278692ef0d7a86ee2f3" else {
+ throw InvalidImage(
+ description: "unreviewed Preferences input; use the pristine reviewed backup",
+ )
}
- if cmd == 0x26 {
- guard n >= 16 else { throw InvalidImage(description: "short function starts") }
- fs = (Int(try word(p + 8)), Int(try word(p + 12)))
+ let image = try Image(original)
+ var edits = try providerEdits(image)
+ edits += try gameCenterEdits(image)
+ edits.sort { $0.fileOffset < $1.fileOffset }
+ guard edits.count == 5 else {
+ throw InvalidImage(description: "expected five instructions for four root rows")
}
- p += n
- }
- if let (at, size) = fs, let text = sections.first(where: { $0.name == "__text" }),
- let base = segments.first(where: { text.va >= $0.va && text.va - $0.va < $0.size })?.va
- {
- try check(at, size)
- var cur = at
- var va = base
- while cur < at + size {
- var value: UInt64 = 0
- var shift = 0
- var byte: UInt8
- repeat {
- guard cur < at + size, shift < 63 else { throw InvalidImage(description: "bad ULEB") }
- byte = data[cur]
- cur += 1
- value |= UInt64(byte & 127) << shift
- shift += 7
- } while byte & 128 != 0
- if value == 0 { break }
- va += value
- starts.insert(va)
+ var output = original
+ var lastEnd = 0
+ for edit in edits {
+ guard edit.fileOffset >= lastEnd, edit.after.count == 4, edit.before.count == 4 else {
+ throw InvalidImage(description: "overlapping or malformed edits")
+ }
+ try image.check(edit.fileOffset, 4)
+ guard output.subdata(in: edit.fileOffset ..< edit.fileOffset + 4) == edit.before else {
+ throw InvalidImage(description: "preimage changed")
+ }
+ output.replaceSubrange(edit.fileOffset ..< edit.fileOffset + 4, with: edit.after)
+ lastEnd = edit.fileOffset + 4
}
- }
+ return Result(data: output, edits: edits)
}
- }
- private static func instructions(_ image: Image, _ va: UInt64) throws -> [ARM64Instruction] {
- let decoder = ARM64Disassembler()
- let end = image.starts.filter { $0 > va }.min() ?? va
- guard end > va, end - va < 20000 else { return [] }
- let off = try image.offset(va)
- try image.check(off, Int(end - va))
- return decoder.disassemble(Data(image.data[off..<off + Int(end - va)]), at: va)
- }
- private static func providerEdits(_ image: Image) throws -> [Edit] {
- let decoder = ARM64Disassembler()
- guard let proto = image.sections.first(where: { $0.name == "__swift5_proto" }) else {
- throw InvalidImage(description: "missing conformance section")
+
+ private static func makeEdit(_ image: Image, _ name: String, _ va: UInt64, _ bytes: Data) throws
+ -> Edit
+ {
+ let offset = try image.offset(va)
+ try image.check(offset, 4)
+ return Edit(
+ identifier: name, address: va, fileOffset: offset,
+ before: image.data.subdata(in: offset ..< offset + 4), after: bytes,
+ )
}
- var sites: [String: [(UInt64, Data)]] = [:]
- let wanted = Set(rootProviders)
- for i in stride(from: 0, to: proto.size, by: 4) {
- let c = try image.relative(proto.va + UInt64(i))
- let cp = try image.offset(c)
- let flags = try image.word(cp + 12)
- guard (flags >> 3) & 7 == 0, flags & 0xff00 == 0, flags & 0x10000 != 0 else { continue }
- let t = try image.relative(c + 4)
- let name = try image.name(image.offset(image.relative(t + 8)))
- guard wanted.contains(name) else { continue }
- let n = Int(try image.word(cp + 16))
- guard n <= 64 else { throw InvalidImage(description: "witness overflow") }
- for slot in 0..<n {
- let impl = try image.relative(c + UInt64(24 + slot * 8))
- guard image.starts.contains(impl) else { continue }
- let wrapper = try instructions(image, impl)
- for call in wrapper where call.mnemonic == "bl" {
- guard let op = call.detail?.operands.first, op.type == .immediate, op.imm > 0,
- image.starts.contains(UInt64(op.imm))
- else { continue }
- let body = try instructions(image, UInt64(op.imm))
- for k in 1..<body.count {
- let prev = body[k - 1]
- let branch = body[k]
- guard prev.mnemonic == "cmp", let ops = prev.detail?.operands, ops.count == 2,
- ops[0].type == .register, ops[0].reg == .w(0), ops[1].type == .immediate,
- ops[1].imm == 1, branch.mnemonic == "b.ne"
- else { continue }
- guard k >= 2, body[k - 2].mnemonic == "blraa",
- let dest = branch.detail?.operands.first, dest.type == .immediate,
- dest.imm > Int64(branch.address),
- let end = body.firstIndex(where: { $0.address == UInt64(dest.imm) }),
- end > k, end - k <= 40
- else { continue }
- let fallthroughBlock = Array(
- body[(k + 1)..<end].prefix(while: { $0.mnemonic != "b" && !$0.isReturn }))
- guard fallthroughBlock.contains(where: { $0.mnemonic == "bl" }),
- k + 1 + fallthroughBlock.count < end,
- body[k + 1 + fallthroughBlock.count].mnemonic == "b"
- else {
- continue
+
+ private struct InvalidImage: Error, CustomStringConvertible { let description: String }
+ private struct Image {
+ let data: Data
+ struct Segment {
+ let va: UInt64
+ let size: UInt64
+ let file: Int
+ }
+
+ struct Section {
+ let name: String
+ let va: UInt64
+ let size: Int
+ let file: Int
+ }
+
+ var segments: [Segment] = []
+ var sections: [Section] = []
+ var starts: Set<UInt64> = []
+ func check(_ p: Int, _ n: Int) throws {
+ guard p >= 0, n >= 0, p <= data.count, n <= data.count - p else {
+ throw InvalidImage(description: "out of bounds \(p), \(n)")
}
- guard
- let replacement = ARM64Encoder.encodeB(
- from: Int(branch.address), to: Int(branch.address + 4)),
- let decoded = decoder.disassembleOne(replacement, at: branch.address),
- decoded.mnemonic == "b",
- decoded.detail?.operands.first?.imm == Int64(branch.address + 4)
- else { throw InvalidImage(description: "encoder round trip failed") }
- sites[name, default: []].append((branch.address, replacement))
- }
}
- }
- }
- for (name, matches) in sites.sorted(by: { $0.key < $1.key }) {
- guard matches.count == 1 else {
- throw InvalidImage(description: "ambiguous sites for \(name)")
- }
- }
- var edits: [Edit] = []
- for name in rootProviders {
- guard let candidates = sites[name], candidates.count == 1 else {
- throw InvalidImage(description: "missing or ambiguous provider \(name)")
- }
- edits.append(try makeEdit(image, name, candidates[0].0, candidates[0].1))
- }
- return edits
- }
- private static func gameCenterEdits(_ image: Image) throws -> [Edit] {
- // Resolve the named import through LC_SYMTAB, LC_DYSYMTAB and pointer sections.
- // No exported r2 JSON or absolute GOT address is part of the patch input.
- var sym: (Int, Int, Int, Int)?
- var indirect: (Int, Int)?
- var pointerSections: [(UInt64, Int, Int)] = []
- var command = 32
- for _ in 0..<(try image.word(16)) {
- let kind = try image.word(command)
- let size = Int(try image.word(command + 4))
- if kind == 2 {
- try image.check(command, 24)
- sym = (
- Int(try image.word(command + 8)), Int(try image.word(command + 12)),
- Int(try image.word(command + 16)), Int(try image.word(command + 20))
- )
- }
- if kind == 0xb {
- try image.check(command, 80)
- indirect = (Int(try image.word(command + 56)), Int(try image.word(command + 60)))
- }
- if kind == 0x19 {
- let count = Int(try image.word(command + 64))
- for i in 0..<count {
- let section = command + 72 + i * 80
- let flags = try image.word(section + 64) & 0xff
- if flags == 6 || flags == 7 {
- pointerSections.append(
- (
- try image.quad(section + 32), Int(try image.quad(section + 40)) / 8,
- Int(try image.word(section + 68))
- ))
- }
+
+ func word(_ p: Int) throws -> UInt32 {
+ try check(p, 4)
+ return data.withUnsafeBytes {
+ UInt32(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt32.self))
+ }
}
- }
- command += size
- }
- guard let (symbols, symbolCount, strings, stringSize) = sym,
- let (indirectOffset, indirectCount) = indirect
- else { throw InvalidImage(description: "missing symbol tables\n") }
- try image.check(symbols, symbolCount * 16)
- try image.check(strings, stringSize)
- try image.check(indirectOffset, indirectCount * 4)
- var targets: [UInt64] = []
- for (base, count, first) in pointerSections {
- guard first <= indirectCount, count <= indirectCount - first else {
- throw InvalidImage(description: "indirect section out of bounds")
- }
- for slot in 0..<count {
- let symbol = try image.word(indirectOffset + (first + slot) * 4)
- if symbol & 0xc000_0000 != 0 { continue }
- guard symbol < symbolCount else { throw InvalidImage(description: "bad symbol index") }
- let nameOffset = Int(try image.word(symbols + Int(symbol) * 16))
- guard nameOffset < stringSize else {
- throw InvalidImage(description: "bad symbol name offset")
+
+ func quad(_ p: Int) throws -> UInt64 {
+ try check(p, 8)
+ return data.withUnsafeBytes {
+ UInt64(littleEndian: $0.loadUnaligned(fromByteOffset: p, as: UInt64.self))
+ }
}
- if try image.name(strings + nameOffset, stringSize - nameOffset)
- == "_MCFeatureGameCenterAllowed"
- {
- targets.append(base + UInt64(slot * 8))
+
+ func name(_ p: Int, _ max: Int = 512) throws -> String {
+ try check(p, 1)
+ let end = min(data.count, p + max)
+ guard let z = data[p ..< end].firstIndex(of: 0) else {
+ throw InvalidImage(description: "unterminated string")
+ }
+ return String(decoding: data[p ..< z], as: UTF8.self)
+ }
+
+ func offset(_ va: UInt64) throws -> Int {
+ guard let s = segments.first(where: { va >= $0.va && va - $0.va < $0.size }) else {
+ throw InvalidImage(description: "unmapped VA")
+ }
+ let p = s.file + Int(va - s.va)
+ try check(p, 1)
+ return p
+ }
+
+ func relative(_ va: UInt64) throws -> UInt64 {
+ let delta = try Int64(Int32(bitPattern: word(offset(va))))
+ let value = Int64(va) + delta
+ guard value >= 0 else { throw InvalidImage(description: "negative address") }
+ return UInt64(value)
+ }
+
+ init(_ data: Data) throws {
+ self.data = data
+ guard try word(0) == 0xFEED_FACF, try word(4) == 0x0100_000C else {
+ throw InvalidImage(description: "expected ARM64 Mach-O")
+ }
+ let end = try 32 + Int(word(20))
+ try check(32, end - 32)
+ var p = 32
+ var fs: (Int, Int)?
+ for _ in try 0 ..< word(16) {
+ let cmd = try word(p)
+ let n = try Int(word(p + 4))
+ guard n >= 8, p + n <= end else { throw InvalidImage(description: "bad load command") }
+ if cmd == 0x19 {
+ guard n >= 72 else { throw InvalidImage(description: "short segment") }
+ let count = try Int(word(p + 64))
+ guard count <= (n - 72) / 80 else { throw InvalidImage(description: "short sections") }
+ let file = try Int(quad(p + 40))
+ let size = try quad(p + 48)
+ try check(file, Int(size))
+ try segments.append(Segment(va: quad(p + 24), size: size, file: file))
+ for i in 0 ..< count {
+ let s = p + 72 + i * 80
+ try sections.append(
+ Section(
+ name: String(decoding: data[s ..< s + 16].prefix(while: { $0 != 0 }), as: UTF8.self),
+ va: quad(s + 32), size: Int(quad(s + 40)), file: Int(word(s + 48)),
+ ),
+ )
+ }
+ }
+ if cmd == 0x26 {
+ guard n >= 16 else { throw InvalidImage(description: "short function starts") }
+ fs = try (Int(word(p + 8)), Int(word(p + 12)))
+ }
+ p += n
+ }
+ if let (at, size) = fs, let text = sections.first(where: { $0.name == "__text" }),
+ let base = segments.first(where: { text.va >= $0.va && text.va - $0.va < $0.size })?.va
+ {
+ try check(at, size)
+ var cur = at
+ var va = base
+ while cur < at + size {
+ var value: UInt64 = 0
+ var shift = 0
+ var byte: UInt8
+ repeat {
+ guard cur < at + size, shift < 63 else { throw InvalidImage(description: "bad ULEB") }
+ byte = data[cur]
+ cur += 1
+ value |= UInt64(byte & 127) << shift
+ shift += 7
+ } while byte & 128 != 0
+ if value == 0 {
+ break
+ }
+ va += value
+ starts.insert(va)
+ }
+ }
}
- }
}
- guard targets.count == 1 else { throw InvalidImage(description: "ambiguous named import\n") }
- let got = targets[0]
- guard let text = image.sections.first(where: { $0.name == "__text" }) else {
- throw InvalidImage(description: "missing text")
+
+ private static func instructions(_ image: Image, _ va: UInt64) throws -> [ARM64Instruction] {
+ let decoder = ARM64Disassembler()
+ let end = image.starts.filter { $0 > va }.min() ?? va
+ guard end > va, end - va < 20000 else { return [] }
+ let off = try image.offset(va)
+ try image.check(off, Int(end - va))
+ return decoder.disassemble(Data(image.data[off ..< off + Int(end - va)]), at: va)
}
- let decoder = ARM64Disassembler()
- let code = decoder.disassemble(Data(image.data[text.file..<text.file + text.size]), at: text.va)
- var candidates: [(Int, Int, UInt32)] = []
- for i in 8..<code.count {
- let a = code[i - 1]
- let l = code[i]
- guard a.mnemonic == "adrp", l.mnemonic == "ldr", let ao = a.detail?.operands,
- let lo = l.detail?.operands, ao.count == 2, lo.count == 2, ao[1].type == .immediate,
- lo[1].type == .memory, ao[0].reg == lo[1].mem.base,
- UInt64(ao[1].imm) + UInt64(lo[1].mem.disp) == got
- else { continue }
- let tag = code[i - 4]
- let call = code[i - 3]
- let store = code[i - 7]
- let arg0 = code[i - 6]
- guard tag.mnemonic == "mov", let t = tag.detail?.operands, t.count == 2, t[0].reg == .w(2),
- t[1].imm == 8, call.mnemonic == "bl", store.mnemonic == "strb",
- let so = store.detail?.operands, so.count == 2, so[1].type == .memory, so[1].mem.disp == 0,
- arg0.mnemonic == "mov", let args = arg0.detail?.operands, args.count == 2,
- args[0].reg == .x(0), args[1].reg == so[1].mem.base
- else { continue }
- guard let rn = (0..<31).first(where: { so[1].mem.base == .x($0) }) else { continue }
- candidates.append((i - 7, i - 4, UInt32(rn)))
+
+ private static func providerEdits(_ image: Image) throws -> [Edit] {
+ let decoder = ARM64Disassembler()
+ guard let proto = image.sections.first(where: { $0.name == "__swift5_proto" }) else {
+ throw InvalidImage(description: "missing conformance section")
+ }
+ var sites: [String: [(UInt64, Data)]] = [:]
+ let wanted = Set(rootProviders)
+ for i in stride(from: 0, to: proto.size, by: 4) {
+ let c = try image.relative(proto.va + UInt64(i))
+ let cp = try image.offset(c)
+ let flags = try image.word(cp + 12)
+ guard (flags >> 3) & 7 == 0, flags & 0xFF00 == 0, flags & 0x10000 != 0 else { continue }
+ let t = try image.relative(c + 4)
+ let name = try image.name(image.offset(image.relative(t + 8)))
+ guard wanted.contains(name) else { continue }
+ let n = try Int(image.word(cp + 16))
+ guard n <= 64 else { throw InvalidImage(description: "witness overflow") }
+ for slot in 0 ..< n {
+ let impl = try image.relative(c + UInt64(24 + slot * 8))
+ guard image.starts.contains(impl) else { continue }
+ let wrapper = try instructions(image, impl)
+ for call in wrapper where call.mnemonic == "bl" {
+ guard let op = call.detail?.operands.first, op.type == .immediate, op.imm > 0,
+ image.starts.contains(UInt64(op.imm))
+ else { continue }
+ let body = try instructions(image, UInt64(op.imm))
+ for k in 1 ..< body.count {
+ let prev = body[k - 1]
+ let branch = body[k]
+ guard prev.mnemonic == "cmp", let ops = prev.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[0].reg == .w(0), ops[1].type == .immediate,
+ ops[1].imm == 1, branch.mnemonic == "b.ne"
+ else { continue }
+ guard k >= 2, body[k - 2].mnemonic == "blraa",
+ let dest = branch.detail?.operands.first, dest.type == .immediate,
+ dest.imm > Int64(branch.address),
+ let end = body.firstIndex(where: { $0.address == UInt64(dest.imm) }),
+ end > k, end - k <= 40
+ else { continue }
+ let fallthroughBlock = Array(
+ body[(k + 1) ..< end].prefix(while: { $0.mnemonic != "b" && !$0.isReturn }),
+ )
+ guard fallthroughBlock.contains(where: { $0.mnemonic == "bl" }),
+ k + 1 + fallthroughBlock.count < end,
+ body[k + 1 + fallthroughBlock.count].mnemonic == "b"
+ else {
+ continue
+ }
+ guard
+ let replacement = ARM64Encoder.encodeB(
+ from: Int(branch.address), to: Int(branch.address + 4),
+ ),
+ let decoded = decoder.disassembleOne(replacement, at: branch.address),
+ decoded.mnemonic == "b",
+ decoded.detail?.operands.first?.imm == Int64(branch.address + 4)
+ else { throw InvalidImage(description: "encoder round trip failed") }
+ sites[name, default: []].append((branch.address, replacement))
+ }
+ }
+ }
+ }
+ for (name, matches) in sites.sorted(by: { $0.key < $1.key }) {
+ guard matches.count == 1 else {
+ throw InvalidImage(description: "ambiguous sites for \(name)")
+ }
+ }
+ var edits: [Edit] = []
+ for name in rootProviders {
+ guard let candidates = sites[name], candidates.count == 1 else {
+ throw InvalidImage(description: "missing or ambiguous provider \(name)")
+ }
+ try edits.append(makeEdit(image, name, candidates[0].0, candidates[0].1))
+ }
+ return edits
}
- guard candidates.count == 1 else {
- throw InvalidImage(description: "expected one construction block, got \(candidates.count)")
+
+ private static func gameCenterEdits(_ image: Image) throws -> [Edit] {
+ // Resolve the named import through LC_SYMTAB, LC_DYSYMTAB and pointer sections.
+ // No exported r2 JSON or absolute GOT address is part of the patch input.
+ var sym: (Int, Int, Int, Int)?
+ var indirect: (Int, Int)?
+ var pointerSections: [(UInt64, Int, Int)] = []
+ var command = 32
+ for _ in try 0 ..< (image.word(16)) {
+ let kind = try image.word(command)
+ let size = try Int(image.word(command + 4))
+ if kind == 2 {
+ try image.check(command, 24)
+ sym = try (
+ Int(image.word(command + 8)), Int(image.word(command + 12)),
+ Int(image.word(command + 16)), Int(image.word(command + 20)),
+ )
+ }
+ if kind == 0xB {
+ try image.check(command, 80)
+ indirect = try (Int(image.word(command + 56)), Int(image.word(command + 60)))
+ }
+ if kind == 0x19 {
+ let count = try Int(image.word(command + 64))
+ for i in 0 ..< count {
+ let section = command + 72 + i * 80
+ let flags = try image.word(section + 64) & 0xFF
+ if flags == 6 || flags == 7 {
+ try pointerSections.append(
+ (
+ image.quad(section + 32), Int(image.quad(section + 40)) / 8,
+ Int(image.word(section + 68)),
+ ),
+ )
+ }
+ }
+ }
+ command += size
+ }
+ guard let (symbols, symbolCount, strings, stringSize) = sym,
+ let (indirectOffset, indirectCount) = indirect
+ else { throw InvalidImage(description: "missing symbol tables\n") }
+ try image.check(symbols, symbolCount * 16)
+ try image.check(strings, stringSize)
+ try image.check(indirectOffset, indirectCount * 4)
+ var targets: [UInt64] = []
+ for (base, count, first) in pointerSections {
+ guard first <= indirectCount, count <= indirectCount - first else {
+ throw InvalidImage(description: "indirect section out of bounds")
+ }
+ for slot in 0 ..< count {
+ let symbol = try image.word(indirectOffset + (first + slot) * 4)
+ if symbol & 0xC000_0000 != 0 {
+ continue
+ }
+ guard symbol < symbolCount else { throw InvalidImage(description: "bad symbol index") }
+ let nameOffset = try Int(image.word(symbols + Int(symbol) * 16))
+ guard nameOffset < stringSize else {
+ throw InvalidImage(description: "bad symbol name offset")
+ }
+ if try image.name(strings + nameOffset, stringSize - nameOffset)
+ == "_MCFeatureGameCenterAllowed"
+ {
+ targets.append(base + UInt64(slot * 8))
+ }
+ }
+ }
+ guard targets.count == 1 else { throw InvalidImage(description: "ambiguous named import\n") }
+ let got = targets[0]
+ guard let text = image.sections.first(where: { $0.name == "__text" }) else {
+ throw InvalidImage(description: "missing text")
+ }
+ let decoder = ARM64Disassembler()
+ let code = decoder.disassemble(Data(image.data[text.file ..< text.file + text.size]), at: text.va)
+ var candidates: [(Int, Int, UInt32)] = []
+ for i in 8 ..< code.count {
+ let a = code[i - 1]
+ let l = code[i]
+ guard a.mnemonic == "adrp", l.mnemonic == "ldr", let ao = a.detail?.operands,
+ let lo = l.detail?.operands, ao.count == 2, lo.count == 2, ao[1].type == .immediate,
+ lo[1].type == .memory, ao[0].reg == lo[1].mem.base,
+ UInt64(ao[1].imm) + UInt64(lo[1].mem.disp) == got
+ else { continue }
+ let tag = code[i - 4]
+ let call = code[i - 3]
+ let store = code[i - 7]
+ let arg0 = code[i - 6]
+ guard tag.mnemonic == "mov", let t = tag.detail?.operands, t.count == 2, t[0].reg == .w(2),
+ t[1].imm == 8, call.mnemonic == "bl", store.mnemonic == "strb",
+ let so = store.detail?.operands, so.count == 2, so[1].type == .memory, so[1].mem.disp == 0,
+ arg0.mnemonic == "mov", let args = arg0.detail?.operands, args.count == 2,
+ args[0].reg == .x(0), args[1].reg == so[1].mem.base
+ else { continue }
+ guard let rn = (0 ..< 31).first(where: { so[1].mem.base == .x($0) }) else { continue }
+ candidates.append((i - 7, i - 4, UInt32(rn)))
+ }
+ guard candidates.count == 1 else {
+ throw InvalidImage(description: "expected one construction block, got \(candidates.count)")
+ }
+ let (s, t, rn) = candidates[0]
+ let changes = [
+ (code[s], ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: rn, offset: 0)!),
+ (code[t], ARM64Encoder.encodeMovzW(rd: 2, imm16: 2)!),
+ ]
+ return try changes.map { try makeEdit(image, "GameCenter", $0.0.address, $0.1) }
}
- let (s, t, rn) = candidates[0]
- let changes = [
- (code[s], ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: rn, offset: 0)!),
- (code[t], ARM64Encoder.encodeMovzW(rd: 2, imm16: 2)!),
- ]
- return try changes.map { try makeEdit(image, "GameCenter", $0.0.address, $0.1) }
- }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
index 4207e695..cca3e509 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
@@ -223,7 +223,7 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
// MARK: - Earlier implementations
-extension DyldSharedCacheUndoLog {
+public extension DyldSharedCacheUndoLog {
/// Patches whose implementation changed under the same identifier, and how
/// a record written by an earlier one looks. A guest receipt only names the
/// identifier, so without this an installed guest would keep the old bytes
@@ -234,14 +234,14 @@ extension DyldSharedCacheUndoLog {
/// instruction, one 4-byte record per entry point. It now writes a 16-byte
/// conditional dispatcher per entry point, so a 4-byte record is the
/// unconditional version, which leaves DeviceHub's capture display black.
- public static let outdatedImplementations: [String: @Sendable (Record) -> Bool] = [
+ static let outdatedImplementations: [String: @Sendable (Record) -> Bool] = [
"dyld-boot-iomfb_force_kern": { $0.original.count == 4 },
]
/// Whether any record of `patchID` was written by an earlier
/// implementation. False for a patch with no records, which cannot be
/// reverted from this log anyway.
- public func hasOutdatedImplementation(of patchID: String) -> Bool {
+ func hasOutdatedImplementation(of patchID: String) -> Bool {
guard let outdated = Self.outdatedImplementations[patchID] else { return false }
return records(forPatchIDs: [patchID]).contains(where: outdated)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
index 371dc036..68fee865 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
@@ -253,7 +253,11 @@ public enum DyldSharedCacheCameraPatcher {
log: ((String) -> Void)?,
) throws -> Result {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
let resolver = try DyldSharedCacheSymbolResolver(
mainCacheURL: symbolCacheURL ?? chunks.mainCacheURL,
)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
index 4993e208..64edeb2c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
@@ -239,7 +239,11 @@ public enum DyldSharedCacheHypervisorVirtualMachinePatcher {
log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,
) throws -> Result {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
log?(
" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "
+ "\(chunks.mappings.count) mapping(s), "
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
index aee28e24..01e8f4f4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
@@ -173,7 +173,11 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
log: ((String) -> Void)? = stdoutLog,
) throws -> Outcome {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)
return try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)
}
@@ -248,7 +252,6 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
try records.append(force(site, chunks: chunks))
}
-
var reattestation: DyldSharedCacheReattestation?
if records.isEmpty {
log?(
@@ -359,7 +362,7 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
}
private static func isConditionalDispatch(
- _ instructions: [ARM64Instruction], entry: EntryPoint
+ _ instructions: [ARM64Instruction], entry: EntryPoint,
) -> Bool {
guard instructions.count >= 4,
instructions[0].mnemonic == "cbz",
@@ -435,7 +438,8 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
),
let virtBranch = ARM64Encoder.encodeB(
from: Int(entry.publicAddress + 12), to: Int(entry.virtAddress),
- ), portLoad.count == 4, kernBranch.count == 4, virtBranch.count == 4 else {
+ ), portLoad.count == 4, kernBranch.count == 4, virtBranch.count == 4
+ else {
throw PatcherError.patchVerificationFailed(
"cannot encode conditional IOMFB dispatch for \(entry.publicName) "
+ "for \(entry.publicName)",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift
index bcda7a6c..f2b89350 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift
@@ -135,7 +135,11 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {
_ = try replacement(forTargetSize: targetSize)
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)
return try patch(
chunks: chunks,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift
index 8de9e1ec..fb035965 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift
@@ -158,7 +158,11 @@ public enum DyldSharedCacheLSDEmbeddedRegPatcher {
log: ((String) -> Void)? = stdoutLog,
) throws -> Report {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "
+ "\(chunks.mappings.count) mapping(s)")
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift
index 9c346cd2..2036874f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift
@@ -137,7 +137,11 @@ public enum DyldSharedCacheLockdownModePatcher {
log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,
) throws -> Outcome {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
return try patch(in: chunks, dryRun: dryRun, log: log)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift
index 20104d6c..da7bfa68 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift
@@ -271,7 +271,11 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
log: ((String) -> Void)? = stdoutLog,
) throws -> Report {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "
+ "\(chunks.mappings.count) mapping(s)")
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
index 60159a04..f4fdfe7c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
@@ -269,7 +269,11 @@ public enum DyldSharedCacheMaxSlidePatcher {
let chunks = try DyldSharedCacheChunkSet(
directory: chunksDirectory, architecture: architecture, captureUndo: captureUndo,
)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
let headerVMA = try headerVMA(of: chunks)
let header = try readHeader(from: chunks, at: headerVMA, chunkName: mainChunkName)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheSettingsRowsPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheSettingsRowsPatcher.swift
index e06c23da..86f04f2a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheSettingsRowsPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheSettingsRowsPatcher.swift
@@ -6,191 +6,201 @@ import VPhonePatchKit
/// Locates the image by its type-name string, checks its UUID, follows resilient
/// Swift witnesses, and validates the cleanup path. No fixed address is used.
public enum DyldSharedCacheSettingsRowsPatcher {
- public struct Failure: Error, CustomStringConvertible { public let description: String }
- public struct Site: Sendable {
- public let address: UInt64
- public let before: Data
- public let replacement: Data
- public let alreadyPatched: Bool
- }
- private static let provider = "SoftwareUpdateListItemProvider"
- private static let installName =
- "/System/Library/PrivateFrameworks/Settings/GeneralSettingsUI.framework/GeneralSettingsUI"
- private static let uuid = Data([
- 0xf8, 0xc2, 0x94, 0xb7, 0x2c, 0xfb, 0x31, 0x2f, 0xa2, 0xab, 0xf8, 0x72, 0x3f, 0x2b, 0x91, 0x07,
- ])
- public static func discover(in chunks: DyldSharedCacheChunkSet) throws -> Site {
- func fail(_ text: String) -> Failure { Failure(description: text) }
- func word(_ va: UInt64) throws -> UInt32 {
- try chunks.readAtVMA(va, length: 4).loadLE(UInt32.self, at: 0)
+ public struct Failure: Error, CustomStringConvertible { public let description: String }
+ public struct Site: Sendable {
+ public let address: UInt64
+ public let before: Data
+ public let replacement: Data
+ public let alreadyPatched: Bool
}
- func relative(_ va: UInt64) throws -> UInt64 {
- let result = Int64(va) + Int64(Int32(bitPattern: try word(va)))
- guard result > 0 else { throw fail("invalid relative address") }
- return UInt64(result)
- }
- var headers = Set<UInt64>()
- for string in try chunks.findStringVMAs(Data((provider + "\0").utf8)) {
- if let h = try chunks.findMachOHeaderBefore(string),
- chunks.readInstallName(atHeaderVMA: h) == installName
- {
- headers.insert(h)
- }
- }
- guard headers.count == 1, let header = headers.first else {
- throw fail("GeneralSettingsUI missing or ambiguous")
+
+ private static let provider = "SoftwareUpdateListItemProvider"
+ private static let installName =
+ "/System/Library/PrivateFrameworks/Settings/GeneralSettingsUI.framework/GeneralSettingsUI"
+ private static let uuid = Data([
+ 0xF8, 0xC2, 0x94, 0xB7, 0x2C, 0xFB, 0x31, 0x2F, 0xA2, 0xAB, 0xF8, 0x72, 0x3F, 0x2B, 0x91, 0x07,
+ ])
+ public static func discover(in chunks: DyldSharedCacheChunkSet) throws -> Site {
+ func fail(_ text: String) -> Failure {
+ Failure(description: text)
+ }
+ func word(_ va: UInt64) throws -> UInt32 {
+ try chunks.readAtVMA(va, length: 4).loadLE(UInt32.self, at: 0)
+ }
+ func relative(_ va: UInt64) throws -> UInt64 {
+ let result = try Int64(va) + Int64(Int32(bitPattern: word(va)))
+ guard result > 0 else { throw fail("invalid relative address") }
+ return UInt64(result)
+ }
+ var headers = Set<UInt64>()
+ for string in try chunks.findStringVMAs(Data((provider + "\0").utf8)) {
+ if let h = try chunks.findMachOHeaderBefore(string),
+ chunks.readInstallName(atHeaderVMA: h) == installName
+ {
+ headers.insert(h)
+ }
+ }
+ guard headers.count == 1, let header = headers.first else {
+ throw fail("GeneralSettingsUI missing or ambiguous")
+ }
+ let head = try chunks.readAtVMA(header, length: 65536, allowShort: true)
+ guard head.count >= 32 else { throw fail("short header") }
+ let commandEnd = 32 + Int(head.loadLE(UInt32.self, at: 20))
+ let commandCount = Int(head.loadLE(UInt32.self, at: 16))
+ guard commandEnd <= head.count, commandCount <= 256 else { throw fail("invalid load commands") }
+ var p = 32
+ var proto: (UInt64, Int)?
+ var link: (UInt64, UInt64, UInt64)?
+ var startsInfo: (UInt64, Int)?
+ var imageUUID: Data?
+ for _ in 0 ..< commandCount {
+ guard p + 8 <= commandEnd else { throw fail("short command") }
+ let cmd = head.loadLE(UInt32.self, at: p)
+ let size = Int(head.loadLE(UInt32.self, at: p + 4))
+ guard size >= 8, size <= commandEnd - p else { throw fail("invalid command size") }
+ if cmd == 0x1B {
+ guard size >= 24 else { throw fail("short UUID") }
+ imageUUID = head.subdata(in: p + 8 ..< p + 24)
+ }
+ if cmd == 0x26 {
+ guard size >= 16 else { throw fail("short starts") }
+ startsInfo = (
+ UInt64(head.loadLE(UInt32.self, at: p + 8)), Int(head.loadLE(UInt32.self, at: p + 12)),
+ )
+ }
+ if cmd == 0x19 {
+ guard size >= 72 else { throw fail("short segment") }
+ let name = String(decoding: head[p + 8 ..< p + 24].prefix(while: { $0 != 0 }), as: UTF8.self)
+ if name == "__LINKEDIT" {
+ link = (
+ head.loadLE(UInt64.self, at: p + 24), head.loadLE(UInt64.self, at: p + 40),
+ head.loadLE(UInt64.self, at: p + 48),
+ )
+ }
+ let count = Int(head.loadLE(UInt32.self, at: p + 64))
+ guard count <= (size - 72) / 80 else { throw fail("bad sections") }
+ for i in 0 ..< count {
+ let s = p + 72 + i * 80
+ let name = String(decoding: head[s ..< s + 16].prefix(while: { $0 != 0 }), as: UTF8.self)
+ if name == "__swift5_proto" {
+ proto = (
+ head.loadLE(UInt64.self, at: s + 32), Int(head.loadLE(UInt64.self, at: s + 40)),
+ )
+ }
+ }
+ }
+ p += size
+ }
+ guard imageUUID == uuid else { throw fail("unreviewed GeneralSettingsUI UUID") }
+ guard let (pv, ps) = proto, ps > 0, ps < 1_048_576, ps % 4 == 0, let (lv, lf, ls) = link,
+ let (fo, fs) = startsInfo, fo >= lf, fo - lf <= ls, fs > 0, fs <= 1_048_576,
+ UInt64(fs) <= ls - (fo - lf)
+ else { throw fail("missing or invalid discovery metadata") }
+ let encoded = try chunks.readAtVMA(lv + fo - lf, length: fs)
+ var starts = Set<UInt64>()
+ var cursor = 0
+ var address = header
+ while cursor < encoded.count {
+ var value: UInt64 = 0
+ var shift = 0
+ var byte: UInt8
+ repeat {
+ guard cursor < encoded.count, shift < 63 else { throw fail("invalid function starts") }
+ byte = encoded[cursor]
+ cursor += 1
+ value |= UInt64(byte & 127) << shift
+ shift += 7
+ } while byte & 128 != 0
+ if value == 0 {
+ break
+ }
+ guard address <= UInt64.max - value else { throw fail("start overflow") }
+ address += value
+ starts.insert(address)
+ }
+ let decoder = ARM64Disassembler()
+ func body(_ start: UInt64) throws -> [ARM64Instruction] {
+ guard starts.contains(start), let end = starts.filter({ $0 > start }).min(),
+ end - start < 20000
+ else { return [] }
+ return try decoder.disassemble(chunks.readAtVMA(start, length: Int(end - start)), at: start)
+ }
+ var sites: [UInt64: Site] = [:]
+ for i in stride(from: 0, to: ps, by: 4) {
+ let c = try relative(pv + UInt64(i))
+ let flags = try word(c + 12)
+ guard (flags >> 3) & 7 == 0, flags & 0xFF00 == 0, flags & 0x10000 != 0 else { continue }
+ let type = try relative(c + 4)
+ let nameVA = try relative(type + 8)
+ let name = try chunks.readAtVMA(nameVA, length: 128, allowShort: true)
+ guard String(decoding: name.prefix(while: { $0 != 0 }), as: UTF8.self) == provider else {
+ continue
+ }
+ let count = try word(c + 16)
+ guard count <= 64 else { throw fail("invalid witness count") }
+ for slot in 0 ..< count {
+ let witness = try relative(c + UInt64(24 + slot * 8))
+ for call in try body(witness) where call.mnemonic == "bl" {
+ guard let op = call.detail?.operands.first, op.type == .immediate, op.imm > 0 else {
+ continue
+ }
+ let instructions = try body(UInt64(op.imm))
+ for k in 2 ..< max(2, instructions.count) {
+ let branch = instructions[k]
+ let cmp = instructions[k - 1]
+ guard instructions[k - 2].mnemonic == "blraa", cmp.mnemonic == "cmp",
+ let operands = cmp.detail?.operands, operands.count == 2, operands[0].reg == .w(0),
+ operands[1].type == .immediate, operands[1].imm == 1
+ else { continue }
+ let patched =
+ branch.mnemonic == "b"
+ && branch.detail?.operands.first?.imm == Int64(branch.address + 4)
+ guard branch.mnemonic == "b.ne" || patched else { continue }
+ let tail = Array(instructions.dropFirst(k + 1).prefix(40))
+ guard let merge = tail.firstIndex(where: { $0.mnemonic == "b" || $0.isReturn }),
+ tail[merge].mnemonic == "b",
+ tail.prefix(merge).contains(where: { $0.mnemonic == "bl" })
+ else { continue }
+ let normal = tail[merge].address + 4
+ guard patched || branch.detail?.operands.first?.imm == Int64(normal) else { continue }
+ guard
+ let replacement = ARM64Encoder.encodeB(
+ from: Int(branch.address), to: Int(branch.address + 4),
+ )
+ else { throw fail("branch encoding failed") }
+ let before = try chunks.readAtVMA(branch.address, length: 4)
+ sites[branch.address] = Site(
+ address: branch.address, before: before, replacement: replacement,
+ alreadyPatched: patched,
+ )
+ }
+ }
+ }
+ }
+ guard sites.count == 1, let site = sites.values.first else {
+ throw fail("missing or ambiguous Optional cleanup branch")
+ }
+ return site
}
- let head = try chunks.readAtVMA(header, length: 65536, allowShort: true)
- guard head.count >= 32 else { throw fail("short header") }
- let commandEnd = 32 + Int(head.loadLE(UInt32.self, at: 20))
- let commandCount = Int(head.loadLE(UInt32.self, at: 16))
- guard commandEnd <= head.count, commandCount <= 256 else { throw fail("invalid load commands") }
- var p = 32
- var proto: (UInt64, Int)?
- var link: (UInt64, UInt64, UInt64)?
- var startsInfo: (UInt64, Int)?
- var imageUUID: Data?
- for _ in 0..<commandCount {
- guard p + 8 <= commandEnd else { throw fail("short command") }
- let cmd = head.loadLE(UInt32.self, at: p)
- let size = Int(head.loadLE(UInt32.self, at: p + 4))
- guard size >= 8, size <= commandEnd - p else { throw fail("invalid command size") }
- if cmd == 0x1b {
- guard size >= 24 else { throw fail("short UUID") }
- imageUUID = head.subdata(in: p + 8..<p + 24)
- }
- if cmd == 0x26 {
- guard size >= 16 else { throw fail("short starts") }
- startsInfo = (
- UInt64(head.loadLE(UInt32.self, at: p + 8)), Int(head.loadLE(UInt32.self, at: p + 12))
+
+ public static func patch(in chunks: DyldSharedCacheChunkSet, dryRun: Bool = false) throws -> Site {
+ let site = try discover(in: chunks)
+ guard !dryRun else { return site }
+ // Validate the signature before any write; no silent skipped attestation.
+ let span = DyldSharedCacheWriteSpan(vma: site.address, length: 4)
+ let preview = try DyldSharedCacheCodeSignature.reattest(
+ in: chunks, modifiedSpans: [span], dryRun: true, log: nil,
)
- }
- if cmd == 0x19 {
- guard size >= 72 else { throw fail("short segment") }
- let name = String(decoding: head[p + 8..<p + 24].prefix(while: { $0 != 0 }), as: UTF8.self)
- if name == "__LINKEDIT" {
- link = (
- head.loadLE(UInt64.self, at: p + 24), head.loadLE(UInt64.self, at: p + 40),
- head.loadLE(UInt64.self, at: p + 48)
- )
+ guard preview.isFullyAttested, preview.pagesAttested == 1 else {
+ throw Failure(description: "cannot attest target page")
}
- let count = Int(head.loadLE(UInt32.self, at: p + 64))
- guard count <= (size - 72) / 80 else { throw fail("bad sections") }
- for i in 0..<count {
- let s = p + 72 + i * 80
- let name = String(decoding: head[s..<s + 16].prefix(while: { $0 != 0 }), as: UTF8.self)
- if name == "__swift5_proto" {
- proto = (
- head.loadLE(UInt64.self, at: s + 32), Int(head.loadLE(UInt64.self, at: s + 40))
- )
- }
+ if !site.alreadyPatched {
+ try chunks.write(at: site.address, site.replacement)
}
- }
- p += size
- }
- guard imageUUID == uuid else { throw fail("unreviewed GeneralSettingsUI UUID") }
- guard let (pv, ps) = proto, ps > 0, ps < 1_048_576, ps % 4 == 0, let (lv, lf, ls) = link,
- let (fo, fs) = startsInfo, fo >= lf, fo - lf <= ls, fs > 0, fs <= 1_048_576,
- UInt64(fs) <= ls - (fo - lf)
- else { throw fail("missing or invalid discovery metadata") }
- let encoded = try chunks.readAtVMA(lv + fo - lf, length: fs)
- var starts = Set<UInt64>()
- var cursor = 0
- var address = header
- while cursor < encoded.count {
- var value: UInt64 = 0
- var shift = 0
- var byte: UInt8
- repeat {
- guard cursor < encoded.count, shift < 63 else { throw fail("invalid function starts") }
- byte = encoded[cursor]
- cursor += 1
- value |= UInt64(byte & 127) << shift
- shift += 7
- } while byte & 128 != 0
- if value == 0 { break }
- guard address <= UInt64.max - value else { throw fail("start overflow") }
- address += value
- starts.insert(address)
- }
- let decoder = ARM64Disassembler()
- func body(_ start: UInt64) throws -> [ARM64Instruction] {
- guard starts.contains(start), let end = starts.filter({ $0 > start }).min(),
- end - start < 20000
- else { return [] }
- return decoder.disassemble(try chunks.readAtVMA(start, length: Int(end - start)), at: start)
- }
- var sites: [UInt64: Site] = [:]
- for i in stride(from: 0, to: ps, by: 4) {
- let c = try relative(pv + UInt64(i))
- let flags = try word(c + 12)
- guard (flags >> 3) & 7 == 0, flags & 0xff00 == 0, flags & 0x10000 != 0 else { continue }
- let type = try relative(c + 4)
- let nameVA = try relative(type + 8)
- let name = try chunks.readAtVMA(nameVA, length: 128, allowShort: true)
- guard String(decoding: name.prefix(while: { $0 != 0 }), as: UTF8.self) == provider else {
- continue
- }
- let count = try word(c + 16)
- guard count <= 64 else { throw fail("invalid witness count") }
- for slot in 0..<count {
- let witness = try relative(c + UInt64(24 + slot * 8))
- for call in try body(witness) where call.mnemonic == "bl" {
- guard let op = call.detail?.operands.first, op.type == .immediate, op.imm > 0 else {
- continue
- }
- let instructions = try body(UInt64(op.imm))
- for k in 2..<max(2, instructions.count) {
- let branch = instructions[k]
- let cmp = instructions[k - 1]
- guard instructions[k - 2].mnemonic == "blraa", cmp.mnemonic == "cmp",
- let operands = cmp.detail?.operands, operands.count == 2, operands[0].reg == .w(0),
- operands[1].type == .immediate, operands[1].imm == 1
- else { continue }
- let patched =
- branch.mnemonic == "b"
- && branch.detail?.operands.first?.imm == Int64(branch.address + 4)
- guard branch.mnemonic == "b.ne" || patched else { continue }
- let tail = Array(instructions.dropFirst(k + 1).prefix(40))
- guard let merge = tail.firstIndex(where: { $0.mnemonic == "b" || $0.isReturn }),
- tail[merge].mnemonic == "b",
- tail.prefix(merge).contains(where: { $0.mnemonic == "bl" })
- else { continue }
- let normal = tail[merge].address + 4
- guard patched || branch.detail?.operands.first?.imm == Int64(normal) else { continue }
- guard
- let replacement = ARM64Encoder.encodeB(
- from: Int(branch.address), to: Int(branch.address + 4))
- else { throw fail("branch encoding failed") }
- let before = try chunks.readAtVMA(branch.address, length: 4)
- sites[branch.address] = Site(
- address: branch.address, before: before, replacement: replacement,
- alreadyPatched: patched)
- }
+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: [span])
+ guard result.isFullyAttested, result.pagesAttested == 1 else {
+ throw Failure(description: "target page not attested")
}
- }
- }
- guard sites.count == 1, let site = sites.values.first else {
- throw fail("missing or ambiguous Optional cleanup branch")
- }
- return site
- }
- public static func patch(in chunks: DyldSharedCacheChunkSet, dryRun: Bool = false) throws -> Site
- {
- let site = try discover(in: chunks)
- guard !dryRun else { return site }
- // Validate the signature before any write; no silent skipped attestation.
- let span = DyldSharedCacheWriteSpan(vma: site.address, length: 4)
- let preview = try DyldSharedCacheCodeSignature.reattest(
- in: chunks, modifiedSpans: [span], dryRun: true, log: nil)
- guard preview.isFullyAttested, preview.pagesAttested == 1 else {
- throw Failure(description: "cannot attest target page")
- }
- if !site.alreadyPatched { try chunks.write(at: site.address, site.replacement) }
- let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: [span])
- guard result.isFullyAttested, result.pagesAttested == 1 else {
- throw Failure(description: "target page not attested")
+ return site
}
- return site
- }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift
index fd633d52..a0e74c9e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift
@@ -121,7 +121,11 @@ public enum DyldSharedCacheXPCLWCRPatcher {
log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,
) throws -> Outcome {
let chunks = try DyldSharedCacheChunkSet(directory: directory, captureUndo: captureUndo)
- defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }
+ defer {
+ if captureUndo, let undo = chunks.takeUndoLog() {
+ onUndo?(undo)
+ }
+ }
return try apply(chunks: chunks, dryRun: dryRun, log: log)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift
index 4d90519c..4a1e72d3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift
@@ -140,7 +140,7 @@ extension KernelCustomFirmwarePatcher {
replacement,
patchID: "kernel-boot-shared_region_size",
virtualAddress: va,
- description: "arm64 shared region size \(hex(stock)) → \(hex(size)) [vm_shared_region_create]"
+ description: "arm64 shared region size \(hex(stock)) → \(hex(size)) [vm_shared_region_create]",
)
return true
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index f6151423..5b5ac3d4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -56,6 +56,7 @@ public enum FirmwareGuestSystemPatchSet {
target: .guestFile(path: "/" + CustomFirmwareLocationdCohorting.relativePath),
applicability: ios27,
),
+
// MARK: Shared Cache Policy
VPhonePatchDeclaration(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift
index e306c650..fbba6951 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift
@@ -235,14 +235,14 @@ public final class TXMDevPatcher: TXMPatcher {
selector.mnemonic == "mov",
let selOps = selector.detail?.operands, selOps.count == 2,
selOps[0].type == .register, selOps[0].reg == .x(17),
- selOps[1].type == .immediate, selOps[1].imm == 0x7e51,
+ selOps[1].type == .immediate, selOps[1].imm == 0x7E51,
let call = disasm.disassembleOne(in: buffer.data, at: off + 4),
call.mnemonic == "blraa"
else {
if verbose, let ins = disasm.disassembleOne(in: buffer.data, at: off),
ins.mnemonic == "mov",
let ops = ins.detail?.operands,
- ops.count == 2, ops[1].type == .immediate, ops[1].imm == 0x7e51
+ ops.count == 2, ops[1].type == .immediate, ops[1].imm == 0x7E51
{
let next = disasm.disassembleOne(in: buffer.data, at: off + 4)
print(" [·] TXM: selector 0x7e51 at \(String(format: "%06X", off)); next: \(next.map { "\($0.mnemonic) \($0.operandString)" } ?? "decode-fail")")
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index 9aca67cd..2280849d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -695,17 +695,17 @@ struct ARM64CompareBranchTests {
@Test func `Compare branch matches Keystone and rejects unreachable targets`() throws {
// Keystone 0.9.2 C API in /tmp/ks2.c, assembled at 0x2000.
let backward = try #require(ARM64Encoder.encodeCompareBranch(
- nonzero: true, register: 16, from: 0x2000, to: 0x1000
+ nonzero: true, register: 16, from: 0x2000, to: 0x1000,
))
#expect(word(backward) == 0x35FF_8010)
// Keystone C API in /tmp/ks.c, cbz x0 to PC+16.
let null = try #require(ARM64Encoder.encodeCompareBranch(
- nonzero: false, register: 0, from: 0x1000, to: 0x1010, width64: true
+ nonzero: false, register: 0, from: 0x1000, to: 0x1010, width64: true,
))
#expect(word(null) == 0xB400_0080)
#expect(ARM64Encoder.encodeCompareBranch(nonzero: true, register: 16,
- from: 0, to: 1 << 20) == nil)
+ from: 0, to: 1 << 20) == nil)
#expect(ARM64Encoder.encodeCompareBranch(nonzero: true, register: 32,
- from: 0, to: 4) == nil)
+ from: 0, to: 4) == nil)
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift
index 9f15bff0..72dd361a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift
@@ -36,7 +36,7 @@ struct CustomFirmwareKernelcacheSwapTests {
let children = try DERTestEncoder.children(of: output)
#expect(children.count == 4)
#expect(children[0] == DERTestEncoder.ia5String("IMG4"))
- #expect(children[1] == new) // the patched IM4P, verbatim
+ #expect(children[1] == new) // the patched IM4P, verbatim
#expect(children[2] == DERTestEncoder.element(tag: 0xA0, value: manifest))
#expect(children[3] == DERTestEncoder.element(tag: 0xA1, value: restoreInfo))
}
@@ -69,10 +69,10 @@ struct CustomFirmwareKernelcacheSwapTests {
@Test
func `a non-kernel source is refused`() throws {
- let preboot = img4(im4p: try im4p("krnl", [1, 2, 3, 4]), manifest: Data(repeating: 3, count: 16))
+ let preboot = try img4(im4p: im4p("krnl", [1, 2, 3, 4]), manifest: Data(repeating: 3, count: 16))
#expect(throws: PatcherError.self) {
_ = try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(
- prebootIMG4: preboot, patchedKernelcache: try im4p("dtre", [1, 2, 3, 4]),
+ prebootIMG4: preboot, patchedKernelcache: im4p("dtre", [1, 2, 3, 4]),
)
}
}
@@ -82,7 +82,7 @@ struct CustomFirmwareKernelcacheSwapTests {
let bare = try im4p("krnl", [1, 2, 3, 4])
#expect(throws: PatcherError.self) {
_ = try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(
- prebootIMG4: bare, patchedKernelcache: try im4p("krnl", [5, 6, 7, 8]),
+ prebootIMG4: bare, patchedKernelcache: im4p("krnl", [5, 6, 7, 8]),
)
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareLocationdCohortingTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareLocationdCohortingTests.swift
index 4390fa69..c0f057d7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareLocationdCohortingTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareLocationdCohortingTests.swift
@@ -6,19 +6,19 @@ import VPhonePatchKit
@Suite("Locationd cohort configuration")
struct CustomFirmwareLocationdCohortingTests {
@Test
- func selectedOnlyForIOS27() throws {
+ func `selected only for IOS 27`() throws {
for base in [nil, "18.6", "26.6.2", "27.0", "27.0.1", "28.0"] as [String?] {
let plan = try VPhonePatchPlan.resolve(
preset: FirmwarePatchSetCatalog.standardPreset,
patchSets: FirmwarePatchSetCatalog.bundled,
- iOSBase: base.flatMap { VPhoneVersion($0) }, cloudOS: VPhoneVersion("26.4")
+ iOSBase: base.flatMap { VPhoneVersion($0) }, cloudOS: VPhoneVersion("26.4"),
)
#expect(plan.isEnabled(FirmwareGuestSystemPatchSet.locationdCohorting) == (base?.hasPrefix("27.") == true))
}
}
@Test(arguments: [PropertyListSerialization.PropertyListFormat.xml, .binary])
- func preservesOtherFeaturesAndEncoding(format: PropertyListSerialization.PropertyListFormat) throws {
+ func `preserves other features and encoding`(format: PropertyListSerialization.PropertyListFormat) throws {
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: url) }
let original: [String: Any] = [
@@ -44,7 +44,7 @@ struct CustomFirmwareLocationdCohortingTests {
}
@Test
- func rejectsUnexpectedSchemaWithoutWriting() throws {
+ func `rejects unexpected schema without writing`() throws {
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: url) }
for root: [String: Any] in [[:], ["CLAutoCohort": "invalid"], ["CLAutoCohort": ["Enabled": 0]]] {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSettingsRowsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSettingsRowsTests.swift
index c6247fdf..ce8690f1 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSettingsRowsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSettingsRowsTests.swift
@@ -6,14 +6,14 @@ import Testing
@Suite("Settings root rows")
struct CustomFirmwareSettingsRowsTests {
@Test(arguments: [0, 31, 64, 4096])
- func rejectsUnreviewedInput(size: Int) {
+ func `rejects unreviewed input`(size: Int) {
#expect(throws: (any Error).self) {
try CustomFirmwareSettingsRows.patchPreferences(Data(repeating: 0, count: size))
}
}
@Test(.enabled(if: ProcessInfo.processInfo.environment["VPHONE_SETTINGS_FIXTURE"] != nil))
- func reviewedFixtureAndUndo() throws {
+ func `reviewed fixture and undo`() throws {
let path = try #require(ProcessInfo.processInfo.environment["VPHONE_SETTINGS_FIXTURE"])
let original = try Data(contentsOf: URL(fileURLWithPath: path))
let result = try CustomFirmwareSettingsRows.patchPreferences(original)
@@ -23,7 +23,7 @@ struct CustomFirmwareSettingsRowsTests {
var restored = result.data
for edit in result.edits {
#expect(edit.before != edit.after)
- restored.replaceSubrange(edit.fileOffset..<edit.fileOffset + 4, with: edit.before)
+ restored.replaceSubrange(edit.fileOffset ..< edit.fileOffset + 4, with: edit.before)
}
#expect(restored == original)
#expect(throws: (any Error).self) {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/SettingsRowsStoreEncodingTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/SettingsRowsStoreEncodingTests.swift
index d9ff2362..7665d0d3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/SettingsRowsStoreEncodingTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/SettingsRowsStoreEncodingTests.swift
@@ -4,11 +4,12 @@ import VPhonePatchKit
@Suite("Settings rule store encoding")
struct SettingsRowsStoreEncodingTests {
- @Test func encodesZeroPayloadStore() {
- #expect(ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: 23, offset: 0) == Data([0xff, 0x02, 0x00, 0xf9]))
+ @Test func `encodes zero payload store`() {
+ #expect(ARM64Encoder.encodeStrXUnsignedOffset(rt: 31, rn: 23, offset: 0) == Data([0xFF, 0x02, 0x00, 0xF9]))
#expect(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 31, offset: 32760) != nil)
}
- @Test func rejectsInvalidOperands() {
+
+ @Test func `rejects invalid operands`() {
#expect(ARM64Encoder.encodeStrXUnsignedOffset(rt: 32, rn: 0, offset: 0) == nil)
#expect(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 32, offset: 0) == nil)
#expect(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 0, offset: 4) == nil)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
index d15be96c..2172b663 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
@@ -464,13 +464,12 @@ private enum Digest {
let mine = try chunkDigests(of: directory)
let changed = mine.filter { pristineDigests[$0.key] != $0.value }.keys.sorted()
#expect(changed == FrozenReference.changedChunks.keys.sorted())
-
}
}
-// The conditional dispatcher requires a real virtual sibling. These ten were
-// independently resolved on the 24A446 cache; the remaining old force sites
-// must not be rewritten by this narrower patch.
+/// The conditional dispatcher requires a real virtual sibling. These ten were
+/// independently resolved on the 24A446 cache; the remaining old force sites
+/// must not be rewritten by this narrower patch.
private enum ConditionalReference {
static let suffixes: Set<String> = [
"Begin", "Cancel", "DebugInfo", "End", "SetEventSignal",
@@ -479,6 +478,7 @@ private enum ConditionalReference {
static let forcedPairs = FrozenReference.forcedPairs.filter {
suffixes.contains(String($0.publicName.dropFirst("_IOMobileFramebufferSwap".count)))
}
+
static let newlyForced = 10
static let leftOnVirtPath: Set<String> = ["_IOMobileFramebufferSwapSignal"]
static let discoveredNames = Set(forcedPairs.map(\.publicName)).union(leftOnVirtPath)
@@ -707,7 +707,6 @@ struct DyldSharedCacheIOMFBForceKernDiscoveryTests {
#expect(decoded[2].detail?.operands[1].imm == Int64(entry.kernAddress))
#expect(decoded[3].detail?.operands[0].imm == Int64(entry.virtAddress))
#expect(try chunks.bytesAtVMA(address, length: 16) == record.patchedBytes)
-
}
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
index 4a296528..ea6c9477 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
@@ -865,7 +865,6 @@ struct DyldSharedCacheMaxSlideGateTests {
/// `requireFitsAtSlideZero`, which `cfw install` runs before any dyld patch.
/// Synthetic caches only, so this runs without the real-cache fixture: the
/// sizes are the iOS 27.0.1 (24A446) headers from issue #596.
-@Suite
struct DyldSharedCacheRegionCheckTests {
private func withCache(
regionSize: UInt64,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheSettingsRowsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheSettingsRowsTests.swift
index 50db947a..c65a4696 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheSettingsRowsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheSettingsRowsTests.swift
@@ -7,14 +7,15 @@ import Testing
@Suite("Settings Software Update cache")
struct DyldSharedCacheSettingsRowsTests {
@Test(.enabled(if: ProcessInfo.processInfo.environment["VPHONE_SETTINGS_CACHE_FIXTURE"] != nil))
- func fixturePatchRepeatAndUndo() throws {
+ func `fixture patch repeat and undo`() throws {
let fm = FileManager.default
- let source = URL(fileURLWithPath: try #require(ProcessInfo.processInfo.environment["VPHONE_SETTINGS_CACHE_FIXTURE"]))
+ let source = try URL(fileURLWithPath: #require(ProcessInfo.processInfo.environment["VPHONE_SETTINGS_CACHE_FIXTURE"]))
let work = fm.temporaryDirectory.appendingPathComponent("settings-cache-test-\(UUID().uuidString)")
try fm.createDirectory(at: work, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: work) }
for url in try fm.contentsOfDirectory(at: source, includingPropertiesForKeys: nil)
- where url.lastPathComponent.hasPrefix("dyld_shared_cache_arm64e") {
+ where url.lastPathComponent.hasPrefix("dyld_shared_cache_arm64e")
+ {
let to = work.appendingPathComponent(url.lastPathComponent)
guard clonefile(url.path, to.path, 0) == 0 else { throw CocoaError(.fileWriteUnknown) }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift
index 4f0f45be..4a6e8afa 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift
@@ -46,7 +46,7 @@ struct DyldSharedCacheUndoLogTests {
let original = try overwrite(chunk, offset: 16, patched: [0xAA, 0xBB, 0xCC, 0xDD])
var log = DyldSharedCacheUndoLog()
- log.capture(chunk: chunk.lastPathComponent, fileOffset: 16, vma: 0x1_0000, original: original)
+ log.capture(chunk: chunk.lastPathComponent, fileOffset: 16, vma: 0x10000, original: original)
log.stamp(patchID: "dyld-boot-example")
// The range reads as the patched bytes before the revert.
@@ -54,7 +54,7 @@ struct DyldSharedCacheUndoLogTests {
let spans = try log.restore(patchIDs: ["dyld-boot-example"], in: dir)
#expect(spans.count == 1)
- #expect(spans.first?.vma == 0x1_0000)
+ #expect(spans.first?.vma == 0x10000)
#expect(spans.first?.length == 4)
// And the original 16,17,18,19 are back.
@@ -105,7 +105,7 @@ struct DyldSharedCacheUndoLogTests {
@Test
func `A plist round-trips through encode and decode`() throws {
var log = DyldSharedCacheUndoLog()
- log.capture(chunk: "dyld_shared_cache_arm64e.01", fileOffset: 0x2000, vma: 0x1_8000, original: Data([1, 2, 3, 4, 5]))
+ log.capture(chunk: "dyld_shared_cache_arm64e.01", fileOffset: 0x2000, vma: 0x18000, original: Data([1, 2, 3, 4, 5]))
log.stamp(patchID: "dyld-cfw-camera")
let decoded = try DyldSharedCacheUndoLog.decode(log.encoded())
#expect(decoded == log)
@@ -219,9 +219,9 @@ struct DyldSharedCacheOutdatedImplementationTests {
@Test func `The unconditional force-kern records are an earlier implementation`() {
let id = "dyld-boot-iomfb_force_kern"
- let old = DyldSharedCacheUndoLog(records: (0..<31).map { record(id, bytes: 4, offset: $0 * 64) })
+ let old = DyldSharedCacheUndoLog(records: (0 ..< 31).map { record(id, bytes: 4, offset: $0 * 64) })
#expect(old.hasOutdatedImplementation(of: id))
- let current = DyldSharedCacheUndoLog(records: (0..<10).map { record(id, bytes: 16, offset: $0 * 64) })
+ let current = DyldSharedCacheUndoLog(records: (0 ..< 10).map { record(id, bytes: 16, offset: $0 * 64) })
#expect(!current.hasOutdatedImplementation(of: id))
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swift
index 886987c4..6029b2b5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swift
@@ -54,7 +54,9 @@ struct KernelCustomFirmwarePatchSharedRegionSizeTests {
let blockOff = textStart + text.count
text += block
text += [UInt8](repeating: 0xD4, count: 0x20) // UDF padding after
- while text.count % 0x100 != 0 { text.append(0xD4) }
+ while text.count % 0x100 != 0 {
+ text.append(0xD4)
+ }
var image = Data()
func append32(_ value: UInt32) {
@@ -126,7 +128,7 @@ struct KernelCustomFirmwarePatchSharedRegionSizeTests {
#expect(Array(patcher.patchedData[(blockOff + 16) ..< (blockOff + 20)]) == Self.branchForward)
}
- @Test func `does not match a second time over patched bytes`() throws {
+ @Test func `does not match a second time over patched bytes`() {
let (data, _) = Self.kernel(withBlock: Self.stockBlock)
let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
patcher.parseMachO()
@@ -140,7 +142,7 @@ struct KernelCustomFirmwarePatchSharedRegionSizeTests {
#expect(second.patches.isEmpty)
}
- @Test func `refuses a block whose constant is not the stock region`() throws {
+ @Test func `refuses a block whose constant is not the stock region`() {
// movz x22, #0x7000, lsl #16 (0xD2AE0016): a different constant, so the
// window must not match even though the dup and the store are present.
let other: [UInt8] = [0x16, 0x00, 0xAE, 0xD2]
@@ -153,7 +155,7 @@ struct KernelCustomFirmwarePatchSharedRegionSizeTests {
#expect(patcher.patches.isEmpty)
}
- @Test func `follows the registers and displacement of the block`() throws {
+ @Test func `follows the registers and displacement of the block`() {
// The same shape with a different register allocation and pair slot —
// x19 size, x20 base, pair at [sp, #0x80] — so the matcher cannot be
// pinned to x22/x26/0x70. All words keystone-verified:
@@ -195,10 +197,10 @@ struct KernelCustomFirmwarePatchSharedRegionSizeTests {
/// <restore>/kernelcache.research.vphone600 xcodebuild … test
@Test(.enabled(
if: ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"] != nil,
- "VPHONE_VP600_KERNEL is not set; point it at a kernelcache.*.vphone600 to run"
+ "VPHONE_VP600_KERNEL is not set; point it at a kernelcache.*.vphone600 to run",
))
func `patches a real vphone600 kernel`() throws {
- let path = ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"]!
+ let path = try #require(ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"])
let (payload, _) = try IM4PHandler.load(contentsOf: URL(fileURLWithPath: path))
let patcher = KernelCustomFirmwarePatcher(data: payload, verbose: true)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index 8b7572c1..fa71a903 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -44,7 +44,7 @@ struct FirmwareGuestPatchResolutionTests {
let guest = FirmwareGuestPatchResolution.guestTargetIdentifiers
let bootChain = Set(
FirmwarePatchSetCatalog.allDeclarations
- .filter { $0.target.isBootChain }
+ .filter(\.target.isBootChain)
.map(\.identifier),
)
guard
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
index 68504e66..33298d7d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
@@ -147,7 +147,7 @@ struct FirmwarePatchDriftTests {
// kernel-b was turned off after the restore put it in.
#expect(result["kernel-b"]?.applied == true)
#expect(result["kernel-b"]?.isPending == true)
-#expect(result["kernel-b"]?.delivery == .updateKernel)
+ #expect(result["kernel-b"]?.delivery == .updateKernel)
#expect(result["kernel-a"]?.isPending == false)
#expect(result["avp"]?.isPending == false)
// No Guest part in the receipt: the plan says what the install wrote.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index d55829dc..a2455628 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -50,7 +50,7 @@ struct FirmwarePatchSetCatalogTests {
let plan = try VPhonePatchPlan.resolve(
preset: FirmwarePatchSetCatalog.standardPreset,
patchSets: FirmwarePatchSetCatalog.bundled,
- iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4")
+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),
)
#expect(plan.isEnabled(FirmwareGuestSystemPatchSet.installCoordinationPersona) == base.hasPrefix("27."))
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
index 85f007d0..f61f9792 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
@@ -37,7 +37,9 @@ struct DyldSharedCacheUndoOptions: ParsableArguments {
@Option(name: .customLong("undo-id"), help: "Patch identifier to tag the recorded bytes with")
var undoID: String?
- var captures: Bool { undoLog != nil }
+ var captures: Bool {
+ undoLog != nil
+ }
/// Fold this verb's captured runs into the log file beside the cache.
///
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index a6675d40..eda6f5d4 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -338,7 +338,7 @@ struct VPhoneCustomFirmwareInstaller {
priorGuest = receiptGuest ?? (wasInstalled ? priorFallback : [])
switch mode {
case .kernelUpdate:
- break // handled by runKernelUpdate, never reached here
+ break // handled by runKernelUpdate, never reached here
case .full:
guard let restore else {
throw ValidationError("A full CFW install needs a prepared restore tree.")
@@ -387,7 +387,7 @@ struct VPhoneCustomFirmwareInstaller {
// An environment update has no restore tree to read the device from;
// the VM's configuration says which board repair its tree takes.
let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)
- liveGuest.formUnion(try patchPreboot(
+ try liveGuest.formUnion(patchPreboot(
volumes: volumes,
work: work,
plan: plan,
@@ -459,7 +459,7 @@ struct VPhoneCustomFirmwareInstaller {
case .environmentOnly:
print("[+] Guest environment updated; start the VM to pick it up")
case .kernelUpdate:
- break // handled by runKernelUpdate
+ break // handled by runKernelUpdate
}
}
@@ -655,7 +655,13 @@ struct VPhoneCustomFirmwareInstaller {
let plan = readPatchPlan(in: bundleDirectory)
if let pristine = try firmwareOriginalsKernelcache(in: bundleDirectory),
let preset = VPhonePatchPresetStore.preset(named: selection.presetIdentifier),
- !preset.patchSets.contains(where: { if case .external = $0 { true } else { false } })
+ !preset.patchSets.contains(where: {
+ if case .external = $0 {
+ true
+ } else {
+ false
+ }
+ })
{
try pristine.directory.copyFile(from: pristine.name, to: "kernelcache.im4p", in: work.directory)
let copy = work.file("kernelcache.im4p")
@@ -676,7 +682,7 @@ struct VPhoneCustomFirmwareInstaller {
)
print(" [*] kernelcache re-patched from \(VPhoneBundleOperations.firmwareOriginalsDirectoryName)"
+ (changed ? "" : " (preset leaves every kernel patch off)"))
- return (try Data(contentsOf: copy), Set(pipeline.resolvedPlan?.enabled ?? []))
+ return try (Data(contentsOf: copy), Set(pipeline.resolvedPlan?.enabled ?? []))
}
// No originals, or an external-set preset: the restore tree's kernelcache
// was patched by `fw patch` running as the user.
@@ -1016,10 +1022,10 @@ struct VPhoneCustomFirmwareInstaller {
var live = Set<String>()
var failures: [String] = []
- /// Whether the VM's plan (its guest half re-resolved from the current
- /// selection) turned this guest patch on. A VM with no plan gets every
- /// legacy patch, which is what it was restored with. New Settings-row
- /// preferences and motion sensors still require an explicit plan.
+ // Whether the VM's plan (its guest half re-resolved from the current
+ // selection) turned this guest patch on. A VM with no plan gets every
+ // legacy patch, which is what it was restored with. New Settings-row
+ // preferences and motion sensors still require an explicit plan.
func on(_ identifier: String) -> Bool {
guard let plan else {
return !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(identifier)
@@ -1033,31 +1039,33 @@ struct VPhoneCustomFirmwareInstaller {
return true
}
- /// A first backup of a file is safe only when no patch that touches the
- /// file was live before this run: otherwise the "original" we would
- /// snapshot already carries a patch, and a later revert to it would be a
- /// lie. When it is not safe the file's patches are not revertible.
+ // A first backup of a file is safe only when no patch that touches the
+ // file was live before this run: otherwise the "original" we would
+ // snapshot already carries a patch, and a later revert to it would be a
+ // lie. When it is not safe the file's patches are not revertible.
func backupSafe(_ ids: String...) -> Bool {
ids.allSatisfy { !priorGuest.contains($0) }
}
- /// Run a patch step so a throw does not abort the run: report it, keep
- /// each covered patch's prior-live state in the receipt, and carry on.
+ // Run a patch step so a throw does not abort the run: report it, keep
+ // each covered patch's prior-live state in the receipt, and carry on.
func isolate(_ ids: [String], _ body: () throws -> Void) {
do {
try body()
} catch {
failures.append(contentsOf: ids)
print(" [!] \(ids.joined(separator: ", ")): patch step failed, left in its prior state: \(error)")
- for id in ids where priorGuest.contains(id) { live.insert(id) }
+ for id in ids where priorGuest.contains(id) {
+ live.insert(id)
+ }
}
}
- /// A Mach-O patch: apply from the pristine backup when on, restore the
- /// backup when off. A binary off with no `.bak` (patched before backups
- /// were kept) is left as it is and, if it was live before, stays
- /// recorded as live — nothing here can put Apple's original back without
- /// the restore tree.
+ // A Mach-O patch: apply from the pristine backup when on, restore the
+ // backup when off. A binary off with no `.bak` (patched before backups
+ // were kept) is left as it is and, if it was live before, stays
+ // recorded as live — nothing here can put Apple's original back without
+ // the restore tree.
func machO(
_ identifier: String,
path: String,
@@ -1074,7 +1082,9 @@ struct VPhoneCustomFirmwareInstaller {
identifier: codeIdentifier, preserveEntitlements: preserveEntitlements,
injectedDylibPath: injectedDylibPath,
)
- if let bundle { try sealGuestBundle(system: system, bundle: bundle) }
+ if let bundle {
+ try sealGuestBundle(system: system, bundle: bundle)
+ }
live.insert(identifier)
} else if try revertMachO(system: system, work: work, path: path, bundle: bundle) {
print(" [+] \(identifier): restored \(path) from backup")
@@ -1184,7 +1194,7 @@ struct VPhoneCustomFirmwareInstaller {
if version.hasPrefix("27."), on(locationdID) {
try patchCopy(
of: locationdPath, in: system, work: work,
- verb: "patch-locationd-cohorting", backupSafe: backupSafe(locationdID)
+ verb: "patch-locationd-cohorting", backupSafe: backupSafe(locationdID),
)
live.insert(locationdID)
} else if try revertCopy(of: locationdPath, in: system) {
@@ -1210,10 +1220,14 @@ struct VPhoneCustomFirmwareInstaller {
try patchCopy(of: path, in: system, work: work, verb: "patch-build-version", arguments: [build], backupSafe: backupSafe(buildID))
applied = true
}
- if applied { live.insert(buildID) }
+ if applied {
+ live.insert(buildID)
+ }
} else if !on(buildID) {
var reverted = false
- for path in buildPaths where try revertCopy(of: path, in: system) { reverted = true }
+ for path in buildPaths where try revertCopy(of: path, in: system) {
+ reverted = true
+ }
if !reverted, priorGuest.contains(buildID) {
print(" [!] \(buildID): off now but no backup to revert (not revertible)")
live.insert(buildID)
@@ -1313,7 +1327,9 @@ struct VPhoneCustomFirmwareInstaller {
verbs: virtualAudioOn.map(\.verb), preserveEntitlements: true,
)
try sealGuestBundle(system: system, bundle: virtualAudioBundle)
- for patch in virtualAudioOn { live.insert(patch.id) }
+ for patch in virtualAudioOn {
+ live.insert(patch.id)
+ }
} else if try revertMachO(system: system, work: work, path: virtualAudioBinary, bundle: virtualAudioBundle) {
print(" [+] VirtualAudio restored from backup (all speaker/mute patches off)")
} else {
@@ -1343,7 +1359,9 @@ struct VPhoneCustomFirmwareInstaller {
let patched = try patchVirtualAudioGraphConfigurations(
system: system, work: work, verb: entry.verb, backupSafe: graphBackupSafe,
)
- if patched { live.insert(entry.id) }
+ if patched {
+ live.insert(entry.id)
+ }
}
} else if !hadGraphBackup {
for entry in graphGroup where priorGuest.contains(entry.id) {
@@ -1425,7 +1443,9 @@ struct VPhoneCustomFirmwareInstaller {
live: inout Set<String>,
failures: inout [String],
) {
- func enabled(_ id: String) -> Bool { plan?.isEnabled(id) ?? !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(id) }
+ func enabled(_ id: String) -> Bool {
+ plan?.isEnabled(id) ?? !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(id)
+ }
let undoAbsolute = (dsc as NSString).appendingPathComponent(Self.dscUndoLogLeaf)
let undoRelative = "\(Self.dscCacheRelative)/\(Self.dscUndoLogLeaf)"
let undoLog = (try? system.readData(undoRelative)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }
@@ -1484,7 +1504,9 @@ struct VPhoneCustomFirmwareInstaller {
} catch {
failures.append(contentsOf: revertable)
print(" [!] dyld revert failed, left in prior state: \(error)")
- for id in revertable { live.insert(id) }
+ for id in revertable {
+ live.insert(id)
+ }
}
}
}
@@ -1506,7 +1528,9 @@ struct VPhoneCustomFirmwareInstaller {
try system.copyFile(from: backup, to: name, in: work.directory)
try system.replaceFile(path, fromFileAt: work.file(name), mode: 0o755, owner: Self.guestOwner)
try system.removeItem(backup)
- if let bundle { try sealGuestBundle(system: system, bundle: bundle) }
+ if let bundle {
+ try sealGuestBundle(system: system, bundle: bundle)
+ }
return true
}
@@ -1810,7 +1834,9 @@ struct VPhoneCustomFirmwareInstaller {
/// infrastructure. A full install writes every library and creates `/vh`.
private func installEnvironment(system: VPhoneConfinedDirectory, environmentOnly: Bool = false) throws {
for name in VPhoneGuestEnvironment.libraries {
- if VPhoneGuestEnvironment.selectedLibraries.contains(name) { continue }
+ if VPhoneGuestEnvironment.selectedLibraries.contains(name) {
+ continue
+ }
let path = "usr/lib/\(name)"
if environmentOnly, try !system.exists(path) {
print(" [·] \(path): not on this VM, left out")
@@ -1961,9 +1987,11 @@ struct VPhoneCustomFirmwareInstaller {
boardDeviceTree: URL?,
) throws -> Set<String> {
var live = Set<String>()
- /// Whether a device-tree patch is enabled. A VM with no plan gets every
- /// one, which is what it was restored with.
- func enabled(_ identifier: String) -> Bool { plan?.isEnabled(identifier) ?? true }
+ // Whether a device-tree patch is enabled. A VM with no plan gets every
+ // one, which is what it was restored with.
+ func enabled(_ identifier: String) -> Bool {
+ plan?.isEnabled(identifier) ?? true
+ }
let identity = FirmwareGuestIdentityPatchSet.prebootDeviceTreeIdentity
var rewriteIdentity = false
@@ -1972,7 +2000,9 @@ struct VPhoneCustomFirmwareInstaller {
print(" [·] \(identity): skipped, the device tree already presents \(guestDevice.productType)")
} else {
rewriteIdentity = enabled(identity)
- if !rewriteIdentity { print(" [·] \(identity): off in the current selection") }
+ if !rewriteIdentity {
+ print(" [·] \(identity): off in the current selection")
+ }
}
} else if priorGuest.contains(identity) {
// An environment update does not touch the identity rewrite; if the
@@ -2066,7 +2096,7 @@ struct VPhoneCustomFirmwareInstaller {
work: WorkDirectory,
rewriteIdentity: Bool,
identity: String,
- includeIdentity: Bool,
+ includeIdentity _: Bool,
repairGroup: [(id: String, verb: String, arguments: [String])],
repairsOn: [(id: String, verb: String, arguments: [String])],
priorGuest: Set<String>,
@@ -2207,7 +2237,7 @@ struct VPhoneCustomFirmwareInstaller {
print("[*] \(originals) has no \(tree); looking for the \(device.productType) \(firmware.version) (\(firmware.build)) IPSW in \(directories.map(\.path).joined(separator: ", "))")
let recover = { () throws -> (source: VPhoneBoardDeviceTree.Source, path: String)? in
guard let source = VPhoneBoardDeviceTree.find(firmware, in: directories) else { return nil }
- return (source, try VPhoneBoardDeviceTree.store(source, for: firmware, in: bundleDirectory))
+ return try (source, VPhoneBoardDeviceTree.store(source, for: firmware, in: bundleDirectory))
}
do {
guard let recovered = try invokingUser.map({ try $0.withUserCredentials(recover) }) ?? recover() else {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.swift
index 76303cf9..c2cdffa7 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.swift
@@ -17,6 +17,8 @@ struct VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand: ParsableCommand {
let before = site.before.map { String(format: "%02x", $0) }.joined()
let after = site.replacement.map { String(format: "%02x", $0) }.joined()
print("SoftwareUpdateListItemProvider: 0x\(String(site.address, radix: 16)) \(before) -> \(after), already patched: \(site.alreadyPatched)")
- if let captured = chunks.takeUndoLog() { try undo.persist(captured, dryRun: dryRun) }
+ if let captured = chunks.takeUndoLog() {
+ try undo.persist(captured, dryRun: dryRun)
+ }
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateKeys.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateKeys.swift
index b3dd3a10..73f4e097 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateKeys.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateKeys.swift
@@ -33,7 +33,9 @@ enum VPhoneMachineTemplateKeys {
)
return enabled.filter { identifier in
guard let target = targets[identifier] else { return true }
- if case .firmware = target { return true }
+ if case .firmware = target {
+ return true
+ }
return false
}.sorted()
}
@@ -233,7 +235,9 @@ enum VPhoneMachineTemplateKeys {
}
let notApplicable = Set(receipt?.parts.values.flatMap(\.notApplicable) ?? [])
let declarations = FirmwarePatchSetCatalog.allDeclarations.filter {
- if case .firmware = $0.target { return true }
+ if case .firmware = $0.target {
+ return true
+ }
return false
}
return FirmwarePatchDrift.states(
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift
index 95ae505e..64032dc9 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift
@@ -124,7 +124,9 @@ enum VPhoneMachineTemplateTrimmer {
guard attach.succeeded, let whole = disks.wholeDisk, VPhoneGuestDiskLayout.isDeviceName(whole) else {
let leftover = disks.wholeDisk.flatMap { VPhoneGuestDiskLayout.isDeviceName($0) ? $0 : nil }
?? attached.range(of: #"/dev/disk[0-9]+"#, options: .regularExpression).map { String(attached[$0]) }
- if let leftover { eject(leftover) }
+ if let leftover {
+ eject(leftover)
+ }
let detail = attach.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
throw VPhoneSystemTrimError.layout(attach.succeeded
? "diskutil attached no disk image"
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
index 950f5338..5439bee9 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
@@ -112,9 +112,9 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
return
}
- /// Every process holding the disk now, by executable. Looked up again
- /// before each signal, so a PID reused by another program meanwhile is
- /// not taken for the VM.
+ // Every process holding the disk now, by executable. Looked up again
+ // before each signal, so a PID reused by another program meanwhile is
+ // not taken for the VM.
func holders() -> (machine: [VPhoneProcessHolder], others: [VPhoneProcessHolder]) {
guard let r = try? VPhoneProcessRunner.runCapturing(
URL(fileURLWithPath: "/usr/sbin/lsof"),
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index db1f8ab4..a67d731d 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -80,7 +80,9 @@ public enum ARM64Encoder {
let imm19 = delta >> 2
guard imm19 >= -(1 << 18), imm19 < (1 << 18) else { return nil }
var insn: UInt32 = (width64 ? 0xB400_0000 : 0x3400_0000)
- if nonzero { insn |= 1 << 24 }
+ if nonzero {
+ insn |= 1 << 24
+ }
insn |= (UInt32(bitPattern: Int32(imm19)) & 0x7FFFF) << 5
insn |= register
return ARM64.encodeU32(insn)
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift b/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift
index 455cd12c..2206be1c 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/GyroscopeModelTests.swift
@@ -31,7 +31,9 @@ final class VPhoneGyroscopeTestGuest {
struct VPhoneMotionModelTests {
@MainActor static func waitFor(_ predicate: () -> Bool) async {
for _ in 0 ..< 10000 {
- if predicate() { return }
+ if predicate() {
+ return
+ }
await Task.yield()
}
fatalError("Timed out waiting for the gyroscope request queue")
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index be67fb45..582518c1 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -36,8 +36,13 @@ final class VPhoneGuestControl {
struct GuestRPCFailure: Error, CustomStringConvertible, @unchecked Sendable {
let body: [String: Any]
- var message: String { body["message"] as? String ?? "Guest operation failed" }
- var description: String { message }
+ var message: String {
+ body["message"] as? String ?? "Guest operation failed"
+ }
+
+ var description: String {
+ message
+ }
}
struct ClipboardContent {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift
index 0bc7876c..5bd344c2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlAttitude.swift
@@ -8,14 +8,14 @@ extension VPhoneGuestControl {
guard guestCapabilities.contains("motion_attitude") else {
throw ControlError.unsupportedCapability("motion_attitude")
}
- return try attitudeReply(await call("motion.attitude.get"))
+ return try await attitudeReply(call("motion.attitude.get"))
}
func setAttitude(_ value: VPhoneMotionConfiguration) async throws -> VPhoneMotionReply {
guard guestCapabilities.contains("motion_attitude") else {
throw ControlError.unsupportedCapability("motion_attitude")
}
- return try attitudeReply(await call("motion.attitude.set", params: [
+ return try await attitudeReply(call("motion.attitude.set", params: [
"enabled": value.enabled, "roll": value.x, "pitch": value.y, "yaw": value.z,
]))
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift
index 1f026522..e034f2e2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionModel.swift
@@ -27,9 +27,18 @@ final class VPhoneMotionModel {
enqueue(value)
}
}
- var xText = "0" { didSet { axesChanged() } }
- var yText = "0" { didSet { axesChanged() } }
- var zText = "0" { didSet { axesChanged() } }
+
+ var xText = "0" {
+ didSet { axesChanged() }
+ }
+
+ var yText = "0" {
+ didSet { axesChanged() }
+ }
+
+ var zText = "0" {
+ didSet { axesChanged() }
+ }
private(set) var isConnected = false
private(set) var isReading = false
@@ -65,19 +74,29 @@ final class VPhoneMotionModel {
self.write = write
}
- var canEdit: Bool { isConnected && hasLoaded && !isReading }
- var hasInvalidAxes: Bool { parsedConfiguration == nil }
- var canRetry: Bool { canEdit && !isSending && hasLocalChanges && error != nil }
+ var canEdit: Bool {
+ isConnected && hasLoaded && !isReading
+ }
+
+ var hasInvalidAxes: Bool {
+ parsedConfiguration == nil
+ }
+
+ var canRetry: Bool {
+ canEdit && !isSending && hasLocalChanges && error != nil
+ }
- // Computed key-path bindings let the steppers repair a partially typed axis.
+ /// Computed key-path bindings let the steppers repair a partially typed axis.
var xValue: Double {
get { number(xText, range: ranges[0]) ?? configuration.x }
set { xText = formatted(newValue) }
}
+
var yValue: Double {
get { number(yText, range: ranges[1]) ?? configuration.y }
set { yText = formatted(newValue) }
}
+
var zValue: Double {
get { number(zText, range: ranges[2]) ?? configuration.z }
set { zText = formatted(newValue) }
@@ -122,7 +141,9 @@ final class VPhoneMotionModel {
enqueue(zero)
}
- func retry() { startWriter() }
+ func retry() {
+ startWriter()
+ }
/// A read belongs to the view's connection task; an accepted edit's write
/// survives closing the panel. Never apply a read/ack from an old connection.
@@ -131,19 +152,27 @@ final class VPhoneMotionModel {
let current = generation
isConnected = connected
hasLoaded = false
- if hasLocalChanges { pending = configuration }
+ if hasLocalChanges {
+ pending = configuration
+ }
guard connected else {
isReading = false
providerRunning = false
return
}
isReading = true
- defer { if generation == current { isReading = false } }
+ defer {
+ if generation == current {
+ isReading = false
+ }
+ }
do {
let reply = try await read()
guard generation == current, isConnected, !Task.isCancelled else { return }
providerRunning = reply.providerRunning
- if !hasLocalChanges { applyFields(reply.configuration) }
+ if !hasLocalChanges {
+ applyFields(reply.configuration)
+ }
hasLoaded = true
error = nil
startWriter()
@@ -191,7 +220,9 @@ final class VPhoneMotionModel {
error = nil
} catch {
guard generation == current, isConnected else { continue }
- if pending != nil { continue } // A newer edit supersedes this failed write.
+ if pending != nil {
+ continue
+ } // A newer edit supersedes this failed write.
self.error = String(describing: error)
pending = configuration
break
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift
index 4b22a414..81978b98 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Motion/VPhoneMotionView.swift
@@ -3,13 +3,25 @@ import SwiftUI
enum VPhoneMotionSensor {
case gyroscope, attitude
- var identifier: String { self == .gyroscope ? "gyroscope" : "attitude" }
- var axes: [String] { self == .gyroscope ? ["X", "Y", "Z"] : ["Roll", "Pitch", "Yaw"] }
+ var identifier: String {
+ self == .gyroscope ? "gyroscope" : "attitude"
+ }
+
+ var axes: [String] {
+ self == .gyroscope ? ["X", "Y", "Z"] : ["Roll", "Pitch", "Yaw"]
+ }
+
var ranges: [ClosedRange<Double>] {
self == .gyroscope ? [-1000 ... 1000, -1000 ... 1000, -1000 ... 1000] : [-180 ... 180, -90 ... 90, -180 ... 180]
}
- var units: String { self == .gyroscope ? "rad/s" : "°" }
- var step: Double { self == .gyroscope ? 0.1 : 1 }
+
+ var units: String {
+ self == .gyroscope ? "rad/s" : "°"
+ }
+
+ var step: Double {
+ self == .gyroscope ? 0.1 : 1
+ }
}
struct VPhoneMotionView: View {
@@ -122,7 +134,7 @@ struct VPhoneMotionSyncStatus: View {
Spacer(minLength: 0)
if model.canRetry {
Button { model.retry() } label: { Text("Retry", bundle: VPhoneLocalization.bundle) }
- } else if model.isConnected && !model.hasLoaded && !model.isReading {
+ } else if model.isConnected, !model.hasLoaded, !model.isReading {
Button { Task { await model.connectionChanged(true) } } label: {
Text("Retry", bundle: VPhoneLocalization.bundle)
}
diff --git a/VPhoneGuestComponents/Tests/ExecutableRemapProbe.swift b/VPhoneGuestComponents/Tests/ExecutableRemapProbe.swift
index 1042a9e5..7af8ca73 100644
--- a/VPhoneGuestComponents/Tests/ExecutableRemapProbe.swift
+++ b/VPhoneGuestComponents/Tests/ExecutableRemapProbe.swift
@@ -1,9 +1,11 @@
import Darwin
-// Standalone guest probe: no app dependencies, injected scripts or kernel writes.
-// The default mode reports the remap mismatch without executing an NX mapping.
-// --copy exercises the RW-copy-then-RX alternative.
-@_cdecl("remap_probe_marker") public func remapProbeMarker() -> Int32 { 42 }
+/// Standalone guest probe: no app dependencies, injected scripts or kernel writes.
+/// The default mode reports the remap mismatch without executing an NX mapping.
+/// --copy exercises the RW-copy-then-RX alternative.
+@_cdecl("remap_probe_marker") public func remapProbeMarker() -> Int32 {
+ 42
+}
func protection(at value: vm_address_t) -> vm_prot_t? {
var address = value, size: vm_size_t = 0
@@ -15,7 +17,9 @@ func protection(at value: vm_address_t) -> vm_prot_t? {
vm_region_64(mach_task_self_, &address, &size, VM_REGION_BASIC_INFO_64, $0, &count, &object)
}
}
- if object != 0 { mach_port_deallocate(mach_task_self_, object) }
+ if object != 0 {
+ mach_port_deallocate(mach_task_self_, object)
+ }
guard result == KERN_SUCCESS, address <= value, value - address < size else { return nil }
return info.protection
}
@@ -37,9 +41,10 @@ if CommandLine.arguments.contains("--copy") {
}
} else {
result = vm_remap(mach_task_self_, &target, vm_size_t(vm_page_size), 0, VM_FLAGS_ANYWHERE,
- mach_task_self_, page, 1, &current, &maximum, VM_INHERIT_NONE)
+ mach_task_self_, page, 1, &current, &maximum, VM_INHERIT_NONE)
print("remap result", result, "reported protections", current, maximum)
}
+
guard result == KERN_SUCCESS else { exit(2) }
let actual = protection(at: target)
print("actual protection", actual ?? -1)
@@ -47,6 +52,7 @@ guard actual == rx else {
vm_deallocate(mach_task_self_, target, vm_size_t(vm_page_size))
exit(3)
}
+
let copied = unsafeBitCast(UnsafeRawPointer(bitPattern: UInt(target + offset))!, to: (@convention(c) () -> Int32).self)
let answer = copied()
print("copied marker", answer)
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneDiskRebase.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneDiskRebase.swift
index a38f3e3c..bd3d59a0 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneDiskRebase.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneDiskRebase.swift
@@ -703,8 +703,12 @@ private final class ImageFile {
while offset < limit {
let data = lseek(descriptor, off_t(offset), SEEK_DATA)
if data < 0 {
- if errno == ENXIO { break } // no data from here to the end
- if errno == EINVAL { return limit > 0 ? [0 ..< limit] : [] }
+ if errno == ENXIO {
+ break
+ } // no data from here to the end
+ if errno == EINVAL {
+ return limit > 0 ? [0 ..< limit] : []
+ }
throw failure()
}
guard Int64(data) < limit else { break }
@@ -757,7 +761,9 @@ private final class ImageFile {
while filled < length {
let got = pread(descriptor, buffer.pointer + filled, length - filled, off_t(offset + Int64(filled)))
if got < 0 {
- if errno == EINTR { continue }
+ if errno == EINTR {
+ continue
+ }
throw failure()
}
if got == 0 {
@@ -774,7 +780,9 @@ private final class ImageFile {
let start = range.lowerBound + written
let put = pwrite(descriptor, buffer.pointer + start, range.count - written, off_t(chunkOffset + Int64(start)))
if put < 0 {
- if errno == EINTR { continue }
+ if errno == EINTR {
+ continue
+ }
throw failure()
}
written += put
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift
index 9f1cdda6..09f1d677 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift
@@ -290,7 +290,9 @@ public enum VPhoneMachineSnapshots {
throw VPhoneMachineSnapshotError.failed(path: live, reason: currentErrorText())
}
steps.append(SwapStep(file: file, movedAside: movedAside))
- if absent.contains(file) { continue }
+ if absent.contains(file) {
+ continue
+ }
guard rename(staging.appendingPathComponent(file).path, live) == 0 else {
throw VPhoneMachineSnapshotError.failed(path: live, reason: currentErrorText())
}
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift
index 89374da2..6147b6fd 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift
@@ -382,6 +382,7 @@ public struct VPhoneMachineTemplateBuild: Sendable {
self.identifier = identifier
self.stagingURL = stagingURL
}
+
/// The library the machine folder is created in: the staging folder.
public var library: VPhoneLibrary {
VPhoneLibrary(root: stagingURL)
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift
index 3210ffac..b0813256 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift
@@ -212,12 +212,16 @@ public struct VPhoneSystemTrimSpec: Equatable, Hashable, Sendable {
for entry in entries {
switch entry.selection {
case .item:
- if relative == entry.path { return true }
+ if relative == entry.path {
+ return true
+ }
case .contents, .languageBundles:
let prefix = entry.path + "/"
guard relative.hasPrefix(prefix) else { continue }
let child = String(relative.dropFirst(prefix.count))
- if entry.selects(child: child) { return true }
+ if entry.selects(child: child) {
+ return true
+ }
}
}
return false
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swift
index c986e468..04aaa663 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swift
@@ -658,7 +658,7 @@ public final class VPhoneTemplateSetupBoot {
}
let removed = Set(outcome.removedApps)
if !removed.isEmpty {
- let listed = (try call("apps.list", [:], deadline: end)["apps"] as? [[String: Any]] ?? [])
+ let listed = try (call("apps.list", [:], deadline: end)["apps"] as? [[String: Any]] ?? [])
.compactMap { $0["bundle_id"] as? String }
let back = listed.filter { removed.contains($0) }
if !back.isEmpty {
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swift
index a0d69a57..aebc18bc 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swift
@@ -129,10 +129,18 @@ public struct VPhoneTemplateSlimmingRequest: Equatable, Sendable {
if trimGiven, trim.tier != .none {
contradicted.append(trimTier.map { "--trim \($0)" } ?? "--keep-languages")
}
- if serviceProfile == "trimmed" { contradicted.append("--service-profile trimmed") }
- if removeApps == true { contradicted.append("--remove-apps on") }
- if !keepApps.isEmpty { contradicted.append("--keep-apps") }
- if accountsOff { contradicted.append("--accounts-off") }
+ if serviceProfile == "trimmed" {
+ contradicted.append("--service-profile trimmed")
+ }
+ if removeApps == true {
+ contradicted.append("--remove-apps on")
+ }
+ if !keepApps.isEmpty {
+ contradicted.append("--keep-apps")
+ }
+ if accountsOff {
+ contradicted.append("--accounts-off")
+ }
if !contradicted.isEmpty {
problems.append("--slim off turns slimming off; it cannot be combined with \(contradicted.joined(separator: ", "))")
}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
index 912678b5..a0fb99cf 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
@@ -213,12 +213,18 @@ public enum VPhoneGuestProcesses {
guard argc > 0 else { return nil }
var index = MemoryLayout<Int32>.size
// Skip the executable path, then the padding after it.
- while index < buffer.count, buffer[index] != 0 { index += 1 }
- while index < buffer.count, buffer[index] == 0 { index += 1 }
+ while index < buffer.count, buffer[index] != 0 {
+ index += 1
+ }
+ while index < buffer.count, buffer[index] == 0 {
+ index += 1
+ }
var arguments: [String] = []
while arguments.count < argc, index < buffer.count {
let start = index
- while index < buffer.count, buffer[index] != 0 { index += 1 }
+ while index < buffer.count, buffer[index] != 0 {
+ index += 1
+ }
arguments.append(String(decoding: buffer[start ..< index], as: UTF8.self))
index += 1
}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift
index 9ab90934..dc784699 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift
@@ -149,12 +149,12 @@ struct BundleOperationsTests {
.init(name: "unlock", cpuCount: 8, memoryMB: 8192, diskSizeGB: 1, romSource: rom, sepromSource: seprom),
in: lib,
)
- #expect(VPhoneBundleReport(bundle: try lib.bundle(named: "unlock")).unlocksAtStartup == false)
+ #expect(try VPhoneBundleReport(bundle: lib.bundle(named: "unlock")).unlocksAtStartup == false)
_ = try VPhoneBundleOperations.updateConfig(
bundleNamed: "unlock", in: lib, cpuCount: nil, memoryMB: nil, unlocksAtStartup: true,
)
- #expect(VPhoneBundleReport(bundle: try lib.bundle(named: "unlock")).unlocksAtStartup)
+ #expect(try VPhoneBundleReport(bundle: lib.bundle(named: "unlock")).unlocksAtStartup)
// Another edit leaves it alone; off turns it off.
_ = try VPhoneBundleOperations.updateConfig(bundleNamed: "unlock", in: lib, cpuCount: 4, memoryMB: nil)
@@ -175,12 +175,12 @@ struct BundleOperationsTests {
.init(name: "location", cpuCount: 8, memoryMB: 8192, diskSizeGB: 1, romSource: rom, sepromSource: seprom),
in: lib,
)
- #expect(VPhoneBundleReport(bundle: try lib.bundle(named: "location")).syncsHostLocation == false)
+ #expect(try VPhoneBundleReport(bundle: lib.bundle(named: "location")).syncsHostLocation == false)
_ = try VPhoneBundleOperations.updateConfig(
bundleNamed: "location", in: lib, cpuCount: nil, memoryMB: nil, syncsHostLocation: true,
)
- #expect(VPhoneBundleReport(bundle: try lib.bundle(named: "location")).syncsHostLocation)
+ #expect(try VPhoneBundleReport(bundle: lib.bundle(named: "location")).syncsHostLocation)
// Another edit leaves it alone; off turns it off.
_ = try VPhoneBundleOperations.updateConfig(
@@ -555,7 +555,11 @@ struct BundleOperationsTests {
for name in ["Disk.img", "SEPStorage", "nvram.bin"] {
var fd: Int32 = -1
- defer { if fd >= 0 { close(fd) } }
+ defer {
+ if fd >= 0 {
+ close(fd)
+ }
+ }
#expect(throws: VPhoneBundleActivityError.running(name: "src", pids: [getpid()])) {
try VPhoneBundleOperations.clone(bundleNamed: "src", to: "dst", in: lib, newIdentity: false) {
// The source starts after the first check passed.
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/DiskRebaseTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/DiskRebaseTests.swift
index af5205d5..d820b669 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/DiskRebaseTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/DiskRebaseTests.swift
@@ -168,7 +168,9 @@ struct DiskRebaseTests {
let ours = try left.read(upToCount: 1 << 20) ?? Data()
let theirs = try right.read(upToCount: 1 << 20) ?? Data()
guard ours == theirs else { return false }
- if ours.isEmpty { return true }
+ if ours.isEmpty {
+ return true
+ }
}
}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift
index 2fed51c4..b63f9bcc 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift
@@ -511,7 +511,7 @@ struct MachineTemplatesTests {
try FileManager.default.createDirectory(at: built.url.appendingPathComponent("iPhone17,3_27.0_24A435_Restore"), withIntermediateDirectories: true)
try VPhoneMachineTemplates.writeRecord(record(key), inBundle: build.bundleURL)
let frozen = try VPhoneMachineTemplates.freeze(build)
- #expect(VPhoneMachineTemplates.restoreTree(of: try frozen.bundle()) == nil)
+ #expect(try VPhoneMachineTemplates.restoreTree(of: frozen.bundle()) == nil)
}
// MARK: - Source and usage
@@ -710,7 +710,7 @@ struct MachineTemplatesTests {
#expect(VPhoneMachineTemplates.unusedTemplate(after: newSource, in: fixture.library)?.identifier == second.identifier)
}
- @Test func `a clone record without a build is matched by its clone date`() throws {
+ @Test func `a clone record without a build is matched by its clone date`() {
let frozenAt = Date(timeIntervalSince1970: 1_800_000_100)
var template = record()
template.frozen = true
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift
index 393747e6..ac91efec 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift
@@ -107,8 +107,8 @@ struct SystemTrimTests {
}
#expect(!spec.permits("System/Library/LinguisticData/ja"))
#expect(!spec.permits("System/Library/LinguisticData/Info.plist"))
- #expect(!spec.permits("usr/standalone/update")) // the folder itself stays
- #expect(!spec.permits("usr/standalone/update/ramdisk/arm64eSURamDisk.dmg")) // only direct children
+ #expect(!spec.permits("usr/standalone/update")) // the folder itself stays
+ #expect(!spec.permits("usr/standalone/update/ramdisk/arm64eSURamDisk.dmg")) // only direct children
#expect(!spec.permits("usr/standalone/update/.."))
#expect(!spec.permits("usr/standalone/update/../../../etc"))
#expect(!spec.permits("/usr/standalone/update/x"))
@@ -226,6 +226,8 @@ struct SystemTrimTests {
// Again: nothing left to delete, nothing absent either.
let again = try VPhoneSystemTrimSpec.standard.apply(to: root)
#expect(again.bytes == 0)
+ // A key path here makes #expect's expansion fail to compile.
+ // swiftformat:disable:next preferKeyPath
#expect(again.entries.allSatisfy { $0.removed.isEmpty })
}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swift
index 0ab9d8fe..7333a3ea 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swift
@@ -85,7 +85,7 @@ private final class FakeGuest: VPhoneTemplateSetupMachine {
VPhoneGuestCallError(kind: .refused, message: message, detail: detail)
}
- func call(_ method: String, params: [String: Any], timeout: TimeInterval) throws -> [String: Any] {
+ func call(_ method: String, params: [String: Any], timeout _: TimeInterval) throws -> [String: Any] {
calls.append(method)
clock.sleep(0.5)
if downCalls > 0 {
@@ -375,7 +375,7 @@ struct TemplateSetupBootTests {
#expect(!guest.calls.contains("system.reboot"))
}
- @Test func `deviations name what fell short of the plan`() {
+ @Test func `deviations name what fell short of the plan`() throws {
let plan = VPhoneTemplateSetupPlan(slimming: VPhoneTemplateSlimmingRequest.defaultSlimming, requiresEveryApp: true)
var outcome = VPhoneTemplateSetupOutcome()
outcome.apps = plan.removedApps.map { VPhoneTemplateSetupAppResult(bundleID: $0, status: "removed") }
@@ -384,7 +384,7 @@ struct TemplateSetupBootTests {
#expect(outcome.deviations(from: plan).isEmpty)
var short = outcome
- short.apps[short.apps.firstIndex { $0.bundleID == "com.apple.findmy" }!] = VPhoneTemplateSetupAppResult(
+ try short.apps[#require(short.apps.firstIndex { $0.bundleID == "com.apple.findmy" })] = VPhoneTemplateSetupAppResult(
bundleID: "com.apple.findmy",
status: "failed",
error: "LaunchServices still lists the app after unregistration",
diff --git a/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift b/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift
index b0049889..a43e2a2d 100644
--- a/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift
+++ b/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift
@@ -70,7 +70,10 @@ struct ConsoleOutputTests {
struct SplitMix {
var state: UInt64
- init(seed: UInt64) { state = seed }
+ init(seed: UInt64) {
+ state = seed
+ }
+
mutating func next() -> UInt64 {
state &+= 0x9E37_79B9_7F4A_7C15
var z = state
diff --git a/VPhoneLaunchpad/Tests/IPSWCacheTests.swift b/VPhoneLaunchpad/Tests/IPSWCacheTests.swift
index 9bd452d5..7fba39ce 100644
--- a/VPhoneLaunchpad/Tests/IPSWCacheTests.swift
+++ b/VPhoneLaunchpad/Tests/IPSWCacheTests.swift
@@ -64,15 +64,17 @@ struct IPSWCacheTests {
// MARK: - Zip
- static var cloudManifest: [String: Any] { [
- "ProductVersion": "26.4",
- "ProductBuildVersion": "23E5207q",
- "SupportedProductTypes": ["ComputeModule14,1"],
- "BuildIdentities": [
- ["Info": ["DeviceClass": "VRESEARCH101AP"]],
- ["Info": ["DeviceClass": "vphone600ap"]],
- ],
- ] }
+ static var cloudManifest: [String: Any] {
+ [
+ "ProductVersion": "26.4",
+ "ProductBuildVersion": "23E5207q",
+ "SupportedProductTypes": ["ComputeModule14,1"],
+ "BuildIdentities": [
+ ["Info": ["DeviceClass": "VRESEARCH101AP"]],
+ ["Info": ["DeviceClass": "vphone600ap"]],
+ ],
+ ]
+ }
static func manifestData(_ plist: [String: Any]) throws -> Data {
// Padding that deflates well, so the member is really compressed.
@@ -125,9 +127,15 @@ struct IPSWCacheTests {
/// ZIP64, as an IPSW over 4 GB has them.
static func zip64Archive(member: String, contents: Data) -> Data {
var data = Data()
- func le16(_ value: Int) { withUnsafeBytes(of: UInt16(value).littleEndian) { data.append(contentsOf: $0) } }
- func le32(_ value: UInt32) { withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) } }
- func le64(_ value: Int) { withUnsafeBytes(of: UInt64(value).littleEndian) { data.append(contentsOf: $0) } }
+ func le16(_ value: Int) {
+ withUnsafeBytes(of: UInt16(value).littleEndian) { data.append(contentsOf: $0) }
+ }
+ func le32(_ value: UInt32) {
+ withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) }
+ }
+ func le64(_ value: Int) {
+ withUnsafeBytes(of: UInt64(value).littleEndian) { data.append(contentsOf: $0) }
+ }
let name = Data(member.utf8)
le32(0x0403_4B50); le16(45); le16(0); le16(0); le16(0); le16(0); le32(0)
diff --git a/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift b/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift
index 5dab0151..d76e1ed1 100644
--- a/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift
+++ b/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift
@@ -148,4 +148,3 @@ struct MachineSnapshotsTests {
print("Snapshot binding tests passed: save, load, revert, invalid sidecar, names, links")
}
}
-
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swift
index f72d7136..dcdece3e 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -50,7 +50,7 @@ struct TemplatesTests {
// trimmed profile; Camera is not one of the apps.
precondition(parts.arguments == ["--trim", "conservative", "--service-profile", "none",
"--keep-apps", "com.apple.findmy,com.apple.Passbook"],
- "Mixed switches: \(parts.arguments)")
+ "Mixed switches: \(parts.arguments)")
precondition(parts.setupArguments == ["--service-profile", "none", "--keep-apps", "com.apple.findmy,com.apple.Passbook"],
"Setup drops the trim: \(parts.setupArguments)")
precondition(parts.trimArguments == ["--tier", "conservative"], "Conservative trim keeps no languages")
@@ -699,7 +699,9 @@ struct TemplatesTests {
},
bind: {
steps.append("bind")
- if bindFails { throw Unwritable() }
+ if bindFails {
+ throw Unwritable()
+ }
},
updateEnvironment: {
steps.append("update")
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
index 7337f831..791634bb 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
@@ -90,7 +90,7 @@ final class VPhoneLaunchpadAppDelegate: NSObject, NSApplicationDelegate {
/// window is still up. Without the menu bar, closing the last window
/// quits, so the alert says Quit. Cancel refuses the close. In menu bar
/// mode closing only hides the window, so no confirmation is needed.
- func windowShouldClose(_ window: NSWindow) -> Bool {
+ func windowShouldClose(_: NSWindow) -> Bool {
guard !VPhoneLaunchpadMenuBar.isEnabled, let model, model.machines.hasActiveCreation else {
return true
}
@@ -121,7 +121,7 @@ private final class VPhoneLaunchpadWindowCloseHook: NSView, NSWindowDelegate {
private weak var delegate: VPhoneLaunchpadAppDelegate?
/// Read from `NSObject`'s nonisolated forwarding methods. AppKit calls
/// those, and moves this view between windows, on the main thread.
- nonisolated(unsafe) private weak var forwarded: NSWindowDelegate?
+ private nonisolated(unsafe) weak var forwarded: NSWindowDelegate?
init(delegate: VPhoneLaunchpadAppDelegate) {
self.delegate = delegate
@@ -129,7 +129,7 @@ private final class VPhoneLaunchpadWindowCloseHook: NSView, NSWindowDelegate {
}
@available(*, unavailable)
- required init?(coder: NSCoder) {
+ required init?(coder _: NSCoder) {
nil
}
@@ -147,11 +147,11 @@ private final class VPhoneLaunchpadWindowCloseHook: NSView, NSWindowDelegate {
return delegate?.windowShouldClose(sender) ?? true
}
- nonisolated override func responds(to selector: Selector!) -> Bool {
+ override nonisolated func responds(to selector: Selector!) -> Bool {
super.responds(to: selector) || forwarded?.responds(to: selector) == true
}
- nonisolated override func forwardingTarget(for selector: Selector!) -> Any? {
+ override nonisolated func forwardingTarget(for selector: Selector!) -> Any? {
if forwarded?.responds(to: selector) == true {
return forwarded
}
@@ -171,11 +171,11 @@ extension View {
private struct VPhoneLaunchpadWindowCloseInstaller: NSViewRepresentable {
let delegate: VPhoneLaunchpadAppDelegate
- func makeNSView(context: Context) -> NSView {
+ func makeNSView(context _: Context) -> NSView {
MainActor.assumeIsolated {
VPhoneLaunchpadWindowCloseHook(delegate: delegate)
}
}
- func updateNSView(_ nsView: NSView, context: Context) {}
+ func updateNSView(_: NSView, context _: Context) {}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index e8a8850e..be531db5 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -424,7 +424,7 @@
func pending(_ part: String, _ value: Bool = false) -> String {
guard machine else { return "" }
// delivery is reported only for a pending patch, by part.
- let deliveryKind: String = switch part {
+ let deliveryKind = switch part {
case "kernelcache": "update-kernel"
case "Guest": "update-environment"
case "AVPBooter": "fw-patch"
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift
index 43c497d6..0c176aff 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift
@@ -258,7 +258,7 @@ nonisolated enum VPhoneLaunchpadZipReader {
/// The central directory's bytes, found through the end record and, for
/// archives over 4 GB, its ZIP64 counterpart.
static func centralDirectory(_ handle: FileHandle, size: UInt64) throws -> Data {
- let tailLength = min(size, 65_535 + 22 + 20)
+ let tailLength = min(size, 65535 + 22 + 20)
let tail = try read(handle, at: size - tailLength, count: Int(tailLength))
guard tail.count >= 22 else {
throw Failure.notZip
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift
index ef49b03f..84b7acb7 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWCache.swift
@@ -105,11 +105,10 @@ nonisolated enum VPhoneLaunchpadIPSWCache {
continue
}
let size = Int64(values.fileSize ?? 0)
- let facts: VPhoneLaunchpadIPSW?
- if let partial {
- facts = VPhoneLaunchpadIPSW(fileName: partial)
+ let facts: VPhoneLaunchpadIPSW? = if let partial {
+ VPhoneLaunchpadIPSW(fileName: partial)
} else {
- facts = manifestFacts(url, size: size, modified: values.contentModificationDate)
+ manifestFacts(url, size: size, modified: values.contentModificationDate)
?? VPhoneLaunchpadIPSW(fileName: name)
}
files.append(VPhoneLaunchpadIPSWFile(
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
index 19ed4679..e7c3cf70 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
@@ -356,8 +356,8 @@ final class VPhoneLaunchpadCreationPipeline {
try await commandLine.runChecked(arguments, onLine: onLine, onProgress: onProgress)
}
- /// For the template steps: a failure names the step and carries the
- /// line `vphone-cli` ended with, which says why.
+ // For the template steps: a failure names the step and carries the
+ // line `vphone-cli` ended with, which says why.
func runReporting(
_ arguments: [String],
onLine: @escaping @Sendable (String) -> Void = output,
@@ -405,12 +405,12 @@ final class VPhoneLaunchpadCreationPipeline {
defer { downloadFraction = nil }
try await run(["fw", "prepare", name, "--iphone-source", options.iphoneSource,
"--cloudos-source", options.cloudOSSource] + deviceArguments + library,
- onProgress: { [weak self] fraction in
- Task { @MainActor in
- guard let self, self.current == .prepare else { return }
- self.downloadFraction = fraction < 1 ? fraction : nil
- }
- })
+ onProgress: { [weak self] fraction in
+ Task { @MainActor in
+ guard let self, self.current == .prepare else { return }
+ self.downloadFraction = fraction < 1 ? fraction : nil
+ }
+ })
case .patch:
// The preset rides on `fw patch` itself; per-patch overrides are
@@ -809,7 +809,6 @@ final class VPhoneLaunchpadCreationPipeline {
}
}
-
#if DEBUG
extension VPhoneLaunchpadCreationPipeline {
enum PreviewState {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift
index 3da4a8f9..8a54c706 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift
@@ -102,7 +102,6 @@ struct VPhoneLaunchpadGuestSystemView: View {
// MARK: - Services
- @ViewBuilder
private var servicesSection: some View {
Section {
if let profile {
@@ -153,7 +152,6 @@ struct VPhoneLaunchpadGuestSystemView: View {
// MARK: - Apps
- @ViewBuilder
private var appsSection: some View {
Section {
if let removedApps {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
index 279a49b0..969915dc 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
@@ -108,7 +108,7 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
private enum CodingKeys: String, CodingKey {
case name, cpuCount, memoryMB, diskSizeBytes, network, restoreInfo, customFirmwareInstalled, udid, unlocksAtStartup,
- syncsHostLocation
+ syncsHostLocation
}
/// The inspector's firmware line. A restore whose CFW install never
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index d49ea201..eb1e241e 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -877,7 +877,11 @@ final class VPhoneLaunchpadMachineLibrary {
/// run, a stop), the last `lsof` named no other process for its disk,
/// and Launchpad has no operation on it or on a whole library.
private func diskAccess(of machine: Path) -> VPhoneLaunchpadDiskAccess {
- let isBusy = if case .busy = state(of: machine) { true } else { false }
+ let isBusy = if case .busy = state(of: machine) {
+ true
+ } else {
+ false
+ }
return VPhoneLaunchpadDiskAccess(
isLaunched: launched[machine] != nil,
isHeld: diskHolders[machine]?.isEmpty == false,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
index a64afb1a..72957f39 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
@@ -165,11 +165,11 @@ struct VPhoneLaunchpadMachineSettingsView: View {
.onChange(of: unlocksAtStartup) { edited.insert(.unlock) }
.onChange(of: syncsHostLocation) { edited.insert(.location) }
#if DEBUG
- .onAppear {
- if VPhoneLaunchpadPreview.isActive {
- page = VPhoneLaunchpadPreview.machineSettingsPage
+ .onAppear {
+ if VPhoneLaunchpadPreview.isActive {
+ page = VPhoneLaunchpadPreview.machineSettingsPage
+ }
}
- }
#endif
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
index 8c986d5a..edf6516b 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
@@ -464,7 +464,7 @@ nonisolated struct VPhoneLaunchpadTemplate: Decodable, Identifiable, Hashable, S
private enum CodingKeys: String, CodingKey {
case id, path, key, created, builtWithBundleVersion, bootChainBundleVersion, sourceMachine, allocatedBytes,
- machines, stale, staleReasons, sources
+ machines, stale, staleReasons, sources
}
static func decoder() -> JSONDecoder {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift b/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift
index 8a3f09d0..2deb7307 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift
@@ -95,12 +95,13 @@ func launchAndConnect(foreground: Bool) -> Int32 {
// MARK: - Main
var words = Array(CommandLine.arguments.dropFirst())
-// --foreground goes before the command, or among the options of any command
-// but exec, whose arguments all belong to vphone-cli.
+/// --foreground goes before the command, or among the options of any command
+/// but exec, whose arguments all belong to vphone-cli.
var foreground = words.first == "--foreground"
if foreground {
words.removeFirst()
}
+
if words.isEmpty || ["help", "-h", "--help"].contains(words[0]) {
print(usage(), terminator: "")
exit(words.isEmpty ? 1 : 0)
@@ -112,6 +113,7 @@ do {
} catch {
fail(error.message, detail: error.detail)
}
+
let fd = connectControl() ?? launchAndConnect(foreground: foreground)
guard var line = try? JSONEncoder().encode(request) else {