Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift
15.3 KB
Raw Blame
// CustomFirmwareIPhoneProductTests.swift — an iPhone guest takes D47AP's product description.
//
// `withPhoneProduct` (the Preboot repair) fills vphone600's `/product`
// placeholders from the board tree, adds the Camera Control and Action Button
// properties vphone600 lacks, and fills `/buttons/function-button_ringeren`.
// The trees here are built in the flat format the restored tree uses, so the
// parse, the edit and the serialization all run.

@testable import FirmwarePatcher
import Foundation
import Testing

@Suite("iPhone product description from the board tree")
struct CustomFirmwareIPhoneProductTests {
    private typealias Node = FlatDeviceTreeNode

    private static let placeholder: UInt16 = 0x8000

    private static func tree(product: Node, buttons: Node) -> Data {
        Node("device-tree", [("model", Data("iPhone17,3\0\0".utf8))], children: [
            Node("chosen"),
            product,
            buttons,
        ]).serialized
    }

    /// vphone600's, trimmed: placeholders, a real value, and a VM-only property.
    private static let guestProduct = Node("product", [
        ("product-name", Data("syscfg/prde\0".utf8)),
        ("assistant", Data("syscfg/assi\0".utf8)),
        ("framebuffer-identifier", Data("syscfg/fbid\0".utf8)),
        ("graphics-featureset-class", Data("APPLE7\0".utf8)),
    ], flags: ["product-name": placeholder, "assistant": placeholder, "framebuffer-identifier": placeholder])

    private static let guestButtons = Node("buttons", [
        ("function-button_ringeren", Data("syscfg/rgen\0".utf8)),
        ("home-button-type", Node.uint32(2)),
    ], flags: ["function-button_ringeren": placeholder])

    /// D47AP's, trimmed: real values, hardware the VM lacks, and its phandle.
    private static let boardProduct = Node("product", [
        ("AAPL,phandle", Node.uint32(363)),
        ("product-name", Data("iPhone 16\0".utf8)),
        ("assistant", Node.uint32(1)),
        ("framebuffer-identifier", Data("A6AC96E7\0".utf8)),
        ("graphics-featureset-class", Data("APPLE9\0".utf8)),
        ("supports-camera-button", Node.uint32(1)),
        ("ringer-button-location", Data(repeating: 7, count: 20)),
        ("nfc-express", Node.uint32(1)),
    ])

    private static let boardButtons = Node("buttons", [
        ("function-button_ringeren", Data("w\0\0\0RntbNIRb".utf8)),
        ("compatible", Data("buttons\0".utf8)),
        ("home-button-type", Node.uint32(2)),
    ])

    /// What the guest's nodes should become.
    private static let presentedProduct = Node("product", [
        ("product-name", Data("iPhone 16\0".utf8)),
        ("assistant", Node.uint32(1)),
        ("framebuffer-identifier", Data("syscfg/fbid\0".utf8)),
        ("graphics-featureset-class", Data("APPLE7\0".utf8)),
        ("ringer-button-location", Data(repeating: 7, count: 20)),
        ("supports-camera-button", Node.uint32(1)),
    ], flags: ["framebuffer-identifier": placeholder])

    private static let presentedButtons = Node("buttons", [
        ("function-button_ringeren", Data("w\0\0\0RntbNIRb".utf8)),
        ("home-button-type", Node.uint32(2)),
    ])

    // MARK: - Tests

