Run a virtual iPhone on an Apple Silicon Mac.
Swift
Drop the haptics node an iPad does not have, so tones play
Jacky3622c26b6159
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 82fa22e5..1d5e58e6 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -28,8 +28,10 @@> M-series board keeps Stage Manager (no `disable-chamois`) and the iPad (A16)> has no `medusa-overlay-app-capability`: `devicetree-cfw-ipad_artwork`,> `devicetree-cfw-ipad_product`, `devicetree-cfw-ipad_buttons`,-> `devicetree-cfw-ipad_identity` and (2026-10-02) `devicetree-cfw-ipad_audio`,-> which takes the board's `/product/audio` node. They are written to a second device tree,+> `devicetree-cfw-ipad_identity`, (2026-10-02) `devicetree-cfw-ipad_audio`,+> which takes the board's `/product/audio` node, and (2026-10-03)+> `devicetree-cfw-ipad_haptics`, which removes `/product/haptics` where the+> board has none. They are written to a second device tree,> `Firmware/all_flash/DeviceTree.vphone600ap.guest.im4p`, which `fw prepare`> copies from the vphone600 one and the hybrid manifest names as `DeviceTree`;> `RestoreDeviceTree` keeps pointing at the original, so restore still boots@@ -2223,10 +2225,28 @@ virtio sound device with a host output sink. Two faults; the full reveal is| `system-virtiosound-cfw-hal_plugin` (new) | `/System/Library/Audio/Plug-Ins/HAL/VPhoneVirtIOSound.driver`, `cfw install` and `cfw update-environment` | Installs the CoreAudio HAL plugin for `AppleVirtIOSound`, built from `VPhoneGuestComponents/VirtIOSound`. || `devicetree-cfw-ipad_audio` (new) | An iPad guest's installed DeviceTree, `fw patch` | Replaces `/product/audio` with the board tree's node (`DeviceTreePatcher.presentBoardAudio`), all properties as the board has them except its `AAPL,phandle`. || `preboot-cfw-devicetree_board_audio` (new) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same replacement for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-audio`), from the board tree in `FirmwareOriginals`. |+| `devicetree-cfw-ipad_haptics` (new, 2026-10-03) | An iPad guest's installed DeviceTree, `fw patch` | Makes `/product/haptics` what the board tree has (`DeviceTreePatcher.presentBoardHaptics`): removed for every iPad so far, none of which has the node. |+| `preboot-cfw-devicetree_board_haptics` (new, 2026-10-03) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same change for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-haptics`), from the board tree in `FirmwareOriginals`. An existing guest also needs its MobileGestalt cache dropped once, see below. |`fw patch` now reads an iPad's board tree through the `FirmwareOriginals` stash,so `DeviceTree.<board>.im4p` stays in the VM folder after the restore tree goes.+**Why the haptics node goes.** vphone600 carries `/product/haptics`+(`closed-loop`, `supports-3rd-party-haptics`); `DeviceTree.j410ap` and+`.j820ap` have no such node. With it MobileGestalt answers yes to+`DeviceSupportsHaptics` and `DeviceSupportsClosedLoopHaptics`, ToneLibrary sets+`playHapticTracks` on every tone, and mediaplaybackd builds a `CHHapticEngine`+whose server, `com.apple.audio.hapticd` in audiomxd, never answers on a VM:+six one-second XPC timeouts, `FigHapticEngineCreate` fails 4099, and+`itemfig_rebuildRenderPipelinesAndBoss` fails the item — the ringtone never+starts although its route and audio queue are built. Without the node the+guest answers as the iPad does and tones play. The answers are cached in+`/private/var/containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist`,+written at first boot, so a guest that has already booted keeps the old ones+until that file is removed and the guest restarted (`files.remove`, then+`system.reboot`); a guest created with the patch never has them. Detail and+the measurements: `Research/Guest/virtio_sound.md` §7.+**Why a plugin.** The cloudOS kernel has `AppleVirtIOSound` and its user client,but only macOS ships the HAL plugin that drives it; neither cloudOS nor any iOSimage has one. `VPhoneVirtIOSound.driver` speaks the same user-client selectorsdiff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.mdindex 26b99760..fc27ad3a 100644--- a/Research/Guest/virtio_sound.md+++ b/Research/Guest/virtio_sound.md@@ -458,6 +458,78 @@ Verified on a guest with all four keys deleted and rebooted: VirtualAudioinitializes, the boot chime and a ringtone preview start I/O on`PuffinOutput (VAD [vdef] AggDev N)`, no `not initialized yet`.+## 7. Tones stayed silent: the guest claimed a Taptic Engine (2026-10-03, night)++With routing and the plugin both working, Safari played and a ringtone preview+still did not. audiomxd shows the tone's route built and its AudioQueue+created (`AudioQueueObject: New output; format 2 ch, 44100 Hz, aac`) and+deleted six seconds later without ever starting. The reason is in+mediaplaybackd, which plays tones for the client:++```+itemfig_postReadyForInspectionPayload…: Track ID 1 soun … Track ID 2 hapt … Track ID 3 hapt+FigHapticEngineCreate: called, AudioSession:… Locality:…+activating connection: mach=true … name=com.apple.audio.hapticd+XPC timeout+AVHapticClient.mm:1160 Initial XPC call to server timed out. Invalidating connection to prevent hang+ (six times, one second apart)+CHHapticEngine.mm:649 createHapticPlayerWithOptions: ERROR: Server failure: … Code=4099+<<< FigHapticEngine >>> signalled err=4099+playerfig_prepareWorkingItem2: itemfig_rebuildRenderPipelinesAndBoss() failed with err=4099+playerfig_prepareWorkingItem: current item … failed to prepare (4099), advancing to next item+```++A system tone carries haptic tracks beside its audio. In MediaToolbox+(26.6.2 cache), `itemfig_rebuildRenderPipelinesAndBossGuts` calls+`FigHapticEngineCreate` when the item's `PlayHapticTracks` is set, and any+error from it leaves through the function's failure exit (`cbnz w27` at+`0x197832dd4`): the item fails as a whole, audio included.+`com.apple.audio.hapticd` is a Mach service of audiomxd+(`com.apple.audiomxd.plist`), and on a VM nothing behind it answers.++`PlayHapticTracks` comes from the client. ToneLibrary sets+`[playerItem setPlayHapticTracks:YES]` when+`-hasSynchronizedVibrationsCapability` is true, and logs how it decided:+"MobileGestalt returned %{BOOL}u for the deviceSupportsHaptics capability, and+%{BOOL}u for the deviceSupportsClosedLoopHaptics capability". Those answers+come from the device tree:++| Tree | `/product` children | `/product/haptics` |+| --- | --- | --- |+| vphone600 (guest) | vphone600-gestalt-variants, maps, haptics, usb-device, util | `closed-loop = 1`, `supports-3rd-party-haptics = 1` |+| `DeviceTree.j410ap` (iPad16,1) | camera, facetime, maps, audio | none |+| `DeviceTree.j820ap` (iPad17,3) | camera, facetime, maps, audio | none |++So the guest says it has a Taptic Engine and the iPad it presents does not.+`devicetree-cfw-ipad_haptics` makes the node follow the board — removed, for+an iPad — and `preboot-cfw-devicetree_board_haptics` does the same to a guest+that is already installed.++**The answers are cached.** libMobileGestalt writes+`/private/var/containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist`+at first boot. On the test guest the node was gone from `IODeviceTree` after+`cfw update-environment`, and Settings still showed the Haptics row and+mediaplaybackd still timed out on hapticd, until that file was removed and the+guest rebooted:++```+vphone-launchpad-cli guest rpc <machine> files.remove \+ '{"path":"/private/var/containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist"}'+vphone-launchpad-cli guest rpc <machine> system.reboot '{"force":true}'+```++A guest created with the patch never caches the wrong answers. An existing one+needs this once after the environment update; nothing does it automatically+yet.++**Verified** (`audiotest-ipad`): after the cache was rebuilt the Ringtone page+has no Haptics row, mediaplaybackd makes no hapticd connection, and a tone+preview plays on the Mac — heard, and in `vpquery.log` a 20 s stream with 237+writes and none starved.++iPhone guests are not changed: an iPhone's own tree has the node, and what a+tone does there with no haptic server has not been measured.+## Reveal and validation1. Kernel side present: `strings` on the decompressed kernelcache shows thediff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex 383912b6..6b41284b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -103,6 +103,29 @@ public enum CustomFirmwarePostRestoreDeviceTree {}}+ /// Make an iPad guest's `devicetree.img4` (or bare `.im4p`) carry the+ /// haptics node of the iPad's own tree at `boardURL` — none, on every iPad+ /// so far — in place. See `DeviceTreePatcher.presentBoardHaptics`.+ @discardableResult+ public static func presentBoardHaptics(+ at url: URL,+ board boardURL: URL,+ dryRun: Bool = false,+ verbose: Bool = true,+ ) throws -> Outcome {+ let boardData: Data+ do {+ boardData = try Data(contentsOf: boardURL)+ } catch {+ throw PatcherError.fileNotFound(boardURL.path)+ }+ let board = try openDeviceTree(boardData, path: boardURL.path).blob+ return try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in+ let (newBlob, changes, delta) = try withBoardHaptics(blob, board: board)+ return (newBlob, changes, blob.count + delta)+ }+ }+/// The container, payload and flat tree of a device tree file. Refuses a/// payload that is not a device tree, is encrypted, or came back still/// compressed.@@ -304,6 +327,37 @@ public enum CustomFirmwarePostRestoreDeviceTree {return (serializeNode(root), [record], change.after.count - change.before.count)}+ /// `blob` with `/product/haptics` as the board's flat tree `board` has it,+ /// through `DeviceTreePatcher.presentBoardHaptics`: removed where the board+ /// has none. Returns the size change with the changes, as `withBoardAudio`+ /// does. A tree that already matches comes back unchanged.+ public static func withBoardHaptics(_ blob: Data, board: Data) throws -> (Data, [Change], Int) {+ let (root, end) = try parseNode(blob, at: 0)+ guard end == blob.count else {+ throw PatcherError.invalidFormat(+ "DT parse length mismatch: ended at \(end), blob is \(blob.count)",+ )+ }+ let (source, sourceEnd) = try parseNode(board, at: 0)+ guard sourceEnd == board.count else {+ throw PatcherError.invalidFormat(+ "board DT parse length mismatch: ended at \(sourceEnd), blob is \(board.count)",+ )+ }+ guard let change = DeviceTreePatcher.presentBoardHaptics(in: root, from: source) else {+ return (blob, [], 0)+ }+ func describe(_ node: Data) -> String {+ node.isEmpty ? "absent" : "present, \(node.count)B"+ }+ let record = Change(+ property: "product/haptics",+ before: describe(change.before),+ after: describe(change.after),+ )+ return (serializeNode(root), [record], change.after.count - change.before.count)+ }+// MARK: - Flat device tree format//diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex e6fe6722..0b0866b8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -52,6 +52,7 @@ extension DeviceTreePatcher {static let iPadButtonsPatch = "devicetree-cfw-ipad_buttons"static let iPadIdentityPatch = "devicetree-cfw-ipad_identity"static let iPadAudioPatch = "devicetree-cfw-ipad_audio"+ static let iPadHapticsPatch = "devicetree-cfw-ipad_haptics"// MARK: - What Is Copied@@ -265,6 +266,70 @@ extension DeviceTreePatcher {return BoardAudioChange(before: before, after: serialize(node))}+ // MARK: - Haptics++ /// What `presentBoardHaptics` changed: the haptics node's serialized bytes+ /// before and after, empty where there was, or now is, no node.+ struct BoardHapticsChange {+ let before: Data+ let after: Data+ }++ /// Make `root`'s `/product/haptics` what the board's tree has — which for+ /// an iPad is nothing.+ ///+ /// vphone600 carries the node (`closed-loop`, `supports-3rd-party-haptics`),+ /// so MobileGestalt answers yes to `DeviceSupportsHaptics` and+ /// `DeviceSupportsClosedLoopHaptics`. ToneLibrary reads the pair as+ /// "synchronized vibrations", sets `playHapticTracks` on every tone's player+ /// item, and mediaplaybackd then builds a `CHHapticEngine` beside the audio+ /// queue. A VM has no haptic server behind `com.apple.audio.hapticd`: the+ /// engine's XPC setup times out six times, `FigHapticEngineCreate` fails+ /// with 4099, and `itemfig_rebuildRenderPipelinesAndBoss` fails the whole+ /// item with it — the tone's audio never starts. An iPad's tree has no+ /// haptics node at all, so the real device never asks.+ ///+ /// Where the board has a node its properties are copied, as the audio+ /// node's are; where it has none the guest's is removed. Returns nil when+ /// the tree already matches the board.+ static func presentBoardHaptics(in root: DTNode, from source: DTNode) -> BoardHapticsChange? {+ func named(_ node: DTNode, _ name: String) -> DTNode? {+ node.children.first { child in+ child.properties.contains { $0.name == "name" && $0.value.prefix(while: { $0 != 0 }) == Data(name.utf8) }+ }+ }+ guard let sourceProduct = named(source, "product"), let product = named(root, "product") else {+ return nil+ }+ let existing = named(product, "haptics")+ guard let sourceHaptics = named(sourceProduct, "haptics") else {+ guard let existing else { return nil }+ let before = serialize(existing)+ product.children.removeAll { $0 === existing }+ return BoardHapticsChange(before: before, after: Data())+ }++ let copied = sourceHaptics.properties.filter { $0.name != "AAPL,phandle" }+ if let existing {+ let current = existing.properties.filter { $0.name != "AAPL,phandle" }+ if current.count == copied.count, zip(current, copied).allSatisfy({ lhs, rhs in+ lhs.name == rhs.name && lhs.flags == rhs.flags && lhs.value == rhs.value+ }) {+ return nil+ }+ }+ let before = existing.map(serialize) ?? Data()+ let node = existing ?? DTNode()+ let phandle = node.properties.filter { $0.name == "AAPL,phandle" }+ node.properties = copied.map {+ DTProperty(name: $0.name, flags: $0.flags, value: $0.value, valueOffset: 0)+ } + phandle+ if existing == nil {+ product.children.append(node)+ }+ return BoardHapticsChange(before: before, after: serialize(node))+ }+/// The flat encoding of one node and its children, for the patch record.private static func serialize(_ node: DTNode) -> Data {var out = Data()@@ -312,6 +377,23 @@ extension DeviceTreePatcher {print(" =node : /product/audio as on \(device.productType) (\(change.after.count)B) [\(Self.iPadAudioPatch)]")}}+ if gateAllows(Self.iPadHapticsPatch), let change = Self.presentBoardHaptics(in: root, from: source) {+ patches.append(PatchRecord(+ patchID: Self.iPadHapticsPatch,+ component: component,+ fileOffset: 0,+ virtualAddress: nil,+ originalBytes: change.before,+ patchedBytes: change.after,+ description: change.after.isEmpty+ ? "Remove /device-tree/product/haptics, which \(device.productType) does not have"+ : "Set /device-tree/product/haptics as on \(device.productType)",+ ))+ if verbose {+ let what = change.after.isEmpty ? "-node : /product/haptics, absent on" : "=node : /product/haptics as on"+ print(" \(what) \(device.productType) [\(Self.iPadHapticsPatch)]")+ }+ }for edit in try Self.guestEdits(from: source) {guard gateAllows(edit.patchID) else { continue }let node = try resolveNode(root, path: edit.nodePath)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swiftindex 91b4aef8..8987305b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift@@ -196,6 +196,11 @@ public enum FirmwareDeviceTreePatchSet {"iPad audio configuration","Takes the audio node from the iPad's tree, so its acoustic ID names tunings the iPad image ships.",),+ property(+ "devicetree-cfw-ipad_haptics",+ "iPad haptics",+ "Removes the Taptic Engine an iPad does not have, so tones play without the haptic track a VM cannot drive.",+ ),],provides: ["vphone.devicetree"],)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 79149af6..3d1b57aa 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -263,6 +263,17 @@ public enum FirmwareGuestSystemPatchSet {""",target: .prebootDeviceTree,),+ VPhonePatchDeclaration(+ identifier: prebootBoardHaptics,+ title: "iPad haptics",+ summary: """+ Removes the haptics node from an iPad guest's restored Preboot device tree, as fw \+ patch now does. With it iOS believes the guest has a Taptic Engine, plays every \+ tone with its haptic track, and drops the tone when the haptic engine a VM does \+ not have fails to start. Needs the iPad's device tree in the VM's FirmwareOriginals.+ """,+ target: .prebootDeviceTree,+ ),VPhonePatchDeclaration(identifier: "system-systemversion-cfw-build_version",@@ -310,6 +321,7 @@ public enum FirmwareGuestSystemPatchSet {/// The iPad audio node repair in the restored Preboot device tree, for an/// iPad VM patched before `fw patch` copied the board's node.public static let prebootBoardAudio = "preboot-cfw-devicetree_board_audio"+ public static let prebootBoardHaptics = "preboot-cfw-devicetree_board_haptics"/// The preset parameter `system-systemversion-cfw-build_version` reads.public static let buildVersionParameter = "BuildVersion"diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swiftnew file mode 100644index 00000000..8e954546--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swift@@ -0,0 +1,151 @@+// CustomFirmwareBoardHapticsTests.swift — an iPad guest has the board's haptics node, or none.+//+// `withBoardHaptics` (the Preboot repair) and+// `DeviceTreePatcher.presentBoardHaptics` (what `fw patch` runs for an iPad's+// installed tree) make `/product/haptics` what the board tree has: removed for+// an iPad, which has no Taptic Engine. 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("iPad haptics node from the board tree")+struct CustomFirmwareBoardHapticsTests {+ // MARK: - A flat device tree++ private struct Node {+ var properties: [(name: String, flags: UInt16, value: Data)]+ var children: [Node] = []+ }++ private static func node(_ name: String, _ properties: [(String, Data)] = [], children: [Node] = []) -> Node {+ Node(+ properties: [("name", 0, Data((name + "\0").utf8))] + properties.map { ($0.0, 0, $0.1) },+ children: children,+ )+ }++ private static func uint32(_ value: UInt32) -> Data {+ withUnsafeBytes(of: value.littleEndian) { Data($0) }+ }++ private static func serialize(_ node: Node) -> Data {+ var out = uint32(UInt32(node.properties.count)) + uint32(UInt32(node.children.count))+ for (name, flags, value) in node.properties {+ var field = Data(name.utf8)+ field.append(contentsOf: [UInt8](repeating: 0, count: 32 - field.count))+ out.append(field)+ out.append(contentsOf: withUnsafeBytes(of: UInt16(value.count).littleEndian) { Array($0) })+ out.append(contentsOf: withUnsafeBytes(of: flags.littleEndian) { Array($0) })+ out.append(value)+ out.append(contentsOf: [UInt8](repeating: 0, count: (4 - value.count % 4) % 4))+ }+ for child in node.children {+ out.append(serialize(child))+ }+ return out+ }++ /// A tree whose `/product` holds `maps`, then `haptics` when given, then+ /// `util` — the node sits between siblings, as it does on vphone600.+ private static func tree(haptics: Node?) -> Data {+ let product = node(+ "product",+ [("product-name", Data("iPad\0".utf8))],+ children: [node("maps", [("regulatory", uint32(1))])]+ + (haptics.map { [$0] } ?? [])+ + [node("util", [("ramdisk", uint32(0))])],+ )+ return serialize(node("device-tree", [("model", Data("iPad16,1\0".utf8))], children: [product]))+ }++ /// What vphone600 carries.+ private static let guestHaptics = node("haptics", [+ ("closed-loop", uint32(1)),+ ("supports-3rd-party-haptics", uint32(1)),+ ("AAPL,phandle", uint32(100)),+ ])++ /// A board that does have an actuator.+ private static let boardHaptics = node("haptics", [+ ("closed-loop", uint32(1)),+ ("supports-3rd-party-haptics", uint32(0)),+ ("AAPL,phandle", uint32(7)),+ ])++ // MARK: - Tests++ @Test func `removes the node an iPad's tree does not have`() throws {+ let original = Self.tree(haptics: Self.guestHaptics)+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(+ original,+ board: Self.tree(haptics: nil),+ )+ #expect(changes.map(\.property) == ["product/haptics"])+ #expect(changes.first?.after == "absent")+ #expect(delta < 0)+ #expect(patched.count == original.count + delta)+ // The siblings on either side survive, in order.+ #expect(patched == Self.tree(haptics: nil))+ }++ @Test func `a tree with no node is left alone`() throws {+ let original = Self.tree(haptics: nil)+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(+ original,+ board: Self.tree(haptics: nil),+ )+ #expect(changes.isEmpty)+ #expect(delta == 0)+ #expect(patched == original)+ }++ @Test func `removing twice changes nothing the second time`() throws {+ let board = Self.tree(haptics: nil)+ let (once, _, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(+ Self.tree(haptics: Self.guestHaptics),+ board: board,+ )+ let (twice, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(once, board: board)+ #expect(changes.isEmpty)+ #expect(twice == once)+ }++ @Test func `a board with a node gives its properties and keeps the guest's phandle`() throws {+ let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(+ Self.tree(haptics: Self.guestHaptics),+ board: Self.tree(haptics: Self.boardHaptics),+ )+ #expect(changes.first?.after.hasPrefix("present") == true)+ let expected = Self.node("haptics", [+ ("closed-loop", Self.uint32(1)),+ ("supports-3rd-party-haptics", Self.uint32(0)),+ ("AAPL,phandle", Self.uint32(100)),+ ])+ #expect(patched == Self.tree(haptics: expected))+ }++ @Test func `a tree that already matches the board's node is left alone`() throws {+ var matching = Self.boardHaptics+ matching.properties[3].value = Self.uint32(100)+ let original = Self.tree(haptics: matching)+ let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(+ original,+ board: Self.tree(haptics: Self.boardHaptics),+ )+ #expect(changes.isEmpty)+ #expect(patched == original)+ }++ @Test func `a truncated tree is refused`() {+ let original = Self.tree(haptics: Self.guestHaptics)+ #expect(throws: (any Error).self) {+ try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(+ original.prefix(original.count - 4),+ board: Self.tree(haptics: nil),+ )+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex b0811eda..1373a2f5 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -771,6 +771,7 @@ struct VPhoneCustomFirmwareInstaller {private static let lateGuestPatches = [FirmwareGuestSystemPatchSet.virtioSoundDriver,FirmwareGuestSystemPatchSet.prebootBoardAudio,+ FirmwareGuestSystemPatchSet.prebootBoardHaptics,FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows,FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow,FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate,@@ -1150,7 +1151,7 @@ struct VPhoneCustomFirmwareInstaller {}/// `includeIdentity` is false for an environment update, which carries- /// only the board audio repair. `boardDeviceTree` is the iPad's own device+ /// only the board audio and haptics repairs. `boardDeviceTree` is the iPad's own device/// tree, staged from the VM's `FirmwareOriginals`, or nil for an iPhone/// guest or a VM patched before `fw patch` kept it.private func patchPreboot(@@ -1183,7 +1184,8 @@ struct VPhoneCustomFirmwareInstaller {}let spoofBuild = includeIdentity ? self.spoofBuild : nillet boardAudio = boardDeviceTree != nil && on(FirmwareGuestSystemPatchSet.prebootBoardAudio)- guard rewriteIdentity || boardAudio || !(spoofBuild ?? "").isEmpty else { return }+ let boardHaptics = boardDeviceTree != nil && on(FirmwareGuestSystemPatchSet.prebootBoardHaptics)+ guard rewriteIdentity || boardAudio || boardHaptics || !(spoofBuild ?? "").isEmpty else { return }guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? String@@ -1220,6 +1222,15 @@ struct VPhoneCustomFirmwareInstaller {arguments: [boardDeviceTree.path],)}+ if boardHaptics, let boardDeviceTree {+ try patchCopy(+ of: deviceTree,+ in: root,+ work: work,+ verb: "patch-dt-board-haptics",+ arguments: [boardDeviceTree.path],+ )+ }if let build = spoofBuild {let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"if try root.isRegularFile(version) {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swiftindex 50c92049..e6c77b69 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift@@ -353,3 +353,42 @@ struct VPhoneCustomFirmwarePatchBoardAudioCommand: ParsableCommand {)}}++// MARK: - patch-dt-board-haptics++struct VPhoneCustomFirmwarePatchBoardHapticsCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-dt-board-haptics",+ abstract: "Make an iPad guest's device tree carry the iPad's own haptics node, or none",+ discussion: """+ Sets /product/haptics in a restored device tree to what the iPad's own+ tree has (DeviceTree.<board>.im4p from its IPSW), in place, preserving+ the container's compression, manifest and restore info. An iPad has no+ haptics node, so the vphone600 one is removed: with it, iOS believes the+ guest has a Taptic Engine, plays every tone with its haptic track, and+ drops the tone when the haptic engine a VM does not have fails to start.+ A tree that already matches is left as it is.++ Takes a devicetree.img4 (preferred) or a bare .im4p, and the board's+ DeviceTree .im4p.+ """,+ )++ @Argument(help: "Path to devicetree.img4 or devicetree.im4p", transform: URL.init(fileURLWithPath:))+ var deviceTree: URL++ @Argument(help: "Path to the iPad's DeviceTree.<board>.im4p", transform: URL.init(fileURLWithPath:))+ var board: URL++ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")+ var dryRun = false++ func run() throws {+ try CustomFirmwarePostRestoreDeviceTree.presentBoardHaptics(+ at: deviceTree,+ board: board,+ dryRun: dryRun,+ verbose: true,+ )+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 5485b2c4..c04b34f9 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -185,6 +185,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {VPhoneCustomFirmwarePatchCampoEntitlementsCommand.self,VPhoneCustomFirmwarePatchPostRestoreDeviceTreeCommand.self,VPhoneCustomFirmwarePatchBoardAudioCommand.self,+ VPhoneCustomFirmwarePatchBoardHapticsCommand.self,] + VPhoneCustomFirmwareMachOVerbs.all + VPhoneCustomFirmwareDyldSharedCacheVerbs.all,)}