Run a virtual iPhone on an Apple Silicon Mac.
Swift
Fix signing mixed armv7 and arm64 Mach-O files
Phineas Guo47a357392630
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swiftindex ef75e53f..6adf0803 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift@@ -433,8 +433,11 @@ struct VPhoneMachOFile {let cpuType: UInt32let cpuSubtype: UInt32let alignment: UInt32+ /// Legacy ARM code is carried byte-for-byte, never re-signed.+ let preservedImage: Data?}+ /// Supported slices, in signing order; preserved ARM slices are excluded.let slices: [VPhoneMachOImage]/// nil for a thin file.let architectures: [Architecture]?@@ -475,12 +478,38 @@ struct VPhoneMachOFile {guard alignment <= 30 else {throw VPhoneSignError.malformed("architecture \(index) is aligned to 2^\(alignment)")}+ let cpuType: UInt32 = data.bigEndianValue(at: entry)+ let cpuSubtype: UInt32 = data.bigEndianValue(at: entry + 4)+ var preservedImage: Data?+ if cpuType == UInt32(CPU_TYPE_ARM) {+ let headerSize = MemoryLayout<mach_header>.size+ guard length >= headerSize,+ data.littleEndianValue(at: offset) as UInt32 == MH_MAGIC,+ data.littleEndianValue(at: offset + 4) as UInt32 == cpuType,+ data.littleEndianValue(at: offset + 8) as UInt32 == cpuSubtype+ else {+ throw VPhoneSignError.malformed("architecture \(index) has an inconsistent ARM header")+ }+ let commandsSize = Int(data.littleEndianValue(at: offset + 20) as UInt32)+ let commandCount = Int(data.littleEndianValue(at: offset + 16) as UInt32)+ guard commandsSize <= length - headerSize, commandCount <= commandsSize / 8 else {+ throw VPhoneSignError.malformed("architecture \(index) has an invalid load command area")+ }+ // Third-party IPAs can bundle armv7 alongside arm64.+ // Preserve the unused legacy slice and its old signature.+ preservedImage = data.subdata(in: offset ..< offset + length)+ } else {+ try slices.append(VPhoneMachOImage(file: data, range: offset ..< offset + length))+ }architectures.append(Architecture(- cpuType: data.bigEndianValue(at: entry),- cpuSubtype: data.bigEndianValue(at: entry + 4),+ cpuType: cpuType,+ cpuSubtype: cpuSubtype,alignment: alignment,+ preservedImage: preservedImage,))- try slices.append(VPhoneMachOImage(file: data, range: offset ..< offset + length))+ }+ guard !slices.isEmpty else {+ throw VPhoneSignError.unsupportedSlice("a fat file with only 32-bit ARM slices")}self.architectures = architecturesself.slices = slices@@ -492,16 +521,24 @@ struct VPhoneMachOFile {}}- /// The file rebuilt from `images`, one per slice. ldid lays the slices- /// out again, each on its own alignment.+ /// The file rebuilt from `images`, one per supported slice, plus the+ /// preserved slices. Each architecture keeps its own alignment and order.func assembled(_ images: [Data]) throws -> Data {guard let architectures else { return images[0] }var header = Data()header.appendBigEndian(FAT_MAGIC)- header.appendBigEndian(UInt32(images.count))+ header.appendBigEndian(UInt32(architectures.count))var body = Data()- let bodyStart = 8 + images.count * MemoryLayout<fat_arch>.size- for (architecture, image) in zip(architectures, images) {+ let bodyStart = 8 + architectures.count * MemoryLayout<fat_arch>.size+ var signedIndex = 0+ for architecture in architectures {+ let image: Data+ if let preservedImage = architecture.preservedImage {+ image = preservedImage+ } else {+ image = images[signedIndex]+ signedIndex += 1+ }let offset = (bodyStart + body.count).aligned(to: 1 << Int(architecture.alignment))body.append(Data(count: offset - bodyStart - body.count))body.append(image)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSignError.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSignError.swiftindex a205a1c2..88618e13 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSignError.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSignError.swift@@ -10,9 +10,9 @@ public enum VPhoneSignError: Error, Equatable, CustomStringConvertible {/// A header, an architecture, a load command or the old signature points/// outside the file.case malformed(String)- /// A slice that is not 64-bit little-endian. ldid signs 32-bit slices- /// too; nothing this project signs has one, so it is refused rather- /// than written wrong.+ /// A slice this signer cannot sign. Legacy 32-bit ARM slices are only+ /// preserved in fat files that also contain a supported 64-bit slice;+ /// thin 32-bit files and fat files containing only 32-bit ARM are refused.case unsupportedSlice(String)/// The longer load commands do not fit in front of the first section,/// which happens when a file that never had a signature has no room fordiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swiftindex d37add53..12b009ea 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift@@ -108,7 +108,8 @@ public enum VPhoneSigner {}/// Signs `data`. `options.identifier` must be set; the file-based entry- /// point fills it in from the name.+ /// point fills it in from the name. In mixed ARM fat files, signing+ /// options apply only to supported slices; 32-bit ARM slices are preserved.public static func sign(_ data: Data, options: VPhoneSignOptions) throws -> Data {guard let identifier = options.identifier else {throw VPhoneSignError.signingFailed("no identifier, and no file name to take one from")@@ -117,12 +118,14 @@ public enum VPhoneSigner {// ldid works out the hashes once, from the first slice it reads, and// keeps them for the rest of the run. Every other slice inherits- // that decision however new its own deployment target is.+ // that decision however new its own deployment target is. Preserved+ // legacy ARM slices do not participate in signing or digest choice.let digests = options.style == .appleAdHoc ? [.sha256] : file.slices[0].digests+ let architectures = file.architectures?.filter { $0.preservedImage == nil }var images: [Data] = []for (index, slice) in file.slices.enumerated() {- let alignment = file.architectures.map { Int($0[index].alignment) } ?? slice.linkeditAlignment+ let alignment = architectures.map { Int($0[index].alignment) } ?? slice.linkeditAlignmentlet signature = try signature(for: slice,identifier: identifier,@@ -210,8 +213,8 @@ public enum VPhoneSigner {return identifier}- /// What `ldid -e` prints: the entitlements of each slice that carries- /// any, in slice order, exactly as the signature stores them. A slice+ /// The entitlements of each supported slice that carries any, in slice+ /// order, exactly as the signature stores them. A slice/// with none contributes nothing, so a file with no entitlements at all/// gives an empty array.public static func entitlements(ofFileAt url: URL) throws -> [Data] {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignFatSliceTests.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignFatSliceTests.swiftnew file mode 100644index 00000000..10257d24--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignFatSliceTests.swift@@ -0,0 +1,126 @@+//+// VPhoneSignFatSliceTests.swift+// vphone-cli+//+// Created by Phineas Guo on 2026/11/01.+//++import Foundation+import MachO+import Testing+@testable import VPhoneSign++@Suite("Legacy ARM slices in universal binaries")+struct VPhoneSignFatSliceTests {+ @Test(arguments: [false, true], [VPhoneSignOptions.Style.ldid, .appleAdHoc])+ func `mixed armv7 and arm64 files preserve armv7 and sign arm64`(+ legacyFirst: Bool,+ style: VPhoneSignOptions.Style,+ ) throws {+ let arm64 = try Data(contentsOf: VPhoneSignFixtures.url("hello-arm64"))+ let legacy = Self.armv7+ let images = legacyFirst ? [legacy, arm64] : [arm64, legacy]+ let input = Self.fat(images)+ let options = VPhoneSignOptions(identifier: "mixed", mergesExisting: true, style: style)++ let signed = try VPhoneSigner.sign(input, options: options)+ // lipo independently checks the table and extracts both slices.+ let directory = try VPhoneSignFixtures.temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let file = directory.appendingPathComponent("mixed")+ let extracted = directory.appendingPathComponent("arm64")+ let preserved = directory.appendingPathComponent("armv7")+ try signed.write(to: file)+ let info = try VPhoneSignFixtures.run(URL(fileURLWithPath: "/usr/bin/lipo"), ["-archs", file.path])+ #expect(info.status == 0, "\(info.error)")+ let expectedArchitectures = legacyFirst ? "armv7 arm64" : "arm64 armv7"+ #expect(String(decoding: info.out, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) == expectedArchitectures)+ let extract = try VPhoneSignFixtures.run(+ URL(fileURLWithPath: "/usr/bin/lipo"),+ [file.path, "-thin", "arm64", "-output", extracted.path],+ )+ #expect(extract.status == 0, "\(extract.error)")+ #expect(try Data(contentsOf: extracted) == VPhoneSigner.sign(arm64, options: options))+ let extractLegacy = try VPhoneSignFixtures.run(+ URL(fileURLWithPath: "/usr/bin/lipo"),+ [file.path, "-thin", "armv7", "-output", preserved.path],+ )+ #expect(extractLegacy.status == 0, "\(extractLegacy.error)")+ #expect(try Data(contentsOf: preserved) == legacy)+ #expect(try VPhoneSignBlobs(fileAt: extracted).slices[0][0] != nil)+ #expect(try VPhoneSigner.sign(signed, options: options) == signed)+ }++ @Test+ func `thin and fat files containing only armv7 are refused`() throws {+ for input in [Self.armv7, Self.fat([Self.armv7])] {+ #expect(throws: VPhoneSignError.self) {+ try VPhoneSigner.sign(input, options: .init(identifier: "legacy"))+ }+ }+ }++ @Test+ func `an out of bounds legacy slice is still refused`() throws {+ let arm64 = try Data(contentsOf: VPhoneSignFixtures.url("hello-arm64"))+ var input = Self.fat([Self.armv7, arm64])+ // First fat_arch.size, deliberately extending beyond the whole file.+ input.replaceSubrange(20 ..< 24, with: [0xFF, 0xFF, 0xFF, 0xFF])+ #expect(throws: VPhoneSignError.self) {+ try VPhoneSigner.sign(input, options: .init(identifier: "bad"))+ }+ }++ @Test+ func `unknown and inconsistent legacy headers are refused`() throws {+ let arm64 = try Data(contentsOf: VPhoneSignFixtures.url("hello-arm64"))+ var wrongCPU = Self.armv7+ wrongCPU.storeLittleEndian(UInt32(CPU_TYPE_X86), at: 4)+ var badCommands = Self.armv7+ badCommands.storeLittleEndian(UInt32.max, at: 20)+ for legacy in [Data(Self.armv7.prefix(12)), wrongCPU, badCommands] {+ var input = Self.fat([legacy, arm64])+ // The container claims ARM even when the embedded header does not.+ input.replaceSubrange(8 ..< 12, with: [0, 0, 0, UInt8(CPU_TYPE_ARM)])+ #expect(throws: VPhoneSignError.self) {+ try VPhoneSigner.sign(input, options: .init(identifier: "bad"))+ }+ }+ }++ // MARK: - Container fixtures++ /// A synthetic ARM header with an opaque old signature to preserve.+ /// It is never signed or executed; the retained arm64 is a real fixture.+ private static var armv7: Data {+ var image = Data()+ for word: UInt32 in [MH_MAGIC, UInt32(CPU_TYPE_ARM), UInt32(CPU_SUBTYPE_ARM_V7), UInt32(MH_BUNDLE), 1, 16, 0] {+ withUnsafeBytes(of: word.littleEndian) { image.append(contentsOf: $0) }+ }+ for word: UInt32 in [UInt32(LC_CODE_SIGNATURE), 16, 44, 12] {+ withUnsafeBytes(of: word.littleEndian) { image.append(contentsOf: $0) }+ }+ image.append(Data("oldSignature".utf8))+ return image+ }++ private static func fat(_ images: [Data]) -> Data {+ var header = Data()+ header.appendBigEndian(FAT_MAGIC)+ header.appendBigEndian(UInt32(images.count))+ var body = Data()+ let headerSize = 8 + images.count * MemoryLayout<fat_arch>.size+ for image in images {+ let cpu: UInt32 = image.littleEndianValue(at: 4)+ let alignment: UInt32 = cpu == UInt32(CPU_TYPE_ARM) ? 12 : 14+ let offset = (headerSize + body.count).aligned(to: 1 << Int(alignment))+ body.append(Data(count: offset - headerSize - body.count))+ body.append(image)+ let subtype: UInt32 = image.littleEndianValue(at: 8)+ for field in [cpu, subtype, UInt32(offset), UInt32(image.count), alignment] {+ header.appendBigEndian(field)+ }+ }+ return header + body+ }+}