    @Test func `fills the placeholders and adds the missing button properties`() throws {
        let original = Self.tree(product: Self.guestProduct, buttons: Self.guestButtons)
        let board = Self.tree(product: Self.boardProduct, buttons: Self.boardButtons)
        let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(original, board: board)
        #expect(changes.map(\.property) == [
            "product/product-name", "product/assistant",
            "product/ringer-button-location", "product/supports-camera-button",
            "buttons/function-button_ringeren",
        ])
        #expect(changes.first?.before == "syscfg/prde")
        #expect(changes.first?.after == "iPhone 16")
        #expect(changes[2].before == "absent")
        #expect(patched.count == original.count + delta)
        #expect(patched == Self.tree(product: Self.presentedProduct, buttons: Self.presentedButtons))
    }

    @Test func `leaves hardware the VM lacks and the board's phandle alone`() throws {
        let original = Self.tree(product: Self.guestProduct, buttons: Self.guestButtons)
        let board = Self.tree(product: Self.boardProduct, buttons: Self.boardButtons)
        let (patched, _, _) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(original, board: board)
        let text = String(decoding: patched, as: UTF8.self)
        #expect(!text.contains("nfc-express"))
        #expect(!text.contains("A6AC96E7"))
        #expect(!text.contains("APPLE9"))
        #expect(!text.contains("compatible"))
    }

    @Test func `a tree that already has them is unchanged`() throws {
        let presented = Self.tree(product: Self.presentedProduct, buttons: Self.presentedButtons)
        let board = Self.tree(product: Self.boardProduct, buttons: Self.boardButtons)
        let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(presented, board: board)
        #expect(changes.isEmpty)
        #expect(delta == 0)
        #expect(patched == presented)
    }

    // MARK: - Always On display

    private static func tree(product: Node, armIO: [Node]) -> Data {
        Node("device-tree", [("model", Data("iPhone18,1\0\0".utf8))], children: [
            Node("arm-io", children: armIO),
            product,
        ]).serialized
    }

    private static let guestArmIO = [Node("gfx", [("compatible", Data("paravirtualizedgraphics,gpu\0".utf8))])]

    @Test func `an Always On board marks the guest's product, once`() throws {
        let original = Self.tree(product: Node("product", [("graphics-featureset-class", Data("APPLE7\0".utf8))]),
                                 armIO: Self.guestArmIO)
        let board = Self.tree(product: Node("product"), armIO: [
            Node("disp0", [("compatible", Data("disp0,t8150\0".utf8)), ("always-on-time", Node.uint32(1))]),
        ])
        let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(original, board: board)
        #expect(changes.map(\.property) == ["product/vphone-always-on-display"])
        #expect(delta == 36 + 4)
        #expect(patched == Self.tree(product: Node("product", [
            ("graphics-featureset-class", Data("APPLE7\0".utf8)),
            ("vphone-always-on-display", Node.uint32(1)),
        ]), armIO: Self.guestArmIO))
        // The marker is all: the guest's arm-io gets no disp0.
        #expect(!String(decoding: patched, as: UTF8.self).contains("always-on-time"))

        let (twice, again, _) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(patched, board: board)
        #expect(again.isEmpty)
        #expect(twice == patched)
    }

    @Test func `a board without an Always On display leaves the product unmarked`() throws {
        let original = Self.tree(product: Node("product", [("graphics-featureset-class", Data("APPLE7\0".utf8))]),
                                 armIO: Self.guestArmIO)
        let board = Self.tree(product: Node("product"), armIO: [
            Node("disp0", [("compatible", Data("disp0,t8140\0".utf8))]),
        ])
        let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(original, board: board)
        #expect(changes.isEmpty)
        #expect(patched == original)
    }
}

@Suite("Foldable VM sub-type")
struct CustomFirmwareFoldableVMSubtypeTests {
    private typealias Node = FlatDeviceTreeNode

    private static func tree(subtype: String) -> Data {
        Node("device-tree", [
            ("model", Data("iPhone19,4\0".utf8)),
            ("target-sub-type", Data("\(subtype)\0".utf8)),
            ("target-type", Data("V68\0".utf8)),
        ], children: [Node("product", [("product-name", Data("iPhone\0".utf8))])]).serialized
    }

    @Test func `a foldable board takes Apple's VM sub-type`() throws {
        let original = Self.tree(subtype: "V68AP")
        let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableVMSubtype(original)
        #expect(changes.map(\.property) == ["target-sub-type"])
        #expect(changes.first?.before == "V68AP")
        #expect(changes.first?.after == "V68VM2025")
        #expect(patched.count == original.count + delta)
        #expect(patched == Self.tree(subtype: "V68VM2025"))
    }

    @Test func `other boards and a second run are left alone`() throws {
        for subtype in ["D47AP", "V63AP", "V68VM2025"] {
            let original = Self.tree(subtype: subtype)
            let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableVMSubtype(original)
            #expect(changes.isEmpty)
            #expect(delta == 0)
            #expect(patched == original)
        }
    }
}

@Suite("Foldable product identity")
struct CustomFirmwareFoldableProductIdTests {
    private typealias Node = FlatDeviceTreeNode

    private static let boardToken = Data((0 ... 19).map { UInt8(0xa0 + $0) })
    private static let vmToken = Data(repeating: 0x5a, count: 20)

    private static func tree(subtype: String, productID: Data?) -> Data {
        var properties: [(String, Data)] = [("product-name", Data("iPhone\0".utf8))]
        if let productID {
            properties.append(("product-id", productID))
        }
        return Node("device-tree", [
            ("model", Data("iPhone19,4\0".utf8)),
            ("target-sub-type", Data("\(subtype)\0".utf8)),
            ("target-type", Data("v68\0".utf8)),
        ], children: [Node("product", properties)]).serialized
    }

    @Test func `a foldable guest takes the board's product token`() throws {
        // Both sub-types the guest can carry: the board's own, and the VM
        // value the sub-type repair writes before this one runs.
        for subtype in ["V68AP", "V68VM2025"] {
            let original = Self.tree(subtype: subtype, productID: Self.vmToken)
            let board = Self.tree(subtype: "V68AP", productID: Self.boardToken)
            let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableProductId(original, board: board)
            #expect(changes.map(\.property) == ["product/product-id"])
            #expect(changes.first?.before == Self.vmToken.hex)
            #expect(changes.first?.after == Self.boardToken.hex)
            #expect(delta == 0)
            #expect(patched == Self.tree(subtype: subtype, productID: Self.boardToken))
        }
    }

