Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Boot new machines from OpenAVB instead of AVPBooter

Jacky286574aff341
diff --git a/AGENTS.md b/AGENTS.md
index bf1cdf1d..766c0b59 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -56,6 +56,8 @@ The `VPhone` scheme puts host programs in `VPhone.bundle/Contents/MacOS` and eve
### Key Patterns
+- New machines boot **OpenAVB**, not Apple's AVPBooter: `VPhone.bundle/Contents/Resources/OpenAVB/OpenAVB.bin`, checked in prebuilt under `VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/` from a pinned OpenAVB commit plus the patches in `patches/` beside it. Rebuild or check it only with `Build/UpdateOpenAVB.sh` (Homebrew LLVM/LLD, outside the repo). `fw patch` skips AVPBooter on an OpenAVB machine; `vphone-cli restore` uploads the iBSS identity first (`MobileRestoreCore/Recovery/openavb.c`); `vm config --rom` switches ROM. See `Research/Firmware/openavb_boot_rom.md`.
+
- `vphone-cli` is the unentitled entry point. `VPhoneGuestLaunchPlanner` resolves `vphone-vm` beside the running executable, checks its entitlements, probes AMFI, and reports the exact allowlist command on refusal. It never obtains root itself.
- `vphone-escalator` manages AMFI cdhash admission only. It writes amfid heap state, not executable code. Root authorization belongs to the user or to `vphone-launchpad`; neither `vphone-cli` nor the bundle has an SMJobBless or sudo password flow.
- `vphone-launchpad` has no private entitlements. `SignLaunchpad.sh` gives its main executable two hardened-runtime resource entitlements, microphone (`com.apple.security.device.audio-input`) and location (`com.apple.security.personal-information.location`), from `VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements`; its helper, CLI and launcher have none. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. `EPDeveloperTool.authorizationStatus` keeps the value the process launched with, while syspolicyd checks the live grant on every exception request, so Host Setup judges access by asking for an exception for Launchpad's own executable; a grant or a revocation in Settings applies without a relaunch. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles`, runs that bundle's `vphone-escalator allow` for its receipt-pinned `vphone-vm`, runs `cfw install` from that store after rechecking the recorded cdhash, and runs that store bundle's `vphone-cli vm leases --release-orphans` for the caller's own library folders. There is no generic command verb. Launchpad starts `vm launch` detached (own session, responsibility disclaimed) through `vphone-launchpad-launcher` in its `Contents/MacOS`, which starts `vphone-cli` as an ordinary child and stays until it exits, forwarding stop signals and exiting the same way. The launcher is therefore the responsible process for `vphone-vm`. As a tool in the app's `Contents/MacOS` it is attributed to the app, so privacy prompts, usage descriptions and grants (microphone, location) are the app's, asked once for its Developer ID signature instead of for each ad hoc signed bundle build; under the hardened runtime macOS refuses them without asking unless the app carries the matching entitlement. It refuses anything but `vm launch` of a `vphone-cli` in the root-owned store (`VPhoneLaunchpadLauncherPolicy`); without the launcher, Launchpad starts `vphone-cli` directly. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index a75dbcc1..b806844a 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -626,6 +626,11 @@ environment fails before publishing a partially patched tree.
| --- | ------------ | -------------------------------- | :-----: | :-: | :-: |
| 1 | `mov x0, #0` | DGST signature validation bypass | Y | Y | Y |
+New machines boot OpenAVB instead of AVPBooter, and OpenAVB checks no image
+digest: `fw patch` skips this component on them (the patch stays selected and
+planned, which is what the machine behaves as). Machines created before keep
+Apple's ROM and this patch. See `Firmware/openavb_boot_rom.md`.
+
### iBSS
| # | Patch | Purpose | Regular | Dev | JB |
@@ -3176,3 +3181,30 @@ steps run there too, without the restore tree, over the driver already in place.
`-[PGSerializerBlitCommandEncoder copyFromTexture:…toBuffer:…]` store
`parentResourceOffset` in 16 bits too. They were not measured and are left as
they are.
+
+## OpenAVB replaces AVPBooter on new machines (2026-10-18)
+
+New machines boot OpenAVB (`Resources/OpenAVB/OpenAVB.bin`, built from
+`owngoal-dev/OpenAVB` at `115169e`, which includes vphone's five
+Virtualization.framework fixes, plus one carried patch that lets a guest
+reboot: the ROM waits for a SEP restarted by the reset) instead of
+Virtualization.framework's `AVPBooter.vresearch1.bin`. OpenAVB checks no image
+digest, so `avpbooter-boot-dgst_bypass` has nothing to patch on such a machine:
+`fw patch` drops the AVPBooter component when `romImages.avpBooter` names an
+OpenAVB image and logs `Boot ROM: OpenAVB, which needs no ROM patch`. The patch
+stays in presets and plans, so `fw patches` reports no drift. Machines created
+before keep Apple's ROM and the patch; `vm config --rom openavb|apple` switches
+one without a restore.
+
+Two boot-chain files change form, not content:
+
+| Component | Before | Now | Why |
+| --- | --- | --- | --- |
+| iBSS IM4P | patched payload written back uncompressed | written back LZFSE-compressed, as Apple ships it | OpenAVB decodes only LZFSE; Apple's ROM takes either |
+| iBSS over DFU | sent as is | preceded by a 112-byte stage-0 identity (payload and image sizes and SHA-256, load base `0x7006c000`, EL2) when the ROM answers OpenAVB's patch-store report | OpenAVB refuses an iBSS nobody described |
+
+No patch site moved and no patch was added or removed. The OpenAVB-side
+changes (read-only ROM aperture, chip ID 0, DFU suffix CRC, remote-boot bit,
+USB device left running) were carried as patches at first and are now
+upstream (owngoal-dev/OpenAVB#1). `Firmware/openavb_boot_rom.md` describes
+each one and how it was found.
diff --git a/Research/Firmware/firmware_manifest_and_origins.md b/Research/Firmware/firmware_manifest_and_origins.md
index 48694bd3..0c62ccc0 100644
--- a/Research/Firmware/firmware_manifest_and_origins.md
+++ b/Research/Firmware/firmware_manifest_and_origins.md
@@ -73,7 +73,7 @@ Key distinctions:
| Component | Source Identity | File | Patches Applied |
| ------------- | ----------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------ |
-| **AVPBooter** | PCC vresearch1 | `AVPBooter*.bin` (vm dir) | DGST validation bypass (`mov x0, #0`) |
+| **AVPBooter** | PCC vresearch1 | `AVPBooter*.bin` (vm dir) | DGST validation bypass (`mov x0, #0`); none on machines booting OpenAVB |
| **iBSS** | PROD (vresearch101ap release) | `Firmware/dfu/iBSS.vresearch101.RELEASE.im4p` | Serial labels + image4 callback bypass |
| **iBEC** | PROD (vresearch101ap release) | `Firmware/dfu/iBEC.vresearch101.RELEASE.im4p` | Serial labels + image4 callback + boot-args |
| **LLB** | PROD (vresearch101ap release) | `Firmware/all_flash/LLB.vresearch101.RELEASE.im4p` | Serial labels + image4 callback + boot-args + rootfs + panic (6 patches) |
@@ -430,7 +430,7 @@ fires **only during installation**. After restore completes, the boot
path is
```
-AVPBooter (patched)
+AVPBooter (patched), or OpenAVB on new machines
→ iBSS / iBEC (image4_validate_property_callback bypass patches)
→ LLB (image4 bypass + rootfs bypass patches)
→ iBoot (research) → DT loaded from disk
diff --git a/Research/Firmware/openavb_boot_rom.md b/Research/Firmware/openavb_boot_rom.md
new file mode 100644
index 00000000..c0814428
--- /dev/null
+++ b/Research/Firmware/openavb_boot_rom.md
@@ -0,0 +1,180 @@
+# OpenAVB boot ROM
+
+New machines boot [OpenAVB](https://github.com/owngoal-dev/OpenAVB), an
+open-source AArch64 boot ROM compatible with AVPBooter, instead of Apple's
+`AVPBooter.vresearch1.bin` from Virtualization.framework. This page is
+vphone's side of OpenAVB's host contract (`docs/external-contract.md` in its
+repository): what the ROM expects, what vphone does about it, what was changed
+in OpenAVB to run under Virtualization.framework, and how it was validated.
+
+## Where the ROM lives
+
+| What | Where |
+| --- | --- |
+| Checked-in image and licences | `VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/` |
+| Rebuild and check | `VPhoneExecutable/VPhoneVirtualization/Build/UpdateOpenAVB.sh` (Homebrew LLVM and LLD, outside the repository) |
+| In the bundle | `VPhone.bundle/Contents/Resources/OpenAVB/OpenAVB.bin`, admitted by `ValidateBundle.sh` |
+| In a machine | `<vm>/OpenAVB.bin`, named by `romImages.avpBooter` in `config.plist` |
+| Recognition | `VPhoneBootROM` (VPhoneCoreKit): an image containing `OpenBootROM:` is OpenAVB, anything else Apple's |
+
+`vm new` copies the bundle's OpenAVB (`VPhoneBundleOperations.defaultROMSource`).
+A machine cloned from a template gets the creating bundle's OpenAVB too
+(`VPhoneVirtualMachineCreator.cloneFromTemplate`): the ROM is not part of a
+template's key, because it changes without a restore. `vm config --rom
+openavb|apple|<file>` switches an existing machine from its next start; the ROM
+it replaces stays in the folder, so an Apple ROM keeps its digest patch. `vm
+new --rom apple` still creates a machine on Apple's ROM. The PCC GPU recovery
+machine (`VPhonePCCGPURecovery`) keeps Apple's ROM: it restores Apple-signed
+PCC firmware, which OpenAVB has not been tried with.
+
+## What changes on the boot chain
+
+**AVPBooter patch.** OpenAVB checks no image digest, so
+`avpbooter-boot-dgst_bypass` has nothing to patch on a machine that boots it.
+`fw patch` reads the ROM kind from the manifest and drops the AVPBooter
+component (`FirmwarePipelineComponents.swift`), logging
+`Boot ROM: OpenAVB, which needs no ROM patch`. The patch stays selected and
+planned, which is what the machine behaves as, so `fw patches` shows no drift
+for it.
+
+**Normal boot.** OpenAVB reads LLB from the firmware block device, checks the
+IMG4 container and that a manifest is present, publishes the manifest's
+SHA-384 for iBoot's LocalPolicy path and hands off. A plaintext payload (what
+`fw patch` writes for LLB) is copied to its resident window at `0x70074000`
+and relocates itself. No patch table is needed: the LLB is already patched.
+Because both ROMs load the same LLB, a machine restored on Apple's ROM boots on
+OpenAVB unchanged.
+
+**DFU.** OpenAVB carries no description of any iBoot build. It refuses a DFU
+iBSS unless the host first uploads the image's identity into patch-store
+stage 0: the IM4P payload's size and SHA-256, the decoded image's size and
+SHA-256, the load base and the entry exception level. `vphone-cli restore`
+does this before it sends iBSS (`MobileRestoreCore/Recovery/openavb.c`, called
+from `dfu_send_component`):
+
+1. Probe with the read-only report request (`0xc0`, `0x73`, 48 bytes). Apple's
+ ROM stalls it, and then nothing is written.
+2. Build the 112-byte `AVPPatchStageHeader` from the personalized iBSS: walk
+ IMG4 → IM4P → first OCTET STRING, require `bvx2`, decode it with
+ libcompression, read iBoot's link base from offset `0x300` (`0x7006c000` for
+ vresearch101), entry level 2, identity flag, no rows.
+3. Open (`0x41 0x70`), append one chunk (`0x41 0x71`), seal with 0 rows
+ (`0x41 0x72`), then report again and require stage 0 `{0, 112, sealed}`.
+
+OpenAVB decodes only LZFSE, so `fw patch` now writes iBSS back LZFSE-compressed,
+as Apple ships it (`IM4PHandler.lzfseFourCCs`); Apple's ROM takes that too.
+Every other image is still written back as before.
+
+iBEC and everything later are loaded by iBSS, not by the ROM, and are
+unaffected. OpenAVB's iBoot handoff diversion (patch rows that branch into
+`0x170000`, the `SCRATCH` page at `0x160000`, `BOOT_ARGS_EXTRA` at `0x161000`)
+is not used: vphone's iBoot is patched in the image.
+
+## Changes to OpenAVB for Virtualization.framework
+
+OpenAVB's first commit, `54b67bf`, was written against hosts that map the ROM
+aperture as RAM and model the platform differently, and under
+Virtualization.framework it did not start. Five changes made it boot and
+restore. vphone carried them as patches until upstream took them in
+[owngoal-dev/OpenAVB#1](https://github.com/owngoal-dev/OpenAVB/pull/1),
+merged as `02ca2e5`. Upstream then rewrote `main` into one commit, `115169e`,
+which keeps those changes, is the pin, and builds the same image the patched
+`54b67bf` did, and OpenAVB's `make verify` passes on it. Each change
+was found on a live machine by the first thing that stopped, in this order:
+
+1. **ROM aperture is read-only.** `_start` stores `avp_el2_present` at
+ `ROM_LIMIT - 16` (`0x17fff0`). The store took a synchronous external abort
+ (ESR `0x97130050`, ELR `0x1000f8`, FAR `0x17fff0`) and the ROM parked in
+ `pvpanic_trigger` with no console output. The byte now lives in the last
+ 16 bytes of the patch-store window, which nothing clears.
+2. **Chip ID register reads 0.** `platform_read_identity` reads the chip ID at
+ `0x4006f0`, which Virtualization.framework leaves at 0. DFU enumerated as
+ `CPID:0000` and idevicerestore stopped at "Unable to discover device type".
+ It now falls back to `0xfe01`, as Apple's ROM reports. Board ID, ECID,
+ security domain and chip revision were already right.
+3. **DFU suffix CRC.** `validate_transport` computed the suffix CRC with the
+ register seeded with 0 and inverted at the end; libirecovery seeds it with
+ all ones and sends it uninverted (the DFU 1.1 form, which Apple's ROM
+ takes). Every image was refused before its container was read, with no
+ diagnostic, and the ROM stayed in DFU, so idevicerestore went on to send
+ iBEC into the same buffer. The libirecovery form is accepted too.
+4. **Remote boot bit.** iBSS reads bit 5 of the boot context word at
+ `0x400300` as "Remote boot" (`0x70085b74` in the 23G90 iBSS: `ldr w8,
+ [0x400300]; ubfx w0, w8, #5, #1`). Apple's ROM sets it for a DFU image;
+ OpenAVB did not, so iBSS printed "Local boot" and panicked at the recovery
+ prompt. The DFU handoff now sets it.
+5. **USB device left running.** OpenAVB reposts a queue-0 event buffer after
+ every response, so at the handoff the device still held one, in RAM the
+ handoff clears. iBSS then panicked in its USB event loop
+ (`4d682d940d6c950:514`: an event record whose type byte is not 1, 2 or 3).
+ The handoff now writes the device's two enable registers (`+0x404`,
+ `+0x400`) back to 0, and iBSS initializes it itself.
+6. **SEP not ready after a warm reset** (carried as
+ `patches/0001-Wait-for-the-SEP-before-the-first-request-after-a-wa.patch`,
+ not upstream yet). A guest reboot is a PSCI `SYSTEM_RESET`, which restarts
+ the SEP together with the AP. Cold boots and restores worked, but every
+ guest reboot hung: the console filled with `SEP RX timeout`, and
+ Launchpad's setup boot failed at "the guest did not come back from the
+ reboot within 300 s". Tracing the mailbox registers (`+0x10`, `+0x14`,
+ `+0x1c`, `+0x20`) on the console showed the order. On a cold start the SEP
+ is already up when OpenAVB takes the slot, and its first message is
+ waiting (`1c=00100000`). After a warm reset OpenAVB is faster: it takes the
+ slot with RX empty and sends at once (`20=00100000`). The mailbox drops the
+ request (`coprocessor.mailbox: Failed to send a message` in the
+ VirtualizationCore log). The SEP's own setup then clears the AP's ownership
+ (`14=00000000`), and the SEP ROM spins in its acquisition loop
+ (`0x200b14c`) while OpenAVB waits for an answer. `sep_initialize` now waits,
+ for at most 5 s, for the SEP's first message before anything is sent,
+ taking the slot back if the SEP's restart drops it. Each request also sets
+ the enable bit at `+0x10` first, as AVPBooter's acquire loop (`0x110c48`)
+ and the SEP ROM do. On a cold start the message is already there, so
+ nothing waits. Clearing work RAM at reset, re-requesting a stale-owned
+ slot, and AVPBooter's "not full" send predicate were each tried and are
+ not needed.
+
+**How these were found.** The VM's GDB stub (the lower of the two ports
+`lsof -iTCP -sTCP:LISTEN` shows for the `com.apple.Virtualization.VirtualMachine`
+XPC process) reads registers and memory: the AP's PC, ESR/ELR/FAR, OpenAVB's
+progress words at `0x400064`, the patch store at `0x71200000` and the upload
+buffer at `0x71000000`. Symbolize ROM addresses with OpenAVB's
+`build/OpenAVB.elf`. Hardware breakpoints wedged the stub, so iBSS was read
+statically (decode the IM4P, find the code that loads a string with ADRP+ADD,
+disassemble with `llvm-mc`). OpenAVB's own diagnostics (`OpenBootROM: …`)
+reach the VM's serial log.
+
+## Validation
+
+- Normal boot: an iPhone17,3 iOS 26.6.2 machine restored on Apple's ROM, with
+ `romImages.avpBooter` pointed at OpenAVB, prints `OpenBootROM: SEP bootstrap
+ complete`, `Loaded LLB` and iBoot, and vphoned answers `device.info`.
+- Restore (2026-10-18): an iPhone17,3 iOS 26.6.2 machine whose `fw patch` ran
+ on this bundle (`Boot ROM: OpenAVB`, 8 components, iBSS saved LZFSE) restores
+ through OpenAVB's DFU with this bundle's `vphone-cli restore`: `Describing
+ iBSS to OpenAVB (payload 374347 bytes, image 740704 bytes at 0x7006c000)`,
+ the ROM logs `iBSS compressed identity accepted` and `raw identity
+ accepted`, iBSS and iBEC print `Remote boot`, and the restore ends `Restore
+ Finished` with 86 boot-chain patches in the receipt.
+ With CFW installed it boots to iOS on OpenAVB and vphoned answers.
+- Guest reboot (2026-10-18, with patch 0001): `system.reboot` on that machine
+ comes back in 10 s, three times out of three, with no `SEP RX timeout`.
+ `vm template setup` (Launchpad's setup boot, which failed at its reboot
+ step without the patch) passes, the reboot taking 9 s. A second full DFU
+ restore on the patched image also ends `Restore Finished`.
+- Unit tests: `OpenAVBIdentityTests` (VPhoneRestoreTests) pin the header
+ layout and refusals; `BootROMTests` (VPhoneCoreKitTests) the naming, the
+ switch and the report; `FirmwarePipelineTests` the AVPBooter skip;
+ `IM4PPayloadParityTests` the LZFSE iBSS.
+
+To check the image after an update: `UpdateOpenAVB.sh` with no argument
+rebuilds the pinned commit, plus any patches in `patches/`, and compares byte
+for byte. To check a
+machine: `vphone-cli vm info <vm>` prints `rom:`, and the first lines of a boot
+log show `OpenBootROM:` for OpenAVB.
+
+## Upstream
+
+Changes 1 to 5 are upstream (owngoal-dev/OpenAVB#1; `main` at `115169e`
+carries them). Change 6 is carried in `Resources/OpenAVB/patches/` as a
+`git format-patch` file until upstream takes it; delete it when the pin moves
+past it.
+`UpdateOpenAVB.sh` refuses a patch that no longer applies.
diff --git a/Research/Firmware/post_creation_patch_changes.md b/Research/Firmware/post_creation_patch_changes.md
index c683643f..102d345b 100644
--- a/Research/Firmware/post_creation_patch_changes.md
+++ b/Research/Firmware/post_creation_patch_changes.md
@@ -49,7 +49,7 @@ Counts are declarations in `FirmwarePatcher/PatchSets/*.swift`.
| Part | Patches | Lives in | Reaches the guest by | After creation |
| --- | --- | --- | --- | --- |
-| AVPBooter | 1 | VM root, `romImages.avpBooter`, read every boot | `fw patch` itself | works, but `fw patch` refuses without a restore tree |
+| AVPBooter | 1 | VM root, `romImages.avpBooter`, read every boot | `fw patch` itself | works, but `fw patch` refuses without a restore tree. A machine booting OpenAVB has no AVPBooter to patch (`openavb_boot_rom.md`) |
| iBSS, iBEC | 7 | restore tree only | DFU during a restore | irrelevant to an installed guest; only the next restore uses them |
| LLB | 6 | NOR (personalized by idevicerestore, `LlbImageData`) | restore | needs a restore, which erases the guest: an in-place one cannot keep its data (`native_restore_architecture.md`, 2026-10-05) |
| kernelcache | 54 | Preboot (personalized) | `cfw update-kernel` | Host-mounts Preboot and swaps the kernelcache IM4P under the original IM4M (the image4 bypass), data-preserving, no restore |
diff --git a/Research/Host/machine_identity_and_clone.md b/Research/Host/machine_identity_and_clone.md
index a38511a8..ceb8c326 100644
--- a/Research/Host/machine_identity_and_clone.md
+++ b/Research/Host/machine_identity_and_clone.md
@@ -69,7 +69,8 @@ The boot chain already ignores the ECID in its tickets
([iBoot patches](../Firmware/iboot_patches.md),
[firmware manifest and origins](../Firmware/firmware_manifest_and_origins.md)):
-- AVPBooter's DGST bypass loads LLB from `nvram.bin`.
+- AVPBooter's DGST bypass loads LLB from `nvram.bin`; OpenAVB, which new
+ machines boot, checks no digest at all ([OpenAVB boot ROM](../Firmware/openavb_boot_rom.md)).
- iBSS, iBEC and LLB force `image4_validate_property_callback` to return 0.
That callback checks `ECID`, `BNCH`, `BORD`, `CHIP` and the rest, so a
mismatched ECID passes with them. LLB and iBoot load the kernel, device tree,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift
index ebdae416..10cc4e3b 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift
@@ -6,6 +6,8 @@ import Img4tool
/// Handles loading, extracting, and re-packaging IM4P firmware containers.
public enum IM4PHandler {
private static let paypPreservingFourCCs: Set<String> = ["trxm", "krnl"]
+ /// Written back LZFSE-compressed: the image the boot ROM decodes itself.
+ static let lzfseFourCCs: Set<String> = ["ibss"]
/// Load a firmware file as IM4P or raw data.
///
@@ -49,10 +51,15 @@ public enum IM4PHandler {
// a new compression mode here; the Python pipeline currently writes
// these patched payloads back uncompressed and preserves any PAYP
// metadata tail from the original container.
+ //
+ // iBSS is the exception: the boot ROM unpacks it, and OpenAVB
+ // decodes only LZFSE (Apple's AVPBooter takes either), so it goes
+ // back compressed the way Apple ships it.
let newIM4P = try IM4P(
fourcc: original.fourcc,
description: original.description,
payload: patchedData,
+ compression: lzfseFourCCs.contains(original.fourcc) ? "lzfse" : nil,
)
let output: Data = if paypPreservingFourCCs.contains(original.fourcc) {
try appendPAYPIfPresent(from: original.data, to: newIM4P.data)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index af69f2d8..2ef7d6d5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -18,6 +18,7 @@
import Darwin
import Foundation
+import VPhoneCoreKit
import VPhonePatchKit
/// Orchestrates firmware patching for all boot-chain components.
@@ -190,6 +191,9 @@ public final class FirmwarePipeline {
let cloudOSVersion = VPhoneVersion(Self.readCloudOSProductVersion(restoreDir))
cloudOSProductVersion = cloudOSVersion
log("[*] cloudOS kernel: \(cloudOSVersion?.description ?? "unknown")")
+ if VPhoneBootROM.kind(ofMachineAt: vmDirectory) == .openAVB {
+ log("[*] Boot ROM: OpenAVB, which needs no ROM patch")
+ }
// The preset resolves here rather than in init: its version gates need the
// two ProductVersions that were just read, and a conflict or a misnamed
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index 3f6e0bb6..41564dba 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -106,25 +106,30 @@ extension FirmwarePipeline {
// mDNSResponder → no DNS). Empty on 26.x bases (stock boot-args).
let extraBootArgs = baseIs18 ? "if_attach_nx=0x3" : ""
- // 1. AVPBooter — always present, lives in VM root.
- // Patched for every non-less variant (regular/dev/jb/exp).
- components.append(ComponentDescriptor(
- name: "AVPBooter",
- inRestoreDir: false,
- searchPatterns: ["AVPBooter*.bin"],
- patcherFactories: {
- if variant != .less, includeBootChain {
- return [
- { data, verbose in
- let p = AVPBooterPatcher(data: data, verbose: verbose)
- p.gate = gate
- return p
- },
- ]
- }
- return []
- }(),
- ))
+ // 1. AVPBooter — Apple's ROM, in the VM root. Patched for every non-less
+ // variant (regular/dev/jb/exp). A machine booting OpenAVB has nothing
+ // here to patch: OpenAVB checks no image digest, so the digest
+ // bypass the plan selects already holds, and an Apple ROM kept in
+ // the folder beside it is not the one that boots.
+ if VPhoneBootROM.kind(ofMachineAt: vmDirectory) != .openAVB {
+ components.append(ComponentDescriptor(
+ name: "AVPBooter",
+ inRestoreDir: false,
+ searchPatterns: ["AVPBooter*.bin"],
+ patcherFactories: {
+ if variant != .less, includeBootChain {
+ return [
+ { data, verbose in
+ let p = AVPBooterPatcher(data: data, verbose: verbose)
+ p.gate = gate
+ return p
+ },
+ ]
+ }
+ return []
+ }(),
+ ))
+ }
// 2. iBSS — JB and EXP variants run the base iBSS patcher, then the nonce-skip extension.
components.append(ComponentDescriptor(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
index aa769bb5..854e9d9a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
@@ -2,7 +2,9 @@
@testable import FirmwarePatcher
import Foundation
+import Img4tool
import Testing
+import VPhoneCoreKit
import VPhonePatchKit
struct ARM64ConstantTests {
@@ -547,7 +549,30 @@ struct IM4PPayloadParityTests {
let (roundTripPayload, _) = try IM4PHandler.load(contentsOf: tempURL)
#expect(roundTripPayload == payload)
- #expect(try (Data(contentsOf: tempURL)).count > originalFile.count)
+ // Written back LZFSE-compressed, as Apple ships it: OpenAVB decodes
+ // nothing else.
+ #expect(originalFile.range(of: Data("bvx2".utf8)) != nil)
+ #expect(try Data(contentsOf: tempURL).range(of: Data("bvx2".utf8)) != nil)
+ }
+
+ @Test func `iBSS is saved LZFSE-compressed and other images as they were`() throws {
+ let payload = Data((0 ..< 200_000).map { UInt8(truncatingIfNeeded: $0 >> 5) })
+ let marker = Data("bvx2".utf8)
+ for fourcc in ["ibss", "ibec", "illb"] {
+ let original = try IM4P(fourcc: fourcc, description: "iBoot-13822", payload: payload)
+ let url = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent(UUID().uuidString)
+ .appendingPathExtension("im4p")
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ try IM4PHandler.save(patchedData: payload, originalIM4P: original, to: url)
+
+ let saved = try Data(contentsOf: url)
+ #expect((saved.range(of: marker) != nil) == (fourcc == "ibss"), "\(fourcc)")
+ let (roundTrip, container) = try IM4PHandler.load(contentsOf: url)
+ #expect(roundTrip == payload, "\(fourcc)")
+ #expect(container?.fourcc == fourcc)
+ }
}
@Test func `saving TXMIM 4 P preserves PAYP trailer`() throws {
@@ -670,6 +695,30 @@ struct FirmwarePipelineTests {
}
}
+ @Test func `a machine booting OpenAVB has no AVPBooter component to patch`() throws {
+ let fm = FileManager.default
+ let vm = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
+ try fm.createDirectory(at: vm, withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: vm) }
+ // An Apple ROM stays in the folder after a switch; it is not the one that boots.
+ try Data([0xAA]).write(to: vm.appendingPathComponent("AVPBooter.vresearch1.bin"))
+ try Data("OpenBootROM: SEP bootstrap complete\n".utf8).write(to: vm.appendingPathComponent("OpenAVB.bin"))
+
+ func components(booting rom: String) throws -> [String] {
+ try VPhoneVirtualMachineManifest(
+ cpuCount: 2,
+ memorySize: 2 << 30,
+ romImages: .init(avpBooter: rom, avpSEPBooter: "AVPSEPBooter.vresearch1.bin"),
+ ).write(to: vm.appendingPathComponent("config.plist"))
+ let pipeline = FirmwarePipeline(vmDirectory: vm, variant: .jb, verbose: false)
+ return pipeline.buildComponentList(restoreDir: vm, iOSBase: VPhoneVersion("26.6.2")).map(\.name)
+ }
+
+ #expect(try !components(booting: "OpenAVB.bin").contains("AVPBooter"))
+ #expect(try components(booting: "OpenAVB.bin").first == "iBSS")
+ #expect(try components(booting: "AVPBooter.vresearch1.bin").first == "AVPBooter")
+ }
+
@Test func `find file supports glob patterns`() throws {
let fm = FileManager.default
let tempDir = URL(fileURLWithPath: NSTemporaryDirectory())
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
index 5319d3dc..c2f91d87 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
@@ -568,6 +568,7 @@
"-lVPhoneCoreKit",
"-lVPhoneArchiveKit",
"-lcurl",
+ "-lcompression",
);
PRODUCT_MODULE_NAME = VPhoneCommand;
PRODUCT_NAME = "vphone-cli";
@@ -609,6 +610,7 @@
"-lVPhoneCoreKit",
"-lVPhoneArchiveKit",
"-lcurl",
+ "-lcompression",
);
PRODUCT_MODULE_NAME = VPhoneCommand;
PRODUCT_NAME = "vphone-cli";
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index 0cf4d0d8..b34444b7 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -490,6 +490,8 @@ struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {
AVPBooter `fw patch`; read at the next boot. Needs
the restore tree (`--keep-artifacts`).
+ A machine booting OpenAVB has no
+ AVPBooter to patch.
kernelcache `cfw update-kernel` (root), which keeps the
guest's data (no restore).
Guest (system, dyld cache, `cfw update-environment` (root), which
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhonePCCGPURecovery.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhonePCCGPURecovery.swift
index c16b8677..26af9301 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhonePCCGPURecovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhonePCCGPURecovery.swift
@@ -35,12 +35,14 @@ enum VPhonePCCGPURecovery {
// The restore runs over the virtual USB device, so the machine needs no
// NIC. With the default nat one, the Mac's shared vmnet network and its
// DHCP service came up between the end of the restore and the stop.
+ // Apple's ROM: this restores Apple-signed PCC firmware, which OpenAVB has
+ // not been tried with.
let vm = try VPhoneBundleOperations.create(.init(
name: name,
cpuCount: 8,
memoryMB: 8192,
diskSizeGB: 64,
- romSource: VPhoneBundleOperations.defaultROMSource(),
+ romSource: VPhoneBootROM.appleSource,
sepromSource: VPhoneBundleOperations.defaultSEPROMSource(),
networkConfig: .init(mode: .off, macAddress: ""),
), in: library)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneBootROMOption.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneBootROMOption.swift
new file mode 100644
index 00000000..d6862037
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneBootROMOption.swift
@@ -0,0 +1,55 @@
+import ArgumentParser
+import FirmwarePatcher
+import Foundation
+import VPhoneCoreKit
+
+// MARK: - --rom
+
+/// `--rom` of `vm new` and `vm config`: `openavb`, `apple`, or a ROM file.
+enum VPhoneBootROMOption {
+ static var help: ArgumentHelp {
+ "Boot ROM: openavb (the bundle's OpenAVB, the default for new machines), apple (Virtualization.framework's AVPBooter), or a ROM file"
+ }
+
+ /// What `vm new` copies into the new machine. An Apple ROM is patched by
+ /// the `fw patch` that follows, as it always was.
+ static func source(for argument: String?) -> URL {
+ switch argument?.lowercased() {
+ case nil, VPhoneBootROM.openAVB.rawValue: VPhoneBootROM.openAVBSource()
+ case VPhoneBootROM.apple.rawValue: VPhoneBootROM.appleSource
+ default: URL(fileURLWithPath: argument ?? "")
+ }
+ }
+
+ /// Makes `argument` the boot ROM of an existing machine.
+ ///
+ /// `apple` takes the Apple ROM already in the folder when there is one: it
+ /// carries the digest patch `fw patch` applied. Otherwise the framework's
+ /// copy comes in and is patched here, because the machine's boot chain is
+ /// resealed and an unpatched AVPBooter refuses it, and the restore tree
+ /// `fw patch` needs is usually gone by now.
+ static func install(_ argument: String, in bundle: VPhoneBundle) throws -> VPhoneBundle {
+ guard argument.lowercased() == VPhoneBootROM.apple.rawValue else {
+ return try VPhoneBundleOperations.installBootROM(from: source(for: argument), in: bundle)
+ }
+ let kept = bundle.url.appendingPathComponent(VPhoneBootROM.apple.fileName)
+ if VPhoneBootROM.kind(at: kept) == .apple {
+ return try VPhoneBundleOperations.installBootROM(from: kept, in: bundle)
+ }
+ let installed = try VPhoneBundleOperations.installBootROM(from: VPhoneBootROM.appleSource, in: bundle)
+ let patcher = try AVPBooterPatcher(data: Data(contentsOf: kept), verbose: false)
+ try patcher.apply()
+ try patcher.patchedData.write(to: kept, options: .atomic)
+ try VPhoneHostFilePermissions.makeAccessible(at: kept)
+ return installed
+ }
+
+ /// `OpenAVB (OpenAVB.bin)`, for listings.
+ static func describe(_ bundle: VPhoneBundle) -> String {
+ guard let name = bundle.manifest.romImages?.avpBooter else {
+ return "Virtualization.framework built-in"
+ }
+ let kind = VPhoneBootROM.kind(ofMachineAt: bundle.url)
+ return "\(kind?.displayName ?? "unreadable") (\(name))"
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
index e25678a5..7ca1e33d 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
@@ -163,6 +163,7 @@ struct VPhoneVirtualMachineInfoCommand: ParsableCommand {
print("net: \(describeNetwork(report.network))")
print("unlock: \(report.unlocksAtStartup ? "on" : "off")")
print("location: \(report.syncsHostLocation ? "on" : "off")")
+ print("rom: \(VPhoneBootROMOption.describe(bundle))")
if let snapshots = try? VPhoneMachineSnapshots.list(of: bundle), !snapshots.isEmpty {
print("snapshots: \(snapshots.count)")
}
@@ -196,7 +197,7 @@ struct VPhoneVirtualMachineNewCommand: ParsableCommand {
@Option(name: .shortAndLong, help: "CPU cores") var cpu: UInt = 8
@Option(name: .shortAndLong, help: "Memory (MB)") var memory: UInt64 = 8192
@Option(name: .shortAndLong, help: "Disk size (GB)") var diskSize: UInt64 = 64
- @Option(name: .shortAndLong, help: "AVPBooter ROM (default: framework built-in)") var rom: String?
+ @Option(name: .shortAndLong, help: VPhoneBootROMOption.help) var rom: String?
@Option(name: .shortAndLong, help: "AVPSEPBooter ROM (default: framework built-in)") var seprom: String?
func run() throws {
@@ -205,7 +206,7 @@ struct VPhoneVirtualMachineNewCommand: ParsableCommand {
cpuCount: cpu,
memoryMB: memory,
diskSizeGB: diskSize,
- romSource: rom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOperations.defaultROMSource(),
+ romSource: VPhoneBootROMOption.source(for: rom),
sepromSource: seprom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOperations.defaultSEPROMSource(),
)
let bundle = try VPhoneBundleOperations.create(spec, in: lib.library)
@@ -218,7 +219,7 @@ struct VPhoneVirtualMachineNewCommand: ParsableCommand {
struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "config",
- abstract: "Edit VM manifest fields (cpu/memory/network/startup)",
+ abstract: "Edit VM manifest fields (cpu/memory/network/startup/rom)",
discussion: """
Network settings are read when the VM starts, so a change applies from the next launch.
@@ -248,6 +249,11 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
runs, as a simulated location; macOS asks once for permission. The guest's own Location \
Services switch is left alone: with it off, apps in the guest get no location. Applies \
from the next start; in a VM window, Location > Sync Host Location changes it at once.
+
+ --rom openavb makes the bundle's OpenAVB the boot ROM, --rom apple Virtualization.framework's \
+ AVPBooter (the machine's own patched copy when it has one), --rom <file> any other ROM. \
+ Applies from the next start, without a restore: both ROMs load the same patched LLB. \
+ Restoring a machine that boots OpenAVB needs a bundle with OpenAVB support.
""",
)
@@ -280,6 +286,8 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
var unlockAtStartup: String?
@Option(name: .long, help: "Forward this Mac's location to the guest: on | off (default)")
var syncHostLocation: String?
+ @Option(name: .long, help: VPhoneBootROMOption.help)
+ var rom: String?
func run() throws {
let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
@@ -295,6 +303,10 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
unlocksAtStartup: unlocks,
syncsHostLocation: syncsLocation,
)
+ if let rom {
+ let installed = try VPhoneBootROMOption.install(rom, in: updated)
+ print("boot ROM: \(VPhoneBootROMOption.describe(installed)), from the next start")
+ }
let m = updated.manifest
print(
"updated \(updated.name): \(m.cpuCount) CPU, \(m.memorySize / (1024 * 1024)) MB, "
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
index f729df03..81afc08b 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
@@ -440,6 +440,10 @@ public struct VPhoneVirtualMachineCreator {
let clone = try VPhoneMachineTemplates.cloneMachine(from: template, to: options.name, in: library)
outputs.add(clone.url)
do {
+ // The ROM is not part of a template's key: it changes without a
+ // restore. A template built before OpenAVB still starts Apple's,
+ // so the machine gets this bundle's ROM, as a `vm new` would.
+ try VPhoneBundleOperations.installBootROM(from: VPhoneBundleOperations.defaultROMSource(), in: clone)
try applySettings(options)
} catch {
try? FileManager.default.removeItem(at: clone.url)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Include/vphone_restore_bridge.h b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Include/vphone_restore_bridge.h
index 8c229598..2ab8f0d2 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Include/vphone_restore_bridge.h
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Include/vphone_restore_bridge.h
@@ -21,6 +21,7 @@
#define VPHONE_RESTORE_BRIDGE_H
#include <stdbool.h>
+#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
@@ -159,6 +160,25 @@ struct vphone_restore_options {
*/
int vphone_restore_run(const struct vphone_restore_options *options);
+/* --- OpenAVB ----------------------------------------------------------- */
+
+/* The size of OpenAVB's patch-store stage header (AVPPatchStageHeader). */
+#define VPHONE_OPENAVB_IDENTITY_SIZE 112
+
+/*
+ * The stage header a restore uploads to OpenAVB before iBSS goes over DFU:
+ * the sizes and SHA-256 digests of the iBSS IM4P payload and of the image it
+ * decodes to, iBoot's link address, entry exception level 2, the identity
+ * flag and no patch rows. `image` is an IMG4 or a bare IM4P whose payload is
+ * LZFSE. The restore does this itself when the ROM is OpenAVB; it is public
+ * so the layout can be tested without a device.
+ *
+ * Returns 0 and fills `header`, or -1 and points `reason` (when non-NULL) at
+ * a static sentence saying what is wrong with the image.
+ */
+int vphone_restore_openavb_ibss_identity(const void *image, size_t size,
+ uint8_t header[VPHONE_OPENAVB_IDENTITY_SIZE], const char **reason);
+
#ifdef __cplusplus
}
#endif
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/dfu.c b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/dfu.c
index 6ba23e7f..e353fd29 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/dfu.c
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/dfu.c
@@ -30,6 +30,7 @@
#include <libtatsu/tss.h>
#include "dfu.h"
+#include "openavb.h"
#include "recovery.h"
#include "idevicerestore.h"
#include "common.h"
@@ -197,6 +198,12 @@ int dfu_send_component(struct idevicerestore_client_t* client, plist_t build_ide
size += fillsize;
}
+ /* vphone: OpenAVB takes an iBSS only after its identity is uploaded. */
+ if (!strcmp(component, "iBSS") && openavb_describe_ibss(client->dfu->client, data, size) < 0) {
+ free(data);
+ return -1;
+ }
+
logger(LL_INFO, "Sending %s (%zu bytes)...\n", component, size);
register_progress('DFUP', "Uploading");
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/openavb.c b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/openavb.c
new file mode 100644
index 00000000..280e5551
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/openavb.c
@@ -0,0 +1,305 @@
+/*
+ * openavb.c
+ * The stage-0 image identity OpenAVB needs before it takes an iBSS over DFU.
+ *
+ * Not part of upstream idevicerestore. New vphone machines boot OpenAVB
+ * (https://github.com/owngoal-dev/OpenAVB) instead of Apple's AVPBooter.
+ * OpenAVB carries no description of any iBoot build: it refuses a DFU iBSS
+ * unless the host first tells it what that image is -- the size and SHA-256
+ * of the IM4P payload, the size and SHA-256 of the decompressed image, its
+ * load address and entry exception level. This file builds that description
+ * from the personalized iBSS and uploads it with the ROM's vendor requests on
+ * the default control pipe:
+ *
+ * 0x41 0x70 wValue=stage open the stage's slot
+ * 0x41 0x71 wValue=stage wIndex=chunk data append, chunks in order
+ * 0x41 0x72 wValue=stage wIndex=rows seal; writes the magic
+ * 0xc0 0x73 48 B report {count, received, sealed}
+ *
+ * The slot holds a 112-byte header (OpenAVB's AVPPatchStageHeader) followed
+ * by `rows` {offset, instruction} words. vphone's iBSS is already patched by
+ * `fw patch`, so the slot carries the identity and no rows.
+ *
+ * Apple's ROM stalls the report request, which is how this tells the two
+ * apart: the request only reads, and nothing is written to a ROM that does
+ * not answer it. The contract is OpenAVB's docs/external-contract.md;
+ * vphone's side of it is Research/Firmware/openavb_boot_rom.md.
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <compression.h>
+#include <CommonCrypto/CommonDigest.h>
+
+#include "openavb.h"
+#include "common.h"
+#include "vphone_restore_bridge.h"
+
+enum {
+ OPENAVB_REQUEST_OPEN = 0x70,
+ OPENAVB_REQUEST_APPEND = 0x71,
+ OPENAVB_REQUEST_SEAL = 0x72,
+ OPENAVB_REQUEST_REPORT = 0x73,
+ OPENAVB_STAGE_IBSS = 0,
+ OPENAVB_STAGE_COUNT = 4,
+ OPENAVB_REPORT_SIZE = OPENAVB_STAGE_COUNT * 12,
+ OPENAVB_MAGIC = 0x48435450, /* 'PTCH' */
+ OPENAVB_VERSION = 1,
+ OPENAVB_FLAG_IDENTITY = 1,
+ OPENAVB_PROBE_TIMEOUT_MS = 1000,
+ OPENAVB_TIMEOUT_MS = 5000,
+ /* iBoot records its link address as a 64-bit word at this offset. */
+ IBOOT_LINK_BASE_OFFSET = 0x300,
+ /* An iBSS runs at EL2 where the CPU offers it; the ROM keeps EL1 on its
+ * own when it was entered at EL1, as it is under Virtualization.framework. */
+ IBOOT_ENTRY_EXCEPTION_LEVEL = 2,
+ /* Far beyond any iBoot; only bounds the decode buffer. */
+ IBOOT_MAX_RAW_SIZE = 64 << 20,
+};
+
+_Static_assert(VPHONE_OPENAVB_IDENTITY_SIZE == 112, "AVPPatchStageHeader is 112 bytes");
+
+/* --- DER ----------------------------------------------------------------- */
+
+/* One element at `*at`, ending no later than `end`: its tag and body.
+ * Advances `*at` past it. */
+static int der_next(const uint8_t *data, size_t end, size_t *at, uint8_t *tag, size_t *body, size_t *body_end)
+{
+ size_t i = *at;
+ if (i > end || end - i < 2) {
+ return -1;
+ }
+ *tag = data[i];
+ size_t length = data[i + 1];
+ i += 2;
+ if (length & 0x80) {
+ size_t count = length & 0x7f;
+ if (count == 0 || count > 4 || end - i < count) {
+ return -1;
+ }
+ length = 0;
+ for (size_t k = 0; k < count; k++) {
+ length = (length << 8) | data[i + k];
+ }
+ i += count;
+ }
+ if (length > end - i) {
+ return -1;
+ }
+ *body = i;
+ *body_end = i + length;
+ *at = *body_end;
+ return 0;
+}
+
+static int der_is_string(const uint8_t *data, size_t body, size_t body_end, const char *text)
+{
+ size_t length = strlen(text);
+ return body_end - body == length && memcmp(data + body, text, length) == 0;
+}
+
+/*
+ * The payload of the IM4P in `data`, which is an IM4P or an IMG4 wrapping
+ * one: SEQUENCE { "IMG4", IM4P, [0] IM4M } and SEQUENCE { "IM4P", type,
+ * description, payload, ... }. The payload is the first OCTET STRING after
+ * the "IM4P" marker. This is what OpenAVB measures as the compressed image.
+ */
+static int im4p_payload(const uint8_t *data, size_t size, const uint8_t **payload, size_t *payload_size)
+{
+ size_t at = 0, body, body_end;
+ uint8_t tag;
+ if (der_next(data, size, &at, &tag, &body, &body_end) < 0 || tag != 0x30) {
+ return -1;
+ }
+ const size_t end = body_end;
+ at = body;
+ if (der_next(data, end, &at, &tag, &body, &body_end) < 0 || tag != 0x16) {
+ return -1;
+ }
+ if (der_is_string(data, body, body_end, "IMG4")) {
+ const size_t inner = at;
+ if (der_next(data, end, &at, &tag, &body, &body_end) < 0 || tag != 0x30) {
+ return -1;
+ }
+ return im4p_payload(data + inner, body_end - inner, payload, payload_size);
+ }
+ if (!der_is_string(data, body, body_end, "IM4P")) {
+ return -1;
+ }
+ while (at < end) {
+ if (der_next(data, end, &at, &tag, &body, &body_end) < 0) {
+ return -1;
+ }
+ if (tag == 0x04) {
+ *payload = data + body;
+ *payload_size = body_end - body;
+ return 0;
+ }
+ }
+ return -1;
+}
+
+/* --- Identity ------------------------------------------------------------ */
+
+static void put_u32(uint8_t *at, uint32_t value)
+{
+ for (int i = 0; i < 4; i++) {
+ at[i] = (uint8_t)(value >> (8 * i));
+ }
+}
+
+static void put_u64(uint8_t *at, uint64_t value)
+{
+ for (int i = 0; i < 8; i++) {
+ at[i] = (uint8_t)(value >> (8 * i));
+ }
+}
+
+static uint32_t get_u32(const uint8_t *at)
+{
+ return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
+}
+
+static uint64_t get_u64(const uint8_t *at)
+{
+ uint64_t value = 0;
+ for (int i = 7; i >= 0; i--) {
+ value = (value << 8) | at[i];
+ }
+ return value;
+}
+
+/*
+ * The whole LZFSE stream decoded. An LZFSE stream is a chain of blocks, each
+ * naming only its own size, so the output size is not known up front: the
+ * buffer doubles until the decoder returns less than it was offered.
+ */
+static uint8_t *lzfse_decode(const uint8_t *payload, size_t size, size_t *decoded)
+{
+ size_t capacity = size * 4 > (1u << 20) ? size * 4 : (1u << 20);
+ while (capacity <= IBOOT_MAX_RAW_SIZE) {
+ uint8_t *buffer = malloc(capacity);
+ if (buffer == NULL) {
+ return NULL;
+ }
+ size_t got = compression_decode_buffer(buffer, capacity, payload, size, NULL, COMPRESSION_LZFSE);
+ if (got == 0) {
+ free(buffer);
+ return NULL;
+ }
+ if (got < capacity) {
+ *decoded = got;
+ return buffer;
+ }
+ free(buffer);
+ capacity *= 2;
+ }
+ return NULL;
+}
+
+int vphone_restore_openavb_ibss_identity(const void *image, size_t size, uint8_t header[VPHONE_OPENAVB_IDENTITY_SIZE], const char **reason)
+{
+ const char *ignored;
+ if (reason == NULL) {
+ reason = &ignored;
+ }
+ const uint8_t *payload = NULL;
+ size_t payload_size = 0;
+ if (image == NULL || header == NULL || im4p_payload(image, size, &payload, &payload_size) < 0) {
+ *reason = "the iBSS is not an IMG4 or IM4P container";
+ return -1;
+ }
+ if (payload_size < 4 || memcmp(payload, "bvx2", 4) != 0) {
+ /* OpenAVB decodes LZFSE only; `fw patch` writes iBSS back that way. */
+ *reason = "the iBSS payload is not LZFSE-compressed; run fw patch with this bundle again";
+ return -1;
+ }
+ if (payload_size > UINT32_MAX) {
+ *reason = "the iBSS payload is too large";
+ return -1;
+ }
+ size_t raw_size = 0;
+ uint8_t *raw = lzfse_decode(payload, payload_size, &raw_size);
+ if (raw == NULL) {
+ *reason = "the iBSS payload does not decode as LZFSE";
+ return -1;
+ }
+ if (raw_size < IBOOT_LINK_BASE_OFFSET + 8) {
+ free(raw);
+ *reason = "the decoded iBSS is too small to be iBoot";
+ return -1;
+ }
+ const uint64_t load_base = get_u64(raw + IBOOT_LINK_BASE_OFFSET);
+ if (load_base == 0 || (load_base & 0x3fff) != 0) {
+ free(raw);
+ *reason = "the decoded iBSS names no page-aligned link address";
+ return -1;
+ }
+
+ memset(header, 0, VPHONE_OPENAVB_IDENTITY_SIZE);
+ put_u32(header + 0x00, OPENAVB_MAGIC);
+ put_u32(header + 0x04, OPENAVB_VERSION);
+ put_u32(header + 0x08, 0); /* rows */
+ put_u32(header + 0x0c, OPENAVB_FLAG_IDENTITY);
+ /* 0x10 received, 0x14 next_chunk: the ROM keeps those. */
+ put_u32(header + 0x18, (uint32_t)payload_size);
+ put_u32(header + 0x1c, (uint32_t)raw_size);
+ put_u64(header + 0x20, load_base);
+ put_u32(header + 0x28, IBOOT_ENTRY_EXCEPTION_LEVEL);
+ CC_SHA256(payload, (CC_LONG)payload_size, header + 0x30);
+ CC_SHA256(raw, (CC_LONG)raw_size, header + 0x50);
+ free(raw);
+ *reason = NULL;
+ return 0;
+}
+
+/* --- Upload -------------------------------------------------------------- */
+
+/* One of the three words the report gives for a stage: count, received, sealed. */
+static uint32_t report_word(const unsigned char *report, int stage, int field)
+{
+ return get_u32(report + stage * 12 + field * 4);
+}
+
+int openavb_describe_ibss(irecv_client_t client, const void *image, size_t size)
+{
+ unsigned char report[OPENAVB_REPORT_SIZE];
+ int got = irecv_usb_control_transfer(client, 0xc0, OPENAVB_REQUEST_REPORT, 0, 0,
+ report, sizeof(report), OPENAVB_PROBE_TIMEOUT_MS);
+ if (got != (int)sizeof(report)) {
+ logger(LL_DEBUG, "The boot ROM does not answer OpenAVB's patch-store report (%d); sending iBSS as is.\n", got);
+ return 0;
+ }
+
+ uint8_t header[VPHONE_OPENAVB_IDENTITY_SIZE];
+ const char *reason = NULL;
+ if (vphone_restore_openavb_ibss_identity(image, size, header, &reason) < 0) {
+ logger(LL_ERROR, "OpenAVB needs the iBSS identity, but %s.\n", reason);
+ return -1;
+ }
+ logger(LL_INFO, "Describing iBSS to OpenAVB (payload %u bytes, image %u bytes at 0x%llx)...\n",
+ get_u32(header + 0x18), get_u32(header + 0x1c), (unsigned long long)get_u64(header + 0x20));
+
+ if (irecv_usb_control_transfer(client, 0x41, OPENAVB_REQUEST_OPEN, OPENAVB_STAGE_IBSS, 0,
+ NULL, 0, OPENAVB_TIMEOUT_MS) < 0
+ || irecv_usb_control_transfer(client, 0x41, OPENAVB_REQUEST_APPEND, OPENAVB_STAGE_IBSS, 0,
+ header, sizeof(header), OPENAVB_TIMEOUT_MS) != (int)sizeof(header)
+ || irecv_usb_control_transfer(client, 0x41, OPENAVB_REQUEST_SEAL, OPENAVB_STAGE_IBSS, 0,
+ NULL, 0, OPENAVB_TIMEOUT_MS) < 0) {
+ logger(LL_ERROR, "OpenAVB refused the iBSS identity.\n");
+ return -1;
+ }
+
+ got = irecv_usb_control_transfer(client, 0xc0, OPENAVB_REQUEST_REPORT, 0, 0,
+ report, sizeof(report), OPENAVB_TIMEOUT_MS);
+ if (got != (int)sizeof(report)
+ || report_word(report, OPENAVB_STAGE_IBSS, 0) != 0
+ || report_word(report, OPENAVB_STAGE_IBSS, 1) != sizeof(header)
+ || report_word(report, OPENAVB_STAGE_IBSS, 2) != 1) {
+ logger(LL_ERROR, "OpenAVB did not seal the iBSS identity.\n");
+ return -1;
+ }
+ return 0;
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/openavb.h b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/openavb.h
new file mode 100644
index 00000000..c3f5691e
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/MobileRestoreCore/Recovery/openavb.h
@@ -0,0 +1,34 @@
+/*
+ * openavb.h
+ * The stage-0 image identity OpenAVB needs before it takes an iBSS over DFU.
+ *
+ * Not part of upstream idevicerestore. See openavb.c.
+ */
+
+#ifndef IDEVICERESTORE_OPENAVB_H
+#define IDEVICERESTORE_OPENAVB_H
+
+#include <stddef.h>
+#include <libirecovery.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Before an iBSS goes over DFU: when the device in DFU is OpenAVB, upload
+ * the identity of `image` (the personalized iBSS about to be sent) into the
+ * ROM's iBSS patch-store slot. Apple's ROM does not answer the probe, and
+ * then nothing is sent.
+ *
+ * Returns 0 when the identity was accepted or the ROM is not OpenAVB, and -1
+ * when it is OpenAVB and the identity could not be built or uploaded; the
+ * ROM would refuse the iBSS, so the restore stops there.
+ */
+int openavb_describe_ibss(irecv_client_t client, const void *image, size_t size);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestore.xcodeproj/project.pbxproj b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestore.xcodeproj/project.pbxproj
index d5860737..3e77d8c4 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestore.xcodeproj/project.pbxproj
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestore.xcodeproj/project.pbxproj
@@ -470,6 +470,7 @@
"$(inherited)",
"-lz",
"-lcurl",
+ "-lcompression",
);
PRODUCT_BUNDLE_IDENTIFIER = com.vphone.restore.tests;
PRODUCT_NAME = VPhoneRestoreTests;
@@ -493,6 +494,7 @@
"$(inherited)",
"-lz",
"-lcurl",
+ "-lcompression",
);
PRODUCT_BUNDLE_IDENTIFIER = com.vphone.restore.tests;
PRODUCT_NAME = VPhoneRestoreTests;
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestoreTests/OpenAVBIdentityTests.swift b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestoreTests/OpenAVBIdentityTests.swift
new file mode 100644
index 00000000..f8d123df
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneRestore/VPhoneRestoreTests/OpenAVBIdentityTests.swift
@@ -0,0 +1,138 @@
+import Compression
+import CryptoKit
+import Foundation
+import MobileRestoreCore
+import Testing
+
+/// The stage header a restore uploads to OpenAVB before iBSS.
+///
+/// The ROM checks the iBSS it receives against these fields and refuses it on
+/// any mismatch, far from here, so the layout is pinned against OpenAVB's
+/// `AVPPatchStageHeader`: magic, version, rows, flags, the two ROM-owned
+/// words, sizes, load base, entry level, then the two SHA-256 digests.
+struct OpenAVBIdentityTests {
+ // MARK: - Fixtures
+
+ /// An iBoot-shaped image: the link base at 0x300 in filler that
+ /// compresses, large enough to decode past the first buffer the decoder
+ /// is offered.
+ private func iBootImage(base: UInt64 = 0x7006_C000, size: Int = 3 << 20) -> Data {
+ var image = (0 ..< size).map { UInt8(truncatingIfNeeded: ($0 >> 6) ^ ($0 >> 13)) }
+ for i in 0 ..< 8 {
+ image[0x300 + i] = UInt8(truncatingIfNeeded: base >> (8 * i))
+ }
+ return Data(image)
+ }
+
+ private func lzfse(_ data: Data) -> Data {
+ var output = Data(count: data.count + 4096)
+ let count = output.withUnsafeMutableBytes { out in
+ data.withUnsafeBytes { input in
+ compression_encode_buffer(
+ out.bindMemory(to: UInt8.self).baseAddress!, out.count,
+ input.bindMemory(to: UInt8.self).baseAddress!, input.count,
+ nil, COMPRESSION_LZFSE,
+ )
+ }
+ }
+ output.count = count
+ return output
+ }
+
+ private func der(_ tag: UInt8, _ body: Data) -> Data {
+ var out = Data([tag])
+ if body.count < 0x80 {
+ out.append(UInt8(body.count))
+ } else {
+ let length = withUnsafeBytes(of: UInt32(body.count).bigEndian) { Data($0) }.drop { $0 == 0 }
+ out.append(0x80 | UInt8(length.count))
+ out.append(length)
+ }
+ out.append(body)
+ return out
+ }
+
+ private func ia5(_ text: String) -> Data {
+ der(0x16, Data(text.utf8))
+ }
+
+ private func im4p(payload: Data) -> Data {
+ der(0x30, ia5("IM4P") + ia5("ibss") + ia5("iBoot-13822") + der(0x04, payload))
+ }
+
+ /// IMG4 { "IMG4", IM4P, [0] IM4M }, as idevicerestore personalizes it.
+ private func img4(wrapping im4p: Data) -> Data {
+ der(0x30, ia5("IMG4") + im4p + der(0xA0, der(0x30, ia5("IM4M"))))
+ }
+
+ private func identity(of image: Data) -> (status: Int32, header: [UInt8], reason: String?) {
+ var header = [UInt8](repeating: 0, count: Int(VPHONE_OPENAVB_IDENTITY_SIZE))
+ var reason: UnsafePointer<CChar>?
+ let status = image.withUnsafeBytes { bytes in
+ vphone_restore_openavb_ibss_identity(bytes.baseAddress, bytes.count, &header, &reason)
+ }
+ return (status, header, reason.map { String(cString: $0) })
+ }
+
+ private func u32(_ bytes: [UInt8], _ offset: Int) -> UInt32 {
+ (0 ..< 4).reduce(0) { $0 | UInt32(bytes[offset + $1]) << (8 * $1) }
+ }
+
+ private func u64(_ bytes: [UInt8], _ offset: Int) -> UInt64 {
+ (0 ..< 8).reduce(0) { $0 | UInt64(bytes[offset + $1]) << (8 * $1) }
+ }
+
+ // MARK: - Layout
+
+ @Test func `the header describes the payload and the image it decodes to`() throws {
+ let raw = iBootImage()
+ let payload = lzfse(raw)
+ #expect(payload.prefix(4) == Data("bvx2".utf8))
+
+ let result = identity(of: img4(wrapping: im4p(payload: payload)))
+ #expect(result.status == 0)
+ #expect(result.reason == nil)
+ let header = result.header
+ #expect(u32(header, 0x00) == 0x4843_5450) // 'PTCH'
+ #expect(u32(header, 0x04) == 1)
+ #expect(u32(header, 0x08) == 0) // no patch rows: fw patch already patched it
+ #expect(u32(header, 0x0C) == 1) // the identity flag
+ #expect(u32(header, 0x10) == 0)
+ #expect(u32(header, 0x14) == 0)
+ #expect(u32(header, 0x18) == UInt32(payload.count))
+ #expect(u32(header, 0x1C) == UInt32(raw.count))
+ #expect(u64(header, 0x20) == 0x7006_C000)
+ #expect(u32(header, 0x28) == 2)
+ #expect(Array(header[0x30 ..< 0x50]) == Array(SHA256.hash(data: payload)))
+ #expect(Array(header[0x50 ..< 0x70]) == Array(SHA256.hash(data: raw)))
+ }
+
+ @Test func `a bare IM4P gives the same header as the IMG4 around it`() {
+ let container = im4p(payload: lzfse(iBootImage()))
+ let bare = identity(of: container)
+ let wrapped = identity(of: img4(wrapping: container))
+ #expect(bare.status == 0)
+ #expect(bare.header == wrapped.header)
+ }
+
+ // MARK: - Refusals
+
+ @Test func `an uncompressed payload is refused, because OpenAVB decodes only LZFSE`() {
+ let result = identity(of: img4(wrapping: im4p(payload: iBootImage())))
+ #expect(result.status == -1)
+ #expect(result.reason?.contains("not LZFSE") == true)
+ }
+
+ @Test func `an image with no link address is refused`() {
+ let result = identity(of: im4p(payload: lzfse(iBootImage(base: 0))))
+ #expect(result.status == -1)
+ #expect(result.reason?.contains("link address") == true)
+ }
+
+ @Test func `something that is not IMG4 or IM4P is refused`() {
+ #expect(identity(of: Data("not a container".utf8)).status == -1)
+ #expect(identity(of: der(0x30, ia5("IM4M"))).status == -1)
+ // A length running past the end of the data.
+ #expect(identity(of: Data([0x30, 0x84, 0x7F, 0xFF, 0xFF, 0xFF, 0x16])).status == -1)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 51eb5fbc..2523e891 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -108,6 +108,14 @@ else
/usr/bin/plutil -remove VPhoneBuildHash "$info_plist" 2>/dev/null || true
fi
+# The boot ROM new machines copy (vm new), with the licences it is
+# distributed under. Checked in prebuilt; see Resources/OpenAVB/README.md.
+/bin/mkdir -p "$resources/OpenAVB"
+/bin/cp "$root/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/OpenAVB.bin" \
+ "$root/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/LICENSE" \
+ "$root/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/APSL-2.0.txt" \
+ "$resources/OpenAVB/"
+
# Patch presets. Prewritten plists, read by vphone-cli at patch time to decide
# which declared patches apply. Nothing generates or edits these.
/bin/mkdir -p "$resources/patches_presets"
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/UpdateOpenAVB.sh b/VPhoneExecutable/VPhoneVirtualization/Build/UpdateOpenAVB.sh
new file mode 100755
index 00000000..924a7965
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/UpdateOpenAVB.sh
@@ -0,0 +1,66 @@
+#!/bin/zsh
+# vphone-tier: build
+#
+# Rebuild Resources/OpenAVB/OpenAVB.bin from OpenAVB's source, with any
+# patches in Resources/OpenAVB/patches applied in order.
+#
+# UpdateOpenAVB.sh build the pinned commit and check it matches
+# the checked-in image byte for byte
+# UpdateOpenAVB.sh <commit> build another commit and replace the image,
+# LICENSE and APSL-2.0.txt with what it builds
+#
+# A patch upstream has taken is deleted from patches/ when moving past it.
+#
+# Nothing here runs during the VPhone build: the image is checked in so the
+# bundle needs no cross toolchain. The clone and the build happen in a
+# temporary folder outside this repository. Needs git and
+# `brew install llvm lld`. After replacing the image, update the commit,
+# toolchain, SHA-256 and size in Resources/OpenAVB/README.md and the pinned
+# commit below, then boot and restore a machine with it.
+set -euo pipefail
+
+repository="https://github.com/owngoal-dev/OpenAVB.git"
+pinned="115169e61a206a967bb2299e5c3145888741bba3"
+
+root="$(cd "${0:a:h}/../../.." && pwd)"
+destination="$root/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB"
+commit="${1:-$pinned}"
+llvm="${LLVM_PREFIX:-/opt/homebrew/opt/llvm/bin}"
+
+for tool in "$llvm/clang" "$llvm/llvm-objcopy" /opt/homebrew/bin/ld.lld; do
+ [[ -x "$tool" ]] || { print -u2 "Missing $tool (brew install llvm lld)"; exit 1; }
+done
+
+work="$(/usr/bin/mktemp -d)"
+trap '/bin/rm -rf "$work"' EXIT
+/usr/bin/git clone --quiet "$repository" "$work/OpenAVB"
+/usr/bin/git -C "$work/OpenAVB" checkout --quiet --detach "$commit"
+for patch in "$destination"/patches/*.patch(N); do
+ /usr/bin/git -C "$work/OpenAVB" apply --whitespace=nowarn "$patch" || {
+ print -u2 "${patch:t} does not apply to $commit; refresh it, or delete it if upstream has it"
+ exit 1
+ }
+ print "patch ${patch:t}"
+done
+/usr/bin/make -C "$work/OpenAVB" LLVM_PREFIX="$llvm" build/OpenAVB.bin >/dev/null
+
+built="$work/OpenAVB/build/OpenAVB.bin"
+print "commit $(/usr/bin/git -C "$work/OpenAVB" rev-parse HEAD)"
+print "sha256 $(/usr/bin/shasum -a 256 "$built" | /usr/bin/awk '{print $1}')"
+print "size $(/usr/bin/stat -f %z "$built")"
+print "clang $("$llvm/clang" --version | /usr/bin/head -1)"
+print "ld.lld $(/opt/homebrew/bin/ld.lld --version)"
+
+if (( $# == 0 )); then
+ /usr/bin/cmp "$built" "$destination/OpenAVB.bin" || {
+ print -u2 "The pinned commit does not build the checked-in OpenAVB.bin with this toolchain."
+ exit 1
+ }
+ print "OpenAVB.bin matches $pinned"
+else
+ /bin/cp "$built" "$destination/OpenAVB.bin"
+ /bin/cp "$work/OpenAVB/LICENSE" "$destination/LICENSE"
+ /bin/cp "$work/OpenAVB/LICENSES/APSL-2.0.txt" "$destination/APSL-2.0.txt"
+ /bin/chmod 644 "$destination/OpenAVB.bin" "$destination/LICENSE" "$destination/APSL-2.0.txt"
+ print "Replaced $destination/OpenAVB.bin; update README.md and the pinned commit."
+fi
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 4a2f6d1f..67991deb 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -92,6 +92,19 @@ done
for preset in "$resources/patches_presets/"*.plist; do
/usr/bin/plutil -lint -s "$preset" || { print -u2 "Malformed patch preset: ${preset:t}"; exit 1; }
done
+# New machines copy this ROM. Without it vm new would fail, and OpenAVB is
+# distributed only with its licences. The ROM window is 512 KiB.
+for name in OpenAVB.bin LICENSE APSL-2.0.txt; do
+ [[ -s "$resources/OpenAVB/$name" ]] || { print -u2 "Missing Contents/Resources/OpenAVB/$name"; exit 1; }
+done
+(( $(/usr/bin/stat -f %z "$resources/OpenAVB/OpenAVB.bin") <= 0x80000 )) || {
+ print -u2 "OpenAVB.bin is larger than the 512 KiB ROM window"
+ exit 1
+}
+/usr/bin/grep -q 'OpenBootROM:' "$resources/OpenAVB/OpenAVB.bin" || {
+ print -u2 "Contents/Resources/OpenAVB/OpenAVB.bin is not an OpenAVB image"
+ exit 1
+}
for name in vphoned vphoned-tvos launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/APSL-2.0.txt b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/APSL-2.0.txt
new file mode 100644
index 00000000..fe81a60c
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/APSL-2.0.txt
@@ -0,0 +1,367 @@
+APPLE PUBLIC SOURCE LICENSE
+Version 2.0 - August 6, 2003
+
+Please read this License carefully before downloading this software.
+By downloading or using this software, you are agreeing to be bound by
+the terms of this License. If you do not or cannot agree to the terms
+of this License, please do not download or use the software.
+
+1. General; Definitions. This License applies to any program or other
+work which Apple Computer, Inc. ("Apple") makes publicly available and
+which contains a notice placed by Apple identifying such program or
+work as "Original Code" and stating that it is subject to the terms of
+this Apple Public Source License version 2.0 ("License"). As used in
+this License:
+
+1.1 "Applicable Patent Rights" mean: (a) in the case where Apple is
+the grantor of rights, (i) claims of patents that are now or hereafter
+acquired, owned by or assigned to Apple and (ii) that cover subject
+matter contained in the Original Code, but only to the extent
+necessary to use, reproduce and/or distribute the Original Code
+without infringement; and (b) in the case where You are the grantor of
+rights, (i) claims of patents that are now or hereafter acquired,
+owned by or assigned to You and (ii) that cover subject matter in Your
+Modifications, taken alone or in combination with Original Code.
+
+1.2 "Contributor" means any person or entity that creates or
+contributes to the creation of Modifications.
+
+1.3 "Covered Code" means the Original Code, Modifications, the
+combination of Original Code and any Modifications, and/or any
+respective portions thereof.
+
+1.4 "Externally Deploy" means: (a) to sublicense, distribute or
+otherwise make Covered Code available, directly or indirectly, to
+anyone other than You; and/or (b) to use Covered Code, alone or as
+part of a Larger Work, in any way to provide a service, including but
+not limited to delivery of content, through electronic communication
+with a client other than You.
+
+1.5 "Larger Work" means a work which combines Covered Code or portions
+thereof with code not governed by the terms of this License.
+
+1.6 "Modifications" mean any addition to, deletion from, and/or change
+to, the substance and/or structure of the Original Code, any previous
+Modifications, the combination of Original Code and any previous
+Modifications, and/or any respective portions thereof. When code is
+released as a series of files, a Modification is: (a) any addition to
+or deletion from the contents of a file containing Covered Code;
+and/or (b) any new file or other representation of computer program
+statements that contains any part of Covered Code.
+
+1.7 "Original Code" means (a) the Source Code of a program or other
+work as originally made available by Apple under this License,
+including the Source Code of any updates or upgrades to such programs
+or works made available by Apple under this License, and that has been
+expressly identified by Apple as such in the header file(s) of such
+work; and (b) the object code compiled from such Source Code and
+originally made available by Apple under this License.
+
+1.8 "Source Code" means the human readable form of a program or other
+work that is suitable for making modifications to it, including all
+modules it contains, plus any associated interface definition files,
+scripts used to control compilation and installation of an executable
+(object code).
+
+1.9 "You" or "Your" means an individual or a legal entity exercising
+rights under this License. For legal entities, "You" or "Your"
+includes any entity which controls, is controlled by, or is under
+common control with, You, where "control" means (a) the power, direct
+or indirect, to cause the direction or management of such entity,
+whether by contract or otherwise, or (b) ownership of fifty percent
+(50%) or more of the outstanding shares or beneficial ownership of
+such entity.
+
+2. Permitted Uses; Conditions & Restrictions. Subject to the terms
+and conditions of this License, Apple hereby grants You, effective on
+the date You accept this License and download the Original Code, a
+world-wide, royalty-free, non-exclusive license, to the extent of
+Apple's Applicable Patent Rights and copyrights covering the Original
+Code, to do the following:
+
+2.1 Unmodified Code. You may use, reproduce, display, perform,
+internally distribute within Your organization, and Externally Deploy
+verbatim, unmodified copies of the Original Code, for commercial or
+non-commercial purposes, provided that in each instance:
+
+(a) You must retain and reproduce in all copies of Original Code the
+copyright and other proprietary notices and disclaimers of Apple as
+they appear in the Original Code, and keep intact all notices in the
+Original Code that refer to this License; and
+
+(b) You must include a copy of this License with every copy of Source
+Code of Covered Code and documentation You distribute or Externally
+Deploy, and You may not offer or impose any terms on such Source Code
+that alter or restrict this License or the recipients' rights
+hereunder, except as permitted under Section 6.
+
+2.2 Modified Code. You may modify Covered Code and use, reproduce,
+display, perform, internally distribute within Your organization, and
+Externally Deploy Your Modifications and Covered Code, for commercial
+or non-commercial purposes, provided that in each instance You also
+meet all of these conditions:
+
+(a) You must satisfy all the conditions of Section 2.1 with respect to
+the Source Code of the Covered Code;
+
+(b) You must duplicate, to the extent it does not already exist, the
+notice in Exhibit A in each file of the Source Code of all Your
+Modifications, and cause the modified files to carry prominent notices
+stating that You changed the files and the date of any change; and
+
+(c) If You Externally Deploy Your Modifications, You must make
+Source Code of all Your Externally Deployed Modifications either
+available to those to whom You have Externally Deployed Your
+Modifications, or publicly available. Source Code of Your Externally
+Deployed Modifications must be released under the terms set forth in
+this License, including the license grants set forth in Section 3
+below, for as long as you Externally Deploy the Covered Code or twelve
+(12) months from the date of initial External Deployment, whichever is
+longer. You should preferably distribute the Source Code of Your
+Externally Deployed Modifications electronically (e.g. download from a
+web site).
+
+2.3 Distribution of Executable Versions. In addition, if You
+Externally Deploy Covered Code (Original Code and/or Modifications) in
+object code, executable form only, You must include a prominent
+notice, in the code itself as well as in related documentation,
+stating that Source Code of the Covered Code is available under the
+terms of this License with information on how and where to obtain such
+Source Code.
+
+2.4 Third Party Rights. You expressly acknowledge and agree that
+although Apple and each Contributor grants the licenses to their
+respective portions of the Covered Code set forth herein, no
+assurances are provided by Apple or any Contributor that the Covered
+Code does not infringe the patent or other intellectual property
+rights of any other entity. Apple and each Contributor disclaim any
+liability to You for claims brought by any other entity based on
+infringement of intellectual property rights or otherwise. As a
+condition to exercising the rights and licenses granted hereunder, You
+hereby assume sole responsibility to secure any other intellectual
+property rights needed, if any. For example, if a third party patent
+license is required to allow You to distribute the Covered Code, it is
+Your responsibility to acquire that license before distributing the
+Covered Code.
+
+3. Your Grants. In consideration of, and as a condition to, the
+licenses granted to You under this License, You hereby grant to any
+person or entity receiving or distributing Covered Code under this
+License a non-exclusive, royalty-free, perpetual, irrevocable license,
+under Your Applicable Patent Rights and other intellectual property
+rights (other than patent) owned or controlled by You, to use,
+reproduce, display, perform, modify, sublicense, distribute and
+Externally Deploy Your Modifications of the same scope and extent as
+Apple's licenses under Sections 2.1 and 2.2 above.
+
+4. Larger Works. You may create a Larger Work by combining Covered
+Code with other code not governed by the terms of this License and
+distribute the Larger Work as a single product. In each such instance,
+You must make sure the requirements of this License are fulfilled for
+the Covered Code or any portion thereof.
+
+5. Limitations on Patent License. Except as expressly stated in
+Section 2, no other patent rights, express or implied, are granted by
+Apple herein. Modifications and/or Larger Works may require additional
+patent licenses from Apple which Apple may grant in its sole
+discretion.
+
+6. Additional Terms. You may choose to offer, and to charge a fee for,
+warranty, support, indemnity or liability obligations and/or other
+rights consistent with the scope of the license granted herein
+("Additional Terms") to one or more recipients of Covered Code.
+However, You may do so only on Your own behalf and as Your sole
+responsibility, and not on behalf of Apple or any Contributor. You
+must obtain the recipient's agreement that any such Additional Terms
+are offered by You alone, and You hereby agree to indemnify, defend
+and hold Apple and every Contributor harmless for any liability
+incurred by or claims asserted against Apple or such Contributor by
+reason of any such Additional Terms.
+
+7. Versions of the License. Apple may publish revised and/or new
+versions of this License from time to time. Each version will be given
+a distinguishing version number. Once Original Code has been published
+under a particular version of this License, You may continue to use it
+under the terms of that version. You may also choose to use such
+Original Code under the terms of any subsequent version of this
+License published by Apple. No one other than Apple has the right to
+modify the terms applicable to Covered Code created under this
+License.
+
+8. NO WARRANTY OR SUPPORT. The Covered Code may contain in whole or in
+part pre-release, untested, or not fully tested works. The Covered
+Code may contain errors that could cause failures or loss of data, and
+may be incomplete or contain inaccuracies. You expressly acknowledge
+and agree that use of the Covered Code, or any portion thereof, is at
+Your sole and entire risk. THE COVERED CODE IS PROVIDED "AS IS" AND
+WITHOUT WARRANTY, UPGRADES OR SUPPORT OF ANY KIND AND APPLE AND
+APPLE'S LICENSOR(S) (COLLECTIVELY REFERRED TO AS "APPLE" FOR THE
+PURPOSES OF SECTIONS 8 AND 9) AND ALL CONTRIBUTORS EXPRESSLY DISCLAIM
+ALL WARRANTIES AND/OR CONDITIONS, EXPRESS OR IMPLIED, INCLUDING, BUT
+NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF
+MERCHANTABILITY, OF SATISFACTORY QUALITY, OF FITNESS FOR A PARTICULAR
+PURPOSE, OF ACCURACY, OF QUIET ENJOYMENT, AND NONINFRINGEMENT OF THIRD
+PARTY RIGHTS. APPLE AND EACH CONTRIBUTOR DOES NOT WARRANT AGAINST
+INTERFERENCE WITH YOUR ENJOYMENT OF THE COVERED CODE, THAT THE
+FUNCTIONS CONTAINED IN THE COVERED CODE WILL MEET YOUR REQUIREMENTS,
+THAT THE OPERATION OF THE COVERED CODE WILL BE UNINTERRUPTED OR
+ERROR-FREE, OR THAT DEFECTS IN THE COVERED CODE WILL BE CORRECTED. NO
+ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE, AN APPLE
+AUTHORIZED REPRESENTATIVE OR ANY CONTRIBUTOR SHALL CREATE A WARRANTY.
+You acknowledge that the Covered Code is not intended for use in the
+operation of nuclear facilities, aircraft navigation, communication
+systems, or air traffic control machines in which case the failure of
+the Covered Code could lead to death, personal injury, or severe
+physical or environmental damage.
+
+9. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO
+EVENT SHALL APPLE OR ANY CONTRIBUTOR BE LIABLE FOR ANY INCIDENTAL,
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING
+TO THIS LICENSE OR YOUR USE OR INABILITY TO USE THE COVERED CODE, OR
+ANY PORTION THEREOF, WHETHER UNDER A THEORY OF CONTRACT, WARRANTY,
+TORT (INCLUDING NEGLIGENCE), PRODUCTS LIABILITY OR OTHERWISE, EVEN IF
+APPLE OR SUCH CONTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES AND NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY
+REMEDY. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OF LIABILITY OF
+INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY
+TO YOU. In no event shall Apple's total liability to You for all
+damages (other than as may be required by applicable law) under this
+License exceed the amount of fifty dollars ($50.00).
+
+10. Trademarks. This License does not grant any rights to use the
+trademarks or trade names "Apple", "Apple Computer", "Mac", "Mac OS",
+"QuickTime", "QuickTime Streaming Server" or any other trademarks,
+service marks, logos or trade names belonging to Apple (collectively
+"Apple Marks") or to any trademark, service mark, logo or trade name
+belonging to any Contributor. You agree not to use any Apple Marks in
+or as part of the name of products derived from the Original Code or
+to endorse or promote products derived from the Original Code other
+than as expressly permitted by and in strict compliance at all times
+with Apple's third party trademark usage guidelines which are posted
+at http://www.apple.com/legal/guidelinesfor3rdparties.html.
+
+11. Ownership. Subject to the licenses granted under this License,
+each Contributor retains all rights, title and interest in and to any
+Modifications made by such Contributor. Apple retains all rights,
+title and interest in and to the Original Code and any Modifications
+made by or on behalf of Apple ("Apple Modifications"), and such Apple
+Modifications will not be automatically subject to this License. Apple
+may, at its sole discretion, choose to license such Apple
+Modifications under this License, or on different terms from those
+contained in this License or may choose not to license them at all.
+
+12. Termination.
+
+12.1 Termination. This License and the rights granted hereunder will
+terminate:
+
+(a) automatically without notice from Apple if You fail to comply with
+any term(s) of this License and fail to cure such breach within 30
+days of becoming aware of such breach;
+
+(b) immediately in the event of the circumstances described in Section
+13.5(b); or
+
+(c) automatically without notice from Apple if You, at any time during
+the term of this License, commence an action for patent infringement
+against Apple; provided that Apple did not first commence
+an action for patent infringement against You in that instance.
+
+12.2 Effect of Termination. Upon termination, You agree to immediately
+stop any further use, reproduction, modification, sublicensing and
+distribution of the Covered Code. All sublicenses to the Covered Code
+which have been properly granted prior to termination shall survive
+any termination of this License. Provisions which, by their nature,
+should remain in effect beyond the termination of this License shall
+survive, including but not limited to Sections 3, 5, 8, 9, 10, 11,
+12.2 and 13. No party will be liable to any other for compensation,
+indemnity or damages of any sort solely as a result of terminating
+this License in accordance with its terms, and termination of this
+License will be without prejudice to any other right or remedy of
+any party.
+
+13. Miscellaneous.
+
+13.1 Government End Users. The Covered Code is a "commercial item" as
+defined in FAR 2.101. Government software and technical data rights in
+the Covered Code include only those rights customarily provided to the
+public as defined in this License. This customary commercial license
+in technical data and software is provided in accordance with FAR
+12.211 (Technical Data) and 12.212 (Computer Software) and, for
+Department of Defense purchases, DFAR 252.227-7015 (Technical Data --
+Commercial Items) and 227.7202-3 (Rights in Commercial Computer
+Software or Computer Software Documentation). Accordingly, all U.S.
+Government End Users acquire Covered Code with only those rights set
+forth herein.
+
+13.2 Relationship of Parties. This License will not be construed as
+creating an agency, partnership, joint venture or any other form of
+legal association between or among You, Apple or any Contributor, and
+You will not represent to the contrary, whether expressly, by
+implication, appearance or otherwise.
+
+13.3 Independent Development. Nothing in this License will impair
+Apple's right to acquire, license, develop, have others develop for
+it, market and/or distribute technology or products that perform the
+same or similar functions as, or otherwise compete with,
+Modifications, Larger Works, technology or products that You may
+develop, produce, market or distribute.
+
+13.4 Waiver; Construction. Failure by Apple or any Contributor to
+enforce any provision of this License will not be deemed a waiver of
+future enforcement of that or any other provision. Any law or
+regulation which provides that the language of a contract shall be
+construed against the drafter will not apply to this License.
+
+13.5 Severability. (a) If for any reason a court of competent
+jurisdiction finds any provision of this License, or portion thereof,
+to be unenforceable, that provision of the License will be enforced to
+the maximum extent permissible so as to effect the economic benefits
+and intent of the parties, and the remainder of this License will
+continue in full force and effect. (b) Notwithstanding the foregoing,
+if applicable law prohibits or restricts You from fully and/or
+specifically complying with Sections 2 and/or 3 or prevents the
+enforceability of either of those Sections, this License will
+immediately terminate and You must immediately discontinue any use of
+the Covered Code and destroy all copies of it that are in your
+possession or control.
+
+13.6 Dispute Resolution. Any litigation or other dispute resolution
+between You and Apple relating to this License shall take place in the
+Northern District of California, and You and Apple hereby consent to
+the personal jurisdiction of, and venue in, the state and federal
+courts within that District with respect to this License. The
+application of the United Nations Convention on Contracts for the
+International Sale of Goods is expressly excluded.
+
+13.7 Entire Agreement; Governing Law. This License constitutes the
+entire agreement between the parties with respect to the subject
+matter hereof. This License shall be governed by the laws of the
+United States and the State of California, except that body of
+California law concerning conflicts of law.
+
+Where You are located in the province of Quebec, Canada, the following
+clause applies: The parties hereby confirm that they have requested
+that this License and all related documents be drafted in English. Les
+parties ont exige que le present contrat et tous les documents
+connexes soient rediges en anglais.
+
+EXHIBIT A.
+
+"Portions Copyright (c) 1999-2003 Apple Computer, Inc. All Rights
+Reserved.
+
+This file contains Original Code and/or Modifications of Original Code
+as defined in and that are subject to the Apple Public Source License
+Version 2.0 (the 'License'). You may not use this file except in
+compliance with the License. Please obtain a copy of the License at
+http://www.opensource.apple.com/apsl/ and read it before using this
+file.
+
+The Original Code and all software distributed under the License are
+distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
+Please see the License for the specific language governing rights and
+limitations under the License."
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/LICENSE b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/LICENSE
new file mode 100644
index 00000000..6b95c1e5
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/LICENSE
@@ -0,0 +1,79 @@
+MIT License
+
+Copyright (c) 2026 owngoal-dev
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+-------------------------------------------------------------------------------
+
+Third-party components
+
+The MIT License above covers the code written for OpenAVB. It does not
+replace the licences of third-party code included in this repository, which
+remain in force for those parts:
+
+Vendored directories (each keeps the upstream licence notice -- a LICENSE or
+COPYRIGHT file, or the notice inside the source -- and records its upstream
+pin in PROVENANCE.md):
+
+- vendor/lzfse BSD-3-Clause Copyright (c) 2015-2016 Apple Inc.
+ (four files modified; see PROVENANCE.md)
+- vendor/tinyusb MIT Copyright (c) 2012-2026 Ha Thach (tinyusb.org)
+- vendor/mbedtls Apache-2.0 Copyright The Mbed TLS Contributors
+ (include/tf-psa-crypto/build_info.h is
+ an OpenAVB-written replacement)
+- vendor/libzbitmap MIT Copyright (c) 2022 Corellium LLC
+- vendor/musl-string MIT Copyright (c) 2005-2020 Rich Felker, et al.
+- vendor/nanoprintf 0BSD OR Unlicense (Charles Nicholson)
+- vendor/zlib-puff zlib Copyright (C) 2002-2013 Mark Adler
+- vendor/freestanding MIT written for OpenAVB
+
+Individual files adapted from third-party sources. Each carries the upstream
+copyright and licence notice and an owngoal-dev modification notice:
+
+Apple Public Source License 2.0 (full text: LICENSES/APSL-2.0.txt):
+- include/avp/image/der/apple_libder.h Apple libDER (Security-57740.60.18)
+- src/image/der/apple_libder_decode.c Apple libDER (Security-57740.60.18)
+- src/image/der/apple_libder_sequence.c Apple libDER (Security-57740.60.18)
+- src/image/compression/apple_lz4.c XNU osfmk/vm/lz4.c
+- src/image/compression/apple_lzss.c XNU libkern/mkext.c (also
+ carries Haruhiko Okumura's
+ LZSS.C notice)
+
+BSD-3-Clause:
+- src/image/compression/apple_compression_v1.c lzfse lzfse_decode_base.c,
+ Copyright (c) 2015-2016 Apple Inc.
+- src/runtime/support/runtime_qsort.c FreeBSD lib/libc/stdlib/qsort.c,
+ Copyright (c) 1992, 1993 The
+ Regents of the University of
+ California
+
+MIT:
+- src/image/img4/img4_decode_compat.c PongoOS src/lib/img4/img4.c,
+ Copyright (C) 2021 checkra1n team
+- src/runtime/support/runtime_string_compat.c musl string routines (see
+ vendor/musl-string/COPYRIGHT)
+
+Data:
+- src/image/img4/img4_trust_rsa4k_anchor.inc the public Apple DDI Secure Boot
+ Root CA - G1 certificate, used
+ as trust-anchor data; not
+ covered by the MIT License above.
+
+OpenAVB is not affiliated with or endorsed by Apple Inc.
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/OpenAVB.bin b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/OpenAVB.bin
new file mode 100644
index 00000000..08a4f977
Binary files /dev/null and b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/OpenAVB.bin differ
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/README.md b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/README.md
new file mode 100644
index 00000000..45618260
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/README.md
@@ -0,0 +1,56 @@
+# OpenAVB
+
+`OpenAVB.bin` is the boot ROM new machines run instead of Apple's
+`AVPBooter.vresearch1.bin`. It is
+[OpenAVB](https://github.com/owngoal-dev/OpenAVB), an open-source AArch64
+boot ROM compatible with AVPBooter, built from source. `StageBundle.sh` copies
+the image and its licences to `VPhone.bundle/Contents/Resources/OpenAVB/`, and `vm new` copies
+the image into each new machine folder.
+
+| | |
+| --- | --- |
+| Source | `https://github.com/owngoal-dev/OpenAVB` |
+| Commit | `115169e61a206a967bb2299e5c3145888741bba3` |
+| Patches | `patches/*.patch`, applied in order (one) |
+| Target | `make build/OpenAVB.bin` |
+| Toolchain | Homebrew LLVM 23.1.3 (`clang`, `llvm-objcopy`), Homebrew LLD 23.1.3 |
+| SHA-256 | `d63ea62226d4383288a5a36c440aa2d1df8cccabe0118cac0ab2e0c23ba4c3d2` |
+| Size | 460057 bytes |
+
+The image is checked in rather than built by the `VPhone` scheme, so building
+the bundle needs no cross toolchain. To move to another commit, or to check
+that this file is what the commit builds, run
+`VPhoneExecutable/VPhoneVirtualization/Build/UpdateOpenAVB.sh` (see its
+header). It clones and builds outside the repository and needs
+`brew install llvm lld`.
+
+## Patches
+
+One, not upstream yet:
+`0001-Wait-for-the-SEP-before-the-first-request-after-a-wa.patch`. After a
+guest reboot the SEP restarts together with the ROM, and a request sent
+before it is up was dropped, so every guest reboot hung. The ROM now waits
+for the SEP's first message before sending.
+
+OpenAVB's first commit, `54b67bf`, did not run under
+Virtualization.framework. Five changes found on live machines made it boot and
+restore, and upstream took them in
+[owngoal-dev/OpenAVB#1](https://github.com/owngoal-dev/OpenAVB/pull/1). Upstream `main`
+(`115169e`) carries them and, without the patch above, builds the same image the patched
+`54b67bf` did. `Research/Firmware/openavb_boot_rom.md` has the evidence for
+each change.
+
+If vphone needs a change upstream has not taken yet, put it in `patches/` as a
+`git format-patch` file. `UpdateOpenAVB.sh` applies patches in order and
+refuses one that no longer applies. Delete a patch once the pin moves past it.
+
+## Licence
+
+`LICENSE` is OpenAVB's licence as published at that commit: MIT for OpenAVB's
+own code, with the third-party notices it lists. A few files built into the
+image are APSL-2.0 (`APSL-2.0.txt`); their modified source is the public
+repository above.
+
+What the ROM expects from the host (the patch store, the stage-0 image
+identity uploaded before iBSS, LZFSE payloads) is described in
+`Research/Firmware/openavb_boot_rom.md`.
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/patches/0001-Wait-for-the-SEP-before-the-first-request-after-a-wa.patch b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/patches/0001-Wait-for-the-SEP-before-the-first-request-after-a-wa.patch
new file mode 100644
index 00000000..14b0fdb9
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/patches/0001-Wait-for-the-SEP-before-the-first-request-after-a-wa.patch
@@ -0,0 +1,88 @@
+From 20ae8738b77e53cf49a3e1cba195cab449368274 Mon Sep 17 00:00:00 2001
+From: Jacky <[email protected]>
+Date: Sun, 18 Oct 2026 19:23:41 +0800
+Subject: [PATCH] Wait for the SEP before the first request after a warm reset
+
+On a guest reboot (PSCI SYSTEM_RESET) Virtualization.framework restarts
+the SEP together with the AP. OpenAVB got to the mailbox first, took it,
+and sent the bootstrap request at once. The mailbox dropped it
+("coprocessor.mailbox: Failed to send a message"), the SEP's own setup
+then cleared the AP's ownership, and each side waited for the other:
+the console filled with "SEP RX timeout" and the guest never came back.
+
+After a cold start the SEP is up long before the ROM gets there and its
+first message is already waiting. So after taking the slot, wait for
+that message, taking the slot back if the SEP's restart drops it, and
+send only then. Each ownership request also sets the enable bit at
++0x10 first, as Apple's ROM and the SEP ROM do.
+---
+ src/protocol/sep/sep.c | 35 ++++++++++++++++++++++++++++++++++-
+ 1 file changed, 34 insertions(+), 1 deletion(-)
+
+diff --git a/src/protocol/sep/sep.c b/src/protocol/sep/sep.c
+index 77c9cbc..6dba128 100644
+--- a/src/protocol/sep/sep.c
++++ b/src/protocol/sep/sep.c
+@@ -15,6 +15,7 @@ enum {
+ SEP_TIMEOUT_RECOVERY_LIMIT = 5,
+ SEP_TIMEOUT_POLL_INTERVAL_US = 100,
+ SEP_FINALIZE_ROUNDS = 8,
++ SEP_READY_TIMEOUT_US = 5000000,
+ };
+
+ static void early_console_write(const char *message) {
+@@ -29,11 +30,20 @@ static uint32_t timeout_recovery_count;
+ static bool preflight_wait_complete;
+ static uint8_t last_protocol_opcode;
+
+-void sep_initialize(void) {
++/*
++ * Request the slot until it reads as owned, setting the enable bit at +0x10
++ * before each request as Apple's ROM does, and as the SEP ROM does on its
++ * side.
++ */
++static void sep_acquire(void) {
+ uint32_t active_control = mmio_read32(SEP_MAILBOX_BASE + 0x14);
+ while ((active_control & SEP_MAILBOX_OWNED) == 0) {
+ /* The ownership register acknowledges writes, so an owned slot is
+ * observed and preserved without issuing another ownership request. */
++ mmio_write32(
++ SEP_MAILBOX_BASE + 0x10,
++ mmio_read32(SEP_MAILBOX_BASE + 0x10) | 1
++ );
+ mmio_write32(
+ SEP_MAILBOX_BASE + 0x14,
+ active_control | SEP_MAILBOX_OWNED
+@@ -47,6 +57,29 @@ void sep_initialize(void) {
+ avp_memory_barrier();
+ }
+
++void sep_initialize(void) {
++ sep_acquire();
++ /*
++ * Do not send before the SEP has announced itself. After a cold start it
++ * is up long before this ROM gets here, and its first message is already
++ * waiting. After a warm reset (a guest reboot) it restarts together with
++ * this ROM and is slower: a request sent now is dropped by the mailbox,
++ * and the SEP's own setup then clears the ownership taken above, so both
++ * sides wait for each other. Wait for its message instead, taking the
++ * slot back when its restart drops it.
++ */
++ const uint64_t start = avp_time_counter();
++ const uint64_t limit = avp_time_microseconds_to_ticks(SEP_READY_TIMEOUT_US);
++ while ((mmio_read32(SEP_MAILBOX_BASE + 0x1c) & 0x00020000) != 0) {
++ if ((mmio_read32(SEP_MAILBOX_BASE + 0x14) & SEP_MAILBOX_OWNED) == 0) {
++ sep_acquire();
++ }
++ if (avp_time_has_elapsed(start, limit)) {
++ break;
++ }
++ }
++}
++
+ static int32_t sep_receive(
+ uint32_t timeout_microseconds,
+ SEPMailboxMessage *message
+--
+2.56.0
+
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
index 96d8597e..e363caf6 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
@@ -29,8 +29,9 @@ public enum VPhoneBundleOperations {
private static let frameworkResources = URL(fileURLWithPath:
"/System/Library/Frameworks/Virtualization.framework/Versions/A/Resources")
+ /// The boot ROM new machines get: this bundle's OpenAVB.
public static func defaultROMSource() -> URL {
- frameworkResources.appendingPathComponent("AVPBooter.vresearch1.bin")
+ VPhoneBootROM.openAVBSource()
}
public static func defaultSEPROMSource() -> URL {
@@ -78,8 +79,10 @@ public enum VPhoneBundleOperations {
// SEP storage: 512 KB of initialized zero bytes.
try Data(count: 512 * 1024).write(to: dir.appendingPathComponent("SEPStorage"))
- // ROMs.
- try fm.copyItem(at: spec.romSource, to: dir.appendingPathComponent("AVPBooter.vresearch1.bin"))
+ // ROMs. The boot ROM keeps the name of its kind, so `fw patch`
+ // finds an Apple ROM to patch and leaves OpenAVB alone.
+ let romName = try bootROMKind(of: spec.romSource).fileName
+ try fm.copyItem(at: spec.romSource, to: dir.appendingPathComponent(romName))
try fm.copyItem(at: spec.sepromSource, to: dir.appendingPathComponent("AVPSEPBooter.vresearch1.bin"))
// Manifest.
@@ -87,7 +90,7 @@ public enum VPhoneBundleOperations {
cpuCount: spec.cpuCount,
memorySize: spec.memoryMB * 1024 * 1024,
networkConfig: spec.networkConfig,
- romImages: .init(avpBooter: "AVPBooter.vresearch1.bin",
+ romImages: .init(avpBooter: romName,
avpSEPBooter: "AVPSEPBooter.vresearch1.bin"),
)
try manifest.write(to: dir.appendingPathComponent("config.plist"))
@@ -102,6 +105,61 @@ public enum VPhoneBundleOperations {
}
}
+ // MARK: - Boot ROM
+
+ /// The kind of the ROM at `url`, refusing a file that cannot be read.
+ static func bootROMKind(of url: URL) throws -> VPhoneBootROM {
+ guard let kind = VPhoneBootROM.kind(at: url) else {
+ throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path])
+ }
+ return kind
+ }
+
+ /// Makes `source` the machine's boot ROM: copies it into the folder under
+ /// the name of its kind, unless it is already that file, and points
+ /// `romImages.avpBooter` at it. vphone-vm reads the ROM when the machine
+ /// starts, so a running machine takes it from its next start.
+ ///
+ /// The ROM it replaces stays in the folder. An Apple ROM there carries the
+ /// digest patch `fw patch` applied, which a fresh copy from the framework
+ /// would not, so going back to it needs only this call again.
+ ///
+ /// Only normal boot reads the ROM after a restore, and both ROMs load the
+ /// same patched LLB, so a restored machine can change ROM without another
+ /// restore. A restore through OpenAVB needs a bundle that uploads the iBSS
+ /// identity, which bundles from before OpenAVB do not.
+ @discardableResult
+ public static func installBootROM(from source: URL, in bundle: VPhoneBundle) throws -> VPhoneBundle {
+ let kind = try bootROMKind(of: source)
+ let fm = FileManager.default
+ let destination = bundle.url.appendingPathComponent(kind.fileName)
+ if source.standardizedFileURL.path != destination.standardizedFileURL.path {
+ let staged = bundle.url.appendingPathComponent(".\(kind.fileName).\(UUID().uuidString)")
+ try fm.copyItem(at: source, to: staged)
+ do {
+ if fm.fileExists(atPath: destination.path) {
+ _ = try fm.replaceItemAt(destination, withItemAt: staged)
+ } else {
+ try fm.moveItem(at: staged, to: destination)
+ }
+ } catch {
+ try? fm.removeItem(at: staged)
+ throw error
+ }
+ }
+ try VPhoneHostFilePermissions.makeAccessible(at: destination)
+
+ let images = VPhoneVirtualMachineManifest.ROMImages(
+ avpBooter: kind.fileName,
+ avpSEPBooter: bundle.manifest.romImages?.avpSEPBooter
+ ?? VPhoneVirtualMachineManifest.ROMImages.default.avpSEPBooter,
+ )
+ let updated = bundle.manifest.updating(romImages: images)
+ try updated.write(to: bundle.configURL)
+ try VPhoneHostFilePermissions.makeAccessible(at: bundle.configURL)
+ return VPhoneBundle(url: bundle.url, manifest: updated)
+ }
+
// MARK: - Config editing
public static func updateConfig(
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift
index 89546191..555f2daf 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift
@@ -26,6 +26,10 @@ public struct VPhoneBundleReport: Codable, Equatable, Sendable {
/// Whether vphone-vm forwards the Mac's location to the guest. Always
/// present, like `unlocksAtStartup`.
public let syncsHostLocation: Bool
+ /// The boot ROM the machine starts from: `openavb` or `apple`. Nil when the
+ /// manifest names none (the framework's built-in ROM) or it cannot be
+ /// read. Added with OpenAVB.
+ public let bootROM: String?
public init(bundle: VPhoneBundle) {
name = bundle.name
@@ -43,5 +47,6 @@ public struct VPhoneBundleReport: Codable, Equatable, Sendable {
let library = VPhoneLibrary(root: bundle.url.deletingLastPathComponent())
templateMatch = source.map { VPhoneMachineTemplates.match(of: $0, in: library) }
syncsHostLocation = bundle.manifest.sharesHostLocation
+ bootROM = VPhoneBootROM.kind(ofMachineAt: bundle.url)?.rawValue
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneBootROM.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneBootROM.swift
new file mode 100644
index 00000000..56a01347
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneBootROM.swift
@@ -0,0 +1,86 @@
+import Foundation
+
+// MARK: - VPhoneBootROM
+
+/// The boot ROM a machine starts from: the file `romImages.avpBooter` names.
+///
+/// New machines run OpenAVB, an open-source ROM compatible with AVPBooter that
+/// ships in `VPhone.bundle/Contents/Resources/OpenAVB/`. Machines created
+/// before it keep Apple's `AVPBooter.vresearch1.bin`, which `fw patch` patches
+/// to skip the image digest check. OpenAVB has no such check, so it needs no
+/// patch; instead, before iBSS goes over DFU, the restore uploads the image's
+/// sizes and digests (see `Research/Firmware/openavb_boot_rom.md`).
+public enum VPhoneBootROM: String, CaseIterable, Sendable {
+ case openAVB = "openavb"
+ case apple
+
+ /// The file name a machine folder keeps this ROM under.
+ public var fileName: String {
+ switch self {
+ case .openAVB: "OpenAVB.bin"
+ case .apple: "AVPBooter.vresearch1.bin"
+ }
+ }
+
+ public var displayName: String {
+ switch self {
+ case .openAVB: "OpenAVB"
+ case .apple: "AVPBooter"
+ }
+ }
+
+ // MARK: - Recognition
+
+ /// The prefix of every OpenAVB console line. OpenAVB keeps it from the
+ /// project's former name so the image and host tooling stay unchanged,
+ /// and Apple's ROM does not contain it.
+ static let openAVBMarker = Data("OpenBootROM:".utf8)
+
+ /// Which ROM these bytes are. Anything that is not OpenAVB is treated as
+ /// Apple's, which is what every ROM was before OpenAVB.
+ public static func kind(of image: Data) -> VPhoneBootROM {
+ image.range(of: openAVBMarker) != nil ? .openAVB : .apple
+ }
+
+ /// The ROM at `url`, or nil when it cannot be read.
+ public static func kind(at url: URL) -> VPhoneBootROM? {
+ guard let image = try? Data(contentsOf: url, options: .mappedIfSafe) else { return nil }
+ return kind(of: image)
+ }
+
+ /// The ROM a machine folder boots: what its manifest names, or nil when
+ /// the manifest names none (vphone-vm then uses the framework's built-in
+ /// ROM) or the file cannot be read.
+ public static func kind(ofMachineAt url: URL) -> VPhoneBootROM? {
+ guard let manifest = try? VPhoneVirtualMachineManifest.load(from: url.appendingPathComponent("config.plist")),
+ let name = manifest.romImages?.avpBooter,
+ VPhoneVirtualMachineManifest.isPlainFileName(name)
+ else { return nil }
+ return kind(at: url.appendingPathComponent(name))
+ }
+
+ // MARK: - Sources
+
+ /// Apple's ROM, from Virtualization.framework.
+ public static let appleSource = URL(fileURLWithPath:
+ "/System/Library/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vresearch1.bin")
+
+ /// The OpenAVB image in this bundle's resources. A source build outside the
+ /// bundle reads the checked-in copy.
+ public static func openAVBSource(resources: VPhoneResources = .resolve()) -> URL {
+ let bundled = resources.base.appendingPathComponent("OpenAVB/OpenAVB.bin")
+ if FileManager.default.fileExists(atPath: bundled.path) {
+ return bundled
+ }
+ return resources.base.appendingPathComponent(
+ "VPhoneExecutable/VPhoneVirtualization/Resources/OpenAVB/OpenAVB.bin")
+ }
+
+ /// Where `vm new` copies this ROM from.
+ public func source(resources: VPhoneResources = .resolve()) -> URL {
+ switch self {
+ case .openAVB: Self.openAVBSource(resources: resources)
+ case .apple: Self.appleSource
+ }
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
index 9f835c45..e4ca80cb 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
@@ -567,6 +567,27 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
)
}
+ /// This manifest with other ROM file names.
+ public func updating(romImages: ROMImages) -> VPhoneVirtualMachineManifest {
+ VPhoneVirtualMachineManifest(
+ platformType: platformType,
+ platformFusing: platformFusing,
+ machineIdentifier: machineIdentifier,
+ cpuCount: cpuCount,
+ memorySize: memorySize,
+ screenConfig: screenConfig,
+ networkConfig: networkConfig,
+ diskImage: diskImage,
+ nvramStorage: nvramStorage,
+ romImages: romImages,
+ sepStorage: sepStorage,
+ guestProductType: guestProductType,
+ hardwareKeyboardEnabled: hardwareKeyboardEnabled,
+ unlocksAtStartup: unlocksAtStartup,
+ syncsHostLocation: syncsHostLocation,
+ )
+ }
+
/// This manifest for a guest running `device`'s OS: its product type and
/// its display. An iPhone17,3 guest records no product type, so its
/// configuration stays readable by bundles that predate iPad guests.
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/BootROMTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/BootROMTests.swift
new file mode 100644
index 00000000..d0c2ce60
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/BootROMTests.swift
@@ -0,0 +1,122 @@
+import Foundation
+import Testing
+@testable import VPhoneCoreKit
+
+/// Which boot ROM a machine starts from, and how it gets there.
+///
+/// New machines copy OpenAVB and keep it as `OpenAVB.bin`; an Apple ROM keeps
+/// `AVPBooter.vresearch1.bin`, the name `fw patch` looks for. Changing ROM only
+/// repoints `romImages.avpBooter` and leaves the other ROM in the folder.
+struct BootROMTests {
+ // MARK: - Fixtures
+
+ private func makeRoot() throws -> URL {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ return dir
+ }
+
+ /// A ROM image of `kind`: OpenAVB's carries its console prefix.
+ private func rom(_ kind: VPhoneBootROM, in dir: URL, tag: UInt8 = 0) throws -> URL {
+ var bytes = Data([0x1F, 0x20, 0x03, 0xD5, tag])
+ if kind == .openAVB {
+ bytes.append(Data("....OpenBootROM: SEP bootstrap complete\n".utf8))
+ }
+ let url = dir.appendingPathComponent(UUID().uuidString + ".bin")
+ try bytes.write(to: url)
+ return url
+ }
+
+ private func newMachine(rom: URL, in root: URL) throws -> VPhoneBundle {
+ let seprom = root.appendingPathComponent("seprom.bin")
+ try Data([0x01]).write(to: seprom)
+ return try VPhoneBundleOperations.create(
+ .init(name: "phone", cpuCount: 2, memoryMB: 2048, diskSizeGB: 1, romSource: rom, sepromSource: seprom),
+ in: VPhoneLibrary(root: root.appendingPathComponent("library")),
+ )
+ }
+
+ // MARK: - Recognition
+
+ @Test func `OpenAVB is recognised by its console prefix and anything else is Apple's`() throws {
+ #expect(VPhoneBootROM.kind(of: Data("xxOpenBootROM: iLLB container accepted\n".utf8)) == .openAVB)
+ #expect(VPhoneBootROM.kind(of: Data("iBoot for vresearch101".utf8)) == .apple)
+ #expect(VPhoneBootROM.kind(of: Data()) == .apple)
+ #expect(VPhoneBootROM.kind(at: URL(fileURLWithPath: "/nonexistent/rom.bin")) == nil)
+ }
+
+ @Test func `the checked-in OpenAVB image is recognised as OpenAVB`() throws {
+ let repository = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent()
+ let image = VPhoneBootROM.openAVBSource(resources: VPhoneResources(base: repository))
+ #expect(image.path.hasSuffix("Resources/OpenAVB/OpenAVB.bin"))
+ #expect(VPhoneBootROM.kind(at: image) == .openAVB)
+ }
+
+ // MARK: - vm new
+
+ @Test func `a new machine keeps each ROM under the name of its kind`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let openAVB = try newMachine(rom: rom(.openAVB, in: root), in: root)
+ #expect(openAVB.manifest.romImages?.avpBooter == "OpenAVB.bin")
+ #expect(FileManager.default.fileExists(atPath: openAVB.url.appendingPathComponent("OpenAVB.bin").path))
+ #expect(!FileManager.default.fileExists(atPath: openAVB.url.appendingPathComponent("AVPBooter.vresearch1.bin").path))
+ #expect(VPhoneBootROM.kind(ofMachineAt: openAVB.url) == .openAVB)
+ #expect(VPhoneBundleReport(bundle: openAVB).bootROM == "openavb")
+
+ let other = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: other) }
+ let apple = try newMachine(rom: rom(.apple, in: other), in: other)
+ #expect(apple.manifest.romImages?.avpBooter == "AVPBooter.vresearch1.bin")
+ #expect(VPhoneBootROM.kind(ofMachineAt: apple.url) == .apple)
+ #expect(VPhoneBundleReport(bundle: apple).bootROM == "apple")
+ }
+
+ @Test func `a new machine refuses a ROM it cannot read`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ #expect(throws: (any Error).self) {
+ try newMachine(rom: root.appendingPathComponent("missing.bin"), in: root)
+ }
+ #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("library/phone").path))
+ }
+
+ // MARK: - Changing ROM
+
+ @Test func `changing ROM repoints the manifest and keeps the other ROM`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let apple = try newMachine(rom: rom(.apple, in: root, tag: 7), in: root)
+ let patchedApple = try Data(contentsOf: apple.url.appendingPathComponent("AVPBooter.vresearch1.bin"))
+
+ let switched = try VPhoneBundleOperations.installBootROM(from: rom(.openAVB, in: root), in: apple)
+ #expect(switched.manifest.romImages?.avpBooter == "OpenAVB.bin")
+ #expect(switched.manifest.romImages?.avpSEPBooter == "AVPSEPBooter.vresearch1.bin")
+ #expect(try VPhoneVirtualMachineManifest.load(from: switched.configURL).romImages?.avpBooter == "OpenAVB.bin")
+ #expect(VPhoneBootROM.kind(ofMachineAt: switched.url) == .openAVB)
+ // The Apple ROM, with whatever fw patch did to it, is still there.
+ #expect(try Data(contentsOf: apple.url.appendingPathComponent("AVPBooter.vresearch1.bin")) == patchedApple)
+
+ // Back to it: the folder's own copy, not a new one.
+ let kept = switched.url.appendingPathComponent("AVPBooter.vresearch1.bin")
+ let back = try VPhoneBundleOperations.installBootROM(from: kept, in: switched)
+ #expect(back.manifest.romImages?.avpBooter == "AVPBooter.vresearch1.bin")
+ #expect(try Data(contentsOf: kept) == patchedApple)
+ #expect(VPhoneBootROM.kind(ofMachineAt: back.url) == .apple)
+ }
+
+ @Test func `installing OpenAVB again replaces the copy in the folder`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let machine = try newMachine(rom: rom(.openAVB, in: root, tag: 1), in: root)
+ let newer = try rom(.openAVB, in: root, tag: 2)
+
+ try VPhoneBundleOperations.installBootROM(from: newer, in: machine)
+ #expect(try Data(contentsOf: machine.url.appendingPathComponent("OpenAVB.bin")) == Data(contentsOf: newer))
+ let leftovers = try FileManager.default.contentsOfDirectory(atPath: machine.url.path).filter { $0.hasPrefix(".") }
+ #expect(leftovers.isEmpty)
+ }
+}