    @Test func `a tree without the property gains it`() throws {
        let original = Self.tree(subtype: "V68VM2025", productID: nil)
        let board = Self.tree(subtype: "V68AP", productID: Self.boardToken)
        let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableProductId(original, board: board)
        #expect(changes.map(\.property) == ["product/product-id"])
        #expect(changes.first?.before == "absent")
        #expect(delta == 36 + 20)
        #expect(patched == Self.tree(subtype: "V68VM2025", productID: Self.boardToken))
    }

    @Test func `other guests and a second run are left alone`() throws {
        let board = Self.tree(subtype: "V68AP", productID: Self.boardToken)
        for subtype in ["D47AP", "V63AP"] {
            let original = Self.tree(subtype: subtype, productID: Self.vmToken)
            let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableProductId(original, board: board)
            #expect(changes.isEmpty)
            #expect(delta == 0)
            #expect(patched == original)
        }
        let settled = Self.tree(subtype: "V68VM2025", productID: Self.boardToken)
        let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableProductId(settled, board: board)
        #expect(changes.isEmpty)
        #expect(delta == 0)
        #expect(patched == settled)
    }

    @Test func `a non-foldable donor is refused`() throws {
        let original = Self.tree(subtype: "V68VM2025", productID: Self.vmToken)
        let donor = Self.tree(subtype: "D47AP", productID: Self.boardToken)
        #expect(throws: (any Error).self) {
            _ = try CustomFirmwarePostRestoreDeviceTree.withFoldableProductId(original, board: donor)
        }
    }
}

@Suite("Foldable panel nodes")
struct CustomFirmwareFoldableDisplaysTests {
    private typealias Node = FlatDeviceTreeNode

    private static func panel(_ name: String, surface: UInt32, rotation: UInt32, phandle: UInt32) -> Node {
        Node(name, [
            ("display-index", Node.uint32(surface - 1)),
            ("surface-type", Node.uint32(surface)),
            ("display-rotation", Node.uint32(rotation)),
            ("chrome-identifier", Data("com.apple.dt.devicekit.chrome.phone1\(surface)\0".utf8)),
            ("AAPL,phandle", Node.uint32(phandle)),
        ])
    }

    /// The board's `/product`: the two panels first, then a sibling without
    /// `surface-type`.
    private static let board = Node("device-tree", [("target-sub-type", Data("V68AP\0".utf8))], children: [
        Node("product", children: [
            panel("display0", surface: 1, rotation: 0, phandle: 470),
            panel("display1", surface: 2, rotation: 270, phandle: 471),
            Node("camera", [("AAPL,phandle", Node.uint32(472))]),
        ]),
    ]).serialized

    private static func guest(subtype: String, panels: [Node] = []) -> Data {
        Node("device-tree", [("target-sub-type", Data("\(subtype)\0".utf8)), ("AAPL,phandle", Node.uint32(1))], children: [
            Node("product", [("AAPL,phandle", Node.uint32(42))], children: panels + [
                Node("camera", [("AAPL,phandle", Node.uint32(143))]),
            ]),
        ]).serialized
    }

    @Test func `a foldable guest gains the board's panels first, renumbered`() throws {
        for subtype in ["V68AP", "V68VM2025"] {
            let original = Self.guest(subtype: subtype)
            let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(original, board: Self.board)
            #expect(changes.map(\.property) == ["product/display0", "product/display1"])
            let expected = Self.guest(subtype: subtype, panels: [
                Self.panel("display0", surface: 1, rotation: 0, phandle: 144),
                Self.panel("display1", surface: 2, rotation: 270, phandle: 145),
            ])
            #expect(patched == expected)
            #expect(delta == expected.count - original.count)
        }
    }

    @Test func `other guests and a second run are left alone`() throws {
        let original = Self.guest(subtype: "D47AP")
        let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(original, board: Self.board)
        #expect(changes.isEmpty)
        #expect(patched == original)

        let (once, _, _) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(Self.guest(subtype: "V68VM2025"), board: Self.board)
        let (twice, again, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(once, board: Self.board)
        #expect(again.isEmpty)
        #expect(delta == 0)
        #expect(twice == once)
    }

    @Test func `a board without two panels is refused`() throws {
        let donor = Node("device-tree", children: [Node("product", children: [Node("camera")])]).serialized
        #expect(throws: (any Error).self) {
            _ = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(Self.guest(subtype: "V68VM2025"), board: donor)
        }
    }
}