People have dreamed of running macOS on iPad for more than a decade. Today, that dream comes true. With Virtual Mac, iPad finally breaks free from iPadOS, enabling pro apps like Xcode, Terminal, Final Cut Pro, Logic Pro, and Pixelmator Pro to run directly on device. Requires iPad Pro (M1, M2) or iPad Air (M1) running iPadOS 14 up to 16.3.1.
Shell
Initial release
nfzerox42648738cb7e
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..591acc7--- /dev/null+++ b/.gitignore@@ -0,0 +1,24 @@+.DS_Store+.env+.venv/+__pycache__/+build/+artifacts/+DerivedData/++# Apple restore/runtime artifacts and VM state never belong in Git.+*.ipsw+*.deb+*.dmg+*.img+*.raw+*.qcow2+*.utm+*.xip+VM.bundle/++# Generated Apple binaries, signatures, diagnostics, and local manifests.+payload/+logs/+*.dSYM/+*.ipsdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..1a1d7a5--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 nfzerox++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.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..1c30206--- /dev/null+++ b/README.md@@ -0,0 +1,65 @@+# Virtual Mac on iPad++People have dreamed of running macOS on iPad for [more](https://www.macstories.net/stories/macpad-how-i-created-the-hybrid-mac-ipad-laptop-and-tablet-that-apple-wont-make/) [than](https://github.com/khanhduytran0/MacWSBootingGuide) [a](https://khronokernel.com/apple/silicon/2021/01/17/QEMU-AS.html) [decade](https://worthdoingbadly.com/macappsios/). Today, that dream comes true. With Virtual Mac, iPad finally breaks free from iPadOS, enabling pro apps like Xcode and Terminal to run directly on device. Requires iPad Pro (M1, M2) or iPad Air (M1) running iPadOS 16 up to 16.3.1.++++Virtual Mac on iPad is a community project and is not affiliated with Dopamine, UTM, VirtualBuddy, or Apple. Contributions are welcome!++## Installation++1. [Jailbreak an iPad Pro (M1, M2) or iPad Air (M1) running iPadOS 16 up to 16.3.1](https://ios.cfw.guide/installing-dopamine/). If jailbreak fails, switch to a different exploit in Dopamine settings.+2. Add the [https://nfzerox.github.io/cydia/](https://nfzerox.github.io/cydia/) repository in Sileo, then search and install Virtual Mac.++## Frequently Asked Questions++### Which iPad and iPadOS versions does this require?++Virtual Mac on iPad requires an iPad Pro (M1, M2) or iPad Air (M1) running iPadOS 16 up to 16.3.1. iPad Pro models with 1 TB or 2 TB of storage have 16 GB of RAM and provide the best performance and experience.++### Which versions of macOS does this support?++Virtual Mac on iPad is compatible with macOS 12 Monterey up to macOS 27 Golden Gate. macOS 13 Ventura up to macOS 15 Sequoia are the recommended versions to install. Because signing into iCloud or Apple Account is not supported, choose Set Up Later. Support for macOS 26 Tahoe and macOS 27 Golden Gate is experimental, and you may encounter visual or performance issues.++### Do I Need a Magic Keyboard?++Magic Keyboard is not required, but is recommended for the best experience. If you don't have a Magic Keyboard, you can use the touchscreen and virtual keyboard instead:++- To select a menu item, tap and drag.+- To open a document or folder, tap it, then press Command + O using the virtual keyboard.+- To make scrolling easier, go to System Settings > Appearance > Show Scroll Bars and set it to Always.+- To access the virtual keyboard, tap the keyboard icon. If the virtual keyboard gets in the way, press and hold the bottom-right icon to switch to Floating mode.+- If the HUD gets in the way, move it to a different corner or hide it from the More menu. To show it again, press and hold the Virtual Mac icon on the iPad Home Screen, then tap Show Virtual Mac Controls.+- To automatically start up your virtual Mac, enable System Settings > Users & Groups > Automatically log in, and set System Settings > Lock Screen to Never. Then in Virtual Mac's in app Settings, change Start on Launch from Show Library to the name of your virtual Mac. To show library again, press and hold the Virtual Mac icon on the iPad Home Screen, then tap Show Library.++### Is it possible to support additional versions of iPadOS?++Supporting iPadOS 16.4 or later presents additional challenges because [Hypervisor support was removed from the iPadOS XNU kernel](https://x.com/UTMapp/status/1708907045314035986). Adding support for iPadOS 15 should be relatively straightforward. Contributions toward either goal are welcome!++### What kind of performance does Virtual Mac on iPad offer?++Virtual Mac on iPad uses hardware CPU virtualization and supports graphics acceleration, providing excellent performance for everyday tasks. Because it uses an extracted and modified version of Apple's macOS virtualization stack, it provides roughly the same class of CPU and GPU performance as VirtualBuddy or UTM virtualizing macOS on an M1 or M2 Mac.++### What if I encounter crashes, bugs, or other issues?++[Open a GitHub issue](https://github.com/nfzerox/VirtualMacOniPad/issues) when you encounter a crash, bug, or other problem. Include clear reproduction steps, a screenshot or screen recording, and the corresponding crash log from Settings > Privacy & Security > Analytics & Improvements > Analytics Data.++If you have access to Codex or Claude Code, you can also point it to this repository and ask it to diagnose and fix the issue. If you find a solution, please update the issue or open a pull request. Contributions are welcome!++## Technical Overview++Creating Virtual Mac on iPad begins with extracting Hypervisor, Virtualization, ParavirtualizedGraphics, and supporting frameworks from macOS. Because dyld shared cache creation is a one way optimization process, extractions are lossy and can't be loaded directly.++To fix this, [`uncache.py`](VirtualMac/vz/uncache.py) makes these extracted arm64e libraries loadable. It walks the cache's slide information, separates in image rebases from cross image binds, resolves their symbols and source images, lays out the Mach-O segments again, and emits new chained pointer fixups while preserving pointer authentication metadata.++The pipeline then rebuilds GOT and authenticated GOT slots, rewrites cross segment PC relative references, repairs Objective-C selectors, protocols, relative method lists, and exports, adds a new chained fixups load command, [restamps the platform to iOS](VirtualMac/vz/stamp_ios.py), and [shims](VirtualMac/vz/host/NSViewShim.m) [many](VirtualMac/vz/host/metalshim.m) [missing](VirtualMac/vz/host/vmmhook.m) [API](VirtualMac/vz/host/vzxpchook.m) expected by these frameworks.++To install macOS into the virtual machine, macOS normally connects to the virtual machine's DFU device through the AppleUSBUserHCI kernel service, which is absent from iPadOS. To bridge this gap, [`installation_usb_shim.m`](VirtualMac/vz/host/installation_usb_shim.m) reconstructs its controller path in userspace and forwards virtual USB endpoint traffic to the matching MobileDevice and usbmuxd components.++## Credits++This project would not be possible without years of prior research by talented developers. The culmination of the following community projects, combined with recent advances in agentic coding, made Virtual Mac on iPad possible:++[dsce](https://github.com/moraea/dsce) proved that loadable x86_64 framework libraries could be extracted from the dyld shared cache. [DyldExtractor](https://github.com/arandomdev/dyldextractor) formed the basis of our [first ever loadable arm64e framework extractor](VirtualMac/vz/uncache.py). [MacWSBootingGuide](https://github.com/khanhduytran0/MacWSBootingGuide) and [iOS-run-macOS-executables-tools](https://worthdoingbadly.com/macappsios/) proved that macOS system frameworks could be restamped and patched to work on iPadOS.++[HvDecompile](https://worthdoingbadly.com/hv/) and [UTM](https://github.com/utmapp/UTM) laid the groundwork for running Windows and Linux VMs with full Hypervisor performance on iPad, while [reims-vgpu](https://github.com/steelbrain/reims-vgpu) proved that accelerated macOS guests on a foreign host were possible with paravirtualized graphics acceleration. [ipsw](https://github.com/blacktop/ipsw) provides essential firmware and dyld shared cache analysis tools, and [VirtualBuddy](https://github.com/insidegui/VirtualBuddy) provides an invaluable reference for Apple's macOS virtualization and restore APIs.diff --git a/VirtualMac/.env.example b/VirtualMac/.env.examplenew file mode 100644index 0000000..74f6db8--- /dev/null+++ b/VirtualMac/.env.example@@ -0,0 +1,25 @@+# Copy to .env and fill only values needed by the command being run. The+# root setup.sh wizard normally makes this file unnecessary. .env is ignored.++VZ_BUILD_ROOT=+VZ_DOWNLOAD_ROOT=+VZ_MACOS_IPSW=+VZ_IPADOS_IPSW=+VZ_DEVICE_SUPPORT_DMG=+VZ_XCODE_PATH=++# Optional matching-Mac oracle configuration (not used by setup.sh).+VZ_REAL_MAC_HOST=+VZ_REAL_MAC_PORT=22+VZ_REAL_MAC_USER=+VZ_REAL_MAC_PASSWORD=++# Optional USB deployment configuration.+VZ_IPAD_UDID=+VZ_IPAD_PORT=2221+VZ_IPAD_PASSWORD=++# Optional guest diagnostic configuration.+VZ_GUEST_HOST=+VZ_GUEST_USER=+VZ_GUEST_PASSWORD=diff --git a/VirtualMac/Brewfile b/VirtualMac/Brewfilenew file mode 100644index 0000000..370f28d--- /dev/null+++ b/VirtualMac/Brewfile@@ -0,0 +1,11 @@+tap "hudochenkov/sshpass"++brew "aria2"+brew "dpkg"+brew "gnu-tar"+brew "go"+brew "ldid"+brew "libimobiledevice"+brew "python"+brew "rsync"+brew "hudochenkov/sshpass/sshpass"diff --git a/VirtualMac/assets/VirtualMac.png b/VirtualMac/assets/VirtualMac.pngnew file mode 100644index 0000000..a35934bBinary files /dev/null and b/VirtualMac/assets/VirtualMac.png differdiff --git a/VirtualMac/assets/wallpapers/golden-gate.jpg b/VirtualMac/assets/wallpapers/golden-gate.jpgnew file mode 100644index 0000000..055145dBinary files /dev/null and b/VirtualMac/assets/wallpapers/golden-gate.jpg differdiff --git a/VirtualMac/assets/wallpapers/monterey.jpg b/VirtualMac/assets/wallpapers/monterey.jpgnew file mode 100644index 0000000..c90a149Binary files /dev/null and b/VirtualMac/assets/wallpapers/monterey.jpg differdiff --git a/VirtualMac/assets/wallpapers/new.png b/VirtualMac/assets/wallpapers/new.pngnew file mode 100644index 0000000..360b101Binary files /dev/null and b/VirtualMac/assets/wallpapers/new.png differdiff --git a/VirtualMac/assets/wallpapers/sequoia.jpg b/VirtualMac/assets/wallpapers/sequoia.jpgnew file mode 100644index 0000000..cf7a92bBinary files /dev/null and b/VirtualMac/assets/wallpapers/sequoia.jpg differdiff --git a/VirtualMac/assets/wallpapers/sonoma.jpg b/VirtualMac/assets/wallpapers/sonoma.jpgnew file mode 100644index 0000000..b05fbb7Binary files /dev/null and b/VirtualMac/assets/wallpapers/sonoma.jpg differdiff --git a/VirtualMac/assets/wallpapers/tahoe.jpg b/VirtualMac/assets/wallpapers/tahoe.jpgnew file mode 100644index 0000000..d26839dBinary files /dev/null and b/VirtualMac/assets/wallpapers/tahoe.jpg differdiff --git a/VirtualMac/assets/wallpapers/tiger.jpg b/VirtualMac/assets/wallpapers/tiger.jpgnew file mode 100644index 0000000..6747d86Binary files /dev/null and b/VirtualMac/assets/wallpapers/tiger.jpg differdiff --git a/VirtualMac/assets/wallpapers/ventura.jpg b/VirtualMac/assets/wallpapers/ventura.jpgnew file mode 100644index 0000000..beb860bBinary files /dev/null and b/VirtualMac/assets/wallpapers/ventura.jpg differdiff --git a/VirtualMac/packaging/DEBIAN/control b/VirtualMac/packaging/DEBIAN/controlnew file mode 100644index 0000000..9e92e41--- /dev/null+++ b/VirtualMac/packaging/DEBIAN/control@@ -0,0 +1,15 @@+Package: com.mac.virtual+Name: Virtual Mac+Version: @VERSION@+Architecture: iphoneos-arm64+Description: People have dreamed of running macOS on iPad for more than a decade.+ Today, that dream comes true. With Virtual Mac, iPad finally breaks free from+ iPadOS, enabling pro apps like Xcode and Terminal to run directly on device.+ Requires iPad Pro (M1, M2) or iPad Air (M1) running iPadOS 16 up to 16.3.1.+Maintainer: Virtual Mac+Author: Virtual Mac+Section: Utilities+Priority: optional+Installed-Size: @INSTALLED_SIZE@+Depends: firmware (>= 16.0), firmware (<< 16.4), dopamine-basebin-link, ellekit+Tag: role::enduserdiff --git a/VirtualMac/packaging/DEBIAN/postinst b/VirtualMac/packaging/DEBIAN/postinstnew file mode 100755index 0000000..0318c71--- /dev/null+++ b/VirtualMac/packaging/DEBIAN/postinst@@ -0,0 +1,59 @@+#!/var/jb/bin/sh++set -eu+export PATH=/var/jb/usr/bin:/var/jb/usr/sbin:/var/jb/bin:/var/jb/sbin:/usr/bin:/bin:/usr/sbin:/sbin++runtime=/var/root/VirtualMac+app=/var/jb/Applications/VirtualMac.app+library=/var/mobile/Media/VirtualMac+support=$library+launchctl=/var/jb/usr/bin/launchctl++chmod 755 "$app/VirtualMac" "$app/VZHostCompat.dylib"+chmod 755 \+ "$runtime/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine" \+ "$runtime/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation" \+ "$runtime/payload/Installation.xpc/Contents/Frameworks/InstallationCompat.dylib" \+ "$runtime/payload/Installation.xpc/Contents/Frameworks/MobileDevice.framework/Versions/A/Resources/usbmuxd" \+ "$runtime/install/VZHostCompat.dylib" \+ "$runtime/install/install-macos" \+ "$runtime/install/start-install.sh"+chown root:wheel "$runtime/install/install-launcher"+chmod 4755 "$runtime/install/install-launcher"++mkdir -p "$library" "$support/Restore Images" "$support/Installations"+chown mobile:mobile "$library" "$support" \+ "$support/Restore Images" "$support/Installations"+chmod 755 "$library" "$support" \+ "$support/Restore Images" "$support/Installations"++mkdir -p /var/db+touch /var/db/dhcpd_leases+chown root:wheel /var/db/dhcpd_leases+chmod 644 /var/db/dhcpd_leases++while IFS="$(printf '\t')" read -r hash file; do+ test -n "$hash"+ test -f "$file"+ jbctl trustcache add "$hash"+done </var/jb/usr/share/VirtualMac/trustcache.txt++for domain in system user/501; do+ "$launchctl" bootout "$domain/com.apple.bootpd" 2>/dev/null || true+ "$launchctl" bootout "$domain/vzi.apple.bootpd" 2>/dev/null || true+ "$launchctl" bootout "$domain/com.apple.NetworkSharing" 2>/dev/null || true+done+"$launchctl" enable user/501/vzi.apple.bootpd+"$launchctl" bootstrap user/501 \+ /var/jb/Library/LaunchDaemons/com.apple.bootpd.plist+"$launchctl" bootstrap user/501 \+ /var/jb/Library/LaunchDaemons/com.apple.NetworkSharing.plist+"$launchctl" kickstart -k user/501/com.apple.NetworkSharing++/var/jb/usr/bin/uicache -p "$app"++# Let Sileo offer its Restart SpringBoard completion button. Never restart the+# user's session from a package maintainer script.+echo "finish:restart"++exit 0diff --git a/VirtualMac/packaging/DEBIAN/postrm b/VirtualMac/packaging/DEBIAN/postrmnew file mode 100755index 0000000..499afec--- /dev/null+++ b/VirtualMac/packaging/DEBIAN/postrm@@ -0,0 +1,11 @@+#!/var/jb/bin/sh++set -eu+export PATH=/var/jb/usr/bin:/var/jb/usr/sbin:/var/jb/bin:/var/jb/sbin:/usr/bin:/bin:/usr/sbin:/sbin++if test "${1:-}" = remove || test "${1:-}" = purge; then+ # VM bundles deliberately remain in /var/mobile/Media/VirtualMac.+ /var/jb/usr/bin/uicache -a 2>/dev/null || true+ echo "finish:restart"+fi+exit 0diff --git a/VirtualMac/packaging/DEBIAN/preinst b/VirtualMac/packaging/DEBIAN/preinstnew file mode 100755index 0000000..e57e9a0--- /dev/null+++ b/VirtualMac/packaging/DEBIAN/preinst@@ -0,0 +1,17 @@+#!/var/jb/bin/sh++set -eu+export PATH=/var/jb/usr/bin:/var/jb/usr/sbin:/var/jb/bin:/var/jb/sbin:/usr/bin:/bin:/usr/sbin:/sbin++killall VirtualMac 2>/dev/null || true+killall com.apple.Virtualization.VirtualMachine 2>/dev/null || true+killall com.apple.Virtualization.Installation 2>/dev/null || true+killall install-macos 2>/dev/null || true++rm -f /tmp/vmm.stderr.log /tmp/restore-vmm.stderr.log+rm -f /tmp/vmm_ep.txt.* /tmp/installation_ep.txt.*++if test -d /var/jb/Applications/VirtualMac.rootless-backup; then+ rm -rf /var/jb/Applications/VirtualMac.rootless-backup+fi+exit 0diff --git a/VirtualMac/packaging/DEBIAN/prerm b/VirtualMac/packaging/DEBIAN/prermnew file mode 100755index 0000000..f5f7a30--- /dev/null+++ b/VirtualMac/packaging/DEBIAN/prerm@@ -0,0 +1,17 @@+#!/var/jb/bin/sh++set -eu+export PATH=/var/jb/usr/bin:/var/jb/usr/sbin:/var/jb/bin:/var/jb/sbin:/usr/bin:/bin:/usr/sbin:/sbin++killall VirtualMac 2>/dev/null || true+killall com.apple.Virtualization.VirtualMachine 2>/dev/null || true+killall com.apple.Virtualization.Installation 2>/dev/null || true+for domain in system user/501; do+ /var/jb/usr/bin/launchctl bootout "$domain/vzi.apple.bootpd" \+ 2>/dev/null || true+ /var/jb/usr/bin/launchctl bootout "$domain/com.apple.NetworkSharing" \+ 2>/dev/null || true+done+/var/jb/usr/bin/uicache -u /var/jb/Applications/VirtualMac.app \+ 2>/dev/null || true+exit 0diff --git a/VirtualMac/patches/dyldextractor-2.2.2-arm64e.patch b/VirtualMac/patches/dyldextractor-2.2.2-arm64e.patchnew file mode 100644index 0000000..57da4a0--- /dev/null+++ b/VirtualMac/patches/dyldextractor-2.2.2-arm64e.patch@@ -0,0 +1,108 @@+--- a/DyldExtractor/converter/objc_fixer.py++++ b/DyldExtractor/converter/objc_fixer.py+@@ -426,6 +426,10 @@+ self._ivarListCache: Dict[int, int] = {}+ self._protocolListCache: Dict[int, int] = {}+ self._protocolCache: Dict[int, int] = {}++ # {mangledName: localProtocolAddr} for protocols THIS image defines (__objc_protolist).++ # Built lazily; used to redirect cross-image cache-uniqued protocol refs to the local++ # protocol of the same name (see _processProtocol).++ self._localProtocolByName: Dict[bytes, int] = None+ self._propertyListCache: Dict[int, int] = {}+ self._methodListCache: Dict[int, int] = {}+ self._stringCache: Dict[int, int] = {}+@@ -465,9 +469,10 @@+ self._usesObjcRoRelativeNames = False+ self._optMethodNamesAddr = None++- # Get __objc_scoffs, __objc_classlist++ # Get __objc_scoffs, __objc_classlist, __objc_opt_ro+ objcScoffs = None+ objcClasslist = None++ objcOptRo = None+ for seg in self._libobjcImage.segmentsI:+ for sect in seg.sectsI:+ if sect.sectname == b"__objc_scoffs":+@@ -476,10 +481,25 @@+ elif sect.sectname == b"__objc_classlist":+ objcClasslist = sect+ pass++ elif sect.sectname == b"__objc_opt_ro":++ objcOptRo = sect++ pass+ pass++- if objcScoffs and objcClasslist:+- break++ # Modern (macOS 13 / iOS 16+) caches have no __objc_scoffs; the relative method++ # selector base is objc_opt_t.relativeMethodSelectorBaseAddressOffset (int64 @ +40++ # from the start of __objc_opt_ro: version,flags,8*int32 offsets, then the int64).++ # See dyld include/objc-shared-cache.h.++ if objcScoffs is None and objcOptRo is not None:++ optOff, ctx = self._dyldCtx.convertAddr(objcOptRo.addr)++ rmsbao = ctx.readFormat("<q", optOff + 40)[0]++ if rmsbao != 0:++ # base is a plain cache vmaddr (the __OBJC_RO selector region is a non-sliding++ # mapping, so slideAddress() would return None here -- use the addr directly).++ self._optMethodNamesAddr = objcOptRo.addr + rmsbao++ self._usesObjcRoRelativeNames = True++ self._logger.info(f"relative method selector base (objc_opt) = {hex(self._optMethodNamesAddr)}") # noqa++ return+ pass++ if objcScoffs is None:+@@ -1051,10 +1071,53 @@+ self._protocolListCache[protoListAddr] = newProtoListAddr+ return newProtoListAddr+++ def _readProtocolName(self, protoAddr: int) -> bytes:++ """mangledName cstring of a protocol_t at protoAddr (any image), or None."""++ try:++ protoDef = self._slider.slideStruct(protoAddr, objc_protocol_t)++ if not protoDef.name:++ return None++ off, ctx = self._dyldCtx.convertAddr(protoDef.name)++ return bytes(ctx.getBytes(off, 256)).split(b"\x00")[0]++ except Exception:++ return None++++ def _buildLocalProtocolMap(self) -> Dict[bytes, int]:++ """{mangledName: addr} for every protocol THIS image defines (__objc_protolist)."""++ m = {}++ for segment in self._machoCtx.segmentsI:++ for sect in segment.sectsI:++ if sect.sectname != b"__objc_protolist":++ continue++ for ptrAddr in range(sect.addr, sect.addr + sect.size, 8):++ pa = self._slider.slideAddress(ptrAddr)++ if pa and self._machoCtx.containsAddr(pa):++ name = self._readProtocolName(pa)++ if name:++ m[name] = pa++ return m+++ def _processProtocol(self, protoAddr: int) -> int:+ if protoAddr in self._protocolCache:+ return self._protocolCache[protoAddr]+++ # A protocol reference (protoref, class baseProtocol, protocol's incorporated protocol,++ # category protocol) that the cache redirected to libobjc's canonical (cross-image)++ # protocol would otherwise be copied into the synthetic __EXTRA_OBJC segment below. But++ # __EXTRA_OBJC addresses don't survive the downstream compact relayout (vz/uncache.py) ->++ # garbage protocol/mangledName pointers at runtime (objc getProtocol/_mapStrHash SIGSEGV++ # in conformsToProtocol). If this image DEFINES a protocol of the same name, redirect to++ # that single local protocol_t instead (no duplicate, no fragile __EXTRA_OBJC copy).++ if not self._machoCtx.containsAddr(protoAddr):++ if self._localProtocolByName is None:++ self._localProtocolByName = self._buildLocalProtocolMap()++ name = self._readProtocolName(protoAddr)++ localAddr = self._localProtocolByName.get(name) if name else None++ if localAddr is not None:++ self._protocolCache[protoAddr] = localAddr # pre-cache: break ref cycles++ self._processProtocol(localAddr) # process the local copy in-place++ return localAddr+++ protoDef = self._slider.slideStruct(protoAddr, objc_protocol_t)++ # protocol isa's should be 0+diff --git a/VirtualMac/requirements.lock.txt b/VirtualMac/requirements.lock.txtnew file mode 100644index 0000000..d3bde10--- /dev/null+++ b/VirtualMac/requirements.lock.txt@@ -0,0 +1,7 @@+capstone==4.0.2+dyldextractor==2.2.2+progressbar2==4.5.0+python-utils==3.9.1+setuptools==80.10.2+typing_extensions==4.15.0+diff --git a/VirtualMac/screenshots/VirtualMac.png b/VirtualMac/screenshots/VirtualMac.pngnew file mode 100644index 0000000..6266c52Binary files /dev/null and b/VirtualMac/screenshots/VirtualMac.png differdiff --git a/VirtualMac/screenshots/VirtualMac_Configuration.png b/VirtualMac/screenshots/VirtualMac_Configuration.pngnew file mode 100644index 0000000..79c1b8dBinary files /dev/null and b/VirtualMac/screenshots/VirtualMac_Configuration.png differdiff --git a/VirtualMac/screenshots/VirtualMac_Library.png b/VirtualMac/screenshots/VirtualMac_Library.pngnew file mode 100644index 0000000..e6f07b3Binary files /dev/null and b/VirtualMac/screenshots/VirtualMac_Library.png differdiff --git a/VirtualMac/screenshots/VirtualMac_macOS.png b/VirtualMac/screenshots/VirtualMac_macOS.pngnew file mode 100644index 0000000..857835dBinary files /dev/null and b/VirtualMac/screenshots/VirtualMac_macOS.png differdiff --git a/VirtualMac/scripts/README.md b/VirtualMac/scripts/README.mdnew file mode 100644index 0000000..b352242--- /dev/null+++ b/VirtualMac/scripts/README.md@@ -0,0 +1,10 @@+# Scripts++Run `../setup.sh` for a complete reproducible build. The scripts directly in this directory are the stages used by building a deb package; they may also be run individually after the environment has been prepared.++- `development/` contains USB deployment, bring-up, and interactive device/real-Mac helpers.+- `tests/` contains test and benchmark harnesses.+- `research/` contains static analysis, tracing, and reverse-engineering helpers.+- `lib/` contains shared implementation used by all three groups and the release build.++All scripts resolve the project directory from their own location. They do not depend on the checkout’s absolute path.diff --git a/VirtualMac/scripts/analyze-device-support.sh b/VirtualMac/scripts/analyze-device-support.shnew file mode 100755index 0000000..33164d4--- /dev/null+++ b/VirtualMac/scripts/analyze-device-support.sh@@ -0,0 +1,133 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++PACKAGE="${VZ_DEVICE_SUPPORT_PKG:-}"+DMG="${VZ_DEVICE_SUPPORT_DMG:-}"+IPAD_DSC="${VZ_IPADOS_DSC:-$VZ_BUILD_ROOT/inputs/ipados/20D67__iPad14,3_4_5_6/dyld_shared_cache_arm64e}"+OUT="${VZ_DEVICE_SUPPORT_ANALYSIS:-$VZ_BUILD_ROOT/analysis/device-support-27}"+EXPANDED="$OUT/expanded"+MOUNT_DIR=""++need_command codesign+need_command file+need_command hdiutil+need_command lipo+need_command nm+need_command otool+need_command pkgutil++if [[ -n "$PACKAGE" && -n "$DMG" ]]; then+ die "set only one of VZ_DEVICE_SUPPORT_PKG or VZ_DEVICE_SUPPORT_DMG"+fi+if [[ -z "$PACKAGE" && -z "$DMG" ]]; then+ DMG="$VZ_BUILD_ROOT/downloads/DeviceSupport_macOS_27_beta.dmg"+fi+if [[ -n "$PACKAGE" ]]; then+ need_file "$PACKAGE"+else+ need_file "$DMG"+fi++cleanup() {+ if [[ -n "$MOUNT_DIR" ]]; then+ hdiutil detach "$MOUNT_DIR" -quiet 2>/dev/null || true+ rmdir "$MOUNT_DIR" 2>/dev/null || true+ fi+}+trap cleanup EXIT++mkdir -p "$OUT"+if [[ ! -d "$EXPANDED" ]]; then+ if [[ -n "$PACKAGE" ]]; then+ pkgutil --expand-full "$PACKAGE" "$EXPANDED"+ else+ MOUNT_DIR="$(mktemp -d /tmp/apple-vz-device-support.XXXXXX)"+ hdiutil attach -readonly -nobrowse -mountpoint "$MOUNT_DIR" "$DMG" -quiet+ package="$(find "$MOUNT_DIR" -maxdepth 2 -name '*.pkg' -print -quit)"+ [[ -n "$package" ]] || die "no package found in $DMG"+ pkgutil --expand-full "$package" "$EXPANDED"+ fi+fi++PAYLOAD="$EXPANDED/Payload"+MOBILE_DEVICE="$PAYLOAD/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice"+USBMUXD="$PAYLOAD/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/Resources/usbmuxd"+USBMUXD_PLIST="$PAYLOAD/System/Library/LaunchDaemons/com.apple.usbmuxd.plist"+need_file "$MOBILE_DEVICE"+need_file "$USBMUXD"+need_file "$USBMUXD_PLIST"++expected_mobile_device=ddcfe9a3ca6be0a7f5d2c231eaad086aaecc4aec9ff49f18d6e731aa8d6da89c+expected_usbmuxd=8c3ae325cef26b0f8ba5a4de45d8a2a4ecdbb89a4b87634a85a51eb6d509d47f+actual_mobile_device="$(shasum -a 256 "$MOBILE_DEVICE" | awk '{print $1}')"+actual_usbmuxd="$(shasum -a 256 "$USBMUXD" | awk '{print $1}')"+[[ "$actual_mobile_device" == "$expected_mobile_device" ]] ||+ die "unsupported DeviceSupport MobileDevice: $actual_mobile_device"+[[ "$actual_usbmuxd" == "$expected_usbmuxd" ]] ||+ die "unsupported DeviceSupport usbmuxd: $actual_usbmuxd"++{+ source_input="${PACKAGE:-$DMG}"+ echo "source=$source_input"+ echo "sha256=$(shasum -a 256 "$source_input" | awk '{print $1}')"+ echo "architectures=$(lipo -archs "$MOBILE_DEVICE")"+ /usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' \+ "$PAYLOAD/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/Resources/Info.plist" 2>/dev/null \+ | sed 's/^/bundle_version=/' || true+} >"$OUT/summary.txt"++otool -L -arch arm64e "$MOBILE_DEVICE" >"$OUT/mobiledevice-linked-images.txt"+nm -um -arch arm64e "$MOBILE_DEVICE" >"$OUT/mobiledevice-imports.txt"+nm -gj -arch arm64e "$MOBILE_DEVICE" | sort -u >"$OUT/mobiledevice-exports.txt"+codesign -d --entitlements :- "$MOBILE_DEVICE" \+ >"$OUT/mobiledevice-entitlements.plist" 2>/dev/null || true+otool -L -arch arm64e "$USBMUXD" >"$OUT/usbmuxd-linked-images.txt"+codesign -d --entitlements :- "$USBMUXD" \+ >"$OUT/usbmuxd-entitlements.plist" 2>/dev/null || true+plutil -p "$USBMUXD_PLIST" >"$OUT/usbmuxd-launchd-plist.txt"++if [[ -f "$IPAD_DSC" ]]; then+ IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+ need_file "$IPSW"+ "$IPSW" dyld info -l "$IPAD_DSC" 2>/dev/null \+ | sed $'s/\033\\[[0-9;]*m//g' >"$OUT/ipados-dyld-images.txt"+ awk '/^[[:space:]]*[0-9]+:/ { print $NF }' "$OUT/ipados-dyld-images.txt" \+ | sed -E 's#/Versions/[A-Z]/#/#' | sort -u >"$OUT/ipados-install-names.txt"++ {+ echo "MobileDevice strong dependency coverage in the iPadOS shared cache"+ echo "(weak dependencies are reported separately and are not required to launch)"+ echo+ otool -L -arch arm64e "$MOBILE_DEVICE" | tail -n +2 | while IFS= read -r line; do+ dependency="${line#"${line%%[![:space:]]*}"}"+ dependency="${dependency%% *}"+ normalized="$(printf '%s\n' "$dependency" | sed -E 's#/Versions/[A-Z]/#/#')"+ if [[ "$line" == *", weak)"* ]]; then+ strength="weak"+ else+ strength="strong"+ fi+ if grep -Fxq "$normalized" "$OUT/ipados-install-names.txt"; then+ state="present"+ else+ state="missing"+ fi+ printf '%-7s %-7s %s\n' "$state" "$strength" "$dependency"+ done+ } >"$OUT/mobiledevice-ipados-dependency-coverage.txt"+else+ printf '%s\n' 'iPadOS shared-cache dependency audit not requested' \+ >"$OUT/mobiledevice-ipados-dependency-coverage.txt"+fi++find "$PAYLOAD" -type f -print0 | while IFS= read -r -d '' candidate; do+ if file "$candidate" | grep -q 'Mach-O'; then+ printf '%s\t%s\n' "${candidate#"$PAYLOAD"/}" "$(lipo -archs "$candidate" 2>/dev/null || true)"+ fi+done | sort >"$OUT/payload-mach-o-files.txt"++echo "DeviceSupport analysis: $OUT"diff --git a/VirtualMac/scripts/audit-entitlements.py b/VirtualMac/scripts/audit-entitlements.pynew file mode 100644index 0000000..66257e8--- /dev/null+++ b/VirtualMac/scripts/audit-entitlements.py@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""Fail a build when a produced Mach-O has unexpected entitlements.++Arguments are EXPECTED_PLIST BINARY pairs. Use '-' for a binary which must+have no entitlements. ldid is used for extraction because it understands the+iOS-style ad-hoc signatures used by the jailbroken-device payload.+"""++import pathlib+import plistlib+import subprocess+import sys+++def load_expected(path_text: str) -> dict:+ if path_text == "-":+ return {}+ with pathlib.Path(path_text).open("rb") as stream:+ value = plistlib.load(stream)+ if not isinstance(value, dict):+ raise SystemExit(f"{path_text}: entitlement plist is not a dictionary")+ return value+++def load_actual(binary: str) -> dict:+ result = subprocess.run(+ ["ldid", "-e", binary], check=True, capture_output=True+ )+ if not result.stdout.strip():+ return {}+ value = plistlib.loads(result.stdout)+ if not isinstance(value, dict):+ raise SystemExit(f"{binary}: embedded entitlements are not a dictionary")+ return value+++def main(arguments: list[str]) -> None:+ if not arguments or len(arguments) % 2:+ raise SystemExit(+ "usage: audit-entitlements.py EXPECTED_PLIST|- BINARY [...]"+ )+ for index in range(0, len(arguments), 2):+ expected_path, binary = arguments[index : index + 2]+ expected = load_expected(expected_path)+ actual = load_actual(binary)+ if actual != expected:+ missing = sorted(set(expected) - set(actual))+ extra = sorted(set(actual) - set(expected))+ changed = sorted(+ key for key in set(expected) & set(actual)+ if expected[key] != actual[key]+ )+ raise SystemExit(+ f"{binary}: entitlement audit failed; "+ f"missing={missing} extra={extra} changed={changed}"+ )+ print(f"entitlements ok: {binary} ({len(actual)} keys)")+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/VirtualMac/scripts/audit-ipad-package-stage.sh b/VirtualMac/scripts/audit-ipad-package-stage.shnew file mode 100755index 0000000..31c94a1--- /dev/null+++ b/VirtualMac/scripts/audit-ipad-package-stage.sh@@ -0,0 +1,87 @@+#!/bin/bash++set -euo pipefail++STAGE="${1:-}"+[[ -n "$STAGE" && -d "$STAGE" ]] || {+ echo "usage: $0 <deb-stage-directory>" >&2+ exit 2+}++RUNTIME="$STAGE/var/root/VirtualMac"+PAYLOAD="$RUNTIME/payload"+FRAMEWORKS="$PAYLOAD/Frameworks"+VMM="$PAYLOAD/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"++die() {+ echo "package audit failed: $*" >&2+ exit 1+}++for binary in \+ "$FRAMEWORKS/Hypervisor.framework/Hypervisor" \+ "$FRAMEWORKS/ParavirtualizedGraphics.framework/ParavirtualizedGraphics" \+ "$FRAMEWORKS/Virtualization.framework/Virtualization" \+ "$FRAMEWORKS/vmnet.framework/vmnet" \+ "$FRAMEWORKS/Netrb.framework/Netrb" \+ "$FRAMEWORKS/VideoToolbox.framework/VideoToolbox" \+ "$FRAMEWORKS/MetalSerializer.framework/MetalSerializer" \+ "$FRAMEWORKS/MetalCompat.dylib" \+ "$FRAMEWORKS/LaunchServicesCompat.dylib" \+ "$FRAMEWORKS/Virtualization.framework/Resources/AVPBooter.vmapple2.bin" \+ "$VMM"; do+ [[ -f "$binary" ]] || die "missing runtime file: ${binary#"$STAGE/"}"+done++[[ ! -e "$PAYLOAD/VirtualMachine.xpc/Contents/Frameworks" ]] ||+ die "VirtualMachine.xpc contains a second framework tree"+[[ ! -e "$PAYLOAD/AVPBooter.vmapple2.bin" ]] ||+ die "AVPBooter duplicates the Virtualization framework resource"++for development_file in \+ "$PAYLOAD/bin" \+ "$PAYLOAD/trustcache.txt" \+ "$RUNTIME/install/restore-image-probe" \+ "$RUNTIME/install/usb-bridge-probe" \+ "$STAGE/var/jb/usr/share/VirtualMac/VM-LIBRARY-README.md"; do+ [[ ! -e "$development_file" ]] ||+ die "development-only file was packaged: ${development_file#"$STAGE/"}"+done++metadata="$(find "$STAGE" -type f \( -name .DS_Store -o -name '._*' \) -print -quit)"+[[ -z "$metadata" ]] || die "host metadata was packaged: ${metadata#"$STAGE/"}"+extended_attribute="$(xattr -lr "$STAGE" 2>/dev/null | head -1)"+[[ -z "$extended_attribute" ]] ||+ die "extended attribute was packaged: $extended_attribute"+bridge_support="$(find "$FRAMEWORKS" -type d -name BridgeSupport -print -quit)"+[[ -z "$bridge_support" ]] ||+ die "developer-only BridgeSupport metadata was packaged: ${bridge_support#"$STAGE/"}"++broken_link="$(find -L "$STAGE" -type l -print -quit)"+[[ -z "$broken_link" ]] || die "broken symlink: ${broken_link#"$STAGE/"}"++unexpected_framework=""+while IFS= read -r framework; do+ case "$framework" in+ "$FRAMEWORKS"/*|"$PAYLOAD/Installation.xpc/Contents/Frameworks"/*) ;;+ *) unexpected_framework="$framework"; break ;;+ esac+done < <(find "$PAYLOAD" -type d -name '*.framework' -print)+[[ -z "$unexpected_framework" ]] ||+ die "framework outside an authoritative dependency directory: ${unexpected_framework#"$STAGE/"}"++if otool -L "$VMM" | grep -Fq '@loader_path/../Frameworks/'; then+ die "VMM still references its removed nested framework directory"+fi+for dependency in \+ '@loader_path/../../../Frameworks/Hypervisor.framework/Hypervisor' \+ '@loader_path/../../../Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics' \+ '@loader_path/../../../Frameworks/MetalCompat.dylib' \+ '@loader_path/../../../Frameworks/LaunchServicesCompat.dylib' \+ '@loader_path/../../../Frameworks/vmnet.framework/vmnet' \+ '@loader_path/../../../Frameworks/VideoToolbox.framework/VideoToolbox'; do+ otool -L "$VMM" | grep -Fq "$dependency" ||+ die "VMM is missing shared dependency: $dependency"+done++echo "package stage audit passed: one shared VM framework tree, XPC installs dependencies only"diff --git a/VirtualMac/scripts/audit-ipados-compatibility.sh b/VirtualMac/scripts/audit-ipados-compatibility.shnew file mode 100755index 0000000..33dadd9--- /dev/null+++ b/VirtualMac/scripts/audit-ipados-compatibility.sh@@ -0,0 +1,58 @@+#!/bin/bash++# Reject a payload that accidentally picked up a macOS platform stamp, an SDK+# deployment target newer than the supported range, or a strong import absent+# from the oldest iPadOS 16 shared cache.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++need_command file+need_command otool++roots=(+ "$VZ_BUILD_ROOT/ipad-app/VirtualMac.app"+ "$VZ_BUILD_ROOT/ipad-vm/payload"+ "$VZ_BUILD_ROOT/ipad-installation/payload"+ "$VZ_BUILD_ROOT/ipad-installation/install"+ "$VZ_BUILD_ROOT/ipad-network-sharing"+ "$VZ_BUILD_ROOT/ipad-network-helpers"+ "$VZ_BUILD_ROOT/ipad-tweak"+)++checked=0+for root in "${roots[@]}"; do+ [[ -d "$root" ]] || continue+ while IFS= read -r -d '' candidate; do+ # Original macOS inputs are retained as *.macos only while producing+ # their restamped siblings; no *.macos file is staged in the deb.+ [[ "$candidate" == *.macos ]] && continue+ file "$candidate" | grep -q 'Mach-O' || continue+ build_version="$(otool -l "$candidate" | awk '+ /cmd LC_BUILD_VERSION/ { in_build=1; next }+ in_build && /platform/ { platform=$2 }+ in_build && /minos/ { minos=$2; print platform " " minos; exit }+ ')"+ [[ "$build_version" == "2 16.0" ]] ||+ die "unsupported platform/minimum OS ($build_version): $candidate"+ checked=$((checked + 1))+ done < <(find "$root" -type f -print0)+done++(( checked > 0 )) || die "no built iPad Mach-O files found"+echo "iPadOS 16.0 deployment stamps verified: $checked Mach-O files"++compat_dsc="${VZ_IPADOS_COMPAT_DSC:-$VZ_BUILD_ROOT/compat/ipados-16.1/20B82__iPad14,3_4_5_6/dyld_shared_cache_arm64e}"+if [[ -f "$compat_dsc" ]]; then+ need_command dyld_info+ ipsw_tool="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+ need_file "$ipsw_tool"+ VZ_IPSW_TOOL="$ipsw_tool" python3 "$SCRIPT_DIR/audit-ipados-dsc.py" \+ "$compat_dsc" "$VZ_BUILD_ROOT/compat/ipados-16.1" "${roots[@]}"+elif [[ "${VZ_REQUIRE_IPADOS_COMPAT_DSC:-0}" == 1 ]]; then+ die "oldest-host cache missing; run scripts/fetch-ipados-compat-cache.sh"+else+ echo "note: oldest-host ABI audit skipped; run scripts/fetch-ipados-compat-cache.sh"+fidiff --git a/VirtualMac/scripts/audit-ipados-dsc.py b/VirtualMac/scripts/audit-ipados-dsc.pynew file mode 100755index 0000000..fbb6556--- /dev/null+++ b/VirtualMac/scripts/audit-ipados-dsc.py@@ -0,0 +1,269 @@+#!/usr/bin/env python3+"""Audit packaged Mach-O dependencies/imports against an iPadOS dyld cache."""++import argparse+import os+import re+import subprocess+import sys+from pathlib import Path+++IPSW_TOOL = os.environ.get("VZ_IPSW_TOOL", "ipsw")+++def command_output(*arguments: str) -> str:+ result = subprocess.run(+ arguments,+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ )+ return result.stdout.decode("utf-8", "ignore")+++def dependency_label(path: str) -> str:+ basename = path.rsplit("/", 1)[-1]+ if basename.endswith(".dylib"):+ basename = basename[:-6]+ return basename+++def possible_labels(path: str) -> set[str]:+ label = dependency_label(path)+ labels = {label}+ components = label.split(".")+ while len(components) > 1 and (+ components[-1].isdigit() or len(components[-1]) == 1+ ):+ components.pop()+ labels.add(".".join(components))+ return labels+++def normalized_install_name(path: str) -> str:+ return path.replace(".framework/Versions/A/", ".framework/")+++class SharedCache:+ def __init__(self, cache_path: Path, work_path: Path) -> None:+ self.path = cache_path+ self.tbd_root = work_path / "tbd"+ self.tbd_root.mkdir(parents=True, exist_ok=True)+ self.parsed_tbds: dict[Path, tuple[set[str], list[str]]] = {}++ listing = command_output(+ IPSW_TOOL, "dyld", "info", "-l", "--no-color", str(cache_path)+ )+ images = re.findall(r"^\s*\d+:\s+.*?(/\S+)\s*$", listing, re.MULTILINE)+ if not images:+ raise RuntimeError(f"could not enumerate images in {cache_path}")+ self.images = {normalized_install_name(image): image for image in images}++ def actual_install_name(self, requested: str) -> str | None:+ return self.images.get(normalized_install_name(requested))++ def tbd_path(self, install_name: str) -> Path:+ return self.tbd_root / (install_name.rsplit("/", 1)[-1] + ".tbd")++ def ensure_tbd(self, install_name: str) -> Path | None:+ actual_name = self.actual_install_name(install_name) or install_name+ output = self.tbd_path(actual_name)+ if output.exists():+ return output+ subprocess.run(+ [+ IPSW_TOOL,+ "dyld",+ "tbd",+ str(self.path),+ actual_name,+ "-o",+ str(self.tbd_root),+ "--no-color",+ ],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ return output if output.exists() else None++ def parse_tbd(self, path: Path) -> tuple[set[str], list[str]]:+ if path in self.parsed_tbds:+ return self.parsed_tbds[path]++ text = path.read_text(errors="ignore")+ documents = text.split("--- !tapi-tbd")+ first_document = documents[1] if len(documents) > 1 else text+ exports: set[str] = set()+ for key in ("symbols", "weak-symbols"):+ for match in re.finditer(+ rf"(?m)^\s*{key}:\s*\[(.*?)\]", first_document, re.DOTALL+ ):+ exports.update(+ token.strip().strip("'\"")+ for token in match.group(1).split(",")+ if token.strip()+ )++ reexports: list[str] = []+ match = re.search(+ r"(?m)^reexported-libraries:\s*(.*?)(?=^exports:|^---)",+ first_document,+ re.DOTALL,+ )+ if match:+ reexports = re.findall(r"'([^']+)'", match.group(1))+ self.parsed_tbds[path] = exports, reexports+ return exports, reexports++ def exports_symbol(+ self, install_name: str, symbol: str, visited: set[str] | None = None+ ) -> bool:+ if visited is None:+ visited = set()+ normalized = normalized_install_name(install_name)+ if normalized in visited:+ return False+ visited.add(normalized)++ tbd = self.ensure_tbd(install_name)+ if tbd is None:+ return False+ exports, reexports = self.parse_tbd(tbd)+ if symbol in exports:+ return True+ return any(self.exports_symbol(item, symbol, visited) for item in reexports)+++def find_machos(roots: list[Path]) -> list[Path]:+ binaries: list[Path] = []+ for root in roots:+ if not root.is_dir():+ continue+ for directory, _, filenames in os.walk(root, followlinks=False):+ for filename in filenames:+ candidate = Path(directory) / filename+ # Build-only macOS inputs; their restamped siblings are audited.+ if candidate.name.endswith(".macos"):+ continue+ if candidate.is_symlink():+ continue+ if "Mach-O" in command_output("file", str(candidate)):+ binaries.append(candidate)+ return binaries+++def linked_dependencies(binary: Path) -> list[tuple[str, bool]]:+ dependencies: list[tuple[str, bool]] = []+ for line in command_output("dyld_info", "-dependents", str(binary)).splitlines():+ columns = line.split()+ if columns and columns[-1].startswith(("/", "@")):+ dependencies.append((columns[-1], "weak-link" in columns[:-1]))+ return dependencies+++def imports(binary: Path):+ pattern = re.compile(+ r"^\s+0x[0-9A-Fa-f]+\s+(\S+)"+ r"(?:\s+\[weak-import\])?\s+\(from ([^)]+)\)"+ )+ for line in command_output("dyld_info", "-imports", str(binary)).splitlines():+ match = pattern.match(line)+ if not match:+ continue+ symbol, label = match.groups()+ symbol = re.sub(r"\+0x[0-9A-Fa-f]+$", "", symbol)+ yield symbol, label, "[weak-import]" in line+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("cache", type=Path)+ parser.add_argument("work", type=Path)+ parser.add_argument("roots", nargs="+", type=Path)+ args = parser.parse_args()++ cache = SharedCache(args.cache, args.work)+ binaries = find_machos(args.roots)+ if not binaries:+ raise RuntimeError("no Mach-O files found for shared-cache audit")++ # This one macOS install name is deliberately redirected to the bundled+ # extracted framework by DYLD_FRAMEWORK_PATH before Virtualization loads.+ hypervisor_name = "/System/Library/Frameworks/Hypervisor.framework/Hypervisor"+ bundled_hypervisor = next(+ (+ root / "Frameworks/Hypervisor.framework/Versions/A/Hypervisor"+ for root in args.roots+ if (root / "Frameworks/Hypervisor.framework/Versions/A/Hypervisor").is_file()+ ),+ None,+ )++ missing_dependencies: list[str] = []+ missing_imports: list[str] = []+ weak_missing_dependencies = 0+ weak_missing_imports = 0+ audited_imports = 0++ for binary in binaries:+ dependencies = linked_dependencies(binary)+ labels: dict[str, list[tuple[str, bool]]] = {}+ for dependency, weak in dependencies:+ for label in possible_labels(dependency):+ labels.setdefault(label, []).append((dependency, weak))++ if not dependency.startswith(("/System/", "/usr/", "/Library/Apple/")):+ continue+ if dependency == hypervisor_name and bundled_hypervisor is not None:+ continue+ if cache.actual_install_name(dependency) is None:+ if weak:+ weak_missing_dependencies += 1+ else:+ missing_dependencies.append(f"{binary}: {dependency}")++ for symbol, label, weak_import in imports(binary):+ if label.startswith("<"):+ continue+ candidates = labels.get(label, [])+ if not candidates:+ missing_imports.append(f"{binary}: cannot resolve import owner {label}")+ continue+ system_candidates = [+ item+ for item in candidates+ if item[0].startswith(("/System/", "/usr/", "/Library/Apple/"))+ ]+ if not system_candidates:+ # The owner is bundled; its own imports are audited separately.+ continue+ dependency, weak_dependency = system_candidates[0]+ if dependency == hypervisor_name and bundled_hypervisor is not None:+ continue++ audited_imports += 1+ if cache.exports_symbol(dependency, symbol):+ continue+ if weak_import or weak_dependency:+ weak_missing_imports += 1+ else:+ missing_imports.append(f"{binary}: {symbol} from {dependency}")++ for problem in missing_dependencies + missing_imports:+ print(f"error: {problem}", file=sys.stderr)+ if missing_dependencies or missing_imports:+ return 1++ print(+ "oldest-host ABI verified: "+ f"{len(binaries)} Mach-O files, {audited_imports} system imports; "+ f"{weak_missing_dependencies} absent weak dylibs and "+ f"{weak_missing_imports} absent weak imports tolerated"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/VirtualMac/scripts/bootstrap.sh b/VirtualMac/scripts/bootstrap.shnew file mode 100755index 0000000..51c1086--- /dev/null+++ b/VirtualMac/scripts/bootstrap.sh@@ -0,0 +1,74 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++need_command brew+need_command git+need_command patch+need_command python3++install_formula() {+ local formula="$1"+ local command_name="${2:-$1}"+ if ! command -v "$command_name" >/dev/null 2>&1; then+ brew install "$formula"+ fi+}++install_formula ldid+install_formula libimobiledevice idevice_id+install_formula go+if ! command -v sshpass >/dev/null 2>&1; then+ brew install hudochenkov/sshpass/sshpass+fi++TOOLCHAIN="$VZ_BUILD_ROOT/toolchain"+VENV="$TOOLCHAIN/venv"+BIN="$TOOLCHAIN/bin"+IPSW_SRC="$TOOLCHAIN/ipsw-src"+IPSW_COMMIT="b7229017247457d7cf310c942dd9910e485624b3"+mkdir -p "$TOOLCHAIN" "$BIN"++if [[ ! -x "$VENV/bin/python3" ]]; then+ python3 -m venv "$VENV"+fi+"$VENV/bin/python3" -m pip install --disable-pip-version-check \+ --requirement "$VZ_REPO_ROOT/requirements.lock.txt"++SITE_PACKAGES="$("$VENV/bin/python3" -c \+ 'import sysconfig; print(sysconfig.get_paths()["purelib"])')"+OBJC_FIXER="$SITE_PACKAGES/DyldExtractor/converter/objc_fixer.py"+need_file "$OBJC_FIXER"+if ! grep -q '_buildLocalProtocolMap' "$OBJC_FIXER"; then+ patch --batch --forward -p1 -d "$SITE_PACKAGES" \+ < "$VZ_REPO_ROOT/patches/dyldextractor-2.2.2-arm64e.patch"+fi+grep -q 'relativeMethodSelectorBaseAddressOffset' "$OBJC_FIXER" ||+ die "DyldExtractor relative-selector patch is missing"+grep -q '_buildLocalProtocolMap' "$OBJC_FIXER" ||+ die "DyldExtractor protocol-localization patch is missing"++if [[ ! -d "$IPSW_SRC/.git" ]]; then+ git clone https://github.com/blacktop/ipsw.git "$IPSW_SRC"+fi+git -C "$IPSW_SRC" fetch --quiet origin "$IPSW_COMMIT"+git -C "$IPSW_SRC" checkout --detach --quiet "$IPSW_COMMIT"+install -m 0644 \+ "$VZ_REPO_ROOT/vz/ipsw_patches/dyld_a2sb.go" \+ "$IPSW_SRC/cmd/ipsw/cmd/dyld/dyld_a2sb.go"+(+ cd "$IPSW_SRC"+ CGO_ENABLED=1 go build -o "$BIN/ipsw-a2sb" ./cmd/ipsw+)+"$BIN/ipsw-a2sb" dyld a2sb --help >/dev/null++cat <<EOF+toolchain ready:+ Python: $VENV/bin/python3+ dyldex: $VENV/bin/dyldex+ ipsw-a2sb: $BIN/ipsw-a2sb+ ipsw source: $IPSW_COMMIT+EOFdiff --git a/VirtualMac/scripts/build-frameworks.sh b/VirtualMac/scripts/build-frameworks.shnew file mode 100755index 0000000..8a626ce--- /dev/null+++ b/VirtualMac/scripts/build-frameworks.sh@@ -0,0 +1,175 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++DSC="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/dyld_shared_cache_arm64e"+PYTHON="$VZ_BUILD_ROOT/toolchain/venv/bin/python3"+DYLDEX="$VZ_BUILD_ROOT/toolchain/venv/bin/dyldex"+IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+RAW_DIR="$VZ_BUILD_ROOT/frameworks/raw"+MAC_DIR="$VZ_BUILD_ROOT/frameworks/macos"+IOS_DIR="$VZ_BUILD_ROOT/frameworks/ios"+BUNDLE_DIR="$VZ_BUILD_ROOT/frameworks/bundles"+MANIFEST="$VZ_BUILD_ROOT/frameworks/manifest.txt"+FRAMEWORK_ROOT="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/System/Library/Frameworks"+PRIVATE_FRAMEWORK_ROOT="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/System/Library/PrivateFrameworks"++need_file "$DSC"+need_file "$DSC.01"+need_file "$PYTHON"+need_file "$DYLDEX"+need_file "$IPSW"+need_command codesign+need_command ditto+need_command dwarfdump+need_command otool++mkdir -p "$RAW_DIR" "$MAC_DIR" "$IOS_DIR" "$BUNDLE_DIR/macos" "$BUNDLE_DIR/ios"++images=(+ "Hypervisor.framework/Versions/A/Hypervisor|Hypervisor|1B1E116F-81FD-3FD6-B424-52D4FA96E9AB"+ "ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics|ParavirtualizedGraphics|732073AB-34E5-38C9-A919-53B628977BDB"+ "Virtualization.framework/Versions/A/Virtualization|Virtualization|DCFC0A79-7728-3089-94D7-1508E71F38E5"+)++for spec in "${images[@]}"; do+ IFS='|' read -r image name expected_uuid <<< "$spec"+ raw="$RAW_DIR/$name"+ mac="$MAC_DIR/$name"+ proto="$IOS_DIR/$name.proto"+ ios="$IOS_DIR/$name"++ if [[ ! -f "$raw" ]]; then+ "$DYLDEX" -e "$image" -o "$raw" "$DSC"+ fi++ VZ_MAC=1 VZ_IPSW="$IPSW" \+ "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$image" "$raw" "$mac" compact+ codesign --force --sign - "$mac"++ VZ_IPSW="$IPSW" VZ_WEAKEN="MetalSerializer,vmnet" \+ "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$image" "$raw" "$proto" compact+ "$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" "$proto" "$ios" 16.0+ chmod 755 "$mac" "$ios"++ for output in "$mac" "$ios"; do+ uuid="$(dwarfdump --uuid "$output" | awk '{print $2}')"+ [[ "$uuid" == "$expected_uuid" ]] ||+ die "$name UUID mismatch in $output: expected $expected_uuid, got $uuid"+ codesign --verify "$output"+ otool -l "$output" | grep -q 'LC_DYLD_CHAINED_FIXUPS' ||+ die "$name is missing LC_DYLD_CHAINED_FIXUPS in $output"+ done++ source_resources="$FRAMEWORK_ROOT/$name.framework/Versions/A/Resources"+ need_file "$source_resources/Info.plist"+ for platform in macos ios; do+ bundle="$BUNDLE_DIR/$platform/$name.framework"+ version="$bundle/Versions/A"+ mkdir -p "$version/Resources"+ ditto "$source_resources" "$version/Resources"+ cp "$VZ_BUILD_ROOT/frameworks/$platform/$name" "$version/$name"+ chmod 755 "$version/$name"+ ln -sfn A "$bundle/Versions/Current"+ ln -sfn "Versions/Current/$name" "$bundle/$name"+ ln -sfn Versions/Current/Resources "$bundle/Resources"+ done++ if [[ "$name" == Virtualization ]]; then+ source_xpc="$FRAMEWORK_ROOT/$name.framework/Versions/A/XPCServices"+ need_file "$source_xpc/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+ mac_bundle="$BUNDLE_DIR/macos/$name.framework"+ ditto "$source_xpc" "$mac_bundle/Versions/A/XPCServices"+ ln -sfn Versions/Current/XPCServices "$mac_bundle/XPCServices"+ for xpc in "$mac_bundle"/Versions/A/XPCServices/*.xpc; do+ # The IPSW signatures use legacy resource envelopes. Re-sign each+ # copied service while retaining its privileged entitlements, then+ # seal those nested signatures into the completed framework.+ codesign --force --sign - \+ --preserve-metadata=entitlements,flags,runtime "$xpc"+ codesign --verify --strict "$xpc"+ done+ fi++ for platform in macos ios; do+ bundle="$BUNDLE_DIR/$platform/$name.framework"+ codesign --force --sign - "$bundle"+ codesign --verify --deep --strict "$bundle"+ done+done++metal_serializer_image="MetalSerializer.framework/Versions/A/MetalSerializer"+metal_serializer_name="MetalSerializer"+metal_serializer_uuid="9C249FB4-2C87-3099-807B-2A3B063C79FA"+metal_serializer_raw="$RAW_DIR/$metal_serializer_name"+metal_serializer_proto="$IOS_DIR/$metal_serializer_name.proto"+metal_serializer_ios="$IOS_DIR/$metal_serializer_name"++if [[ ! -f "$metal_serializer_raw" ]]; then+ "$DYLDEX" -e "$metal_serializer_image" \+ -o "$metal_serializer_raw" "$DSC"+fi+VZ_IPSW="$IPSW" \+ "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$metal_serializer_image" "$metal_serializer_raw" \+ "$metal_serializer_proto" compact+"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" \+ "$metal_serializer_proto" "$metal_serializer_ios" 16.0+chmod 755 "$metal_serializer_ios"+uuid="$(dwarfdump --uuid "$metal_serializer_ios" | awk '{print $2}')"+[[ "$uuid" == "$metal_serializer_uuid" ]] ||+ die "MetalSerializer UUID mismatch: expected $metal_serializer_uuid, got $uuid"+codesign --verify "$metal_serializer_ios"+otool -l "$metal_serializer_ios" | grep -q 'LC_DYLD_CHAINED_FIXUPS' ||+ die "MetalSerializer is missing LC_DYLD_CHAINED_FIXUPS"++metal_serializer_resources="$PRIVATE_FRAMEWORK_ROOT/MetalSerializer.framework/Versions/A/Resources"+need_file "$metal_serializer_resources/Info.plist"+metal_serializer_bundle="$BUNDLE_DIR/ios/MetalSerializer.framework"+metal_serializer_version="$metal_serializer_bundle/Versions/A"+rm -rf "$metal_serializer_bundle"+mkdir -p "$metal_serializer_version/Resources"+ditto "$metal_serializer_resources" "$metal_serializer_version/Resources"+cp "$metal_serializer_ios" "$metal_serializer_version/MetalSerializer"+chmod 755 "$metal_serializer_version/MetalSerializer"+ln -sfn A "$metal_serializer_bundle/Versions/Current"+ln -sfn Versions/Current/MetalSerializer \+ "$metal_serializer_bundle/MetalSerializer"+ln -sfn Versions/Current/Resources "$metal_serializer_bundle/Resources"+codesign --force --sign - "$metal_serializer_bundle"+codesign --verify --deep --strict "$metal_serializer_bundle"++hash_line() {+ local label="$1"+ local file="$2"+ printf '%s\t%s\t%s\t%s\t%s\n' \+ "$label" \+ "$(stat -f %z "$file")" \+ "$(shasum -a 256 "$file" | awk '{print $1}')" \+ "$(dwarfdump --uuid "$file" | awk '{print $2}')" \+ "$file"+}++{+ printf 'FRAMEWORK_MANIFEST\t1\n'+ printf 'generated_utc\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ printf 'repository_commit\t%s\n' "$(git -C "$VZ_REPO_ROOT" rev-parse HEAD)"+ printf 'dsc_sha256\t%s\n' "$(shasum -a 256 "$DSC" | awk '{print $1}')"+ for spec in "${images[@]}"; do+ IFS='|' read -r _ name _ <<< "$spec"+ hash_line "$name.raw" "$RAW_DIR/$name"+ hash_line "$name.macos" "$MAC_DIR/$name"+ hash_line "$name.ios" "$IOS_DIR/$name"+ done+ hash_line "$metal_serializer_name.raw" "$metal_serializer_raw"+ hash_line "$metal_serializer_name.ios" "$metal_serializer_ios"+ hash_line "$metal_serializer_name.bundle" \+ "$metal_serializer_version/MetalSerializer"+} > "$MANIFEST"++echo "frameworks built and validated: $MANIFEST"diff --git a/VirtualMac/scripts/build-ipad-app.sh b/VirtualMac/scripts/build-ipad-app.shnew file mode 100755index 0000000..19a0d9b--- /dev/null+++ b/VirtualMac/scripts/build-ipad-app.sh@@ -0,0 +1,84 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/ipad-app"+APP="$OUT/VirtualMac.app"+BIN="$APP/VirtualMac"+HOOK="$APP/VZHostCompat.dylib"+ENTS="$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements"++need_command ldid+need_command sips+need_command xattr+need_command xcrun+need_file "$VZ_REPO_ROOT/vz/host/VirtualMac-Info.plist"+need_file "$VZ_REPO_ROOT/vz/host/VirtualMacLaunchScreen.storyboard"+need_file "$VZ_REPO_ROOT/assets/VirtualMac.png"+need_file "$VZ_REPO_ROOT/vz/host/NSViewShim.m"+need_file "$VZ_REPO_ROOT/vz/host/VZAppSettings.m"+need_file "$VZ_REPO_ROOT/vz/host/VZRestoreCatalog.m"+need_file "$VZ_REPO_ROOT/vz/host/VZNewVMViewController.m"+need_file "$VZ_REPO_ROOT/vz/host/VZProgressViewController.m"+need_file "$VZ_REPO_ROOT/vz/host/VZSettingsViewController.m"+need_file "$VZ_REPO_ROOT/vz/host/VZVMLibraryViewController.m"+need_file "$VZ_REPO_ROOT/vz/host/VirtualMacApp.m"+need_file "$VZ_REPO_ROOT/vz/host/vzxpchook.m"+need_file "$ENTS"++rm -rf "$APP"+mkdir -p "$APP"+cp "$VZ_REPO_ROOT/vz/host/VirtualMac-Info.plist" "$APP/Info.plist"+cp "$VZ_REPO_ROOT/vendor/VirtualBuddy/ipsws_v2.json" "$APP/ipsws_v2.json"+if [[ -d "$VZ_REPO_ROOT/assets/wallpapers" ]]; then+ mkdir -p "$APP/Wallpapers"+ cp "$VZ_REPO_ROOT/assets/wallpapers"/*.jpg "$APP/Wallpapers/"+ cp "$VZ_REPO_ROOT/assets/wallpapers"/*.png "$APP/Wallpapers/"+fi+xcrun ibtool --compile "$APP/VirtualMacLaunchScreen.storyboardc" \+ "$VZ_REPO_ROOT/vz/host/VirtualMacLaunchScreen.storyboard" \+ --target-device ipad --minimum-deployment-target 16.0 >/dev/null++# Generate the exact legacy icon filenames consumed by iPadOS 16. The checked+# in 1024-pixel RGB master has no alpha channel, as required for app icons.+cp "$VZ_REPO_ROOT/assets/VirtualMac.png" "$APP/AppIcon1024x1024.png"+for spec in \+ '120 [email protected]' \+ '180 [email protected]' \+ '152 [email protected]' \+ '167 [email protected]'; do+ read -r size name <<<"$spec"+ sips -z "$size" "$size" "$VZ_REPO_ROOT/assets/VirtualMac.png" \+ --out "$APP/$name" >/dev/null+done++xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" -fblocks \+ -framework AVFAudio -framework Foundation -framework GameController \+ -framework UIKit \+ -framework UniformTypeIdentifiers \+ -Wl,-export_dynamic -Wl,-undefined,dynamic_lookup \+ "$VZ_REPO_ROOT/vz/host/NSViewShim.m" \+ "$VZ_REPO_ROOT/vz/host/VZAppSettings.m" \+ "$VZ_REPO_ROOT/vz/host/VZRestoreCatalog.m" \+ "$VZ_REPO_ROOT/vz/host/VZNewVMViewController.m" \+ "$VZ_REPO_ROOT/vz/host/VZProgressViewController.m" \+ "$VZ_REPO_ROOT/vz/host/VZSettingsViewController.m" \+ "$VZ_REPO_ROOT/vz/host/VZVMLibraryViewController.m" \+ "$VZ_REPO_ROOT/vz/host/VirtualMacApp.m" \+ -o "$BIN"+xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -fblocks -Wl,-undefined,dynamic_lookup \+ -install_name "@executable_path/VZHostCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/vzxpchook.m" \+ -o "$HOOK"++xattr -cr "$APP"+ldid -S"$ENTS" "$BIN"+ldid -S"$ENTS" "$HOOK"+echo "native iPad VM app built: $APP"diff --git a/VirtualMac/scripts/build-ipad-deb.sh b/VirtualMac/scripts/build-ipad-deb.shnew file mode 100755index 0000000..29deade--- /dev/null+++ b/VirtualMac/scripts/build-ipad-deb.sh@@ -0,0 +1,129 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++need_command ditto+need_command dpkg-deb+need_command file+need_command ldid+need_command rsync+need_command xattr++if [[ "${VZ_SKIP_REBUILD:-0}" != 1 ]]; then+ "$SCRIPT_DIR/build-ipad-vm.sh"+ "$SCRIPT_DIR/build-ipad-network-helpers.sh"+ "$SCRIPT_DIR/build-ipad-network-sharing.sh"+ "$SCRIPT_DIR/build-ipad-installation.sh"+ "$SCRIPT_DIR/build-ipad-app.sh"+ "$SCRIPT_DIR/build-springboard-tweak.sh"+fi+"$SCRIPT_DIR/audit-ipados-compatibility.sh"++commit_count="$(git -C "$VZ_REPO_ROOT" rev-list --count HEAD)"+commit_hash="$(git -C "$VZ_REPO_ROOT" rev-parse --short=10 HEAD)"+RELEASE_VERSION="${VZ_RELEASE_VERSION:-1.0}"+if [[ -n "${VZ_PACKAGE_VERSION:-}" ]]; then+ VERSION="$VZ_PACKAGE_VERSION"+else+ # Epoch 1 supersedes the early hash-only development packages. Commit+ # count supplies monotonic Debian ordering; the hash keeps provenance.+ VERSION="1:${RELEASE_VERSION}+git${commit_count}.${commit_hash}"+fi+PACKAGE_NAME="VirtualMac_${RELEASE_VERSION}_${commit_hash}.deb"+RELEASE="$VZ_BUILD_ROOT/release"+STAGE="$(mktemp -d -t VirtualMac-deb.XXXXXX)"+trap 'rm -rf "$STAGE"' EXIT++# mktemp intentionally creates a private 0700 directory. A package archive+# must not carry that mode on its `./` entry: dpkg may otherwise try to apply+# it to the filesystem root while unpacking. All payload parents are public+# system directories, so normalize the staging root before creating them.+chmod 755 "$STAGE"++mkdir -p \+ "$STAGE/DEBIAN" \+ "$STAGE/var/root/VirtualMac" \+ "$STAGE/var/jb/Applications" \+ "$STAGE/var/jb/Library/LaunchDaemons" \+ "$STAGE/var/jb/basebin/LaunchDaemons" \+ "$STAGE/var/jb/Library/MobileSubstrate/DynamicLibraries" \+ "$STAGE/var/jb/usr/lib" \+ "$STAGE/var/jb/usr/libexec" \+ "$STAGE/var/jb/usr/sbin" \+ "$STAGE/var/jb/usr/share/VirtualMac" \+ "$RELEASE"++ditto "$VZ_BUILD_ROOT/ipad-vm/payload" \+ "$STAGE/var/root/VirtualMac/payload"+ditto "$VZ_BUILD_ROOT/ipad-installation/payload" \+ "$STAGE/var/root/VirtualMac/payload"+ditto "$VZ_BUILD_ROOT/ipad-installation/install" \+ "$STAGE/var/root/VirtualMac/install"+ditto "$VZ_BUILD_ROOT/ipad-app/VirtualMac.app" \+ "$STAGE/var/jb/Applications/VirtualMac.app"++# The component builds retain command-line probes for developer iteration.+# They are not used by the app and do not belong in the end-user package.+rm -rf "$STAGE/var/root/VirtualMac/payload/bin"+rm -f \+ "$STAGE/var/root/VirtualMac/payload/trustcache.txt" \+ "$STAGE/var/root/VirtualMac/install/restore-image-probe" \+ "$STAGE/var/root/VirtualMac/install/usb-bridge-probe"++install -m 755 "$VZ_BUILD_ROOT/ipad-network-sharing/InternetSharing" \+ "$STAGE/var/jb/usr/libexec/InternetSharing"+install -m 755 "$VZ_BUILD_ROOT/ipad-network-sharing/AuthorizationCompat.dylib" \+ "$STAGE/var/jb/usr/lib/AuthorizationCompat.dylib"+install -m 755 "$VZ_BUILD_ROOT/ipad-network-helpers/bootpd" \+ "$STAGE/var/jb/usr/libexec/bootpd"+install -m 755 "$VZ_BUILD_ROOT/ipad-network-helpers/rtadvd" \+ "$STAGE/var/jb/usr/sbin/rtadvd"+install -m 755 "$VZ_BUILD_ROOT/ipad-network-helpers/OpenDirectoryCompat.dylib" \+ "$STAGE/var/jb/usr/lib/OpenDirectoryCompat.dylib"+install -m 644 "$VZ_BUILD_ROOT/ipad-network-helpers/com.apple.bootpd.plist" \+ "$STAGE/var/jb/Library/LaunchDaemons/com.apple.bootpd.plist"+# This is an intentional mirror, not a second runtime payload: postinst uses+# Library/LaunchDaemons for the immediate user-domain bootstrap, while+# Dopamine's launchd hook discovers basebin/LaunchDaemons across a userspace+# reboot. Both entries must describe the same daemon.+for destination in \+ "$STAGE/var/jb/Library/LaunchDaemons/com.apple.NetworkSharing.plist" \+ "$STAGE/var/jb/basebin/LaunchDaemons/com.apple.NetworkSharing.plist"; do+ install -m 644 "$VZ_BUILD_ROOT/ipad-network-sharing/com.apple.NetworkSharing.plist" \+ "$destination"+done+install -m 755 "$VZ_BUILD_ROOT/ipad-tweak/VZKeyboardPassthrough.dylib" \+ "$STAGE/var/jb/Library/MobileSubstrate/DynamicLibraries/VZKeyboardPassthrough.dylib"+install -m 644 "$VZ_BUILD_ROOT/ipad-tweak/VZKeyboardPassthrough.plist" \+ "$STAGE/var/jb/Library/MobileSubstrate/DynamicLibraries/VZKeyboardPassthrough.plist"++# Never package host filesystem metadata. Component builders also remove it+# before signing, but this catches metadata from every independently built+# app, XPC, framework, and packaging input.+find "$STAGE" -type f \( -name .DS_Store -o -name '._*' \) -delete+xattr -cr "$STAGE"++trustcache="$STAGE/var/jb/usr/share/VirtualMac/trustcache.txt"+: >"$trustcache"+while IFS= read -r -d '' candidate; do+ file "$candidate" | grep -q 'Mach-O' || continue+ hash="$(ldid -h "$candidate" | sed -n 's/^CDHash=//p')"+ [[ -n "$hash" ]] || die "could not read CDHash: $candidate"+ printf '%s\t/%s\n' "$hash" "${candidate#"$STAGE/"}" >>"$trustcache"+done < <(find "$STAGE" -type f -print0)++rsync -a "$VZ_REPO_ROOT/packaging/DEBIAN/" "$STAGE/DEBIAN/"+chmod 755 "$STAGE/DEBIAN/preinst" "$STAGE/DEBIAN/postinst" \+ "$STAGE/DEBIAN/prerm" "$STAGE/DEBIAN/postrm"+chmod 4755 "$STAGE/var/root/VirtualMac/install/install-launcher"+"$SCRIPT_DIR/audit-ipad-package-stage.sh" "$STAGE"+installed_size="$(du -sk "$STAGE" | awk '{print $1}')"+sed -i '' -e "s/@VERSION@/$VERSION/g" \+ -e "s/@INSTALLED_SIZE@/$installed_size/g" "$STAGE/DEBIAN/control"++dpkg-deb --root-owner-group --build "$STAGE" "$RELEASE/$PACKAGE_NAME"+dpkg-deb --info "$RELEASE/$PACKAGE_NAME"+echo "standalone package built: $RELEASE/$PACKAGE_NAME"diff --git a/VirtualMac/scripts/build-ipad-installation.sh b/VirtualMac/scripts/build-ipad-installation.shnew file mode 100755index 0000000..5c204a9--- /dev/null+++ b/VirtualMac/scripts/build-ipad-installation.sh@@ -0,0 +1,451 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+SOURCE_VZ="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/System/Library/Frameworks/Virtualization.framework/Versions/A"+SOURCE_XPC="$SOURCE_VZ/XPCServices/com.apple.Virtualization.Installation.xpc"+OUT="$VZ_BUILD_ROOT/ipad-installation"+PAYLOAD="$OUT/payload"+VMM_COMPAT_SOURCE="$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/LaunchServicesCompat.dylib"+VMM_COMPAT="$PAYLOAD/Frameworks/LaunchServicesCompat.dylib"+INSTALL_ROOT="$OUT/install"+XPC="$PAYLOAD/Installation.xpc"+INSTALLER="$XPC/Contents/MacOS/com.apple.Virtualization.Installation"+XPC_FRAMEWORKS="$XPC/Contents/Frameworks"+COMPAT="$XPC_FRAMEWORKS/InstallationCompat.dylib"+MOBILE_DEVICE_FRAMEWORK="$XPC_FRAMEWORKS/MobileDevice.framework"+MOBILE_DEVICE="$MOBILE_DEVICE_FRAMEWORK/Versions/A/MobileDevice"+USBMUXD="$MOBILE_DEVICE_FRAMEWORK/Versions/A/Resources/usbmuxd"+CRYPTO="$XPC_FRAMEWORKS/crypto.dylib"+SSL="$XPC_FRAMEWORKS/ssl.dylib"+TRUST_EVALUATION_FRAMEWORK="$XPC_FRAMEWORKS/TrustEvaluationAgent.framework"+TRUST_EVALUATION="$TRUST_EVALUATION_FRAMEWORK/TrustEvaluationAgent"+COREUTILS_COMPAT="$XPC_FRAMEWORKS/CoreUtilsCompat.dylib"+CRASHREPORTER_COMPAT="$XPC_FRAMEWORKS/CrashReporterCompat.dylib"+DISKIMAGES_COMPAT="$XPC_FRAMEWORKS/DiskImagesCompat.dylib"+CORESERVICES_COMPAT="$XPC_FRAMEWORKS/CoreServicesCompat.dylib"+SECURITY_COMPAT="$XPC_FRAMEWORKS/SecurityCompat.dylib"+HOST_HOOK="$INSTALL_ROOT/VZHostCompat.dylib"+PROBE="$INSTALL_ROOT/restore-image-probe"+INSTALL_TOOL="$INSTALL_ROOT/install-macos"+USB_BRIDGE_PROBE="$INSTALL_ROOT/usb-bridge-probe"+INSTALL_LAUNCHER="$INSTALL_ROOT/install-launcher"+ENTS="$VZ_REPO_ROOT/vz/patches/installation.ents.xml"+HOST_ENTS="$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements"+DA_TBD="$VZ_REPO_ROOT/vz/host/DiskArbitration-iOS.tbd"+COREUTILS_TBD="$VZ_REPO_ROOT/vz/host/CoreUtils-iOS.tbd"+DISKIMAGES_TBD="$VZ_REPO_ROOT/vz/host/DiskImages-iOS.tbd"+SECURITY_TBD="$VZ_REPO_ROOT/vz/host/Security-iOS.tbd"+DEVICE_SUPPORT_ROOT="$VZ_BUILD_ROOT/analysis/device-support-27/expanded/Payload"+SOURCE_MOBILE_DEVICE="$DEVICE_SUPPORT_ROOT/System/Library/PrivateFrameworks/MobileDevice.framework"+DSC="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/dyld_shared_cache_arm64e"+PYTHON="$VZ_BUILD_ROOT/toolchain/venv/bin/python3"+DYLDEX="$VZ_BUILD_ROOT/toolchain/venv/bin/dyldex"+IPSW_TOOL="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+CACHE="$VZ_BUILD_ROOT/cache/device-support-runtime"++need_command codesign+need_command ditto+need_command dwarfdump+need_command install_name_tool+need_command ldid+need_command lipo+need_command otool+need_command plutil+need_command shasum+need_command xcrun+"$SCRIPT_DIR/analyze-device-support.sh" >/dev/null+need_file "$SOURCE_XPC/Contents/MacOS/com.apple.Virtualization.Installation"+need_file "$SOURCE_MOBILE_DEVICE/Versions/A/MobileDevice"+need_file "$SOURCE_MOBILE_DEVICE/Versions/A/Resources/usbmuxd"+need_file "$DSC"+need_file "$DSC.01"+need_file "$PYTHON"+need_file "$DYLDEX"+need_file "$IPSW_TOOL"+need_file "$VZ_REPO_ROOT/vz/host/installationhook.m"+need_file "$VZ_REPO_ROOT/vz/host/installation_usb_shim.m"+need_file "$VZ_REPO_ROOT/vz/host/NSViewShim.m"+need_file "$VZ_REPO_ROOT/vz/host/vzxpchook.m"+need_file "$VZ_REPO_ROOT/vz/development/probes/restore_image_probe.m"+need_file "$VZ_REPO_ROOT/vz/install/install_macos.m"+need_file "$VZ_REPO_ROOT/vz/install/start-install.sh"+need_file "$VZ_REPO_ROOT/vz/install/install_launcher.c"+need_file "$VZ_REPO_ROOT/vz/development/probes/usb_bridge_probe.c"+need_file "$VZ_REPO_ROOT/vz/stamp_ios.py"+need_file "$VZ_REPO_ROOT/vz/uncache.py"+need_file "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py"+need_file "$ENTS"+need_file "$HOST_ENTS"+need_file "$DA_TBD"+need_file "$COREUTILS_TBD"+need_file "$DISKIMAGES_TBD"+need_file "$SECURITY_TBD"+need_file "$VZ_REPO_ROOT/vz/host/coreutils_compat.c"+need_file "$VZ_REPO_ROOT/vz/host/crashreporter_compat.c"+need_file "$VZ_REPO_ROOT/vz/host/diskimages_compat.c"+need_file "$VZ_REPO_ROOT/vz/host/coreservices_compat.c"+need_file "$VZ_REPO_ROOT/vz/host/security_compat.c"++# Installation launches the same VirtualMachine.xpc used by ordinary boots.+# Rebuild and package its compatibility library too so USB-controller bridge+# changes are never accidentally tested against a stale iPad deployment.+"$SCRIPT_DIR/build-vmm-compat.sh" >/dev/null+need_file "$VMM_COMPAT_SOURCE"++rm -rf "$OUT"+mkdir -p "$PAYLOAD" "$INSTALL_ROOT" "$CACHE"+cp "$VZ_REPO_ROOT/vz/install/start-install.sh" \+ "$INSTALL_ROOT/"+chmod 755 "$INSTALL_ROOT/start-install.sh"+mkdir -p "$(dirname "$VMM_COMPAT")"+ditto "$VMM_COMPAT_SOURCE" "$VMM_COMPAT"+ditto "$SOURCE_XPC" "$XPC"+rm -rf "$XPC/Contents/_CodeSignature"+mkdir -p "$XPC_FRAMEWORKS"++lipo -thin arm64e \+ "$SOURCE_XPC/Contents/MacOS/com.apple.Virtualization.Installation" \+ -output "$INSTALLER.macos"+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VZ_REPO_ROOT/vz/stamp_ios.py" \+ "$INSTALLER.macos" "$INSTALLER" 16.0+rm -f "$INSTALLER.macos"++# Installation.xpc soft-loads the installed DeviceSupport MobileDevice. Keep+# that contract but point both Ventura search paths at the framework embedded+# beside this helper.+"$PYTHON" "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py" \+ "$INSTALLER" \+ softlink:r:path:/System/Library/PrivateFrameworks/MobileDevice.framework/MobileDevice \+ softlink:r:path:@loader_path/../Frameworks/MobileDevice.framework/MobileDevice \+ 3+"$PYTHON" "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py" \+ "$INSTALLER" \+ /System/Library/PrivateFrameworks/MobileDevice.framework/Contents/MacOS/MobileDevice \+ @loader_path/../Frameworks/MobileDevice.framework/MobileDevice++# MobileDevice 1857 is an ordinary arm64e Mach-O in the supplied+# DeviceSupport package, so it needs no dyld-cache extraction.+mkdir -p "$MOBILE_DEVICE_FRAMEWORK/Versions/A"+lipo -thin arm64e "$SOURCE_MOBILE_DEVICE/Versions/A/MobileDevice" \+ -output "$CACHE/MobileDevice.macos"+"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" \+ "$CACHE/MobileDevice.macos" "$MOBILE_DEVICE" 16.0+if [[ -d "$SOURCE_MOBILE_DEVICE/Versions/A/Resources" ]]; then+ ditto "$SOURCE_MOBILE_DEVICE/Versions/A/Resources" \+ "$MOBILE_DEVICE_FRAMEWORK/Versions/A/Resources"+fi+# DeviceSupport also ships a standalone macOS updater app. Installation.xpc+# needs its matching usbmuxd resources, not an AppKit executable that cannot+# run on iPadOS and would invalidate the payload-wide platform audit.+rm -rf "$MOBILE_DEVICE_FRAMEWORK/Versions/A/Resources/MobileDeviceUpdater.app"+ln -sfn A "$MOBILE_DEVICE_FRAMEWORK/Versions/Current"+ln -sfn Versions/Current/MobileDevice "$MOBILE_DEVICE_FRAMEWORK/MobileDevice"+ln -sfn Versions/Current/Resources "$MOBILE_DEVICE_FRAMEWORK/Resources"++# Run DeviceSupport's genuine host-side usbmuxd beside its matching+# MobileDevice framework. This daemon owns Apple's USBMux wire protocol;+# InstallationCompat supplies only the IORegistry/IOUSBLib façade that routes+# its transfers to VMM's real AVP USB controller.+lipo -thin arm64e "$SOURCE_MOBILE_DEVICE/Versions/A/Resources/usbmuxd" \+ -output "$CACHE/usbmuxd.macos"+"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" \+ "$CACHE/usbmuxd.macos" "$USBMUXD" 16.0+install_name_tool \+ -change /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice \+ @loader_path/../MobileDevice \+ -change /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit \+ /System/Library/Frameworks/IOKit.framework/IOKit \+ -change /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation \+ /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation \+ "$USBMUXD"+"$PYTHON" "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py" \+ "$USBMUXD" /var/run/usbmuxd /tmp/vzusbmuxd++install_name_tool \+ -change /System/Library/PrivateFrameworks/CoreUtils.framework/Versions/A/CoreUtils \+ @loader_path/../../../CoreUtilsCompat.dylib \+ -change /System/Library/PrivateFrameworks/DiskImages2.framework/Versions/A/DiskImages2 \+ /System/Library/PrivateFrameworks/DiskImages2.framework/DiskImages2 \+ -change /System/Library/PrivateFrameworks/RemoteXPC.framework/Versions/A/RemoteXPC \+ /System/Library/PrivateFrameworks/RemoteXPC.framework/RemoteXPC \+ -change /System/Library/PrivateFrameworks/RemoteServiceDiscovery.framework/Versions/A/RemoteServiceDiscovery \+ /System/Library/PrivateFrameworks/RemoteServiceDiscovery.framework/RemoteServiceDiscovery \+ -change /System/Library/PrivateFrameworks/CrashReporterSupport.framework/Versions/A/CrashReporterSupport \+ @loader_path/../../../CrashReporterCompat.dylib \+ -change /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation \+ /System/Library/Frameworks/Foundation.framework/Foundation \+ -change /usr/lib/libcrypto.35.dylib \+ @loader_path/../../../crypto.dylib \+ -change /System/Library/PrivateFrameworks/DiskImages.framework/Versions/A/DiskImages \+ @loader_path/../../../DiskImagesCompat.dylib \+ -change /System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration \+ /System/Library/PrivateFrameworks/DiskArbitration.framework/DiskArbitration \+ -change /System/Library/PrivateFrameworks/Bom.framework/Versions/A/Bom \+ /System/Library/PrivateFrameworks/Bom.framework/Bom \+ -change /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation \+ /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation \+ -change /System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices \+ @loader_path/../../../CoreServicesCompat.dylib \+ -change /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit \+ /System/Library/Frameworks/IOKit.framework/IOKit \+ -change /System/Library/Frameworks/Security.framework/Versions/A/Security \+ @loader_path/../../../SecurityCompat.dylib \+ -change /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration \+ /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration \+ -change /usr/lib/libssl.35.dylib \+ @loader_path/../../../ssl.dylib \+ -change /System/Library/Frameworks/CFNetwork.framework/Versions/A/CFNetwork \+ /System/Library/Frameworks/CFNetwork.framework/CFNetwork \+ "$MOBILE_DEVICE"++# The two OpenSSL libraries expected by MobileDevice are in Ventura's shared+# cache, not in iPadOS or in the DeviceSupport package. Reconstruct only these+# images with the existing arm64e-safe uncache pipeline.+for spec in 'libcrypto.35.dylib|crypto.dylib' \+ 'libssl.35.dylib|ssl.dylib'; do+ IFS='|' read -r library packagedName <<<"$spec"+ image="/usr/lib/$library"+ raw="$CACHE/$library.raw"+ proto="$CACHE/$library.proto"+ output="$XPC_FRAMEWORKS/$packagedName"+ if [[ ! -f "$raw" ]]; then+ "$DYLDEX" -e "$image" -o "$raw" "$DSC"+ fi+ VZ_IPSW="$IPSW_TOOL" "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$image" "$raw" "$proto" compact+ "$PYTHON" "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py" \+ "$proto" \+ /System/Library/PrivateFrameworks/TrustEvaluationAgent.framework/TrustEvaluationAgent \+ @loader_path/TrustEvaluationAgent.framework/TrustEvaluationAgent+ if [[ "$library" == libssl.35.dylib ]]; then+ "$PYTHON" "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py" \+ "$proto" /usr/lib/libcrypto.35.dylib \+ @loader_path/crypto.dylib+ fi+ "$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" \+ "$proto" "$output" 16.0+done++trustImage="TrustEvaluationAgent.framework/Versions/A/TrustEvaluationAgent"+trustRaw="$CACHE/TrustEvaluationAgent.raw"+trustProto="$CACHE/TrustEvaluationAgent.proto"+if [[ ! -f "$trustRaw" ]]; then+ "$DYLDEX" -e "$trustImage" -o "$trustRaw" "$DSC"+fi+VZ_IPSW="$IPSW_TOOL" "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$trustImage" "$trustRaw" "$trustProto" compact+mkdir -p "$TRUST_EVALUATION_FRAMEWORK"+"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" \+ "$trustProto" "$TRUST_EVALUATION" 16.0++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib \+ -Wl,-reexport_library,"$COREUTILS_TBD" \+ -install_name "@rpath/CoreUtilsCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/coreutils_compat.c" \+ -o "$COREUTILS_COMPAT"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib \+ -install_name "@rpath/CrashReporterCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/crashreporter_compat.c" \+ -o "$CRASHREPORTER_COMPAT"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib \+ -Wl,-reexport_library,"$DISKIMAGES_TBD" \+ -install_name "@rpath/DiskImagesCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/diskimages_compat.c" \+ -o "$DISKIMAGES_COMPAT"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib \+ -install_name "@rpath/CoreServicesCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/coreservices_compat.c" \+ -o "$CORESERVICES_COMPAT"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib \+ -Wl,-reexport_library,"$SECURITY_TBD" \+ -install_name "@rpath/SecurityCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/security_compat.c" \+ -o "$SECURITY_COMPAT"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -fblocks -Wl,-undefined,dynamic_lookup \+ -framework CoreFoundation -framework IOKit \+ -Wl,-reexport_library,"$DA_TBD" \+ -install_name "@rpath/InstallationCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/installationhook.m" \+ "$VZ_REPO_ROOT/vz/host/installation_usb_shim.m" \+ -o "$COMPAT"++install_name_tool \+ -change \+ /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation \+ /System/Library/Frameworks/Foundation.framework/Foundation \+ -change \+ /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation \+ /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation \+ -change \+ /System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration \+ @loader_path/../Frameworks/InstallationCompat.dylib \+ -change \+ /System/Library/Frameworks/IOSurface.framework/Versions/A/IOSurface \+ /System/Library/Frameworks/IOSurface.framework/IOSurface \+ -change \+ /System/Library/PrivateFrameworks/DiskImages2.framework/Versions/A/DiskImages2 \+ /System/Library/PrivateFrameworks/DiskImages2.framework/DiskImages2 \+ -change \+ /System/Library/PrivateFrameworks/SoftLinking.framework/Versions/A/SoftLinking \+ /System/Library/PrivateFrameworks/SoftLinking.framework/SoftLinking \+ "$INSTALLER"++INFO="$XPC/Contents/Info.plist"+plutil -replace CFBundleSupportedPlatforms -json '["iPhoneOS"]' "$INFO"+plutil -replace DTPlatformName -string iphoneos "$INFO"+plutil -replace DTPlatformVersion -string 16.0 "$INFO"+plutil -replace DTSDKName -string iphoneos16.0.internal "$INFO"+plutil -remove LSMinimumSystemVersion "$INFO" 2>/dev/null || true+plutil -replace MinimumOSVersion -string 16.0 "$INFO" 2>/dev/null || \+ plutil -insert MinimumOSVersion -string 16.0 "$INFO"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -fblocks -Wl,-undefined,dynamic_lookup \+ -install_name "@rpath/VZHostCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/vzxpchook.m" \+ -o "$HOST_HOOK"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" -fblocks \+ -framework Foundation -framework Metal -framework UIKit \+ -Wl,-export_dynamic \+ "$VZ_REPO_ROOT/vz/host/NSViewShim.m" \+ "$VZ_REPO_ROOT/vz/development/probes/restore_image_probe.m" \+ -o "$PROBE"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" -fblocks \+ -framework Foundation -framework Metal -framework UIKit \+ -Wl,-export_dynamic \+ "$VZ_REPO_ROOT/vz/host/NSViewShim.m" \+ "$VZ_REPO_ROOT/vz/install/install_macos.m" \+ -o "$INSTALL_TOOL"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" \+ "$VZ_REPO_ROOT/vz/development/probes/usb_bridge_probe.c" \+ -o "$USB_BRIDGE_PROBE"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" \+ "$VZ_REPO_ROOT/vz/install/install_launcher.c" \+ -o "$INSTALL_LAUNCHER"++ldid -S"$ENTS" "$INSTALLER"+ldid -S"$ENTS" "$COMPAT"+ldid -S"$ENTS" "$MOBILE_DEVICE"+ldid -S"$ENTS" "$USBMUXD"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime "$CRYPTO"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime "$SSL"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime \+ "$TRUST_EVALUATION"+ldid -S"$ENTS" "$COREUTILS_COMPAT"+ldid -S"$ENTS" "$CRASHREPORTER_COMPAT"+ldid -S"$ENTS" "$DISKIMAGES_COMPAT"+ldid -S"$ENTS" "$CORESERVICES_COMPAT"+ldid -S"$ENTS" "$SECURITY_COMPAT"+ldid -S"$HOST_ENTS" "$HOST_HOOK"+ldid -S"$HOST_ENTS" "$PROBE"+ldid -S"$HOST_ENTS" "$INSTALL_TOOL"+ldid -S "$USB_BRIDGE_PROBE"+ldid -S"$HOST_ENTS" "$INSTALL_LAUNCHER"++"$PYTHON" "$VZ_REPO_ROOT/scripts/audit-entitlements.py" \+ "$ENTS" "$INSTALLER" \+ "$ENTS" "$COMPAT" \+ "$ENTS" "$MOBILE_DEVICE" \+ "$ENTS" "$USBMUXD" \+ "$ENTS" "$COREUTILS_COMPAT" \+ "$ENTS" "$CRASHREPORTER_COMPAT" \+ "$ENTS" "$DISKIMAGES_COMPAT" \+ "$ENTS" "$CORESERVICES_COMPAT" \+ "$ENTS" "$SECURITY_COMPAT" \+ "$HOST_ENTS" "$HOST_HOOK" \+ "$HOST_ENTS" "$PROBE" \+ "$HOST_ENTS" "$INSTALL_TOOL" \+ - "$CRYPTO" \+ - "$SSL" \+ - "$TRUST_EVALUATION" \+ - "$USB_BRIDGE_PROBE" \+ "$HOST_ENTS" "$INSTALL_LAUNCHER"++otool -l "$INSTALLER" |+ awk '/LC_BUILD_VERSION/{show=1; left=7} show && left-- > 0 {print}' |+ grep -q 'platform 2' || die "Installation.xpc is not stamped for iOS"+otool -L "$INSTALLER" | grep -Fq \+ '@loader_path/../Frameworks/InstallationCompat.dylib' ||+ die "Installation.xpc does not load InstallationCompat"+otool -L "$COMPAT" | grep -Fq \+ '/System/Library/PrivateFrameworks/DiskArbitration.framework/DiskArbitration' ||+ die "InstallationCompat does not re-export iPad DiskArbitration"+otool -L "$MOBILE_DEVICE" | grep -Fq \+ '@loader_path/../../../crypto.dylib' ||+ die "MobileDevice does not load bundled libcrypto"+otool -L "$MOBILE_DEVICE" | grep -Fq \+ '@loader_path/../../../ssl.dylib' ||+ die "MobileDevice does not load bundled libssl"+otool -L "$CRYPTO" | grep -Fq \+ '@loader_path/TrustEvaluationAgent.framework/TrustEvaluationAgent' ||+ die "libcrypto does not load bundled TrustEvaluationAgent"+otool -L "$MOBILE_DEVICE" | grep -Fq \+ '@loader_path/../../../CoreUtilsCompat.dylib' ||+ die "MobileDevice does not load CoreUtils compatibility image"+otool -L "$COREUTILS_COMPAT" | grep -Fq \+ '/System/Library/PrivateFrameworks/CoreUtils.framework/CoreUtils' ||+ die "CoreUtils compatibility image does not re-export iPad CoreUtils"+otool -L "$USBMUXD" | grep -Fq '@loader_path/../MobileDevice' ||+ die "usbmuxd does not load bundled MobileDevice"++{+ for file in "$INSTALLER" "$COMPAT" "$MOBILE_DEVICE" "$USBMUXD" \+ "$CRYPTO" "$SSL" "$TRUST_EVALUATION" \+ "$COREUTILS_COMPAT" \+ "$CRASHREPORTER_COMPAT" \+ "$DISKIMAGES_COMPAT" \+ "$CORESERVICES_COMPAT" \+ "$SECURITY_COMPAT" \+ "$VMM_COMPAT" \+ "$HOST_HOOK" "$PROBE" "$INSTALL_TOOL" \+ "$USB_BRIDGE_PROBE" "$INSTALL_LAUNCHER"; do+ printf '%s\t%s\n' \+ "$(ldid -h "$file" | sed -n 's/^CDHash=//p')" \+ "${file#"$OUT"/}"+ done+} >"$OUT/trustcache.txt"++{+ printf 'IPAD_INSTALLATION_MANIFEST\t1\n'+ printf 'generated_utc\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ printf 'repository_commit\t%s\n' "$(git -C "$VZ_REPO_ROOT" rev-parse HEAD)"+ printf 'source_installer_sha256\t%s\n' "$(shasum -a 256 "$SOURCE_XPC/Contents/MacOS/com.apple.Virtualization.Installation" | awk '{print $1}')"+ printf 'source_installer_uuid\t%s\n' "$(dwarfdump --uuid "$SOURCE_XPC/Contents/MacOS/com.apple.Virtualization.Installation" | awk '/arm64e/{print $2}')"+ printf 'installer_sha256\t%s\n' "$(shasum -a 256 "$INSTALLER" | awk '{print $1}')"+ printf 'installer_uuid\t%s\n' "$(dwarfdump --uuid "$INSTALLER" | awk '{print $2}')"+ printf 'mobile_device_version\t1857\n'+ printf 'mobile_device_sha256\t%s\n' "$(shasum -a 256 "$MOBILE_DEVICE" | awk '{print $1}')"+} >"$OUT/manifest.txt"++echo "iPad installation payload built: $OUT"diff --git a/VirtualMac/scripts/build-ipad-netrb.sh b/VirtualMac/scripts/build-ipad-netrb.shnew file mode 100755index 0000000..632ace3--- /dev/null+++ b/VirtualMac/scripts/build-ipad-netrb.sh@@ -0,0 +1,45 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++DSC="${VZ_MACOS_DSC:-$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/dyld_shared_cache_arm64e}"+OUT="$VZ_BUILD_ROOT/ipad-netrb/Netrb.framework"+RAW="$VZ_BUILD_ROOT/ipad-netrb/Netrb.macos.raw"+PROTO="$VZ_BUILD_ROOT/ipad-netrb/Netrb.proto"+BIN="$OUT/Netrb"+PYTHON="$VZ_BUILD_ROOT/toolchain/venv/bin/python3"+DYLDEX="$VZ_BUILD_ROOT/toolchain/venv/bin/dyldex"+IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+PATCH="$VZ_REPO_ROOT/vz/patches/patch_netrb_lookup.py"+ENTITLEMENT_AUDIT="$VZ_REPO_ROOT/scripts/audit-entitlements.py"+IMAGE="Netrb.framework/Versions/A/Netrb"++need_command codesign+need_file "$DSC"+need_file "$DSC.01"+need_file "$PYTHON"+need_file "$DYLDEX"+need_file "$IPSW"+need_file "$PATCH"+need_file "$ENTITLEMENT_AUDIT"+need_file "$VZ_REPO_ROOT/vz/stamp_ios.py"+mkdir -p "$OUT" "$(dirname "$RAW")"++if [[ ! -f "$RAW" ]]; then+ "$DYLDEX" -e "$IMAGE" -o "$RAW" "$DSC"+fi+VZ_IPSW="$IPSW" "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$IMAGE" "$RAW" "$PROTO" compact+"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" "$PROTO" "$BIN" 16.0+"$PYTHON" "$PATCH" "$BIN"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime "$BIN"+codesign --verify "$BIN"+"$PYTHON" "$ENTITLEMENT_AUDIT" - "$BIN"+otool -l "$BIN" |+ awk '/LC_BUILD_VERSION/{show=1; left=7} show && left-- > 0 {print}' |+ grep -q "platform 2" || die "Netrb is not stamped for iOS"+echo "iPad Netrb framework built from matching macOS 13.2.1 DSC: $OUT"diff --git a/VirtualMac/scripts/build-ipad-network-helpers.sh b/VirtualMac/scripts/build-ipad-network-helpers.shnew file mode 100755index 0000000..989bcb4--- /dev/null+++ b/VirtualMac/scripts/build-ipad-network-helpers.sh@@ -0,0 +1,91 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SOURCE_ROOT="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS"+SOURCE_BOOTPD="$SOURCE_ROOT/usr/libexec/bootpd"+SOURCE_RTADVD="$SOURCE_ROOT/usr/sbin/rtadvd"+SOURCE_BOOTPD_PLIST="$SOURCE_ROOT/System/Library/LaunchDaemons/bootps.plist"+ENTS="$VZ_REPO_ROOT/vz/patches/network-helper.ents.xml"+COMPAT_PATCH="$VZ_REPO_ROOT/vz/patches/patch_network_helper.py"+OUT="$VZ_BUILD_ROOT/ipad-network-helpers"+BOOTPD="$OUT/bootpd"+RTADVD="$OUT/rtadvd"+OD_COMPAT="$OUT/OpenDirectoryCompat.dylib"+BOOTPD_PLIST="$OUT/com.apple.bootpd.plist"++need_command codesign+need_command install_name_tool+need_command ldid+need_command lipo+need_command plutil+need_file "$SOURCE_BOOTPD"+need_file "$SOURCE_RTADVD"+need_file "$SOURCE_BOOTPD_PLIST"+need_file "$ENTS"+need_file "$COMPAT_PATCH"++rm -rf "$OUT"+mkdir -p "$OUT"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$(xcrun --sdk iphoneos --show-sdk-path)" \+ -dynamiclib -framework CoreFoundation \+ -install_name @loader_path/../lib/OpenDirectoryCompat.dylib \+ "$VZ_REPO_ROOT/vz/host/open_directory_compat.c" \+ -o "$OD_COMPAT"+codesign --force --sign - "$OD_COMPAT"++for source in "$SOURCE_BOOTPD" "$SOURCE_RTADVD"; do+ name="$(basename "$source")"+ lipo -thin arm64e "$source" -output "$OUT/$name.macos"+done++install_name_tool \+ -change /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation \+ /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation \+ -change /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration \+ /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration \+ -change /System/Library/Frameworks/OpenDirectory.framework/Versions/A/OpenDirectory \+ @loader_path/../lib/OpenDirectoryCompat.dylib \+ -change /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit \+ /System/Library/Frameworks/IOKit.framework/IOKit \+ "$OUT/bootpd.macos"++for name in bootpd rtadvd; do+ "$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VZ_REPO_ROOT/vz/stamp_ios.py" "$OUT/$name.macos" "$OUT/$name" 16.0+ codesign --force --sign - --entitlements "$ENTS" \+ --generate-entitlement-der "$OUT/$name"+ codesign --verify --strict "$OUT/$name"+ rm "$OUT/$name.macos"+done++"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" "$COMPAT_PATCH" "$BOOTPD"+codesign --force --sign - --entitlements "$ENTS" \+ --generate-entitlement-der "$BOOTPD"+codesign --verify --strict "$BOOTPD"+codesign --verify --strict "$OD_COMPAT"+python3 "$VZ_REPO_ROOT/scripts/audit-entitlements.py" \+ "$ENTS" "$BOOTPD" \+ "$ENTS" "$RTADVD" \+ - "$OD_COMPAT"++cp "$SOURCE_BOOTPD_PLIST" "$BOOTPD_PLIST"+plutil -replace Label -string vzi.apple.bootpd "$BOOTPD_PLIST"+plutil -replace ProgramArguments -json \+ '["/var/jb/usr/libexec/bootpd"]' "$BOOTPD_PLIST"+plutil -insert Program -string /var/jb/usr/libexec/bootpd "$BOOTPD_PLIST"+plutil -replace Disabled -bool NO "$BOOTPD_PLIST"+plutil -insert UserName -string root "$BOOTPD_PLIST"+plutil -insert POSIXSpawnType -string Interactive "$BOOTPD_PLIST"+plutil -insert ProcessType -string Interactive "$BOOTPD_PLIST"+plutil -insert ExecuteAllowed -bool YES "$BOOTPD_PLIST"+plutil -insert StandardOutPath -string /tmp/bootpd.out "$BOOTPD_PLIST"+plutil -insert StandardErrorPath -string /tmp/bootpd.err "$BOOTPD_PLIST"+plutil -lint "$BOOTPD_PLIST"++echo "iPad NetworkSharing helpers built: $OUT"diff --git a/VirtualMac/scripts/build-ipad-network-sharing.sh b/VirtualMac/scripts/build-ipad-network-sharing.shnew file mode 100755index 0000000..4fd60b3--- /dev/null+++ b/VirtualMac/scripts/build-ipad-network-sharing.sh@@ -0,0 +1,100 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SOURCE_ROOT="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS"+SOURCE_BIN="$SOURCE_ROOT/usr/libexec/InternetSharing"+SOURCE_PLIST="$SOURCE_ROOT/System/Library/LaunchDaemons/com.apple.NetworkSharing.plist"+ENTS="$VZ_REPO_ROOT/vz/patches/internet-sharing.ents.xml"+COMPAT_PATCH="$VZ_REPO_ROOT/vz/patches/patch_internet_sharing.py"+OUT="$VZ_BUILD_ROOT/ipad-network-sharing"+BIN="$OUT/InternetSharing"+PLIST="$OUT/com.apple.NetworkSharing.plist"+AUTH_COMPAT="$OUT/AuthorizationCompat.dylib"+SDK="$(xcrun --sdk iphoneos --show-sdk-path)"++need_command codesign+need_command ldid+need_command install_name_tool+need_command lipo+need_command plutil+need_command xcrun+need_file "$SOURCE_BIN"+need_file "$SOURCE_PLIST"+need_file "$ENTS"+need_file "$COMPAT_PATCH"++rm -rf "$OUT"+mkdir -p "$OUT"+lipo -thin arm64e "$SOURCE_BIN" -output "$BIN.macos"++xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -framework CoreFoundation -framework Security \+ -Wl,-reexport_framework,Security \+ -Wl,-undefined,dynamic_lookup \+ -install_name @rpath/AuthorizationCompat.dylib \+ "$VZ_REPO_ROOT/vz/host/authorization_compat.c" \+ -o "$AUTH_COMPAT"++install_name_tool \+ -change /System/Library/PrivateFrameworks/PacketFilter.framework/Versions/A/PacketFilter \+ /System/Library/PrivateFrameworks/PacketFilter.framework/PacketFilter \+ -change /System/Library/Frameworks/Security.framework/Versions/A/Security \+ @loader_path/../lib/AuthorizationCompat.dylib \+ -change /System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement \+ /System/Library/PrivateFrameworks/ServiceManagement.framework/ServiceManagement \+ -change /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation \+ /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation \+ -change /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation \+ /System/Library/Frameworks/Foundation.framework/Foundation \+ -change /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration \+ /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration \+ -change /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit \+ /System/Library/Frameworks/IOKit.framework/IOKit \+ "$BIN.macos"++"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VZ_REPO_ROOT/vz/stamp_ios.py" "$BIN.macos" "$BIN" 16.0+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" "$COMPAT_PATCH" "$BIN"+# Use Apple's signer so the entitlements are encoded in both the XML and DER+# slots consumed by iOS 16 AMFI, with a valid modern ad-hoc CodeDirectory.+codesign --force --sign - --entitlements "$ENTS" \+ --generate-entitlement-der "$BIN"+ldid -S "$AUTH_COMPAT"+rm "$BIN.macos"++cp "$SOURCE_PLIST" "$PLIST"+plutil -remove ProgramArguments "$PLIST"+plutil -insert ProgramArguments -json \+ '["/var/jb/usr/libexec/InternetSharing"]' "$PLIST"+plutil -insert Program -string /var/jb/usr/libexec/InternetSharing "$PLIST"+plutil -insert UserName -string root "$PLIST"+plutil -insert POSIXSpawnType -string Interactive "$PLIST"+plutil -insert ProcessType -string Interactive "$PLIST"+plutil -insert ExecuteAllowed -bool YES "$PLIST"+if [[ "${VZ_NETWORK_SHARING_DOMAIN:-user/501}" == system ]]; then+ plutil -insert LimitLoadToSessionType -string System "$PLIST"+fi+plutil -insert JetsamProperties -json \+ '{"JetsamMemoryLimit":131072,"JetsamPriority":40}' "$PLIST"+plutil -insert StandardOutPath -string /tmp/InternetSharing.out "$PLIST"+plutil -insert StandardErrorPath -string /tmp/InternetSharing.err "$PLIST"+if [[ "${VZ_NETWORK_SHARING_WAIT_FOR_DEBUGGER:-0}" == 1 ]]; then+ plutil -insert WaitForDebugger -bool YES "$PLIST"+fi+plutil -lint "$PLIST"++otool -L "$BIN" | grep -Fq \+ /System/Library/PrivateFrameworks/ServiceManagement.framework/ServiceManagement+ldid -h "$BIN" >/dev/null+ldid -h "$AUTH_COMPAT" >/dev/null+codesign --verify --strict "$BIN"+python3 "$VZ_REPO_ROOT/scripts/audit-entitlements.py" \+ "$ENTS" "$BIN" \+ - "$AUTH_COMPAT"+"$SCRIPT_DIR/build-ipad-network-helpers.sh"+echo "iPad NetworkSharing daemon built: $OUT"diff --git a/VirtualMac/scripts/build-ipad-videotoolbox.sh b/VirtualMac/scripts/build-ipad-videotoolbox.shnew file mode 100755index 0000000..3d8e6aa--- /dev/null+++ b/VirtualMac/scripts/build-ipad-videotoolbox.sh@@ -0,0 +1,59 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++DSC="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/dyld_shared_cache_arm64e"+IMAGE="VideoToolbox.framework/Versions/A/VideoToolbox"+EXPECTED_UUID="3CDCD75D-0D43-3B00-8F86-8F3DCED33F5D"+PYTHON="$VZ_BUILD_ROOT/toolchain/venv/bin/python3"+DYLDEX="$VZ_BUILD_ROOT/toolchain/venv/bin/dyldex"+IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+OUT="$VZ_BUILD_ROOT/ipad-videotoolbox"+RAW="$OUT/VideoToolbox.raw"+PROTO="$OUT/VideoToolbox.proto"+FRAMEWORK="$OUT/VideoToolbox.framework"+BIN="$FRAMEWORK/VideoToolbox"++need_file "$DSC"+need_file "$DSC.01"+need_file "$PYTHON"+need_file "$DYLDEX"+need_file "$IPSW"+need_command codesign+need_command dyld_info+need_command dwarfdump+need_command otool+mkdir -p "$OUT" "$FRAMEWORK"++if [[ ! -f "$RAW" ]]; then+ "$DYLDEX" -e "$IMAGE" -o "$RAW" "$DSC"+fi++VZ_IPSW="$IPSW" VZ_WEAKEN=AppleVA \+ "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$IMAGE" "$RAW" "$PROTO" compact+"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" "$PROTO" "$BIN" 16.0+chmod 755 "$BIN"++uuid="$(dwarfdump --uuid "$BIN" | awk '{print $2}')"+[[ "$uuid" == "$EXPECTED_UUID" ]] ||+ die "VideoToolbox UUID mismatch: expected $EXPECTED_UUID, got $uuid"+codesign --verify "$BIN"+otool -l "$BIN" >"$OUT/load-commands.txt"+grep -A5 LC_LOAD_WEAK_DYLIB "$OUT/load-commands.txt" |+ grep -F /System/Library/PrivateFrameworks/AppleVA.framework/AppleVA \+ >/dev/null ||+ die "VideoToolbox AppleVA dependency is not weak"+dyld_info -exports "$BIN" >"$OUT/exports.txt"+for symbol in \+ _VTParavirtualizationHostSessionCreate \+ _VTParavirtualizationHostSessionDeliverMessageFromGuest \+ _VTParavirtualizationHostSessionInvalidate; do+ grep -F "$symbol" "$OUT/exports.txt" >/dev/null ||+ die "VideoToolbox is missing export: $symbol"+done++echo "matching Ventura VideoToolbox host endpoint built: $FRAMEWORK"diff --git a/VirtualMac/scripts/build-ipad-vm.sh b/VirtualMac/scripts/build-ipad-vm.shnew file mode 100755index 0000000..e566351--- /dev/null+++ b/VirtualMac/scripts/build-ipad-vm.sh@@ -0,0 +1,325 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/ipad-vm"+PAYLOAD="$OUT/payload"+BIN="$PAYLOAD/bin"+FRAMEWORKS="$PAYLOAD/Frameworks"+VMM="$PAYLOAD/VirtualMachine.xpc"+VMM_BIN="$VMM/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+# The host and VMM are separate processes, but dyld can load both from this+# shared runtime directory. Keep XPC-private compatibility dylibs here too so+# the package has one authoritative framework location.+VMM_FRAMEWORKS="$FRAMEWORKS"+SOURCE_VZ="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/System/Library/Frameworks/Virtualization.framework/Versions/A"+SOURCE_VMM="$SOURCE_VZ/XPCServices/com.apple.Virtualization.VirtualMachine.xpc"+IOS_FRAMEWORKS="$VZ_BUILD_ROOT/frameworks/bundles/ios"+ENTS="$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements"+VMM_ENTS="$VZ_REPO_ROOT/vz/patches/vmm.ents.xml"+VMM_OPTIONAL_DEVICES_PATCH="$VZ_REPO_ROOT/vz/patches/patch_vmm_optional_devices.py"+VMM_PCI_ADDRESS_PATCH="$VZ_REPO_ROOT/vz/patches/patch_vmm_pci_address.py"+PVG_EXCEPTION_LOG_PATCH="$VZ_REPO_ROOT/vz/patches/patch_pvg_exception_log.py"+MACHO_CSTRING_PATCH="$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py"+METAL_SERIALIZER_FRAMEWORK="$IOS_FRAMEWORKS/MetalSerializer.framework"+VMNET_FRAMEWORK="$VZ_BUILD_ROOT/ipad-vmnet/vmnet.framework"+NETRB_FRAMEWORK="$VZ_BUILD_ROOT/ipad-netrb/Netrb.framework"+VIDEOTOOLBOX_FRAMEWORK="$VZ_BUILD_ROOT/ipad-videotoolbox/VideoToolbox.framework"+ENTITLEMENT_AUDIT="$VZ_REPO_ROOT/scripts/audit-entitlements.py"++need_command codesign+need_command ditto+need_command install_name_tool+need_command ldid+need_command lipo+need_command otool+need_command xcrun+need_file "$SOURCE_VMM/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+need_file "$SOURCE_VZ/Resources/AVPBooter.vmapple2.bin"+need_file "$ENTS"+need_file "$VMM_ENTS"+need_file "$VMM_OPTIONAL_DEVICES_PATCH"+need_file "$VMM_PCI_ADDRESS_PATCH"+need_file "$PVG_EXCEPTION_LOG_PATCH"+need_file "$MACHO_CSTRING_PATCH"+need_file "$ENTITLEMENT_AUDIT"+need_file "$METAL_SERIALIZER_FRAMEWORK/Versions/A/MetalSerializer"+need_file "$VZ_REPO_ROOT/vz/host/pvg_trace.m"+need_file "$VZ_REPO_ROOT/vz/shaders/pvg_display.metal"+for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ need_file "$IOS_FRAMEWORKS/$name.framework/Versions/A/$name"+done++"$SCRIPT_DIR/build-ipad-vmnet.sh"+"$SCRIPT_DIR/build-ipad-netrb.sh"+"$SCRIPT_DIR/build-ipad-videotoolbox.sh"+need_file "$VMNET_FRAMEWORK/vmnet"+need_file "$NETRB_FRAMEWORK/Netrb"+need_file "$VIDEOTOOLBOX_FRAMEWORK/VideoToolbox"++rm -rf "$PAYLOAD"+mkdir -p "$BIN" "$FRAMEWORKS"+for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ ditto "$IOS_FRAMEWORKS/$name.framework" \+ "$FRAMEWORKS/$name.framework"+done+ditto "$VMNET_FRAMEWORK" "$FRAMEWORKS/vmnet.framework"+HOST_VZ_BINARY="$FRAMEWORKS/Virtualization.framework/Versions/A/Virtualization"+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$MACHO_CSTRING_PATCH" "$HOST_VZ_BINARY" \+ /System/Library/Frameworks/vmnet.framework/vmnet \+ @loader_path/../../../vmnet.framework/vmnet+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime \+ "$FRAMEWORKS/Virtualization.framework"+ditto "$SOURCE_VMM" "$VMM"+rm -rf "$VMM/Contents/_CodeSignature" "$VMM/Contents/Frameworks"+/usr/libexec/PlistBuddy -c \+ "Add :NSMicrophoneUsageDescription string Virtual Mac microphone input" \+ "$VMM/Contents/Info.plist" 2>/dev/null || \+ /usr/libexec/PlistBuddy -c \+ "Set :NSMicrophoneUsageDescription Virtual Mac microphone input" \+ "$VMM/Contents/Info.plist"+mkdir -p "$VMM_FRAMEWORKS"+lipo -thin arm64e \+ "$SOURCE_VMM/Contents/MacOS/com.apple.Virtualization.VirtualMachine" \+ -output "$VMM_BIN"+ditto "$NETRB_FRAMEWORK" "$VMM_FRAMEWORKS/Netrb.framework"+ditto "$VIDEOTOOLBOX_FRAMEWORK" \+ "$VMM_FRAMEWORKS/VideoToolbox.framework"+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$MACHO_CSTRING_PATCH" \+ "$VMM_FRAMEWORKS/vmnet.framework/vmnet" \+ /System/Library/PrivateFrameworks/Netrb.framework/Netrb \+ @loader_path/../Netrb.framework/Netrb+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime \+ "$VMM_FRAMEWORKS/vmnet.framework/vmnet"+ditto "$METAL_SERIALIZER_FRAMEWORK" \+ "$VMM_FRAMEWORKS/MetalSerializer.framework"+METAL_SERIALIZER_FRAMEWORK="$VMM_FRAMEWORKS/MetalSerializer.framework"+METAL_SERIALIZER_BINARY="$METAL_SERIALIZER_FRAMEWORK/Versions/A/MetalSerializer"++PVG_BINARY="$VMM_FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics"+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$MACHO_CSTRING_PATCH" "$PVG_BINARY" \+ /System/Library/PrivateFrameworks/MetalSerializer.framework/MetalSerializer \+ @loader_path/../../../MetalSerializer.framework/MetalSerializer+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$PVG_EXCEPTION_LOG_PATCH" "$PVG_BINARY"++PVG_RESOURCES="$VMM_FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/Resources"+cp "$PVG_RESOURCES/default.metallib" \+ "$PVG_RESOURCES/default.macos.metallib"+xcrun --sdk iphoneos metal \+ -std=metal3.0 -mios-version-min=16.0 -ffast-math \+ -c "$VZ_REPO_ROOT/vz/shaders/pvg_display.metal" \+ -o "$OUT/pvg_display.air"+xcrun --sdk iphoneos metallib \+ "$OUT/pvg_display.air" \+ -o "$PVG_RESOURCES/default.metallib"++xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" -fblocks \+ -framework Foundation \+ "$VZ_REPO_ROOT/vz/host/vzboot.m" \+ -o "$BIN/vzboot"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -framework Foundation -framework Metal -framework UIKit \+ -Wl,-export_dynamic \+ "$VZ_REPO_ROOT/vz/host/NSViewShim.m" \+ "$VZ_REPO_ROOT/vz/development/probes/objc_methods.m" \+ -o "$BIN/objc-methods"+xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -fblocks -Wl,-undefined,dynamic_lookup \+ -install_name "@rpath/VZHostCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/vzxpchook.m" \+ -o "$BIN/VZHostCompat.dylib"+xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib \+ -framework Foundation -framework Metal \+ -Wl,-reexport_framework,Metal \+ -install_name "@rpath/MetalCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/metalshim.m" \+ -o "$VMM_FRAMEWORKS/MetalCompat.dylib"+xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -fblocks -Wl,-undefined,dynamic_lookup \+ -framework AVFAudio \+ -framework CoreFoundation -framework CoreServices \+ -framework Foundation -framework IOKit -framework Metal \+ -Wl,-reexport_framework,CoreServices \+ -install_name "@rpath/LaunchServicesCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/lsshim.m" \+ "$VZ_REPO_ROOT/vz/host/vmmhook.m" \+ "$VZ_REPO_ROOT/vz/host/pvg_trace.m" \+ -o "$VMM_FRAMEWORKS/LaunchServicesCompat.dylib"++"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VZ_REPO_ROOT/vz/stamp_ios.py" "$VMM_BIN" "$VMM_BIN.ios" 16.0+mv "$VMM_BIN.ios" "$VMM_BIN"++install_name_tool \+ -change \+ /System/Library/Frameworks/CoreMedia.framework/Versions/A/CoreMedia \+ /System/Library/Frameworks/CoreMedia.framework/CoreMedia \+ -change \+ /System/Library/Frameworks/Hypervisor.framework/Versions/A/Hypervisor \+ @loader_path/../../../Frameworks/Hypervisor.framework/Hypervisor \+ -change \+ /System/Library/Frameworks/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics \+ @loader_path/../../../Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics \+ -change \+ /System/Library/Frameworks/Metal.framework/Versions/A/Metal \+ @loader_path/../../../Frameworks/MetalCompat.dylib \+ -change \+ /System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices \+ @loader_path/../../../Frameworks/LaunchServicesCompat.dylib \+ -change \+ /System/Library/Frameworks/vmnet.framework/Versions/A/vmnet \+ @loader_path/../../../Frameworks/vmnet.framework/vmnet \+ -change \+ /System/Library/PrivateFrameworks/ParavirtualizedANE.framework/Versions/A/ParavirtualizedANE \+ /System/Library/PrivateFrameworks/ParavirtualizedANE.framework/ParavirtualizedANE \+ -change \+ /System/Library/Frameworks/ExtensionFoundation.framework/Versions/A/ExtensionFoundation \+ /System/Library/Frameworks/ExtensionFoundation.framework/ExtensionFoundation \+ -change \+ /System/Library/Frameworks/Security.framework/Versions/A/Security \+ /System/Library/Frameworks/Security.framework/Security \+ -change \+ /System/Library/Frameworks/VideoToolbox.framework/Versions/A/VideoToolbox \+ @loader_path/../../../Frameworks/VideoToolbox.framework/VideoToolbox \+ -change \+ /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation \+ /System/Library/Frameworks/Foundation.framework/Foundation \+ -change \+ /System/Library/Frameworks/AudioToolbox.framework/Versions/A/AudioToolbox \+ /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox \+ -change \+ /System/Library/Frameworks/CoreAudio.framework/Versions/A/CoreAudio \+ /System/Library/Frameworks/CoreAudio.framework/CoreAudio \+ -change \+ /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation \+ /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation \+ -change \+ /System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics \+ /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics \+ -change \+ /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit \+ /System/Library/Frameworks/IOKit.framework/IOKit \+ -change \+ /System/Library/Frameworks/IOSurface.framework/Versions/A/IOSurface \+ /System/Library/Frameworks/IOSurface.framework/IOSurface \+ -change \+ /System/Library/Frameworks/IOUSBHost.framework/Versions/A/IOUSBHost \+ /System/Library/PrivateFrameworks/IOUSBHost.framework/IOUSBHost \+ -change \+ /System/Library/PrivateFrameworks/DiskImages2.framework/Versions/A/DiskImages2 \+ /System/Library/PrivateFrameworks/DiskImages2.framework/DiskImages2 \+ "$VMM_BIN"++"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VMM_OPTIONAL_DEVICES_PATCH" "$VMM_BIN"+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VMM_PCI_ADDRESS_PATCH" "$VMM_BIN"++ldid -S"$ENTS" "$BIN/vzboot"+ldid -S"$ENTS" "$BIN/objc-methods"+ldid -S"$ENTS" "$BIN/VZHostCompat.dylib"+for dylib in \+ "$VMM_FRAMEWORKS/MetalCompat.dylib" \+ "$VMM_FRAMEWORKS/LaunchServicesCompat.dylib"; do+ ldid -S"$VMM_ENTS" "$dylib"+done+codesign --verify "$VMM_FRAMEWORKS/vmnet.framework/vmnet"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime \+ "$METAL_SERIALIZER_FRAMEWORK"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime "$PVG_BINARY"+ldid -S"$VMM_ENTS" "$VMM_BIN"++# Finder and BridgeSupport metadata from the extracted frameworks are not+# used by the Objective-C runtime. Remove them before resealing every+# structured framework whose resource envelope may have referenced them.+find "$PAYLOAD" -type f \( -name .DS_Store -o -name '._*' \) -delete+find "$FRAMEWORKS" -type d -name BridgeSupport -prune \+ -exec rm -rf {} ++for framework in \+ "$FRAMEWORKS/Hypervisor.framework" \+ "$FRAMEWORKS/ParavirtualizedGraphics.framework" \+ "$FRAMEWORKS/Virtualization.framework" \+ "$FRAMEWORKS/MetalSerializer.framework"; do+ codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime \+ "$framework"+ codesign --verify --deep --strict "$framework"+done++"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" "$ENTITLEMENT_AUDIT" \+ "$ENTS" "$BIN/vzboot" \+ "$ENTS" "$BIN/objc-methods" \+ "$ENTS" "$BIN/VZHostCompat.dylib" \+ "$VMM_ENTS" "$VMM_BIN" \+ "$VMM_ENTS" "$VMM_FRAMEWORKS/MetalCompat.dylib" \+ "$VMM_ENTS" "$VMM_FRAMEWORKS/LaunchServicesCompat.dylib" \+ - "$FRAMEWORKS/Hypervisor.framework/Versions/A/Hypervisor" \+ - "$FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics" \+ - "$FRAMEWORKS/Virtualization.framework/Versions/A/Virtualization" \+ - "$VMM_FRAMEWORKS/vmnet.framework/vmnet" \+ - "$VMM_FRAMEWORKS/Netrb.framework/Netrb" \+ - "$METAL_SERIALIZER_BINARY" \+ - "$VMM_FRAMEWORKS/VideoToolbox.framework/VideoToolbox"++otool -l "$VMM_BIN" | grep -q "LC_DYLD_CHAINED_FIXUPS" ||+ die "VMM lost LC_DYLD_CHAINED_FIXUPS"+otool -l "$VMM_BIN" |+ awk '/LC_BUILD_VERSION/{show=1; left=7} show && left-- > 0 {print}' |+ grep -q "platform 2" ||+ die "VMM is not stamped for iOS"+for dependency in \+ "@loader_path/../../../Frameworks/Hypervisor.framework/Hypervisor" \+ "@loader_path/../../../Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics" \+ "@loader_path/../../../Frameworks/MetalCompat.dylib" \+ "@loader_path/../../../Frameworks/LaunchServicesCompat.dylib" \+ "@loader_path/../../../Frameworks/vmnet.framework/vmnet" \+ "@loader_path/../../../Frameworks/VideoToolbox.framework/VideoToolbox"; do+ otool -L "$VMM_BIN" | grep -Fq "$dependency" ||+ die "VMM is missing dependency: $dependency"+done+otool -L "$VMM_FRAMEWORKS/vmnet.framework/vmnet" | grep -Fq \+ "@loader_path/../Netrb.framework/Netrb" ||+ die "VMM vmnet is missing its patched Netrb dependency"++{+ files=(+ "$BIN/vzboot"+ "$BIN/objc-methods"+ "$BIN/VZHostCompat.dylib"+ "$VMM_BIN"+ "$VMM_FRAMEWORKS/MetalCompat.dylib"+ "$VMM_FRAMEWORKS/LaunchServicesCompat.dylib"+ "$VMM_FRAMEWORKS/vmnet.framework/vmnet"+ "$VMM_FRAMEWORKS/Netrb.framework/Netrb"+ "$METAL_SERIALIZER_BINARY"+ "$VMM_FRAMEWORKS/VideoToolbox.framework/VideoToolbox"+ "$FRAMEWORKS/Hypervisor.framework/Versions/A/Hypervisor"+ "$FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics"+ "$FRAMEWORKS/Virtualization.framework/Versions/A/Virtualization"+ )+ for file in "${files[@]}"; do+ printf '%s\t%s\n' \+ "$(ldid -h "$file" | sed -n 's/^CDHash=//p')" \+ "${file#"$PAYLOAD/"}"+ done+} >"$PAYLOAD/trustcache.txt"++echo "iPad VM payload built with unavailable host devices optional and without validator/registry/PAC bypasses: $PAYLOAD"diff --git a/VirtualMac/scripts/build-ipad-vmnet.sh b/VirtualMac/scripts/build-ipad-vmnet.shnew file mode 100755index 0000000..0deab89--- /dev/null+++ b/VirtualMac/scripts/build-ipad-vmnet.sh@@ -0,0 +1,57 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++DSC="${VZ_MACOS_DSC:-$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/dyld_shared_cache_arm64e}"+OUT="${VZ_VMNET_OUTPUT:-$VZ_BUILD_ROOT/ipad-vmnet/vmnet.framework}"+RAW="$VZ_BUILD_ROOT/ipad-vmnet/vmnet.raw"+PROTO="$VZ_BUILD_ROOT/ipad-vmnet/vmnet.proto"+BIN="$OUT/vmnet"+ENTS="$VZ_REPO_ROOT/vz/patches/vmm.ents.xml"+PYTHON="$VZ_BUILD_ROOT/toolchain/venv/bin/python3"+DYLDEX="$VZ_BUILD_ROOT/toolchain/venv/bin/dyldex"+IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+ENTITLEMENT_AUDIT="$VZ_REPO_ROOT/scripts/audit-entitlements.py"+IMAGE="vmnet.framework/Versions/A/vmnet"++need_command codesign+need_command otool+need_file "$DSC"+need_file "$DSC.01"+need_file "$PYTHON"+need_file "$DYLDEX"+need_file "$IPSW"+need_file "$VZ_REPO_ROOT/vz/stamp_ios.py"+need_file "$VZ_REPO_ROOT/vz/uncache.py"+need_file "$ENTITLEMENT_AUDIT"++rm -rf "$OUT"+mkdir -p "$OUT" "$(dirname "$RAW")"+if [[ ! -f "$RAW" ]]; then+ "$DYLDEX" -e "$IMAGE" -o "$RAW" "$DSC"+fi+VZ_IPSW="$IPSW" "$PYTHON" "$VZ_REPO_ROOT/vz/uncache.py" \+ "$DSC" "$IMAGE" "$RAW" "$PROTO" compact++"$PYTHON" "$VZ_REPO_ROOT/vz/stamp_ios.py" "$PROTO" "$BIN" 16.0+codesign --verify "$BIN"+"$PYTHON" "$ENTITLEMENT_AUDIT" - "$BIN"++otool -l "$BIN" |+ awk '/LC_BUILD_VERSION/{show=1; left=7} show && left-- > 0 {print}' |+ grep -q "platform 2" || die "vmnet is not stamped for iOS"+otool -L "$BIN" | grep -Fq "/Netrb.framework/Netrb" ||+ die "vmnet does not use the iPadOS Netrb install name"++# A compact standalone image must not retain ADRP targets in the original+# Ventura shared-cache address range. Those references may remain latent in+# light start/stop probes but crash as soon as vmnet enables event callbacks or+# packet I/O.+if otool -tvV "$BIN" | grep -Eq 'adrp.*; 0x1[1-9a-fA-F]'; then+ die "vmnet contains stale shared-cache ADRP targets"+fi++echo "iPad vmnet framework built from macOS 13.2.1 DSC: $OUT"diff --git a/VirtualMac/scripts/build-springboard-tweak.sh b/VirtualMac/scripts/build-springboard-tweak.shnew file mode 100755index 0000000..5f8ef90--- /dev/null+++ b/VirtualMac/scripts/build-springboard-tweak.sh@@ -0,0 +1,26 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/ipad-tweak"+DYLIB="$OUT/VZKeyboardPassthrough.dylib"+PLIST="$OUT/VZKeyboardPassthrough.plist"++need_command ldid+need_command xcrun+need_file "$VZ_REPO_ROOT/vz/tweak/VZKeyboardPassthrough.m"+need_file "$VZ_REPO_ROOT/vz/tweak/VZKeyboardPassthrough.plist"++mkdir -p "$OUT"+xcrun --sdk iphoneos clang -arch arm64e -miphoneos-version-min=16.0 \+ -isysroot "$SDK" -dynamiclib -fblocks -framework Foundation \+ -Wl,-undefined,dynamic_lookup \+ -install_name /var/jb/Library/MobileSubstrate/DynamicLibraries/VZKeyboardPassthrough.dylib \+ "$VZ_REPO_ROOT/vz/tweak/VZKeyboardPassthrough.m" -o "$DYLIB"+cp "$VZ_REPO_ROOT/vz/tweak/VZKeyboardPassthrough.plist" "$PLIST"+ldid -S "$DYLIB"+echo "SpringBoard keyboard passthrough tweak built: $OUT"diff --git a/VirtualMac/scripts/build-vmm-compat.sh b/VirtualMac/scripts/build-vmm-compat.shnew file mode 100755index 0000000..4838d89--- /dev/null+++ b/VirtualMac/scripts/build-vmm-compat.sh@@ -0,0 +1,34 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUTPUT="${VZ_VMM_COMPAT_OUTPUT:-$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/LaunchServicesCompat.dylib}"+ENTITLEMENTS="$VZ_REPO_ROOT/vz/patches/vmm.ents.xml"++need_command ldid+need_command xcrun+need_file "$ENTITLEMENTS"+need_file "$VZ_REPO_ROOT/vz/host/lsshim.m"+need_file "$VZ_REPO_ROOT/vz/host/vmmhook.m"+need_file "$VZ_REPO_ROOT/vz/host/pvg_trace.m"++mkdir -p "$(dirname "$OUTPUT")"+xcrun --sdk iphoneos clang \+ -arch arm64e -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -dynamiclib -fblocks -Wl,-undefined,dynamic_lookup \+ -framework CoreFoundation -framework CoreServices \+ -framework Foundation -framework IOKit -framework Metal \+ -Wl,-reexport_framework,CoreServices \+ -install_name "@rpath/LaunchServicesCompat.dylib" \+ "$VZ_REPO_ROOT/vz/host/lsshim.m" \+ "$VZ_REPO_ROOT/vz/host/vmmhook.m" \+ "$VZ_REPO_ROOT/vz/host/pvg_trace.m" \+ -o "$OUTPUT"+ldid -S"$ENTITLEMENTS" "$OUTPUT"++echo "VMM compatibility library built: $OUTPUT"+echo "CDHash: $(ldid -h "$OUTPUT" | sed -n 's/^CDHash=//p')"diff --git a/VirtualMac/scripts/development/boot-ipad-good-guest.sh b/VirtualMac/scripts/development/boot-ipad-good-guest.shnew file mode 100755index 0000000..82c0f50--- /dev/null+++ b/VirtualMac/scripts/development/boot-ipad-good-guest.sh@@ -0,0 +1,67 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++ATTEMPTS="${VZ_BOOT_ATTEMPTS:-4}"+TIMEOUT="${VZ_BOOT_TIMEOUT:-90}"+STALL_LIMIT="${VZ_BOOT_STALL_LIMIT:-30}"+[[ "$ATTEMPTS" =~ ^[1-9][0-9]*$ ]] ||+ die "VZ_BOOT_ATTEMPTS must be a positive integer"+[[ "$TIMEOUT" =~ ^[1-9][0-9]*$ ]] ||+ die "VZ_BOOT_TIMEOUT must be a positive integer"+[[ "$STALL_LIMIT" =~ ^[1-9][0-9]*$ ]] ||+ die "VZ_BOOT_STALL_LIMIT must be a positive integer"++for ((attempt = 1; attempt <= ATTEMPTS; attempt++)); do+ echo "desktop-qualified boot attempt $attempt/$ATTEMPTS"+ VZ_GUEST_STOP_TIMEOUT=5 "$SCRIPT_DIR/restore-ipad-good-guest.sh"+ VZ_IPAD_BOOT_TIMEOUT="$TIMEOUT" \+ "$SCRIPT_DIR/boot-ipad-vm-bundle.sh" \+ /var/mobile/Media/VirtualMac/GoodVM.bundle++ previous_frames=-1+ unchanged=0+ for ((elapsed = 0; elapsed < TIMEOUT; elapsed += 5)); do+ result="$(ipad_ssh "+if grep -Eq 'PVG cursor=.*image=1 size=[1-9][0-9]*x[1-9][0-9]*' \+ /tmp/VirtualMac.log; then+ echo desktop+elif ! ps ax | grep -F \+ '/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine' | \+ grep -v grep >/dev/null 2>&1; then+ echo stopped+else+ frames=\$(grep 'health state=' /tmp/VirtualMac.log | tail -1 | \+ sed -n 's/.*frames=\([0-9][0-9]*\).*/\1/p')+ echo frames:\${frames:-0}+fi+")"+ if [[ "$result" == desktop ]]; then+ ipad_ssh "tail -20 /tmp/VirtualMac.log; \+ grep '\[vmmhook\] health' /tmp/vmmhook.log | tail -4"+ echo "macOS desktop cursor observed on attempt $attempt"+ exit 0+ fi+ if [[ "$result" == stopped ]]; then+ echo "VMM stopped before the desktop on attempt $attempt"+ break+ fi+ frames="${result#frames:}"+ if [[ "$frames" == "$previous_frames" && "$frames" != 0 ]]; then+ unchanged=$((unchanged + 5))+ else+ previous_frames="$frames"+ unchanged=0+ fi+ if (( unchanged >= STALL_LIMIT )); then+ echo "PVG stalled at frame $frames for ${unchanged}s"+ break+ fi+ sleep 5+ done+done++die "macOS did not reach a desktop cursor after $ATTEMPTS clean attempts"diff --git a/VirtualMac/scripts/development/boot-ipad-vm-bundle.sh b/VirtualMac/scripts/development/boot-ipad-vm-bundle.shnew file mode 100755index 0000000..6063e2a--- /dev/null+++ b/VirtualMac/scripts/development/boot-ipad-vm-bundle.sh@@ -0,0 +1,66 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++BUNDLE="${1:-/var/mobile/Media/VirtualMac/Sequoia.bundle}"+TIMEOUT="${VZ_IPAD_BOOT_TIMEOUT:-120}"+REMOTE_APP_PATTERN="/VirtualMac.app/VirtualMac"++[[ "$TIMEOUT" =~ ^[1-9][0-9]*$ ]] ||+ die "VZ_IPAD_BOOT_TIMEOUT must be a positive integer"+printf -v bundle_quoted '%q' "$BUNDLE"++VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"+ipad_ssh "+set -eu+bundle=$bundle_quoted+for name in Disk.img AuxiliaryStorage HardwareModel MachineIdentifier; do+ test -f \"\$bundle/\$name\"+done+killall VirtualMac 2>/dev/null || true+killall com.apple.Virtualization.Installation 2>/dev/null || true+killall usbmuxd 2>/dev/null || true+rm -f /var/run/usbmuxd /tmp/vzusbmuxd /tmp/vz-usbmuxd-enable+rm -f /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+touch /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+chown mobile:mobile /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+printf '%s\\n' \"\$bundle\" >/tmp/vz-autoboot-path+chown mobile:mobile /tmp/vz-autoboot-path+/var/jb/usr/bin/uiopen --bundleid com.mac.virtual+"++for ((elapsed = 0; elapsed < TIMEOUT; elapsed++)); do+ result="$(ipad_ssh "+if grep -Fq '[VirtualMac] VM STARTED state=1' /tmp/VirtualMac.log; then+ echo started+elif grep -q 'VM start failed:' /tmp/VirtualMac.log; then+ echo failed+elif test '$elapsed' -ge 10 &&+ ! ps ax | grep -F '$REMOTE_APP_PATTERN' | grep -v grep >/dev/null 2>&1; then+ echo stopped+else+ echo pending+fi+")"+ case "$result" in+ started)+ ipad_ssh "tail -n 20 /tmp/VirtualMac.log"+ printf 'IPAD_VM_BUNDLE_STARTED\t%s\n' "$BUNDLE"+ exit 0+ ;;+ failed|stopped)+ ipad_ssh "tail -n 60 /tmp/VirtualMac.log; tail -n 60 /tmp/vmmhook.log"+ die "iPad VM $result while booting $BUNDLE"+ ;;+ esac+ sleep 1+done++ipad_ssh "tail -n 60 /tmp/VirtualMac.log; tail -n 60 /tmp/vmmhook.log"+die "iPad VM did not start within ${TIMEOUT}s: $BUNDLE"diff --git a/VirtualMac/scripts/development/build-ipad-smoke.sh b/VirtualMac/scripts/development/build-ipad-smoke.shnew file mode 100755index 0000000..57acac1--- /dev/null+++ b/VirtualMac/scripts/development/build-ipad-smoke.sh@@ -0,0 +1,62 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/ipad-smoke"+BIN="$OUT/bin"+FRAMEWORKS="$VZ_BUILD_ROOT/frameworks/bundles/ios"+PAYLOAD_FRAMEWORKS="$OUT/Frameworks"++need_command codesign+need_command ldid+need_command xcrun+for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ need_file "$FRAMEWORKS/$name.framework/Versions/A/$name"+done+need_file "$VZ_REPO_ROOT/vz/development/probes/vzload.c"+need_file "$VZ_REPO_ROOT/vz/development/probes/vzcfg.m"+need_file "$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements"++rm -rf "$PAYLOAD_FRAMEWORKS"+mkdir -p "$BIN" "$PAYLOAD_FRAMEWORKS"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" \+ "$VZ_REPO_ROOT/vz/development/probes/vzload.c" \+ -lobjc -o "$BIN/vzload"+xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -framework Foundation \+ "$VZ_REPO_ROOT/vz/development/probes/vzcfg.m" \+ -o "$BIN/vzcfg"++for binary in "$BIN/vzload" "$BIN/vzcfg"; do+ ldid -S"$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements" "$binary"+ file "$binary"+ ldid -e "$binary" | grep -Fq "com.apple.private.hypervisor"+done++for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ ditto "$FRAMEWORKS/$name.framework" \+ "$PAYLOAD_FRAMEWORKS/$name.framework"+ codesign --verify --deep --strict \+ "$PAYLOAD_FRAMEWORKS/$name.framework"+done++{+ for file in \+ "$BIN/vzload" \+ "$BIN/vzcfg" \+ "$PAYLOAD_FRAMEWORKS/Hypervisor.framework/Versions/A/Hypervisor" \+ "$PAYLOAD_FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics" \+ "$PAYLOAD_FRAMEWORKS/Virtualization.framework/Versions/A/Virtualization"; do+ printf '%s\t%s\n' \+ "$(ldid -h "$file" | sed -n 's/^CDHash=//p')" \+ "${file#"$OUT/"}"+ done+} >"$OUT/trustcache.txt"++echo "iPad framework smoke payload built: $OUT"diff --git a/VirtualMac/scripts/development/build-ipad-vmnet-probe.sh b/VirtualMac/scripts/development/build-ipad-vmnet-probe.shnew file mode 100755index 0000000..a3b9e38--- /dev/null+++ b/VirtualMac/scripts/development/build-ipad-vmnet-probe.sh@@ -0,0 +1,44 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/probes/vmnet-probe"+RUNTIME="$VZ_BUILD_ROOT/probes/vmnet-runtime"+SOURCE="$VZ_REPO_ROOT/vz/development/probes/vmnet_probe.c"+ENTS="$VZ_REPO_ROOT/vz/patches/vmm.ents.xml"++need_command ldid+need_command codesign+need_command install_name_tool+need_command xcrun+need_file "$SOURCE"+need_file "$ENTS"+mkdir -p "$(dirname "$OUT")"++"$VZ_REPO_ROOT/scripts/build-ipad-vmnet.sh"+"$VZ_REPO_ROOT/scripts/build-ipad-netrb.sh"+rm -rf "$RUNTIME"+mkdir -p "$RUNTIME/vmnet.framework" "$RUNTIME/Netrb.framework"+cp "$VZ_BUILD_ROOT/ipad-vmnet/vmnet.framework/vmnet" \+ "$RUNTIME/vmnet.framework/vmnet"+cp "$VZ_BUILD_ROOT/ipad-netrb/Netrb.framework/Netrb" \+ "$RUNTIME/Netrb.framework/Netrb"+"$VZ_BUILD_ROOT/toolchain/venv/bin/python3" \+ "$VZ_REPO_ROOT/vz/patches/patch_macho_cstring.py" \+ "$RUNTIME/vmnet.framework/vmnet" \+ /System/Library/PrivateFrameworks/Netrb.framework/Netrb \+ @loader_path/../Netrb.framework/Netrb+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime \+ "$RUNTIME/vmnet.framework/vmnet"++xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" -fblocks \+ -framework CoreFoundation \+ "$SOURCE" -o "$OUT"+ldid -S"$ENTS" "$OUT"+echo "iPad vmnet probe built: $OUT"diff --git a/VirtualMac/scripts/development/collect-ipad-network-logs.sh b/VirtualMac/scripts/development/collect-ipad-network-logs.shnew file mode 100755index 0000000..7728e91--- /dev/null+++ b/VirtualMac/scripts/development/collect-ipad-network-logs.sh@@ -0,0 +1,22 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++LAST="${1:-10m}"+STAMP="$(date +%Y%m%d-%H%M%S)"+OUT="${2:-$VZ_BUILD_ROOT/analysis/ipad-logs/network-$STAMP.logarchive}"+REPORT="${OUT%.logarchive}.txt"+mkdir -p "$(dirname "$OUT")"++if [[ "$EUID" -ne 0 ]]; then+ exec sudo "$0" "$LAST" "$OUT"+fi++/usr/bin/log collect --device --last "$LAST" --output "$OUT"+/usr/bin/log show --archive "$OUT" --style compact --last "$LAST" \+ --predicate 'process == "InternetSharing" OR eventMessage CONTAINS[c] "vmnet" OR eventMessage CONTAINS[c] "IOUserEthernet" OR eventMessage CONTAINS[c] "Netrb"' \+ >"$REPORT"+echo "iPad network log report: $REPORT"diff --git a/VirtualMac/scripts/development/copy-good-guest-to-ipad.sh b/VirtualMac/scripts/development/copy-good-guest-to-ipad.shnew file mode 100755index 0000000..848981e--- /dev/null+++ b/VirtualMac/scripts/development/copy-good-guest-to-ipad.sh@@ -0,0 +1,74 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_VM:?set VZ_REAL_MAC_VM to the VM bundle on the reference Mac}"+REMOTE_VM="$VZ_REAL_MAC_VM"+LOCAL_PARENT="$VZ_BUILD_ROOT/good-guest"+LOCAL_VM="$LOCAL_PARENT/VM.bundle"+IPAD_RUNTIME="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+IPAD_ROOT="/var/mobile/Media/VirtualMac"+IPAD_STAGE="$IPAD_ROOT/Transfers/good-guest-stage"+IPAD_INCOMING="$IPAD_STAGE/VM.bundle"+IPAD_VM="$IPAD_ROOT/GoodVM.bundle"+IPAD_BASELINE="$IPAD_ROOT/Baselines/GoodVM.bundle"++need_command rsync+need_command sshpass+GNU_TAR="${VZ_GNU_TAR:-$(command -v gtar || true)}"+[[ -n "$GNU_TAR" ]] ||+ die "GNU tar is required for sparse transfer (brew install gnu-tar)"++if [[ "${VZ_SKIP_REAL_MAC_SYNC:-0}" != 1 ]]; then+ active="$(real_mac_ssh \+ "ps ax | grep -E 'macOSVirtualMachineSampleApp|com.apple.Virtualization.VirtualMachine' | grep -v grep || true")"+ [[ -z "$active" ]] ||+ die "the matching-Mac VM must be shut down before copying"+fi+active_ipad="$(ipad_ssh \+ "ps ax | grep -E '$IPAD_RUNTIME/payload/bin/vzboot|$IPAD_RUNTIME/payload/VirtualMachine.xpc' | grep -v grep || true")"+[[ -z "$active_ipad" ]] ||+ die "the native iPad VM must be stopped before replacing its guest"++mkdir -p "$LOCAL_VM"+if [[ "${VZ_SKIP_REAL_MAC_SYNC:-0}" != 1 ]]; then+ real_mac_ssh_args+ sshpass -p "$VZ_REAL_MAC_PASSWORD" rsync \+ -aSzh --partial --progress \+ -e "ssh -p $VZ_REAL_MAC_PORT \+ -o StrictHostKeyChecking=no \+ -o UserKnownHostsFile=/dev/null \+ -o PubkeyAuthentication=no \+ -o PreferredAuthentications=password" \+ "$REAL_MAC_TARGET:$REMOTE_VM/" "$LOCAL_VM/"+else+ echo "using completed local staging bundle: $LOCAL_VM"+fi++for file in Disk.img AuxiliaryStorage HardwareModel MachineIdentifier; do+ need_file "$LOCAL_VM/$file"+done+disk_size="$(stat -f %z "$LOCAL_VM/Disk.img")"+[[ "$disk_size" == 68719476736 ]] ||+ die "expected a 64 GiB good-guest disk, got $disk_size bytes"++ipad_ssh "rm -rf '$IPAD_STAGE'; mkdir -p '$IPAD_STAGE' '$IPAD_ROOT/Baselines'"+ensure_ipad_usb+"$GNU_TAR" --sparse -C "$LOCAL_PARENT" -cf - VM.bundle |+ sshpass -p "$VZ_IPAD_PASSWORD" ssh \+ "${IPAD_SSH_ARGS[@]}" "$IPAD_TARGET" \+ "tar --sparse -xf - -C '$IPAD_STAGE'"++ipad_ssh \+ "test \"\$(stat -c %s '$IPAD_INCOMING/Disk.img')\" = '$disk_size'; \+ rm -rf '$IPAD_VM'; mv '$IPAD_INCOMING' '$IPAD_VM'; \+ rmdir '$IPAD_STAGE'; \+ rm -rf '$IPAD_BASELINE'; \+ /var/jb/usr/bin/cp -a --reflink=always '$IPAD_VM' '$IPAD_BASELINE'; \+ stat -c '%s %n' '$IPAD_VM/'*"++echo "known-good matching-Mac guest copied to: $IPAD_VM"+echo "clean on-device recovery baseline: $IPAD_BASELINE"diff --git a/VirtualMac/scripts/development/copy-install-ipsw-to-ipad.sh b/VirtualMac/scripts/development/copy-install-ipsw-to-ipad.shnew file mode 100755index 0000000..9ef4483--- /dev/null+++ b/VirtualMac/scripts/development/copy-install-ipsw-to-ipad.sh@@ -0,0 +1,36 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_INSTALL_IPSW:?set VZ_INSTALL_IPSW to the restore image to copy}"+LOCAL_IPSW="$VZ_INSTALL_IPSW"+REMOTE_DIR="${VZ_IPAD_RESTORE_IMAGES:-/var/mobile/Media/VirtualMac/Restore Images}"+NAME="$(basename "$LOCAL_IPSW")"+REMOTE_IPSW="$REMOTE_DIR/$NAME"+REMOTE_PARTIAL="$REMOTE_IPSW.partial"++need_command shasum+need_file "$LOCAL_IPSW"+local_size="$(stat -f %z "$LOCAL_IPSW")"+local_hash="$(shasum -a 256 "$LOCAL_IPSW" | awk '{print $1}')"++ensure_ipad_usb+ipad_ssh "mkdir -p '$REMOTE_DIR'; chown mobile:mobile '$REMOTE_DIR'"+remote_size="$(ipad_ssh "stat -c %s '$REMOTE_IPSW' 2>/dev/null || echo 0")"+if [[ "$remote_size" != "$local_size" ]]; then+ partial_size="$(ipad_ssh "stat -c %s '$REMOTE_PARTIAL' 2>/dev/null || echo 0")"+ if [[ "$partial_size" != "$local_size" ]]; then+ ipad_scp "$LOCAL_IPSW" "$IPAD_TARGET:$REMOTE_PARTIAL"+ fi+ ipad_ssh "test \$(stat -c %s '$REMOTE_PARTIAL') = '$local_size'; \+ mv '$REMOTE_PARTIAL' '$REMOTE_IPSW'; chown mobile:mobile '$REMOTE_IPSW'"+fi++remote_hash="$(ipad_ssh "sha256sum '$REMOTE_IPSW' | sed 's/ .*//'")"+[[ "$remote_hash" == "$local_hash" ]] ||+ die "iPad IPSW hash mismatch: local=$local_hash remote=$remote_hash"+printf 'IPSW_READY\t%s\t%s\t%s\n' \+ "$local_size" "$local_hash" "$REMOTE_IPSW"diff --git a/VirtualMac/scripts/development/deploy-ipad-app.sh b/VirtualMac/scripts/development/deploy-ipad-app.shnew file mode 100755index 0000000..2cca77c--- /dev/null+++ b/VirtualMac/scripts/development/deploy-ipad-app.sh@@ -0,0 +1,91 @@+#!/bin/bash++# Install Virtual Mac in the rootless jailbreak application directory. This is+# the proven System-app configuration used by the native VMM. VM bundles live+# outside the app registration/container model at /var/mobile/Media/VirtualMac.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++APP="$VZ_BUILD_ROOT/ipad-app/VirtualMac.app"+BIN="$APP/VirtualMac"+HOOK="$APP/VZHostCompat.dylib"+BUNDLE_ID="com.mac.virtual"+REMOTE_APP="/var/jb/Applications/VirtualMac.app"+REMOTE_LIBRARY="/var/mobile/Media/VirtualMac"+ARCHIVE="$(mktemp -t virtual-mac-app.XXXXXX.tar.gz)"+trap 'rm -f "$ARCHIVE"' EXIT++need_command ldid+need_command tar+need_file "$BIN"+need_file "$HOOK"++DISMISS_RESTART_ALERT="${VZ_IPAD_DISMISS_RESTART_ALERT:-0}"+[[ "$DISMISS_RESTART_ALERT" == 0 || "$DISMISS_RESTART_ALERT" == 1 ]] ||+ die "VZ_IPAD_DISMISS_RESTART_ALERT must be 0 or 1"++tar -C "$VZ_BUILD_ROOT/ipad-app" -czf "$ARCHIVE" VirtualMac.app+ensure_ipad_usb+ipad_scp "$ARCHIVE" "$IPAD_TARGET:/tmp/virtual-mac-app.tar.gz"++bin_hash="$(ldid -h "$BIN" | sed -n 's/^CDHash=//p')"+hook_hash="$(ldid -h "$HOOK" | sed -n 's/^CDHash=//p')"+VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"+ipad_ssh "+set -eu+current_path=\$(/var/jb/usr/bin/uicache -i '$BUNDLE_ID' 2>/dev/null |+ sed -n 's/^Path: //p')+if test -n \"\$current_path\"; then+ /var/jb/usr/bin/uicache -u \"\$current_path\" || true+fi+rm -rf '$REMOTE_APP'+tar -xzf /tmp/virtual-mac-app.tar.gz -C /var/jb/Applications+rm -f /tmp/virtual-mac-app.tar.gz+chmod 755 '$REMOTE_APP/VirtualMac' '$REMOTE_APP/VZHostCompat.dylib'+mkdir -p '$REMOTE_LIBRARY'+chown mobile:mobile '$REMOTE_LIBRARY'+chmod 755 '$REMOTE_LIBRARY'+jbctl trustcache add '$bin_hash'+jbctl trustcache add '$hook_hash'+/var/jb/usr/bin/uicache -p '$REMOTE_APP'+rm -f /tmp/VirtualMac.log \\+ /tmp/vzxpchook.log /tmp/vmmhook.log \\+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+touch /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \\+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+chown mobile:mobile /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \\+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+if test '$DISMISS_RESTART_ALERT' = 1; then+ touch /tmp/vz-dismiss-restart-alert+ chown mobile:mobile /tmp/vz-dismiss-restart-alert+else+ rm -f /tmp/vz-dismiss-restart-alert+fi+/var/jb/usr/bin/uiopen --bundleid '$BUNDLE_ID'+"++for _ in {1..5}; do+ if ipad_ssh "ps ax | grep '/VirtualMac.app/VirtualMac' | grep -v grep" \+ >/dev/null 2>&1; then+ break+ fi+ ipad_ssh "/var/jb/usr/bin/uiopen --bundleid '$BUNDLE_ID'" || true+ sleep 1+done+ipad_ssh "+echo REGISTRATION+/var/jb/usr/bin/uicache -i '$BUNDLE_ID'+echo PROCESS+ps ax | grep '/VirtualMac.app/VirtualMac' | grep -v grep || true+echo VM_LIBRARY+ls -la '$REMOTE_LIBRARY'+echo APP_LOG+cat /tmp/VirtualMac.log 2>/dev/null || true+echo HOST_HOOK_LOG+cat /tmp/vzxpchook.log 2>/dev/null || true+echo VMM_HOOK_LOG+cat /tmp/vmmhook.log 2>/dev/null || true+"diff --git a/VirtualMac/scripts/development/deploy-ipad-installation.sh b/VirtualMac/scripts/development/deploy-ipad-installation.shnew file mode 100755index 0000000..fc80efb--- /dev/null+++ b/VirtualMac/scripts/development/deploy-ipad-installation.sh@@ -0,0 +1,72 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++OUT="$VZ_BUILD_ROOT/ipad-installation"+REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+ARCHIVE="$(mktemp -t VirtualMac-installation.XXXXXX.tar.gz)"+trap 'rm -f "$ARCHIVE"' EXIT++need_command ldid+need_command tar+need_file "$OUT/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation"+need_file "$OUT/install/VZHostCompat.dylib"+need_file "$OUT/install/restore-image-probe"+need_file "$OUT/install/install-macos"+need_file "$OUT/install/start-install.sh"+need_file "$OUT/install/install-launcher"+need_file "$OUT/install/usb-bridge-probe"+need_file "$OUT/payload/Frameworks/LaunchServicesCompat.dylib"+need_file "$OUT/trustcache.txt"++tar -C "$OUT" -czf "$ARCHIVE" payload install trustcache.txt manifest.txt+ensure_ipad_usb+ipad_scp "$ARCHIVE" "$IPAD_TARGET:/tmp/vz-installation.tar.gz"++ipad_ssh "+set -eu+killall restore-image-probe 2>/dev/null || true+ps -axo pid=,command= | while read -r stale_pid stale_command; do+ case "\$stale_command" in+ '$REMOTE/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation')+ kill -9 "\$stale_pid" 2>/dev/null || true+ ;;+ esac+done+launchctl bootout system/com.mac.virtual.installer 2>/dev/null || true+rm -f /var/jb/Library/LaunchDaemons/com.mac.virtual.installer.plist+rm -rf '$REMOTE/payload/Installation.xpc' '$REMOTE/install'+mkdir -p '$REMOTE'+tar -xzf /tmp/vz-installation.tar.gz -C '$REMOTE'+rm -f /tmp/vz-installation.tar.gz+chmod 755 \+ '$REMOTE/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation' \+ '$REMOTE/payload/Installation.xpc/Contents/Frameworks/InstallationCompat.dylib' \+ '$REMOTE/payload/Installation.xpc/Contents/Frameworks/MobileDevice.framework/Versions/A/Resources/usbmuxd' \+ '$REMOTE/payload/Frameworks/LaunchServicesCompat.dylib' \+ '$REMOTE/install/VZHostCompat.dylib' \+ '$REMOTE/install/restore-image-probe' \+ '$REMOTE/install/install-macos' \+ '$REMOTE/install/usb-bridge-probe'+chmod 755 '$REMOTE/install/start-install.sh'+chown root:wheel '$REMOTE/install/install-launcher'+chmod 4755 '$REMOTE/install/install-launcher'+PATH=/var/jb/usr/bin:/var/jb/bin:/usr/bin:/bin:/usr/sbin:/sbin+export PATH+for utility in cat rm killall grep sleep touch ln; do+ command -v "\$utility" >/dev/null+done+while IFS=\$(printf '\\t') read -r hash file; do+ test -n \"\$hash\"+ test -f '$REMOTE/'\"\$file\"+ jbctl trustcache add \"\$hash\"+done <'$REMOTE/trustcache.txt'+rm -f /tmp/installation_ep.txt /tmp/installation.stderr.log \+ /tmp/restore-vmm.stderr.log \+ /tmp/installationhook.log /tmp/restore-image-probe.log+echo INSTALLATION_DEPLOYED+cat '$REMOTE/manifest.txt'+"diff --git a/VirtualMac/scripts/development/deploy-ipad-network-sharing.sh b/VirtualMac/scripts/development/deploy-ipad-network-sharing.shnew file mode 100755index 0000000..e37327f--- /dev/null+++ b/VirtualMac/scripts/development/deploy-ipad-network-sharing.sh@@ -0,0 +1,100 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++OUT="$VZ_BUILD_ROOT/ipad-network-sharing"+BIN="$OUT/InternetSharing"+PLIST="$OUT/com.apple.NetworkSharing.plist"+AUTH_COMPAT="$OUT/AuthorizationCompat.dylib"+HELPERS="$VZ_BUILD_ROOT/ipad-network-helpers"+BOOTPD="$HELPERS/bootpd"+RTADVD="$HELPERS/rtadvd"+OD_COMPAT="$HELPERS/OpenDirectoryCompat.dylib"+BOOTPD_PLIST="$HELPERS/com.apple.bootpd.plist"+LAUNCH_DOMAIN="${VZ_NETWORK_SHARING_DOMAIN:-user/501}"+BOOTPD_DOMAIN="${VZ_BOOTPD_DOMAIN:-$LAUNCH_DOMAIN}"++need_command ldid+need_file "$BIN"+need_file "$PLIST"+need_file "$AUTH_COMPAT"+need_file "$BOOTPD"+need_file "$RTADVD"+need_file "$OD_COMPAT"+need_file "$BOOTPD_PLIST"+ensure_ipad_usb+ipad_scp "$BIN" "$IPAD_TARGET:/tmp/InternetSharing"+ipad_scp "$PLIST" "$IPAD_TARGET:/tmp/com.apple.NetworkSharing.plist"+ipad_scp "$AUTH_COMPAT" "$IPAD_TARGET:/tmp/AuthorizationCompat.dylib"+ipad_scp "$BOOTPD" "$IPAD_TARGET:/tmp/bootpd"+ipad_scp "$RTADVD" "$IPAD_TARGET:/tmp/rtadvd"+ipad_scp "$OD_COMPAT" "$IPAD_TARGET:/tmp/OpenDirectoryCompat.dylib"+ipad_scp "$BOOTPD_PLIST" "$IPAD_TARGET:/tmp/com.apple.bootpd.plist"++hash="$(ldid -h "$BIN" | sed -n 's/^CDHash=//p')"+compat_hash="$(ldid -h "$AUTH_COMPAT" | sed -n 's/^CDHash=//p')"+bootpd_hash="$(ldid -h "$BOOTPD" | sed -n 's/^CDHash=//p')"+rtadvd_hash="$(ldid -h "$RTADVD" | sed -n 's/^CDHash=//p')"+od_compat_hash="$(ldid -h "$OD_COMPAT" | sed -n 's/^CDHash=//p')"+ipad_ssh "+set -eu+mkdir -p /var/jb/usr/lib /var/jb/usr/libexec /var/jb/usr/sbin \+ /var/jb/Library/LaunchDaemons /var/jb/basebin/LaunchDaemons+/var/jb/usr/bin/launchctl bootout system/com.apple.bootpd \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout user/501/com.apple.bootpd \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout system/vzi.apple.bootpd \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout user/501/vzi.apple.bootpd \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout system/com.apple.NetworkSharing \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout user/501/com.apple.NetworkSharing \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout system/com.mac.virtual.NetworkSharing \+ 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout user/501/com.mac.virtual.NetworkSharing \+ 2>/dev/null || true+install -o root -g wheel -m 755 /tmp/InternetSharing \+ /var/jb/usr/libexec/InternetSharing+install -o root -g wheel -m 755 /tmp/AuthorizationCompat.dylib \+ /var/jb/usr/lib/AuthorizationCompat.dylib+install -o root -g wheel -m 755 /tmp/bootpd \+ /var/jb/usr/libexec/bootpd+install -o root -g wheel -m 755 /tmp/rtadvd \+ /var/jb/usr/sbin/rtadvd+install -o root -g wheel -m 755 /tmp/OpenDirectoryCompat.dylib \+ /var/jb/usr/lib/OpenDirectoryCompat.dylib+install -o root -g wheel -m 644 /tmp/com.apple.bootpd.plist \+ /var/jb/Library/LaunchDaemons/com.apple.bootpd.plist+# Ventura bootpd creates and updates this file but expects its parent and the+# initial file to be writable. The iPad data volume provides /var/db; seed the+# file without truncating an existing lease database.+touch /var/db/dhcpd_leases+chown root:wheel /var/db/dhcpd_leases+chmod 644 /var/db/dhcpd_leases+install -o root -g wheel -m 644 /tmp/com.apple.NetworkSharing.plist \+ /var/jb/Library/LaunchDaemons/com.apple.NetworkSharing.plist+install -o root -g wheel -m 644 /tmp/com.apple.NetworkSharing.plist \+ /var/jb/basebin/LaunchDaemons/com.apple.NetworkSharing.plist+rm -f /tmp/InternetSharing /tmp/AuthorizationCompat.dylib /tmp/bootpd \+ /tmp/rtadvd /tmp/OpenDirectoryCompat.dylib /tmp/com.apple.bootpd.plist \+ /tmp/com.apple.NetworkSharing.plist+jbctl trustcache add '$hash'+jbctl trustcache add '$compat_hash'+jbctl trustcache add '$bootpd_hash'+jbctl trustcache add '$rtadvd_hash'+jbctl trustcache add '$od_compat_hash'+/var/jb/usr/bin/launchctl enable '$BOOTPD_DOMAIN/vzi.apple.bootpd'+/var/jb/usr/bin/launchctl bootstrap '$BOOTPD_DOMAIN' \+ /var/jb/Library/LaunchDaemons/com.apple.bootpd.plist+/var/jb/usr/bin/launchctl bootstrap '$LAUNCH_DOMAIN' \+ /var/jb/Library/LaunchDaemons/com.apple.NetworkSharing.plist+/var/jb/usr/bin/launchctl kickstart -k \+ '$LAUNCH_DOMAIN/com.apple.NetworkSharing'+/var/jb/usr/bin/launchctl print '$LAUNCH_DOMAIN/com.apple.NetworkSharing'+"diff --git a/VirtualMac/scripts/development/deploy-ipad-smoke.sh b/VirtualMac/scripts/development/deploy-ipad-smoke.shnew file mode 100755index 0000000..d00db15--- /dev/null+++ b/VirtualMac/scripts/development/deploy-ipad-smoke.sh@@ -0,0 +1,66 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++LOCAL="$VZ_BUILD_ROOT/ipad-smoke"+REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+ARCHIVE="$(mktemp -t VirtualMac-smoke.XXXXXX.tar.gz)"+RESULT_DIR="$VZ_BUILD_ROOT/validation"+RESULT="$RESULT_DIR/ipad-smoke.txt"+trap 'rm -f "$ARCHIVE"' EXIT++need_command sshpass+need_command tar+for file in \+ "$LOCAL/bin/vzload" \+ "$LOCAL/bin/vzcfg" \+ "$LOCAL/Frameworks/Hypervisor.framework/Versions/A/Hypervisor" \+ "$LOCAL/Frameworks/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics" \+ "$LOCAL/Frameworks/Virtualization.framework/Versions/A/Virtualization" \+ "$LOCAL/trustcache.txt"; do+ need_file "$file"+done++mkdir -p "$RESULT_DIR"+tar -C "$LOCAL" -czf "$ARCHIVE" \+ bin Frameworks trustcache.txt++ipad_ssh "mkdir -p '$REMOTE'; rm -rf '$REMOTE/smoke'"+ipad_scp "$ARCHIVE" "$IPAD_TARGET:$REMOTE/smoke.tar.gz"++remote_script="$(cat <<EOF+set -eu+mkdir -p '$REMOTE/smoke'+tar -xzf '$REMOTE/smoke.tar.gz' -C '$REMOTE/smoke'+rm -f '$REMOTE/smoke.tar.gz'+chmod 755 '$REMOTE/smoke/bin/vzload' '$REMOTE/smoke/bin/vzcfg'+while IFS=\$(printf '\\t') read -r hash file; do+ test -n "\$hash"+ test -f '$REMOTE/smoke/'"\$file"+ jbctl trustcache add "\$hash"+done <'$REMOTE/smoke/trustcache.txt'+echo LOAD_PROBE+'$REMOTE/smoke/bin/vzload' \+ '$REMOTE/smoke/Frameworks/Hypervisor.framework/Hypervisor' \+ '$REMOTE/smoke/Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics' \+ '$REMOTE/smoke/Frameworks/Virtualization.framework/Virtualization'+echo DISPATCH_PROBE+'$REMOTE/smoke/bin/vzcfg' \+ '$REMOTE/smoke/Frameworks/Hypervisor.framework/Hypervisor' \+ '$REMOTE/smoke/Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics' \+ '$REMOTE/smoke/Frameworks/Virtualization.framework/Virtualization'+EOF+)"++ipad_ssh "$remote_script" | tee "$RESULT"+grep -Fq "class VZVirtualMachineConfiguration" "$RESULT" ||+ die "Virtualization classes did not realize on iPad"+grep -Fq "ALL RESOLVE" "$RESULT" ||+ die "Virtualization selectors did not resolve on iPad"+grep -Fq "DISPATCH OK" "$RESULT" ||+ die "Virtualization method dispatch failed on iPad"++echo "iPad framework smoke validation passed: $RESULT"diff --git a/VirtualMac/scripts/development/deploy-ipad-vm.sh b/VirtualMac/scripts/development/deploy-ipad-vm.shnew file mode 100755index 0000000..ee22792--- /dev/null+++ b/VirtualMac/scripts/development/deploy-ipad-vm.sh@@ -0,0 +1,59 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++LOCAL="$VZ_BUILD_ROOT/ipad-vm"+PAYLOAD="$LOCAL/payload"+REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+ARCHIVE="$(mktemp -t VirtualMac-vm.XXXXXX.tar.gz)"+trap 'rm -f "$ARCHIVE"' EXIT++need_command sshpass+need_command tar+need_file "$PAYLOAD/bin/vzboot"+need_file "$PAYLOAD/trustcache.txt"++tar -C "$LOCAL" -czf "$ARCHIVE" payload+ipad_ssh "mkdir -p '$REMOTE'"+ipad_scp "$ARCHIVE" "$IPAD_TARGET:$REMOTE/deploy.tar.gz"++remote_script="$(cat <<EOF+set -eu+# Installation.xpc is a separately built DeviceSupport overlay. Replacing the+# whole payload here used to silently delete its bundled usbmuxd and made a+# later in-app IPSW restore fail before launch. Replace only VM-owned paths so+# the VM and installation deployments are order-independent.+rm -rf \+ '$REMOTE/payload/bin' \+ '$REMOTE/payload/Frameworks' \+ '$REMOTE/payload/VirtualMachine.xpc' \+ '$REMOTE/payload/trustcache.txt'+tar -xzf '$REMOTE/deploy.tar.gz' -C '$REMOTE'+rm -f '$REMOTE/deploy.tar.gz'+chmod 755 \+ '$REMOTE/payload/bin/vzboot' \+ '$REMOTE/payload/bin/VZHostCompat.dylib' \+ '$REMOTE/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine'++while IFS=\$(printf '\\t') read -r hash file; do+ test -n "\$hash"+ test -f '$REMOTE/payload/'"\$file"+ jbctl trustcache add "\$hash"+done <'$REMOTE/payload/trustcache.txt'++if test -d '$REMOTE/payload/Installation.xpc'; then+ test -x '$REMOTE/payload/Installation.xpc/Contents/Frameworks/MobileDevice.framework/Versions/A/Resources/usbmuxd'+ printf 'INSTALLATION_OVERLAY\\tpreserved\\n'+else+ printf 'INSTALLATION_OVERLAY\\tnot-installed\\n'+fi++printf 'VM_LIBRARY\\t%s\\n' '/var/mobile/Media/VirtualMac'+EOF+)"++ipad_ssh "$remote_script"+echo "iPad VM payload deployed without altering /var/mobile/Media/VirtualMac"diff --git a/VirtualMac/scripts/development/deploy-springboard-tweak.sh b/VirtualMac/scripts/development/deploy-springboard-tweak.shnew file mode 100755index 0000000..9bb7060--- /dev/null+++ b/VirtualMac/scripts/development/deploy-springboard-tweak.sh@@ -0,0 +1,45 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++OUT="$VZ_BUILD_ROOT/ipad-tweak"+DYLIB="$OUT/VZKeyboardPassthrough.dylib"+PLIST="$OUT/VZKeyboardPassthrough.plist"+REMOTE=/var/jb/Library/MobileSubstrate/DynamicLibraries++need_command ldid+need_file "$DYLIB"+need_file "$PLIST"+hash="$(ldid -h "$DYLIB" | sed -n 's/^CDHash=//p')"++VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"+ensure_ipad_usb+ipad_scp "$DYLIB" "$IPAD_TARGET:/tmp/VZKeyboardPassthrough.dylib"+ipad_scp "$PLIST" "$IPAD_TARGET:/tmp/VZKeyboardPassthrough.plist"+ipad_ssh "+set -eu+mkdir -p '$REMOTE'+install -m 755 /tmp/VZKeyboardPassthrough.dylib '$REMOTE/VZKeyboardPassthrough.dylib'+install -m 644 /tmp/VZKeyboardPassthrough.plist '$REMOTE/VZKeyboardPassthrough.plist'+jbctl trustcache add '$hash'+rm -f /tmp/VZKeyboardPassthrough.dylib /tmp/VZKeyboardPassthrough.plist \+ /tmp/vz-springboard-shortcuts.log+touch /tmp/virtual-mac-open-after-respring+chown mobile:mobile /tmp/virtual-mac-open-after-respring+/var/jb/usr/bin/sbreload+" || true++for _ in {1..30}; do+ if ipad_ssh "test -f /tmp/vz-springboard-shortcuts.log" \+ >/dev/null 2>&1; then+ break+ fi+ sleep 1+done+ipad_ssh "+/var/jb/usr/bin/uiopen --bundleid com.mac.virtual || true+cat /tmp/vz-springboard-shortcuts.log 2>/dev/null || true+"diff --git a/VirtualMac/scripts/development/deploy-vmm-compat.sh b/VirtualMac/scripts/development/deploy-vmm-compat.shnew file mode 100755index 0000000..41d5cd0--- /dev/null+++ b/VirtualMac/scripts/development/deploy-vmm-compat.sh@@ -0,0 +1,30 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++LOCAL="${VZ_VMM_COMPAT_OUTPUT:-$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/LaunchServicesCompat.dylib}"+REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}/payload/Frameworks/LaunchServicesCompat.dylib"++need_command ldid+need_file "$LOCAL"+hash="$(ldid -h "$LOCAL" | sed -n 's/^CDHash=//p')"+[[ -n "$hash" ]] || die "could not read VMM hook CDHash"++ensure_ipad_usb+ipad_scp "$LOCAL" "$IPAD_TARGET:/tmp/LaunchServicesCompat.dylib"+VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"+ipad_ssh "+set -eu+install -m 755 /tmp/LaunchServicesCompat.dylib '$REMOTE'+rm -f /tmp/LaunchServicesCompat.dylib+jbctl trustcache add '$hash'+"+# The launchd Mach service can respawn between the pre-copy stop and install.+# Stop once more so the next client cannot reuse a process holding the old+# compatibility image.+VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"++echo "Loaded VMM hook library deployed; launch with scripts/launch-ipad-app.sh"diff --git a/VirtualMac/scripts/development/fetch-network-sharing.sh b/VirtualMac/scripts/development/fetch-network-sharing.shnew file mode 100755index 0000000..7108539--- /dev/null+++ b/VirtualMac/scripts/development/fetch-network-sharing.sh@@ -0,0 +1,30 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++OUT="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS"+mkdir -p "$OUT/usr/libexec" "$OUT/usr/sbin" \+ "$OUT/System/Library/LaunchDaemons"++need_command sshpass+real_mac_ssh_args+real_mac_scp \+ "$REAL_MAC_TARGET:/usr/libexec/InternetSharing" \+ "$OUT/usr/libexec/InternetSharing"+real_mac_scp \+ "$REAL_MAC_TARGET:/System/Library/LaunchDaemons/com.apple.NetworkSharing.plist" \+ "$OUT/System/Library/LaunchDaemons/com.apple.NetworkSharing.plist"+real_mac_scp \+ "$REAL_MAC_TARGET:/usr/libexec/bootpd" \+ "$OUT/usr/libexec/bootpd"+real_mac_scp \+ "$REAL_MAC_TARGET:/usr/sbin/rtadvd" \+ "$OUT/usr/sbin/rtadvd"+real_mac_scp \+ "$REAL_MAC_TARGET:/System/Library/LaunchDaemons/bootps.plist" \+ "$OUT/System/Library/LaunchDaemons/bootps.plist"++echo "Ventura NetworkSharing inputs fetched from $REAL_MAC_TARGET"diff --git a/VirtualMac/scripts/development/install-apple-sample-vm-real-mac.sh b/VirtualMac/scripts/development/install-apple-sample-vm-real-mac.shnew file mode 100755index 0000000..09b89fd--- /dev/null+++ b/VirtualMac/scripts/development/install-apple-sample-vm-real-mac.sh@@ -0,0 +1,35 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+: "${VZ_REAL_MAC_VM:?set VZ_REAL_MAC_VM to the restore destination bundle}"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+REMOTE_IPSW="${VZ_REAL_MAC_IPSW:-$REMOTE_ROOT/input/UniversalMac_13.2.1_22D68_Restore.ipsw}"+REMOTE_VM="$VZ_REAL_MAC_VM"+INSTALLER="$REMOTE_ROOT/DerivedData/Build/Products/Debug/InstallationTool-Objective-C"++need_command sshpass++remote_script="$(cat <<EOF+set -eu+test -x '$INSTALLER'+test -f '$REMOTE_IPSW'+if test -e '$REMOTE_VM'; then+ echo 'refusing to overwrite existing VM: $REMOTE_VM' >&2+ exit 1+fi+if test "$(basename "$REMOTE_VM")" != VM.bundle; then+ echo 'the pinned Apple sample requires a destination named VM.bundle' >&2+ exit 1+fi+cd '$(dirname "$REMOTE_VM")'+NSUnbufferedIO=YES '$INSTALLER' '$REMOTE_IPSW'+EOF+)"++echo "Installing a fresh 64 GiB VM. The sparse image will consume less physical space."+real_mac_ssh "$remote_script"diff --git a/VirtualMac/scripts/development/install-ipad-network-tools.sh b/VirtualMac/scripts/development/install-ipad-network-tools.shnew file mode 100755index 0000000..e047b4b--- /dev/null+++ b/VirtualMac/scripts/development/install-ipad-network-tools.sh@@ -0,0 +1,10 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++ensure_ipad_usb+ipad_ssh \+ "DEBIAN_FRONTEND=noninteractive apt-get install -y network-cmds"diff --git a/VirtualMac/scripts/development/ipad.sh b/VirtualMac/scripts/development/ipad.shnew file mode 100755index 0000000..4916101--- /dev/null+++ b/VirtualMac/scripts/development/ipad.sh@@ -0,0 +1,21 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++case "${1:-}" in+ ssh)+ shift+ ipad_ssh "$@"+ ;;+ scp)+ shift+ ensure_ipad_usb+ ipad_scp "$@"+ ;;+ *)+ die "usage: scripts/development/ipad.sh ssh command | scp source destination"+ ;;+esacdiff --git a/VirtualMac/scripts/development/open-ipad-ui.sh b/VirtualMac/scripts/development/open-ipad-ui.shnew file mode 100755index 0000000..e79d8c7--- /dev/null+++ b/VirtualMac/scripts/development/open-ipad-ui.sh@@ -0,0 +1,16 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++DESTINATION="${1:-library}"+case "$DESTINATION" in+ library|new|settings|keyboard-show|keyboard-hide) ;;+ *) die "usage: $0 library | new | settings | keyboard-show | keyboard-hide" ;;+esac++ensure_ipad_usb+ipad_ssh "/var/jb/usr/bin/uiopen 'virtualmac://$DESTINATION'"+echo "opened visible Virtual Mac $DESTINATION UI on the iPad"diff --git a/VirtualMac/scripts/development/prepare-apple-sample-real-mac.sh b/VirtualMac/scripts/development/prepare-apple-sample-real-mac.shnew file mode 100755index 0000000..e5cb9a4--- /dev/null+++ b/VirtualMac/scripts/development/prepare-apple-sample-real-mac.sh@@ -0,0 +1,59 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SAMPLE_COMMIT="d7c5d919a3ff1364f9114ad48f71b6b63a8a23f2"+: "${VZ_APPLE_SAMPLE_SOURCE:?set VZ_APPLE_SAMPLE_SOURCE to the Apple sample checkout}"+: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK to an absolute work directory on the reference Mac}"+LOCAL_SAMPLE="$VZ_APPLE_SAMPLE_SOURCE"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+REMOTE_SOURCE="$REMOTE_ROOT/RunningMacOSInAVirtualMachineOnAppleSilicon"+REMOTE_DERIVED_DATA="$REMOTE_ROOT/DerivedData"+ARCHIVE="$(mktemp -t apple-vz-sample.XXXXXX.tar)"+trap 'rm -f "$ARCHIVE"' EXIT++need_command git+need_command sshpass+[[ -d "$LOCAL_SAMPLE/.git" ]] || die "missing Apple sample repository: $LOCAL_SAMPLE"+[[ "$(git -C "$LOCAL_SAMPLE" rev-parse "$SAMPLE_COMMIT")" == "$SAMPLE_COMMIT" ]] ||+ die "Apple sample commit is not available locally: $SAMPLE_COMMIT"++git -C "$LOCAL_SAMPLE" archive --format=tar -o "$ARCHIVE" "$SAMPLE_COMMIT"+real_mac_ssh "mkdir -p '$REMOTE_ROOT' '$REMOTE_SOURCE'"+real_mac_ssh_args+real_mac_scp "$ARCHIVE" "$REAL_MAC_TARGET:$REMOTE_ROOT/apple-vz-sample.tar"++remote_script="$(cat <<EOF+set -eu+export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer+test "\$(xcodebuild -version | head -1)" = "Xcode 14.2"+rm -rf '$REMOTE_SOURCE'+mkdir -p '$REMOTE_SOURCE'+tar -xf '$REMOTE_ROOT/apple-vz-sample.tar' -C '$REMOTE_SOURCE'+rm -f '$REMOTE_ROOT/apple-vz-sample.tar'+grep -Fq '64ull * 1024ull * 1024ull * 1024ull' \+ '$REMOTE_SOURCE/Objective-C/InstallationTool/MacOSVirtualMachineInstaller.m'+xcodebuild -project '$REMOTE_SOURCE/macOSVirtualMachineSampleApp.xcodeproj' \+ -scheme InstallationTool-Objective-C -configuration Debug \+ -derivedDataPath '$REMOTE_DERIVED_DATA' \+ CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= build+xcodebuild -project '$REMOTE_SOURCE/macOSVirtualMachineSampleApp.xcodeproj' \+ -scheme macOSVirtualMachineSampleApp-Objective-C -configuration Debug \+ -derivedDataPath '$REMOTE_DERIVED_DATA' \+ CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= build+APP='$REMOTE_DERIVED_DATA/Build/Products/Debug/macOSVirtualMachineSampleApp-Objective-C.app'+INSTALLER='$REMOTE_DERIVED_DATA/Build/Products/Debug/InstallationTool-Objective-C'+file "\$APP/Contents/MacOS/macOSVirtualMachineSampleApp-Objective-C"+file "\$INSTALLER"+codesign --verify --strict "\$APP"+codesign --verify --strict "\$INSTALLER"+EOF+)"++real_mac_ssh "$remote_script"+echo "built pinned Objective-C Apple sample on the real Mac"+echo "source commit: $SAMPLE_COMMIT"+echo "disk size in pinned installer: 64 GiB"diff --git a/VirtualMac/scripts/development/prepare-ipad-vm-metadata.sh b/VirtualMac/scripts/development/prepare-ipad-vm-metadata.shnew file mode 100755index 0000000..012beb0--- /dev/null+++ b/VirtualMac/scripts/development/prepare-ipad-vm-metadata.sh@@ -0,0 +1,33 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_VM:?set VZ_REAL_MAC_VM to the VM bundle on the reference Mac}"+REMOTE_VM="$VZ_REAL_MAC_VM"+OUT="$VZ_BUILD_ROOT/ipad-vm/VM.bundle"++need_command sshpass+mkdir -p "$OUT"+real_mac_ssh "test -f '$REMOTE_VM/HardwareModel'; test -f '$REMOTE_VM/MachineIdentifier'"+real_mac_ssh_args+real_mac_scp \+ "$REAL_MAC_TARGET:$REMOTE_VM/HardwareModel" \+ "$OUT/HardwareModel"+real_mac_scp \+ "$REAL_MAC_TARGET:$REMOTE_VM/MachineIdentifier" \+ "$OUT/MachineIdentifier"++{+ printf 'VM_METADATA\t1\n'+ for file in HardwareModel MachineIdentifier; do+ printf '%s\t%s\t%s\n' \+ "$file" \+ "$(stat -f %z "$OUT/$file")" \+ "$(shasum -a 256 "$OUT/$file" | awk '{print $1}')"+ done+} >"$OUT/manifest.txt"++echo "matching-Mac VM metadata prepared: $OUT"diff --git a/VirtualMac/scripts/development/probe-ipad-amfi-entitlement.sh b/VirtualMac/scripts/development/probe-ipad-amfi-entitlement.shnew file mode 100755index 0000000..bdeaffe--- /dev/null+++ b/VirtualMac/scripts/development/probe-ipad-amfi-entitlement.sh@@ -0,0 +1,60 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SOURCE="$VZ_REPO_ROOT/vz/development/probes/amfi_entitlement_probe.c"+LIBJAILBREAK="$VZ_BUILD_ROOT/analysis/libjailbreak.dylib"+DOPAMINE_HEADERS="$VZ_BUILD_ROOT/toolchain/Dopamine-src/BaseBin/libjailbreak/src"+DOPAMINE_COMMIT="e89072adc591881146c9513a616fa68b7323d6a7"+OUT="$VZ_BUILD_ROOT/probes/amfi-entitlement-probe"+REMOTE="/var/jb/usr/local/bin/amfi-entitlement-probe"+SDK="$(xcrun --sdk iphoneos --show-sdk-path)"++need_command ldid+need_command xcrun+need_command git+need_file "$SOURCE"+mkdir -p "$(dirname "$OUT")"++if [[ ! -f "$DOPAMINE_HEADERS/info.h" ]]; then+ git clone https://github.com/opa334/Dopamine.git \+ "$VZ_BUILD_ROOT/toolchain/Dopamine-src"+ git -C "$VZ_BUILD_ROOT/toolchain/Dopamine-src" checkout --detach \+ "$DOPAMINE_COMMIT"+fi+if [[ ! -f "$LIBJAILBREAK" ]]; then+ ensure_ipad_usb+ mkdir -p "$(dirname "$LIBJAILBREAK")"+ ipad_scp \+ "$IPAD_TARGET:/var/jb/basebin/libjailbreak.dylib" \+ "$LIBJAILBREAK"+fi+need_file "$LIBJAILBREAK"+need_file "$DOPAMINE_HEADERS/info.h"++xcrun --sdk iphoneos clang -arch arm64e \+ -miphoneos-version-min=16.0 -isysroot "$SDK" \+ -I"$DOPAMINE_HEADERS" \+ "$SOURCE" "$LIBJAILBREAK" -o "$OUT"+install_name_tool -change @loader_path/libjailbreak.dylib \+ /var/jb/basebin/libjailbreak.dylib "$OUT"+ldid -S"$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements" "$OUT"++ensure_ipad_usb+ipad_scp "$OUT" "$IPAD_TARGET:/tmp/amfi-entitlement-probe"+ipad_ssh "+set -eu+mkdir -p /var/jb/usr/local/bin+install -o root -g wheel -m 755 /tmp/amfi-entitlement-probe '$REMOTE'+rm -f /tmp/amfi-entitlement-probe+jbctl trustcache add '$(ldid -h "$OUT" | sed -n 's/^CDHash=//p')'+/var/jb/usr/bin/launchctl kickstart -k \+ user/501/com.apple.NetworkSharing+pid=\$(/var/jb/usr/bin/launchctl print user/501/com.apple.NetworkSharing | \+ sed -n 's/^[[:space:]]*pid = \\([0-9][0-9]*\\)\$/\\1/p' | head -1)+test -n \"\$pid\"+'$REMOTE' \"\$pid\"+"diff --git a/VirtualMac/scripts/development/probe-ipad-native-netrb-interface.sh b/VirtualMac/scripts/development/probe-ipad-native-netrb-interface.shnew file mode 100755index 0000000..6f88821--- /dev/null+++ b/VirtualMac/scripts/development/probe-ipad-native-netrb-interface.sh@@ -0,0 +1,56 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+SOURCE="$VZ_REPO_ROOT/vz/development/probes/netrb_native_interface_probe.c"+PLIST="$VZ_REPO_ROOT/vz/development/probes/netrb-native-probe-launchd.plist"+ENTS="$VZ_REPO_ROOT/vz/development/probes/netrb-native-probe.ents.xml"+OUT="$VZ_BUILD_ROOT/probes/netrb-native-interface-probe"+need_command ldid+need_command xcrun+need_file "$SOURCE"+need_file "$PLIST"+need_file "$ENTS"+mkdir -p "$(dirname "$OUT")"+xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=16.0 \+ -isysroot "$SDK" -fblocks -Wl,-undefined,dynamic_lookup \+ "$SOURCE" -o "$OUT"+ldid -S"$ENTS" "$OUT"+ensure_ipad_usb+ipad_scp "$OUT" "$IPAD_TARGET:/tmp/netrb-native-interface-probe"+ipad_scp "$PLIST" "$IPAD_TARGET:/tmp/netrb-native-probe.plist"+hash="$(ldid -h "$OUT" | sed -n 's/^CDHash=//p')"+ipad_ssh "+set -eu+mkdir -p /var/jb/usr/local/bin /var/jb/Library/LaunchDaemons+/var/jb/usr/bin/launchctl bootout \+ user/501/com.mac.virtual.netrb-native-probe 2>/dev/null || true+install -o root -g wheel -m 755 /tmp/netrb-native-interface-probe \+ /var/jb/usr/local/bin/netrb-native-interface-probe+install -o root -g wheel -m 644 /tmp/netrb-native-probe.plist \+ /var/jb/Library/LaunchDaemons/netrb-native-probe.plist+rm -f /tmp/netrb-native-interface-probe /tmp/netrb-native-probe.plist \+ /tmp/netrb-native-interface-probe.log+jbctl trustcache add '$hash'+/var/jb/usr/bin/launchctl bootstrap user/501 \+ /var/jb/Library/LaunchDaemons/netrb-native-probe.plist+i=0+probe_status=+while test "\$i" -lt 20; do+ job_output=\$(/var/jb/usr/bin/launchctl print \+ user/501/com.mac.virtual.netrb-native-probe 2>/dev/null || true)+ probe_status=\$(printf '%s\n' "\$job_output" | \+ sed -n 's/^[[:space:]]*last exit code = \([0-9][0-9]*\)$/\1/p' | \+ tail -1)+ test -z "\$probe_status" || break+ i=\$((i + 1))+ sleep 1+done+cat /tmp/netrb-native-interface-probe.log 2>/dev/null || true+test -n "\$probe_status" || exit 124+exit "\$probe_status"+"diff --git a/VirtualMac/scripts/development/probe-ipad-network.sh b/VirtualMac/scripts/development/probe-ipad-network.shnew file mode 100755index 0000000..12206c5--- /dev/null+++ b/VirtualMac/scripts/development/probe-ipad-network.sh@@ -0,0 +1,23 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/probes/net-interfaces"+ENTS="$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements"++need_command ldid+need_command xcrun+need_file "$ENTS"+need_file "$VZ_REPO_ROOT/vz/development/probes/net_interfaces.c"+mkdir -p "$(dirname "$OUT")"+xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=16.0 \+ -isysroot "$SDK" "$VZ_REPO_ROOT/vz/development/probes/net_interfaces.c" -o "$OUT"+ldid -S"$ENTS" "$OUT"++ipad_ssh_args+ipad_scp "$OUT" "$IPAD_TARGET:/tmp/vz-net-interfaces"+ipad_ssh "chmod 755 /tmp/vz-net-interfaces && /tmp/vz-net-interfaces"diff --git a/VirtualMac/scripts/development/probe-ipad-videotoolbox.sh b/VirtualMac/scripts/development/probe-ipad-videotoolbox.shnew file mode 100755index 0000000..ba76d28--- /dev/null+++ b/VirtualMac/scripts/development/probe-ipad-videotoolbox.sh@@ -0,0 +1,48 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++need_command ldid+need_command codesign+need_command xcrun+ensure_ipad_usb++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/ipad-videotoolbox-probe"+BIN="$OUT/vt-pv-probe"+REMOTE=/var/root/VirtualMac/vt-pv-probe+REMOTE_VT=/var/root/VirtualMac/VideoToolbox.probe+mkdir -p "$OUT"++cdhash() {+ local candidate="$1"+ local hash+ hash="$(ldid -h "$candidate" 2>/dev/null | sed -n 's/^CDHash=//p')"+ if [[ -z "$hash" ]]; then+ hash="$(codesign -dvv "$candidate" 2>&1 |+ sed -n 's/^CDHash=//p' | head -1)"+ fi+ printf '%s' "$hash"+}++xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=16.0 \+ -isysroot "$SDK" "$VZ_REPO_ROOT/vz/development/probes/vt_pv_probe.c" \+ -o "$BIN"+ldid -S"$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements" "$BIN"+hash="$(cdhash "$BIN")"+[[ -n "$hash" ]] || die "could not read probe CDHash"++ipad_scp "$BIN" "$IPAD_TARGET:$REMOTE"+argument=""+if [[ -n "${VZ_VIDEO_TOOLBOX_PATH:-}" ]]; then+ need_file "$VZ_VIDEO_TOOLBOX_PATH"+ vt_hash="$(cdhash "$VZ_VIDEO_TOOLBOX_PATH")"+ [[ -n "$vt_hash" ]] || die "could not read VideoToolbox CDHash"+ ipad_scp "$VZ_VIDEO_TOOLBOX_PATH" "$IPAD_TARGET:$REMOTE_VT"+ argument="'$REMOTE_VT'"+ ipad_ssh "chmod 755 '$REMOTE_VT'; jbctl trustcache add '$vt_hash'"+fi+ipad_ssh "chmod 755 '$REMOTE'; jbctl trustcache add '$hash'; '$REMOTE' $argument"diff --git a/VirtualMac/scripts/development/probe-ipad-vz-class.sh b/VirtualMac/scripts/development/probe-ipad-vz-class.shnew file mode 100755index 0000000..0ece34d--- /dev/null+++ b/VirtualMac/scripts/development/probe-ipad-vz-class.sh@@ -0,0 +1,19 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+CLASS_NAME="${1:?usage: $0 ClassName}"++ipad_ssh "+export DYLD_INSERT_LIBRARIES='$REMOTE/payload/bin/VZHostCompat.dylib'+export VZ_INSTANTIATE='${VZ_INSTANTIATE:-0}'+'$REMOTE/payload/bin/objc-methods' \+ '$REMOTE/payload/Frameworks/Hypervisor.framework/Hypervisor' \+ '$REMOTE/payload/Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics' \+ '$REMOTE/payload/Frameworks/Virtualization.framework/Virtualization' \+ '$CLASS_NAME'+"diff --git a/VirtualMac/scripts/development/real-mac.sh b/VirtualMac/scripts/development/real-mac.shnew file mode 100755index 0000000..a93c3ae--- /dev/null+++ b/VirtualMac/scripts/development/real-mac.sh@@ -0,0 +1,25 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++need_command sshpass++case "${1:-}" in+ ssh)+ shift+ real_mac_ssh "$@"+ ;;+ scp)+ shift+ real_mac_scp "$@"+ ;;+ *)+ echo "usage: scripts/development/real-mac.sh ssh '<command>'" >&2+ echo " scripts/development/real-mac.sh scp <source> <destination>" >&2+ exit 2+ ;;+esac+diff --git a/VirtualMac/scripts/development/restart-ipad-userspace.sh b/VirtualMac/scripts/development/restart-ipad-userspace.shnew file mode 100755index 0000000..a6ecafa--- /dev/null+++ b/VirtualMac/scripts/development/restart-ipad-userspace.sh@@ -0,0 +1,26 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++TIMEOUT="${VZ_IPAD_RESTART_TIMEOUT:-60}"+[[ "$TIMEOUT" =~ ^[0-9]+$ ]] ||+ die "VZ_IPAD_RESTART_TIMEOUT must be a non-negative integer"++VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"+echo "requesting iPad userspace reboot"+ipad_ssh '/var/jb/usr/bin/launchctl reboot userspace' >/dev/null 2>&1 || true++remaining="$TIMEOUT"+while ((remaining > 0)); do+ if ipad_ssh 'test -x /var/jb/usr/bin/launchctl' >/dev/null 2>&1; then+ echo "iPad userspace is reachable"+ exit 0+ fi+ sleep 2+ ((remaining = remaining >= 2 ? remaining - 2 : 0))+done++die "iPad did not return over USB SSH within ${TIMEOUT}s"diff --git a/VirtualMac/scripts/development/restore-ipad-good-guest.sh b/VirtualMac/scripts/development/restore-ipad-good-guest.shnew file mode 100755index 0000000..8a5fdb4--- /dev/null+++ b/VirtualMac/scripts/development/restore-ipad-good-guest.sh@@ -0,0 +1,27 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++IPAD_ROOT="/var/mobile/Media/VirtualMac"+BASELINE="${VZ_IPAD_BASELINE:-$IPAD_ROOT/Baselines/GoodVM.bundle}"+WORKING="$IPAD_ROOT/GoodVM.bundle"+STAGE="$IPAD_ROOT/Transfers/GoodVM-restore-stage.bundle"++VZ_STOP_HOST=1 "$SCRIPT_DIR/stop-ipad-vm.sh"+ipad_ssh "+set -eu+test -f '$BASELINE/Disk.img'+test -f '$BASELINE/AuxiliaryStorage'+test \"\$(stat -c %s '$BASELINE/Disk.img')\" = 68719476736+mkdir -p '$IPAD_ROOT/Transfers'+rm -rf '$STAGE'+/var/jb/usr/bin/cp -a --reflink=always '$BASELINE' '$STAGE'+rm -rf '$WORKING'+mv '$STAGE' '$WORKING'+stat -c '%s %n' '$WORKING/'*+"++echo "working iPad guest restored from the clean on-device baseline"diff --git a/VirtualMac/scripts/development/run-apple-sample-vm-real-mac.sh b/VirtualMac/scripts/development/run-apple-sample-vm-real-mac.shnew file mode 100755index 0000000..db7e9df--- /dev/null+++ b/VirtualMac/scripts/development/run-apple-sample-vm-real-mac.sh@@ -0,0 +1,21 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+: "${VZ_REAL_MAC_VM:?set VZ_REAL_MAC_VM to the VM bundle on the reference Mac}"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+APP="$REMOTE_ROOT/DerivedData/Build/Products/Debug/macOSVirtualMachineSampleApp-Objective-C.app"++need_command sshpass++active="$(real_mac_ssh \+ "pgrep -f 'macOSVirtualMachineSampleApp-Objective-C|com.apple.Virtualization.VirtualMachine' || true")"+[[ -z "$active" ]] ||+ die "a Virtualization VM is already active on the real Mac (PIDs: $active)"++real_mac_ssh "test -d '$VZ_REAL_MAC_VM'; test -d '$APP'; open -n '$APP'"+echo "launched the arm64 Objective-C sample with system frameworks"diff --git a/VirtualMac/scripts/development/run-ipad-macos-install.sh b/VirtualMac/scripts/development/run-ipad-macos-install.shnew file mode 100755index 0000000..c324ffb--- /dev/null+++ b/VirtualMac/scripts/development/run-ipad-macos-install.sh@@ -0,0 +1,50 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+: "${VZ_IPAD_INSTALL_IPSW:?set VZ_IPAD_INSTALL_IPSW to an on-device restore image}"+: "${VZ_IPAD_INSTALL_BUNDLE:?set VZ_IPAD_INSTALL_BUNDLE to an on-device staging bundle}"+: "${VZ_IPAD_INSTALL_FINAL_BUNDLE:?set VZ_IPAD_INSTALL_FINAL_BUNDLE to the final on-device VM bundle}"+: "${VZ_IPAD_INSTALL_LOG:?set VZ_IPAD_INSTALL_LOG to an on-device log path}"+IPSW="$VZ_IPAD_INSTALL_IPSW"+STAGING="$VZ_IPAD_INSTALL_BUNDLE"+FINAL="$VZ_IPAD_INSTALL_FINAL_BUNDLE"+LOG="$VZ_IPAD_INSTALL_LOG"+TRACE_USB="${VZ_IPAD_INSTALL_TRACE_USB:-0}"+TRACE_IOKIT="${VZ_IPAD_INSTALL_TRACE_IOKIT:-1}"+TRACE_XPC_LIMIT="${VZ_IPAD_INSTALL_TRACE_XPC_LIMIT:-200}"+FAKE_USB="${VZ_IPAD_INSTALL_FAKE_USB:-1}"+USB_DEBUG_DELAY_MS="${VZ_IPAD_INSTALL_USB_DEBUG_DELAY_MS:-}"+USB_HANDSHAKE_PROBE="${VZ_IPAD_INSTALL_USB_HANDSHAKE_PROBE:-0}"+CPU_COUNT="${VZ_IPAD_INSTALL_CPU_COUNT:-4}"+MEMORY_SIZE="${VZ_IPAD_INSTALL_MEMORY_SIZE:-4294967296}"+STORAGE_SIZE="${VZ_IPAD_INSTALL_STORAGE_SIZE:-68719476736}"++ipad_ssh "+set -eu+VMMHOOK_TRACE_USB='$TRACE_USB' \+VMMHOOK_TRACE_IOKIT='$TRACE_IOKIT' \+VMMHOOK_TRACE_XPC_LIMIT='$TRACE_XPC_LIMIT' \+VMMHOOK_FAKE_USB='$FAKE_USB' \+INSTALL_USB_DEBUG_DELAY_MS='$USB_DEBUG_DELAY_MS' \+INSTALL_USB_TRACE_TRANSFERS='$TRACE_USB' \+ '$REMOTE/install/start-install.sh' '$IPSW' '$STAGING' '$FINAL' '$LOG' \+ '$CPU_COUNT' '$MEMORY_SIZE' '$STORAGE_SIZE'+"++for _ in {1..30}; do+ output="$(ipad_ssh "cat '$LOG' 2>/dev/null || true")"+ printf '%s\n' "$output"+ if [[ "$output" == *INSTALL_BEGIN* ||+ "$output" == *INSTALL_FAILED* ||+ "$output" == *INSTALL_SUCCEEDED* ]]; then+ exit+ fi+ sleep 1+done++die "installer did not reach its initial start marker"diff --git a/VirtualMac/scripts/development/run-ipad-restore-image-probe.sh b/VirtualMac/scripts/development/run-ipad-restore-image-probe.shnew file mode 100755index 0000000..24cc9d5--- /dev/null+++ b/VirtualMac/scripts/development/run-ipad-restore-image-probe.sh@@ -0,0 +1,44 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+: "${VZ_IPAD_INSTALL_IPSW:?set VZ_IPAD_INSTALL_IPSW to an on-device restore image}"+IPSW="$VZ_IPAD_INSTALL_IPSW"++ipad_ssh "+set -eu+test -f '$IPSW'+killall restore-image-probe 2>/dev/null || true+killall com.apple.Virtualization.Installation 2>/dev/null || true+rm -f /tmp/installation_ep.txt /tmp/installation.stderr.log \+ /tmp/restore-vmm.stderr.log \+ /tmp/installationhook.log /tmp/vzxpchook.log+'$REMOTE/install/restore-image-probe' '$IPSW' \+ > /tmp/restore-image-probe.log 2>&1 &+echo \$! >/tmp/restore-image-probe.pid+"++for _ in {1..180}; do+ result="$(ipad_ssh "+ if ! kill -0 \$(cat /tmp/restore-image-probe.pid) 2>/dev/null; then+ cat /tmp/restore-image-probe.log+ echo PROBE_FINISHED+ else+ tail -20 /tmp/restore-image-probe.log+ fi+ ")"+ if [[ "$result" == *PROBE_FINISHED* ]]; then+ printf '%s\n' "$result"+ [[ "$result" == *RESTORE_LOAD_OK* ]]+ exit+ fi+ sleep 1+done++ipad_ssh "cat /tmp/restore-image-probe.log; cat /tmp/vzxpchook.log; \+ cat /tmp/installationhook.log; cat /tmp/installation.stderr.log"+die "restore-image probe timed out"diff --git a/VirtualMac/scripts/development/run-ipad-vm.sh b/VirtualMac/scripts/development/run-ipad-vm.shnew file mode 100755index 0000000..6b1e6a7--- /dev/null+++ b/VirtualMac/scripts/development/run-ipad-vm.sh@@ -0,0 +1,71 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+BUNDLE="${VZ_IPAD_VM_BUNDLE:-/var/mobile/Media/VirtualMac/Sequoia.bundle}"+RUN_SECONDS="${VZ_RUN_SECONDS:-120}"+RESULT_DIR="$VZ_BUILD_ROOT/validation"+RESULT="$RESULT_DIR/ipad-vm-start.txt"++mkdir -p "$RESULT_DIR"+active="$(ipad_ssh \+ "ps ax | grep -E '$REMOTE/payload/bin/vzboot|$REMOTE/payload/VirtualMachine.xpc' | grep -v grep || true")"+[[ -z "$active" ]] ||+ die "native VZ processes are already active on the iPad (PIDs: $active)"+ipad_ssh "test -f '$BUNDLE/Disk.img'; test -f '$BUNDLE/AuxiliaryStorage'; \+ test -f '$BUNDLE/HardwareModel'; test -f '$BUNDLE/MachineIdentifier'"++remote_optional_env=""+for name in VZ_NO_GRAPHICS VZ_NO_INPUT VZ_NO_STORAGE VZ_SKIP_VALIDATE \+ VMMHOOK_DEBUG_SLEEP VMMHOOK_TRACE_USB VMMHOOK_TRACE_IOKIT \+ VMMHOOK_TRACE_VCPU; do+ value="${!name:-}"+ if [[ -n "$value" ]]; then+ printf -v quoted_value '%q' "$value"+ remote_optional_env+="export $name=$quoted_value+"+ fi+done++remote_script="$(cat <<EOF+set -eu+rm -f /tmp/vzxpchook.log /tmp/vmmhook.log /tmp/vmm.stderr.log \+ /tmp/vmm_ep.txt '$REMOTE/vzboot.log'+export VZ_VMM_BIN='$REMOTE/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine'+export VZ_AVP_BOOTER='$REMOTE/payload/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin'+export VZ_RUN_SECONDS='$RUN_SECONDS'+export DYLD_INSERT_LIBRARIES='$REMOTE/payload/bin/VZHostCompat.dylib'+$remote_optional_env+'$REMOTE/payload/bin/vzboot' \+ '$REMOTE/payload/Frameworks/Hypervisor.framework/Hypervisor' \+ '$REMOTE/payload/Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics' \+ '$REMOTE/payload/Frameworks/Virtualization.framework/Virtualization' \+ '$BUNDLE' \+ >'$REMOTE/vzboot.log' 2>&1 &+host_pid=\$!+printf 'HOST_PID\\t%s\\n' "\$host_pid"+i=0+while kill -0 "\$host_pid" 2>/dev/null && test "\$i" -lt '$RUN_SECONDS'; do+ sleep 1+ i=\$((i + 1))+done+echo HOST_LOG+cat '$REMOTE/vzboot.log' 2>/dev/null || true+echo HOST_HOOK_LOG+cat /tmp/vzxpchook.log 2>/dev/null || true+echo VMM_HOOK_LOG+cat /tmp/vmmhook.log 2>/dev/null || true+echo VMM_STDERR+cat /tmp/vmm.stderr.log 2>/dev/null || true+echo PROCESSES+ps ax | grep -E 'vzboot|com.apple.Virtualization.VirtualMachine' | grep -v grep || true+wait "\$host_pid" || true+EOF+)"++ipad_ssh "$remote_script" | tee "$RESULT"+echo "iPad VM start evidence: $RESULT"diff --git a/VirtualMac/scripts/development/run-ipad-vmnet-probe.sh b/VirtualMac/scripts/development/run-ipad-vmnet-probe.shnew file mode 100755index 0000000..c13ee61--- /dev/null+++ b/VirtualMac/scripts/development/run-ipad-vmnet-probe.sh@@ -0,0 +1,74 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++PROBE="$VZ_BUILD_ROOT/probes/vmnet-probe"+REMOTE="/var/jb/usr/local/bin/vmnet-probe"+RUNTIME="$VZ_BUILD_ROOT/probes/vmnet-runtime"+PLIST="$VZ_REPO_ROOT/vz/development/probes/vmnet-probe-launchd.plist"+DEPLOY_PLIST="$VZ_BUILD_ROOT/probes/vmnet-probe-launchd.plist"+need_command ldid+need_command plutil+need_file "$PROBE"+need_file "$RUNTIME/vmnet.framework/vmnet"+need_file "$RUNTIME/Netrb.framework/Netrb"+need_file "$PLIST"+cp "$PLIST" "$DEPLOY_PLIST"+if [[ "${VZ_VMNET_PROBE_WAIT_FOR_DEBUGGER:-0}" == 1 ]]; then+ plutil -insert WaitForDebugger -bool YES "$DEPLOY_PLIST"+fi+ensure_ipad_usb+ipad_scp "$PROBE" "$IPAD_TARGET:/tmp/vmnet-probe"+ipad_scp "$RUNTIME/vmnet.framework/vmnet" "$IPAD_TARGET:/tmp/vmnet"+ipad_scp "$RUNTIME/Netrb.framework/Netrb" "$IPAD_TARGET:/tmp/Netrb"+ipad_scp "$DEPLOY_PLIST" "$IPAD_TARGET:/tmp/vmnet-probe.plist"+hash="$(ldid -h "$PROBE" | sed -n 's/^CDHash=//p')"+vmnet_hash="$(ldid -h "$RUNTIME/vmnet.framework/vmnet" | sed -n 's/^CDHash=//p')"+netrb_hash="$(ldid -h "$RUNTIME/Netrb.framework/Netrb" | sed -n 's/^CDHash=//p')"+ipad_ssh "+set -eu+mkdir -p /var/jb/usr/local/bin /var/jb/usr/local/lib/vmnet.framework \+ /var/jb/usr/local/lib/Netrb.framework /var/jb/Library/LaunchDaemons+/var/jb/usr/bin/launchctl bootout \+ user/501/com.mac.virtual.vmnet-probe 2>/dev/null || true+/var/jb/usr/bin/launchctl bootout \+ system/com.mac.virtual.vmnet-probe 2>/dev/null || true+install -o root -g wheel -m 755 /tmp/vmnet-probe '$REMOTE'+install -o root -g wheel -m 755 /tmp/vmnet \+ /var/jb/usr/local/lib/vmnet.framework/vmnet+install -o root -g wheel -m 755 /tmp/Netrb \+ /var/jb/usr/local/lib/Netrb.framework/Netrb+install -o root -g wheel -m 644 /tmp/vmnet-probe.plist \+ /var/jb/Library/LaunchDaemons/com.mac.virtual.vmnet-probe.plist+rm -f /tmp/vmnet-probe /tmp/vmnet /tmp/Netrb /tmp/vmnet-probe.plist \+ /tmp/vmnet-probe-launchd.log+jbctl trustcache add '$hash'+jbctl trustcache add '$vmnet_hash'+jbctl trustcache add '$netrb_hash'+/var/jb/usr/bin/launchctl bootstrap user/501 \+ /var/jb/Library/LaunchDaemons/com.mac.virtual.vmnet-probe.plist+/var/jb/usr/bin/launchctl kickstart -k \+ user/501/com.mac.virtual.vmnet-probe+i=0+probe_status=+while [ x\$probe_status = x ]; do+ i=\$((i + 1))+ if [ "\$i" -ge 130 ]; then+ echo 'vmnet probe: launchd job timed out' >&2+ exit 124+ fi+ probe_status=\$(/var/jb/usr/bin/launchctl print \+ user/501/com.mac.virtual.vmnet-probe 2>/dev/null | \+ sed -n 's/^[[:space:]]*last exit code = \([0-9][0-9]*\)$/\1/p' | \+ tail -1 || true)+ if [ x\$probe_status != x ]; then+ break+ fi+ sleep 1+done+cat /tmp/vmnet-probe-launchd.log 2>/dev/null || true+exit "\${probe_status:-1}"+"diff --git a/VirtualMac/scripts/development/start-ipad-installation-trace.sh b/VirtualMac/scripts/development/start-ipad-installation-trace.shnew file mode 100755index 0000000..13c4255--- /dev/null+++ b/VirtualMac/scripts/development/start-ipad-installation-trace.sh@@ -0,0 +1,24 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}"+COMMANDS="$VZ_REPO_ROOT/vz/development/lldb/trace_installation_restore.lldb"+need_file "$COMMANDS"+ensure_ipad_usb+ipad_ssh "killall lldb 2>/dev/null || true; mkdir -p '$REMOTE/lldb'"+ipad_scp "$COMMANDS" \+ "$IPAD_TARGET:$REMOTE/lldb/trace_installation_restore.lldb"+ipad_ssh "+rm -f /tmp/installation-restore-lldb.log+nohup /var/jb/usr/bin/lldb -b \+ -o 'process attach --name com.apple.Virtualization.Installation --waitfor' \+ -s '$REMOTE/lldb/trace_installation_restore.lldb' \+ -o continue \+ >/tmp/installation-restore-lldb.log 2>&1 </dev/null &+echo LLDB_TRACE_STARTED+echo LOG=/tmp/installation-restore-lldb.log+"diff --git a/VirtualMac/scripts/development/start-visible-ipad-install.sh b/VirtualMac/scripts/development/start-visible-ipad-install.shnew file mode 100755index 0000000..1890cde--- /dev/null+++ b/VirtualMac/scripts/development/start-visible-ipad-install.sh@@ -0,0 +1,49 @@+#!/bin/bash++# Launch a restore through Virtual Mac's real, visible UIKit installation flow.+# This is intended for repeatable end-to-end validation of the same path a+# person triggers with Add -> Install from IPSW, including its progress UI.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_IPAD_INSTALL_IPSW:?set VZ_IPAD_INSTALL_IPSW to an on-device restore image}"+: "${VZ_IPAD_INSTALL_NAME:?set VZ_IPAD_INSTALL_NAME to the VM display name}"+IPSW="$VZ_IPAD_INSTALL_IPSW"+NAME="$VZ_IPAD_INSTALL_NAME"+LIBRARY="/var/mobile/Media/VirtualMac"+SUPPORT="$LIBRARY"+REQUEST="$SUPPORT/.visible-install-request"+BUNDLE="$LIBRARY/$NAME.bundle"++[[ "$IPSW" == "$SUPPORT/Restore Images/"* ]] ||+ die "VZ_IPAD_INSTALL_IPSW must be in $SUPPORT/Restore Images"+[[ "$NAME" =~ ^[A-Za-z0-9._\ -]+$ ]] ||+ die "VZ_IPAD_INSTALL_NAME contains unsupported characters"++ensure_ipad_usb+ipad_ssh "+set -eu+test -f '$IPSW'+test ! -e '$BUNDLE'+mkdir -p '$SUPPORT'+printf '%s\\n%s\\n' '$NAME' '$IPSW' >'$REQUEST'+chown mobile:mobile '$REQUEST'+chmod 600 '$REQUEST'+killall VirtualMac 2>/dev/null || true+sleep 1+/var/jb/usr/bin/uiopen --bundleid com.mac.virtual+"++for _ in {1..20}; do+ log="$(ipad_ssh "cat /tmp/VirtualMac.log 2>/dev/null || true")"+ if [[ "$log" == *"visible installation request name=$NAME"* ]]; then+ echo "VISIBLE_INSTALL_STARTED name=$NAME ipsw=$IPSW"+ exit 0+ fi+ sleep 0.25+done++die "Virtual Mac did not consume the visible installation request"diff --git a/VirtualMac/scripts/development/stop-ipad-vm.sh b/VirtualMac/scripts/development/stop-ipad-vm.shnew file mode 100755index 0000000..d26c666--- /dev/null+++ b/VirtualMac/scripts/development/stop-ipad-vm.sh@@ -0,0 +1,176 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++TIMEOUT="${VZ_GUEST_STOP_TIMEOUT:-12}"+FORCE_TIMEOUT="${VZ_FORCE_STOP_TIMEOUT:-15}"+STOP_HOST="${VZ_STOP_HOST:-0}"+GUEST_HOST="${VZ_GUEST_HOST:-}"+GUEST_USER="${VZ_GUEST_USER:-}"+GUEST_PASSWORD="${VZ_GUEST_PASSWORD:-}"+GUEST_SHUTDOWN_PORT="${VZ_GUEST_SHUTDOWN_PORT:-2218}"+[[ "$TIMEOUT" =~ ^[0-9]+$ ]] ||+ die "VZ_GUEST_STOP_TIMEOUT must be a non-negative integer"+[[ "$FORCE_TIMEOUT" =~ ^[0-9]+$ ]] ||+ die "VZ_FORCE_STOP_TIMEOUT must be a non-negative integer"+[[ "$STOP_HOST" == 0 || "$STOP_HOST" == 1 ]] ||+ die "VZ_STOP_HOST must be 0 or 1"++# Prefer an OS-level shutdown over Virtualization's virtual power button. The+# latter intentionally presents a macOS confirmation sheet and is not a+# dependable unattended control path. If guest SSH is not ready, continue to+# the VZ request/stop fallback below.+if [[ "$TIMEOUT" -gt 0 && -n "$GUEST_HOST" && -n "$GUEST_USER" &&+ -n "$GUEST_PASSWORD" ]] &&+ ! lsof -nP -iTCP:"$GUEST_SHUTDOWN_PORT" -sTCP:LISTEN >/dev/null 2>&1; then+ ensure_ipad_usb+ sshpass -p "$VZ_IPAD_PASSWORD" ssh "${IPAD_SSH_ARGS[@]}" \+ -o ControlMaster=no -o ControlPath=none \+ -N -L "127.0.0.1:$GUEST_SHUTDOWN_PORT:$GUEST_HOST:22" \+ "$IPAD_TARGET" &+ shutdown_tunnel_pid=$!+ for _ in {1..12}; do+ lsof -nP -iTCP:"$GUEST_SHUTDOWN_PORT" -sTCP:LISTEN \+ >/dev/null 2>&1 && break+ sleep 0.25+ done+ if lsof -nP -iTCP:"$GUEST_SHUTDOWN_PORT" -sTCP:LISTEN \+ >/dev/null 2>&1; then+ printf -v guest_password_quoted '%q' "$GUEST_PASSWORD"+ set +e+ shutdown_output="$(sshpass -p "$GUEST_PASSWORD" ssh \+ -p "$GUEST_SHUTDOWN_PORT" \+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -o ConnectTimeout=4 -o PubkeyAuthentication=no \+ -o PreferredAuthentications=password \+ -o NumberOfPasswordPrompts=1 "[email protected]" \+ "printf '%s\\n' $guest_password_quoted | sudo -S -p '' -v && \+ echo VZ_GUEST_SHUTDOWN_REQUESTED && sudo shutdown -h now" 2>&1)"+ set -e+ if [[ "$shutdown_output" == *VZ_GUEST_SHUTDOWN_REQUESTED* ]]; then+ echo "requested guest OS shutdown over SSH"+ # Give launchd/filesystems time to finish, then skip the virtual+ # power-button sheet and go straight to the bounded VZ stop path.+ sleep 8+ TIMEOUT=0+ FORCE_TIMEOUT=3+ fi+ fi+ listener_pids="$(lsof -t -iTCP:"$GUEST_SHUTDOWN_PORT" \+ -sTCP:LISTEN 2>/dev/null || true)"+ if [[ -n "$listener_pids" ]]; then+ # shellcheck disable=SC2086+ kill $listener_pids 2>/dev/null || true+ fi+ kill "$shutdown_tunnel_pid" 2>/dev/null || true+ wait "$shutdown_tunnel_pid" 2>/dev/null || true+fi++ipad_ssh "+set -eu+app=/var/jb/Applications/VirtualMac.app/VirtualMac+host_pattern=/VirtualMac.app/VirtualMac+vmm_pattern=/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine+find_pids() {+ target=\$1+ ps -axo pid=,comm= | while read -r pid executable; do+ case "\$executable" in+ *"\$target") echo "\$pid" ;;+ esac+ done+}+host_pids=\$(find_pids "\$host_pattern" || true)+vmm_pids=\$(find_pids "\$vmm_pattern" || true)+if test -z \"\$host_pids\" && test -z \"\$vmm_pids\"; then+ exit 0+fi+if test -z \"\$vmm_pids\"; then+ if test '$STOP_HOST' = 1; then+ test -z \"\$host_pids\" || kill -9 \$host_pids 2>/dev/null || true+ sleep 1+ else+ echo 'no VM is running; host remains in the library'+ fi+ exit 0+fi+rm -f /tmp/vz-guest-stopped /tmp/vz-guest-stop-failed \+ /tmp/vz-force-stop-failed /tmp/vz-request-guest-stop \+ /tmp/vz-request-force-stop+if test -x \"\$app\"; then+ touch /tmp/vz-request-guest-stop+ chown mobile:mobile /tmp/vz-request-guest-stop+ remaining='$TIMEOUT'+ while test \"\$remaining\" -gt 0 &&+ test ! -f /tmp/vz-guest-stopped &&+ test ! -f /tmp/vz-guest-stop-failed; do+ sleep 1+ remaining=\$((remaining - 1))+ done+fi+if test -f /tmp/vz-guest-stopped; then+ echo 'guest reported a clean stop'+else+ if test -f /tmp/vz-guest-stop-failed; then+ echo 'guest clean stop failed:'+ cat /tmp/vz-guest-stop-failed+ else+ echo 'guest clean stop did not complete; requesting direct VM stop'+ fi+ touch /tmp/vz-request-force-stop+ chown mobile:mobile /tmp/vz-request-force-stop+ remaining='$FORCE_TIMEOUT'+ while test "\$remaining" -gt 0 &&+ test ! -f /tmp/vz-guest-stopped &&+ test ! -f /tmp/vz-force-stop-failed; do+ sleep 1+ remaining=\$((remaining - 1))+ done+ if test -f /tmp/vz-guest-stopped; then+ echo 'direct VM stop completed'+ elif test -f /tmp/vz-force-stop-failed; then+ echo 'direct VM stop failed:'+ cat /tmp/vz-force-stop-failed+ else+ echo 'direct VM stop timed out; terminating host processes'+ fi+fi+if test '$STOP_HOST' = 0; then+ remaining=10+ while test \"\$remaining\" -gt 0; do+ vmm_pids=\$(find_pids \"\$vmm_pattern\" || true)+ test -z \"\$vmm_pids\" && break+ sleep 1+ remaining=\$((remaining - 1))+ done+ vmm_pids=\$(find_pids \"\$vmm_pattern\" || true)+ test -z \"\$vmm_pids\" || kill -9 \$vmm_pids 2>/dev/null || true+ rm -f /tmp/vz-request-guest-stop /tmp/vz-request-force-stop+ echo 'VM stopped; host returned to the library'+ exit 0+fi+test -z \"\$host_pids\" || kill \$host_pids 2>/dev/null || true+test -z \"\$vmm_pids\" || kill \$vmm_pids 2>/dev/null || true+sleep 1+host_pids=\$(find_pids "\$host_pattern" || true)+vmm_pids=\$(find_pids "\$vmm_pattern" || true)+test -z \"\$host_pids\" || kill -9 \$host_pids 2>/dev/null || true+test -z \"\$vmm_pids\" || kill -9 \$vmm_pids 2>/dev/null || true+rm -f /tmp/vz-request-guest-stop /tmp/vz-request-force-stop+remaining=10+while test "\$remaining" -gt 0; do+ host_pids=\$(find_pids "\$host_pattern" || true)+ vmm_pids=\$(find_pids "\$vmm_pattern" || true)+ if test -z \"\$host_pids\" && test -z \"\$vmm_pids\"; then+ break+ fi+ sleep 1+ remaining=\$((remaining - 1))+done+if test -n \"\$host_pids\" || test -n \"\$vmm_pids\"; then+ echo 'error: VM host processes remain after stop' >&2+ exit 1+fi+"diff --git a/VirtualMac/scripts/development/transfer-real-mac-vm.sh b/VirtualMac/scripts/development/transfer-real-mac-vm.shnew file mode 100755index 0000000..8273cab--- /dev/null+++ b/VirtualMac/scripts/development/transfer-real-mac-vm.sh@@ -0,0 +1,42 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_MACOS_IPSW:?set VZ_MACOS_IPSW to the macOS restore image}"+: "${VZ_SOURCE_VM:?set VZ_SOURCE_VM to the source UTM bundle}"+: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+DISK="$VZ_SOURCE_VM/Data/disk.img"+AUX="$VZ_SOURCE_VM/Data/aux.img"++need_file "$VZ_MACOS_IPSW"+need_file "$DISK"+need_file "$AUX"+need_command sshpass++real_mac_ssh_args+real_mac_ssh "mkdir -p '$VZ_REAL_MAC_WORK/VM.bundle' '$VZ_REAL_MAC_WORK/input'"++copy_if_size_differs() {+ local source="$1"+ local destination="$2"+ local local_size remote_size+ local_size="$(stat -f %z "$source")"+ remote_size="$(real_mac_ssh "stat -f %z '$destination' 2>/dev/null || echo 0")"+ if [[ "$local_size" == "$remote_size" ]]; then+ echo "already transferred: $destination ($local_size bytes)"+ return+ fi+ echo "transferring: $source -> $destination ($local_size bytes)"+ sshpass -p "$VZ_REAL_MAC_PASSWORD" scp -C \+ "${REAL_MAC_SCP_ARGS[@]}" "$source" "$REAL_MAC_TARGET:$destination"+}++copy_if_size_differs "$VZ_MACOS_IPSW" \+ "$VZ_REAL_MAC_WORK/input/UniversalMac_13.2.1_22D68_Restore.ipsw"+copy_if_size_differs "$DISK" "$VZ_REAL_MAC_WORK/VM.bundle/Disk.img"+copy_if_size_differs "$AUX" "$VZ_REAL_MAC_WORK/VM.bundle/AuxiliaryStorage"++echo "real Mac VM inputs transferred: $VZ_REAL_MAC_WORK"diff --git a/VirtualMac/scripts/development/validate-frameworks-real-mac.sh b/VirtualMac/scripts/development/validate-frameworks-real-mac.shnew file mode 100755index 0000000..c42f9cf--- /dev/null+++ b/VirtualMac/scripts/development/validate-frameworks-real-mac.sh@@ -0,0 +1,75 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++MAC_DIR="$VZ_BUILD_ROOT/frameworks/macos"+IOS_DIR="$VZ_BUILD_ROOT/frameworks/ios"+BUNDLE_DIR="$VZ_BUILD_ROOT/frameworks/bundles/macos"+RESULT_DIR="$VZ_BUILD_ROOT/validation"+RESULT="$RESULT_DIR/frameworks-real-mac.txt"+REMOTE_DIR="/tmp/VirtualMac-validation"++need_command sshpass+for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ need_file "$MAC_DIR/$name"+ need_file "$IOS_DIR/$name"+ need_file "$BUNDLE_DIR/$name.framework/Versions/A/$name"+done++mkdir -p "$RESULT_DIR"++real_mac_ssh "mkdir -p '$REMOTE_DIR'; find '$REMOTE_DIR' -type f -delete"+real_mac_ssh_args+for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ real_mac_scp "$MAC_DIR/$name" "$REAL_MAC_TARGET:$REMOTE_DIR/$name.macos"+ real_mac_scp "$IOS_DIR/$name" "$REAL_MAC_TARGET:$REMOTE_DIR/$name.ios"+ real_mac_scp -r "$BUNDLE_DIR/$name.framework" "$REAL_MAC_TARGET:$REMOTE_DIR/"+done+real_mac_scp "$VZ_REPO_ROOT/vz/development/probes/vzcfg.m" "$REAL_MAC_TARGET:$REMOTE_DIR/vzcfg.m"++remote_script="$(cat <<'EOF'+set -eu+cd /tmp/VirtualMac-validation+echo "REAL_MAC_FRAMEWORK_VALIDATION 1"+sw_vers+uname -a+sysctl kern.bootargs+xcrun clang -arch arm64e -mmacosx-version-min=13.0 \+ -framework Foundation vzcfg.m -o vzcfg+printf 'PROBE_HEADER\t'+otool -hv vzcfg | tail -1+for variant in macos ios; do+ for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ file="$name.$variant"+ printf 'FIXUPS\t%s\t' "$file"+ /usr/bin/dyld_info -fixups "$file" > "$file.fixups"+ printf '%s\n' "$(wc -l < "$file.fixups" | tr -d ' ')"+ done+done+echo "SYSTEM_BASELINE"+./vzcfg \+ /System/Library/Frameworks/Hypervisor.framework/Versions/A/Hypervisor \+ /System/Library/Frameworks/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics \+ /System/Library/Frameworks/Virtualization.framework/Versions/A/Virtualization+echo "EXTRACTED_MACOS"+./vzcfg \+ ./Hypervisor.framework/Versions/A/Hypervisor \+ ./ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics \+ ./Virtualization.framework/Versions/A/Virtualization+EOF+)"++real_mac_ssh "$remote_script" | tee "$RESULT"+grep -q $'FIXUPS\tHypervisor.macos\t190' "$RESULT" ||+ die "unexpected Hypervisor fixup count on the real Mac"+grep -q $'FIXUPS\tVirtualization.ios\t18437' "$RESULT" ||+ die "unexpected Virtualization fixup count on the real Mac"+[[ "$(grep -c '^ALL RESOLVE$' "$RESULT")" == 2 ]] ||+ die "system or extracted Objective-C dispatch failed"+[[ "$(grep -c '^DISPATCH OK$' "$RESULT")" == 2 ]] ||+ die "system or extracted framework method dispatch failed"++echo "real Mac framework validation passed: $RESULT"diff --git a/VirtualMac/scripts/fetch-ipados-compat-cache.sh b/VirtualMac/scripts/fetch-ipados-compat-cache.shnew file mode 100755index 0000000..3cd3601--- /dev/null+++ b/VirtualMac/scripts/fetch-ipados-compat-cache.sh@@ -0,0 +1,34 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+need_file "$IPSW"++URL="${VZ_IPADOS_COMPAT_URL:-https://updates.cdn-apple.com/2022FallFCS/fullrestores/012-92967/0A594653-0CC9-40AF-81A9-822C59BE0AC6/iPad14%2C3%2CiPad14%2C4%2CiPad14%2C5%2CiPad14%2C6_16.1_20B82_Restore.ipsw}"+OUT="${VZ_IPADOS_COMPAT_ROOT:-$VZ_BUILD_ROOT/compat/ipados-16.1}"+CACHE="$OUT/20B82__iPad14,3_4_5_6/dyld_shared_cache_arm64e"++if [[ ! -f "$CACHE" ]]; then+ mkdir -p "$OUT"+ "$IPSW" extract --remote --dyld --dyld-arch arm64e -o "$OUT" "$URL"+fi++need_file "$CACHE"+info="$("$IPSW" dyld info --no-color "$CACHE")"+grep -Fq 'Platform = iOS' <<<"$info" ||+ die "compatibility cache is not an iOS cache: $CACHE"+grep -Fq 'OS Version = 16.1' <<<"$info" ||+ die "compatibility cache is not iPadOS 16.1: $CACHE"++cat >"$OUT/source.txt" <<EOF+Build: 20B82+Product: iPad14,3,iPad14,4,iPad14,5,iPad14,6+URL: $URL+IPSW SHA-256: 61bc8a8683bc27bc154bf9e9d3a694f6d6b78f55e9e134af839ed5750f4b14a9+EOF++echo "oldest supported iPadOS shared cache ready: $CACHE"diff --git a/VirtualMac/scripts/install-ipad-deb.sh b/VirtualMac/scripts/install-ipad-deb.shnew file mode 100755index 0000000..b46d5be--- /dev/null+++ b/VirtualMac/scripts/install-ipad-deb.sh@@ -0,0 +1,56 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++need_command scp+need_command sshpass+ensure_ipad_usb++if [[ -n "${VZ_IPAD_DEB:-}" ]]; then+ DEB="$VZ_IPAD_DEB"+else+ DEB="$(find "$VZ_BUILD_ROOT/release" -maxdepth 1 -type f \+ -name 'VirtualMac_*.deb' \+ -print0 | xargs -0 ls -1t 2>/dev/null | head -1)"+fi+[[ -n "$DEB" && -f "$DEB" ]] ||+ die "standalone package not found; run scripts/build-ipad-deb.sh first"++REMOTE_DEB="/tmp/$(basename "$DEB")"+echo "copying standalone package to iPad: $DEB"+sshpass -p "$VZ_IPAD_PASSWORD" scp \+ "${IPAD_SCP_ARGS[@]}" "$DEB" "$IPAD_TARGET:$REMOTE_DEB"++# Package preinst owns VM termination. Do not invoke the UI stop action here:+# it asks macOS to shut down and can leave an unattended guest confirmation+# sheet in front of the install.+set +e+install_output="$(ipad_ssh "dpkg -i '$REMOTE_DEB' 2>&1" 2>&1)"+install_status=$?+set -e+printf '%s\n' "$install_output"+((install_status == 0)) || die "dpkg installation failed"++# Maintainer scripts never respring. Sileo consumes finish:restart and offers+# the user its Restart SpringBoard button; direct dpkg installs remain online.+status="$(ipad_ssh "dpkg-query -W -f='\${db:Status-Status}' \+ com.mac.virtual 2>/dev/null || true")"+[[ "$status" == installed ]] ||+ die "package did not reach installed state (status: ${status:-missing})"++ipad_ssh "+set -eu+test -x /var/jb/Applications/VirtualMac.app/VirtualMac+test -u /var/root/VirtualMac/install/install-launcher+test -d /var/mobile/Media/VirtualMac+test -f /var/jb/Library/MobileSubstrate/DynamicLibraries/VZKeyboardPassthrough.dylib+launchctl print user/501/vzi.apple.bootpd >/dev/null+launchctl print user/501/com.apple.NetworkSharing >/dev/null+/var/jb/usr/bin/uicache -l | grep -F 'com.mac.virtual' >/dev/null+rm -f '$REMOTE_DEB'+"++echo "standalone package installed and registered on iPad"diff --git a/VirtualMac/scripts/launch-ipad-app.sh b/VirtualMac/scripts/launch-ipad-app.shnew file mode 100755index 0000000..7c6f65d--- /dev/null+++ b/VirtualMac/scripts/launch-ipad-app.sh@@ -0,0 +1,87 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++ATTEMPTS="${1:-5}"+START_WAIT="${VZ_IPAD_START_WAIT:-12}"+INPUT_SELF_TEST="${VZ_IPAD_INPUT_SELF_TEST:-0}"+DISMISS_RESTART_ALERT="${VZ_IPAD_DISMISS_RESTART_ALERT:-0}"+REMOTE_APP="/var/jb/Applications/VirtualMac.app"++[[ "$ATTEMPTS" =~ ^[1-9][0-9]*$ ]] ||+ die "attempt count must be a positive integer"+[[ "$START_WAIT" =~ ^[1-9][0-9]*$ ]] ||+ die "VZ_IPAD_START_WAIT must be a positive integer"+[[ "$INPUT_SELF_TEST" == "0" || "$INPUT_SELF_TEST" == "1" ]] ||+ die "VZ_IPAD_INPUT_SELF_TEST must be 0 or 1"+[[ "$DISMISS_RESTART_ALERT" == "0" || "$DISMISS_RESTART_ALERT" == "1" ]] ||+ die "VZ_IPAD_DISMISS_RESTART_ALERT must be 0 or 1"++ipad_ssh "+find /tmp -maxdepth 1 -name 'vz-launch-attempt-*' -exec rm -f {} ++"+for ((attempt = 1; attempt <= ATTEMPTS; attempt++)); do+ echo "native VZ launch attempt $attempt/$ATTEMPTS"+ VZ_STOP_HOST=1 "$SCRIPT_DIR/development/stop-ipad-vm.sh"+ ipad_ssh "+set -eu+test -x '$REMOTE_APP/VirtualMac'+rm -f /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+touch /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+chown mobile:mobile /tmp/VirtualMac.log /tmp/vzxpchook.log /tmp/vmmhook.log \+ /tmp/vmm.stderr.log /tmp/vmm_ep.txt /tmp/pvg-trace.log+if test '$INPUT_SELF_TEST' = 1; then+ touch /tmp/vz-input-self-test+ chown mobile:mobile /tmp/vz-input-self-test+else+ rm -f /tmp/vz-input-self-test+fi+if test '$DISMISS_RESTART_ALERT' = 1; then+ touch /tmp/vz-dismiss-restart-alert+ chown mobile:mobile /tmp/vz-dismiss-restart-alert+else+ rm -f /tmp/vz-dismiss-restart-alert+fi+/var/jb/usr/bin/uiopen --bundleid com.mac.virtual+"+ sleep "$START_WAIT"+ result="$(ipad_ssh "+if grep -q 'VM STARTED state=1' /tmp/VirtualMac.log; then+ echo started+elif grep -q 'VM start failed:' /tmp/VirtualMac.log; then+ echo failed+else+ echo pending+fi+")"+ if [[ "$result" == "started" ]]; then+ ipad_ssh "+tail -12 /tmp/VirtualMac.log+grep -E 'hv_vcpu_(create|run)' /tmp/vmmhook.log | tail -6+"+ echo "native iPad VM started on attempt $attempt"+ exit 0+ fi+ echo "attempt $attempt result: $result"+ ipad_ssh "+for log in VirtualMac vzxpchook vmmhook vmm.stderr pvg-trace; do+ test ! -f /tmp/\$log.log ||+ cp /tmp/\$log.log /tmp/vz-launch-attempt-$attempt.\$log.log+done+"+done++ipad_ssh "+echo APP_LOG+tail -40 /tmp/VirtualMac.log 2>/dev/null || true+echo HOST_HOOK_LOG+tail -60 /tmp/vzxpchook.log 2>/dev/null || true+echo VMM_HOOK_LOG+tail -80 /tmp/vmmhook.log 2>/dev/null || true+"+die "native iPad VM did not start after $ATTEMPTS attempts"diff --git a/VirtualMac/scripts/lib/common.sh b/VirtualMac/scripts/lib/common.shnew file mode 100755index 0000000..7a106d8--- /dev/null+++ b/VirtualMac/scripts/lib/common.sh@@ -0,0 +1,136 @@+#!/bin/bash++set -euo pipefail++VZ_REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+VZ_BUILD_ROOT="${VZ_BUILD_ROOT:-$VZ_REPO_ROOT/build}"++if [[ "${VZ_IGNORE_ENV_FILE:-0}" != 1 && -f "$VZ_REPO_ROOT/.env" ]]; then+ set -a+ # shellcheck disable=SC1091+ source "$VZ_REPO_ROOT/.env"+ set +a+fi++die() {+ echo "error: $*" >&2+ exit 1+}++need_command() {+ command -v "$1" >/dev/null 2>&1 || die "missing command: $1"+}++need_file() {+ [[ -f "$1" ]] || die "missing file: $1"+}++real_mac_ssh_args() {+ : "${VZ_REAL_MAC_HOST:?set VZ_REAL_MAC_HOST in .env or the environment}"+ VZ_REAL_MAC_PORT="${VZ_REAL_MAC_PORT:-22}"+ : "${VZ_REAL_MAC_USER:?set VZ_REAL_MAC_USER in .env or the environment}"+ : "${VZ_REAL_MAC_PASSWORD:?set VZ_REAL_MAC_PASSWORD in .env or the environment}"++ REAL_MAC_SSH_ARGS=(+ -p "$VZ_REAL_MAC_PORT"+ -o StrictHostKeyChecking=no+ -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10+ -o PubkeyAuthentication=no+ -o PreferredAuthentications=password+ -o NumberOfPasswordPrompts=1+ )+ REAL_MAC_SCP_ARGS=(+ -P "$VZ_REAL_MAC_PORT"+ -o StrictHostKeyChecking=no+ -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10+ -o PubkeyAuthentication=no+ -o PreferredAuthentications=password+ -o NumberOfPasswordPrompts=1+ )+ REAL_MAC_TARGET="$VZ_REAL_MAC_USER@$VZ_REAL_MAC_HOST"+}++real_mac_ssh() {+ real_mac_ssh_args+ sshpass -p "$VZ_REAL_MAC_PASSWORD" ssh "${REAL_MAC_SSH_ARGS[@]}" "$REAL_MAC_TARGET" "$@"+}++real_mac_scp() {+ real_mac_ssh_args+ sshpass -p "$VZ_REAL_MAC_PASSWORD" scp "${REAL_MAC_SCP_ARGS[@]}" "$@"+}++ipad_ssh_args() {+ if [[ -z "${VZ_IPAD_UDID:-}" ]]; then+ need_command idevice_id+ local devices count+ devices="$(idevice_id -l)"+ count="$(printf '%s\n' "$devices" | awk 'NF { count++ } END { print count+0 }')"+ [[ "$count" == 1 ]] ||+ die "attach exactly one iPad or set VZ_IPAD_UDID"+ VZ_IPAD_UDID="$devices"+ fi+ VZ_IPAD_PORT="${VZ_IPAD_PORT:-2221}"+ # Package installation, trust-cache updates, and userspace restart are+ # privileged operations. The supported Dopamine deployment is root-only.+ VZ_IPAD_USER=root+ : "${VZ_IPAD_PASSWORD:?set VZ_IPAD_PASSWORD in .env or the environment}"+ local control_path="/tmp/VirtualMac-ssh-%C"++ IPAD_SSH_ARGS=(+ -p "$VZ_IPAD_PORT"+ -o StrictHostKeyChecking=no+ -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10+ -o PubkeyAuthentication=no+ -o PreferredAuthentications=password+ -o NumberOfPasswordPrompts=1+ -o ControlMaster=auto+ -o ControlPersist=60+ -o "ControlPath=$control_path"+ )+ IPAD_SCP_ARGS=(+ -P "$VZ_IPAD_PORT"+ -o StrictHostKeyChecking=no+ -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10+ -o PubkeyAuthentication=no+ -o PreferredAuthentications=password+ -o NumberOfPasswordPrompts=1+ -o ControlMaster=auto+ -o ControlPersist=60+ -o "ControlPath=$control_path"+ )+ IPAD_TARGET="[email protected]"+}++ensure_ipad_usb() {+ ipad_ssh_args+ need_command iproxy+ mkdir -p "$VZ_BUILD_ROOT"+ if lsof -nP -iTCP:"$VZ_IPAD_PORT" -sTCP:LISTEN >/dev/null 2>&1; then+ return+ fi++ nohup iproxy -u "$VZ_IPAD_UDID" -l -s 127.0.0.1 \+ "$VZ_IPAD_PORT:22" >"$VZ_BUILD_ROOT/iproxy.log" 2>&1 </dev/null &+ for _ in {1..20}; do+ lsof -nP -iTCP:"$VZ_IPAD_PORT" -sTCP:LISTEN >/dev/null 2>&1 &&+ return+ sleep 0.25+ done+ die "iproxy did not open USB SSH port $VZ_IPAD_PORT"+}++ipad_ssh() {+ ensure_ipad_usb+ sshpass -p "$VZ_IPAD_PASSWORD" ssh \+ "${IPAD_SSH_ARGS[@]}" "$IPAD_TARGET" "$@"+}++ipad_scp() {+ ensure_ipad_usb+ sshpass -p "$VZ_IPAD_PASSWORD" scp "${IPAD_SCP_ARGS[@]}" "$@"+}diff --git a/VirtualMac/scripts/prepare-inputs.sh b/VirtualMac/scripts/prepare-inputs.shnew file mode 100755index 0000000..f8e309b--- /dev/null+++ b/VirtualMac/scripts/prepare-inputs.sh@@ -0,0 +1,183 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++: "${VZ_MACOS_IPSW:?set VZ_MACOS_IPSW to the 13.2.1 22D68 restore image}"+INCLUDE_IPADOS_AUDIT="${VZ_INCLUDE_IPADOS_AUDIT:-0}"+if [[ -n "${VZ_IPADOS_IPSW:-}" ]]; then+ INCLUDE_IPADOS_AUDIT=1+fi+[[ "$INCLUDE_IPADOS_AUDIT" == 0 || "$INCLUDE_IPADOS_AUDIT" == 1 ]] ||+ die "VZ_INCLUDE_IPADOS_AUDIT must be 0 or 1"+if [[ "$INCLUDE_IPADOS_AUDIT" == 1 ]]; then+ : "${VZ_IPADOS_IPSW:?set VZ_IPADOS_IPSW for the full iPadOS audit}"+fi+IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+MAC_OUT="$VZ_BUILD_ROOT/inputs/macos"+IPAD_OUT="$VZ_BUILD_ROOT/inputs/ipados"+MAC_ROOT="$MAC_OUT/22D68__MacOS"+DSC="$MAC_ROOT/dyld_shared_cache_arm64e"+IPAD_DSC="$IPAD_OUT/20D67__iPad14,3_4_5_6/dyld_shared_cache_arm64e"+VZ_ROOT="$MAC_ROOT/System/Library/Frameworks/Virtualization.framework/Versions/A"+VMM="$VZ_ROOT/XPCServices/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+EVENT_TAP="$VZ_ROOT/XPCServices/com.apple.Virtualization.EventTap.xpc/Contents/MacOS/com.apple.Virtualization.EventTap"+RES="$VZ_ROOT/Resources"+HV_INFO="$MAC_ROOT/System/Library/Frameworks/Hypervisor.framework/Versions/A/Resources/Info.plist"+PVG_INFO="$MAC_ROOT/System/Library/Frameworks/ParavirtualizedGraphics.framework/Versions/A/Resources/Info.plist"+METAL_SERIALIZER_INFO="$MAC_ROOT/System/Library/PrivateFrameworks/MetalSerializer.framework/Versions/A/Resources/Info.plist"+VZ_LOCALIZABLE="$RES/Localizable.loctable"+THIN="$MAC_OUT/VirtualMachine.arm64e"+MANIFEST="$VZ_BUILD_ROOT/inputs/manifest.txt"+INTERNET_SHARING="$MAC_ROOT/usr/libexec/InternetSharing"+BOOTPD="$MAC_ROOT/usr/libexec/bootpd"+RTADVD="$MAC_ROOT/usr/sbin/rtadvd"+NETWORK_SHARING_PLIST="$MAC_ROOT/System/Library/LaunchDaemons/com.apple.NetworkSharing.plist"+BOOTPD_PLIST="$MAC_ROOT/System/Library/LaunchDaemons/bootps.plist"++need_file "$VZ_MACOS_IPSW"+if [[ "$INCLUDE_IPADOS_AUDIT" == 1 ]]; then+ need_file "$VZ_IPADOS_IPSW"+fi+need_file "$IPSW"+need_command codesign+need_command lipo+need_command shasum++mkdir -p "$MAC_OUT" "$IPAD_OUT"++if [[ ! -f "$DSC" || ! -f "$DSC.01" ]]; then+ "$IPSW" extract --dyld --dyld-arch arm64e \+ --output "$MAC_OUT" "$VZ_MACOS_IPSW"+fi++if [[ ! -f "$VMM" || ! -f "$EVENT_TAP" || ! -f "$VZ_LOCALIZABLE" ||+ ! -f "$HV_INFO" || ! -f "$PVG_INFO" ||+ ! -f "$METAL_SERIALIZER_INFO" ]]; then+ "$IPSW" extract --files \+ --pattern '^(System/Library/Frameworks/(Hypervisor|ParavirtualizedGraphics|Virtualization)\.framework/Versions/A/(Resources/.*|XPCServices/.*)|System/Library/PrivateFrameworks/MetalSerializer\.framework/Versions/A/Resources/.*)$' \+ --output "$MAC_OUT" "$VZ_MACOS_IPSW"+fi++if [[ ! -f "$INTERNET_SHARING" || ! -f "$BOOTPD" ||+ ! -f "$RTADVD" || ! -f "$NETWORK_SHARING_PLIST" ||+ ! -f "$BOOTPD_PLIST" ]]; then+ "$IPSW" extract --files \+ --pattern '^(usr/libexec/(InternetSharing|bootpd)|usr/sbin/rtadvd|System/Library/LaunchDaemons/(com\.apple\.NetworkSharing\.plist|bootps\.plist))$' \+ --output "$MAC_OUT" "$VZ_MACOS_IPSW"+fi++MAC_KERNEL="$MAC_OUT/22D68__MacBookAir10,1/kernelcache.release.MacBookAir10,1_MacBookPro17,1_Macmini9,1_iMac21,1_2"+if [[ ! -f "$MAC_KERNEL" ]]; then+ "$IPSW" extract --kernel --device MacBookAir10,1 \+ --output "$MAC_OUT" "$VZ_MACOS_IPSW"+fi++IPAD_KERNEL="$IPAD_OUT/20D67__iPad14,6/kernelcache.release.iPad14,3_4_5_6"+if [[ "$INCLUDE_IPADOS_AUDIT" == 1 ]]; then+ if [[ ! -f "$IPAD_KERNEL" ]]; then+ "$IPSW" extract --kernel --device iPad14,6 \+ --output "$IPAD_OUT" "$VZ_IPADOS_IPSW"+ fi++ if [[ ! -f "$IPAD_DSC" || ! -f "$IPAD_DSC.01" ]]; then+ "$IPSW" extract --dyld --dyld-arch arm64e \+ --output "$IPAD_OUT" "$VZ_IPADOS_IPSW"+ fi+fi++lipo "$VMM" -thin arm64e -output "$THIN"++assert_sha256() {+ local file="$1"+ local expected="$2"+ local actual+ actual="$(shasum -a 256 "$file" | awk '{print $1}')"+ [[ "$actual" == "$expected" ]] ||+ die "hash mismatch for $file: expected $expected, got $actual"+}++# Values captured independently from the live matching 13.2.1/22D68 Mac.+assert_sha256 "$THIN" \+ e96f04f6daf44ecb5199e7c67c458e58a6276606c64e42cf354b9fe4feb188aa+assert_sha256 "$RES/AVPBooter.vmapple2.bin" \+ 758e18c43a049448dd8fd1100968503bc13ced11b1619aa40a72377b7fddac24+assert_sha256 "$RES/VZG11.fd" \+ 106605b56eb9927a4d1d9eed038f90fed5a5aa95f1ad588a020cea50e1932a88+assert_sha256 "$RES/VZG21.fd" \+ 51ffd0f3adc9ae7c7ed59f829405aa2dfed584f8208de4bceed067a749312cb3+assert_sha256 "$INTERNET_SHARING" \+ 2df10d5444f99b68226234e67ffc1ee463b0ccb87bb10538ccc4fbcc277d7541+assert_sha256 "$BOOTPD" \+ 3cb7b984f544b4bbd151cca952d7f3fbe208f7e3f1e06715446cabadcaf4d0b7+assert_sha256 "$RTADVD" \+ 9eab82037da516d8ac92fd90b01a2ef6f871e5ab70c3f5d1c67566affd26fdf3+assert_sha256 "$NETWORK_SHARING_PLIST" \+ 4b7538f63d2abc33fe05ac82ed9b441012e12b2116af4b2e34113abfa828d591+assert_sha256 "$BOOTPD_PLIST" \+ 04cb8e8e584d8a4e1595dd78ea71b56592c8bbe9ab56371c9e19eeb51ae504b0+assert_sha256 "$METAL_SERIALIZER_INFO" \+ a0fdc113e5aeecc56fff3023cb48880b627e4ae1056c7bc5a9ac8324d3b13345++hash_line() {+ local label="$1"+ local file="$2"+ printf '%s\t%s\t%s\t%s\n' \+ "$label" \+ "$(stat -f %z "$file")" \+ "$(shasum -a 256 "$file" | awk '{print $1}')" \+ "$file"+}++{+ printf 'INPUT_MANIFEST\t1\n'+ printf 'generated_utc\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ printf 'repository_commit\t%s\n' "$(git -C "$VZ_REPO_ROOT" rev-parse HEAD)"+ printf 'ipsw_tool_commit\t%s\n' \+ "$(git -C "$VZ_BUILD_ROOT/toolchain/ipsw-src" rev-parse HEAD)"+ printf 'python\t%s\n' "$("$VZ_BUILD_ROOT/toolchain/venv/bin/python3" --version 2>&1)"+ printf 'dyldextractor\t2.2.2+VirtualMac-arm64e\n'+ hash_line macos_ipsw "$VZ_MACOS_IPSW"+ hash_line macos_dsc "$DSC"+ hash_line macos_dsc_01 "$DSC.01"+ if [[ "$INCLUDE_IPADOS_AUDIT" == 1 ]]; then+ hash_line ipados_ipsw "$VZ_IPADOS_IPSW"+ hash_line ipados_dsc "$IPAD_DSC"+ else+ printf 'ipados_audit\tskipped\n'+ fi+ hash_line vmm_fat "$VMM"+ hash_line vmm_arm64e "$THIN"+ hash_line avpbooter "$RES/AVPBooter.vmapple2.bin"+ hash_line vzg11 "$RES/VZG11.fd"+ hash_line vzg21 "$RES/VZG21.fd"+ hash_line macos_kernel "$MAC_KERNEL"+ if [[ "$INCLUDE_IPADOS_AUDIT" == 1 ]]; then+ hash_line ipados_kernel "$IPAD_KERNEL"+ fi+ hash_line internet_sharing "$INTERNET_SHARING"+ hash_line bootpd "$BOOTPD"+ hash_line rtadvd "$RTADVD"+ hash_line metal_serializer_info "$METAL_SERIALIZER_INFO"+ printf 'macos_kernel_version\t%s\n' \+ "$("$IPSW" kernel version "$MAC_KERNEL")"+ if [[ "$INCLUDE_IPADOS_AUDIT" == 1 ]]; then+ printf 'ipados_kernel_version\t%s\n' \+ "$("$IPSW" kernel version "$IPAD_KERNEL")"+ fi+ printf 'vmm_uuid\t%s\n' \+ "$(dwarfdump --uuid "$THIN" | awk '{print $2}')"+ printf 'vmm_entitlements_begin\n'+ codesign -d --entitlements :- "$VMM" 2>&1+ printf 'vmm_entitlements_end\n'+} > "$MANIFEST"++cat <<EOF+inputs ready and verified:+ DSC: $DSC+ VMM: $THIN+ resources: $RES+ manifest: $MANIFEST+EOFdiff --git a/VirtualMac/scripts/prepare-wallpapers.sh b/VirtualMac/scripts/prepare-wallpapers.shnew file mode 100755index 0000000..20bfa10--- /dev/null+++ b/VirtualMac/scripts/prepare-wallpapers.sh@@ -0,0 +1,33 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++SOURCE_DIRECTORY="${1:-}"+if [[ -z "$SOURCE_DIRECTORY" || ! -d "$SOURCE_DIRECTORY" ]]; then+ echo "usage: $0 /path/to/macOS-wallpapers" >&2+ exit 2+fi++OUTPUT_DIRECTORY="$VZ_REPO_ROOT/assets/wallpapers"+mkdir -p "$OUTPUT_DIRECTORY"++render() {+ local pattern="$1" output="$2" source+ source="$(find "$SOURCE_DIRECTORY" -maxdepth 1 -type f -iname "$pattern" -print -quit)"+ [[ -n "$source" ]] || { echo "missing wallpaper matching $pattern" >&2; exit 1; }+ sips -Z 1280 -s format jpeg -s formatOptions 72 "$source" \+ --out "$OUTPUT_DIRECTORY/$output.jpg" >/dev/null+}++render '*Monterey*' monterey+render '*Ventura*' ventura+render '*Sonoma*' sonoma+render '*Sequoia*' sequoia+render '*Tahoe*' tahoe+render '*Golden*Gate*' golden-gate+render '*Tiger*' tiger++du -h "$OUTPUT_DIRECTORY"/*.jpgdiff --git a/VirtualMac/scripts/research/analyze-ghidra.sh b/VirtualMac/scripts/research/analyze-ghidra.shnew file mode 100755index 0000000..12f75bf--- /dev/null+++ b/VirtualMac/scripts/research/analyze-ghidra.sh@@ -0,0 +1,71 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++GHIDRA_HOME="${VZ_GHIDRA_HOME:-/Applications/ghidra_12.1.2_PUBLIC}"+HEADLESS="$GHIDRA_HOME/support/analyzeHeadless"+PROJECT_DIR="$VZ_BUILD_ROOT/ghidra"+PROJECT_NAME="VirtualMac"+REPORT_DIR="$PROJECT_DIR/reports"+VIRTUALIZATION="$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/Virtualization.framework/Versions/A/Virtualization"+VMM="$VZ_BUILD_ROOT/ipad-vm/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+PVG="$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics"+VMNET="$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/vmnet.framework/vmnet"+INTERNET_SHARING="$VZ_BUILD_ROOT/ipad-network-sharing/InternetSharing"++need_file "$HEADLESS"+need_file "$VIRTUALIZATION"+need_file "$VMM"+need_file "$PVG"+need_file "$VMNET"+need_file "$INTERNET_SHARING"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpTargetFunctions.java"+mkdir -p "$PROJECT_DIR" "$REPORT_DIR"++if [[ -f "$PROJECT_DIR/$PROJECT_NAME.gpr" ]]; then+ if ! "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process ParavirtualizedGraphics -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$PVG" -analysisTimeoutPerFile 1800 -max-cpu 8 \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"+ fi+ for program in Virtualization com.apple.Virtualization.VirtualMachine; do+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process "$program" -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"+ done+ if ! "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process vmnet -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$VMNET" -analysisTimeoutPerFile 1800 -max-cpu 8 \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"+ fi+ if ! "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process InternetSharing -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$INTERNET_SHARING" -analysisTimeoutPerFile 1800 -max-cpu 8 \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"+ fi+else+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$VIRTUALIZATION" "$VMM" "$PVG" "$VMNET" "$INTERNET_SHARING" \+ -overwrite -analysisTimeoutPerFile 1800 -max-cpu 8 \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$REPORT_DIR"+fi++echo "Ghidra project: $PROJECT_DIR/$PROJECT_NAME.gpr"+echo "Targeted decompilations: $REPORT_DIR"diff --git a/VirtualMac/scripts/research/analyze-metalserializer-buffer-failure.sh b/VirtualMac/scripts/research/analyze-metalserializer-buffer-failure.shnew file mode 100755index 0000000..c1673a8--- /dev/null+++ b/VirtualMac/scripts/research/analyze-metalserializer-buffer-failure.sh@@ -0,0 +1,36 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++GHIDRA_HOME="${VZ_GHIDRA_HOME:-/Applications/ghidra_12.1.2_PUBLIC}"+HEADLESS="$GHIDRA_HOME/support/analyzeHeadless"+PROJECT_DIR="$VZ_BUILD_ROOT/ghidra-metalserializer"+PROJECT_NAME="MetalSerializer"+BINARY="$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/MetalSerializer.framework/MetalSerializer"+REPORT="$VZ_BUILD_ROOT/analysis/metalserializer/invalid-buffer-xrefs.c"+FUNCTION_REPORT="$VZ_BUILD_ROOT/analysis/metalserializer/buffer-reference-functions.c"++need_file "$HEADLESS"+need_file "$BINARY"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpStringXrefs.java"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpNamedFunctions.java"+mkdir -p "$PROJECT_DIR" "$(dirname "$REPORT")"++if [[ ! -f "$PROJECT_DIR/$PROJECT_NAME.gpr" ]]; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$BINARY" -analysisTimeoutPerFile 1800 -max-cpu 8+fi+"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process MetalSerializer -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpStringXrefs.java "Got invalid buffer" "$REPORT"+"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process MetalSerializer -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpNamedFunctions.java "BufferForReference" "$FUNCTION_REPORT"++echo "MetalSerializer invalid-buffer report: $REPORT"+echo "MetalSerializer buffer-reference functions: $FUNCTION_REPORT"diff --git a/VirtualMac/scripts/research/analyze-usb-restore-transport.sh b/VirtualMac/scripts/research/analyze-usb-restore-transport.shnew file mode 100755index 0000000..f0f44f5--- /dev/null+++ b/VirtualMac/scripts/research/analyze-usb-restore-transport.sh@@ -0,0 +1,105 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++GHIDRA_HOME="${VZ_GHIDRA_HOME:-/Applications/ghidra_12.1.2_PUBLIC}"+HEADLESS="$GHIDRA_HOME/support/analyzeHeadless"+KDK_KEXT="$VZ_BUILD_ROOT/analysis/kdk-22d68/KDK.pkg/Payload/System/Library/Extensions/IOUSBHostFamily.kext/Contents/PlugIns/AppleUSBUserHCI.kext/Contents/MacOS/AppleUSBUserHCI"+IOUSBHOST="$VZ_BUILD_ROOT/analysis/iousbhost/IOUSBHost.macos.raw"+VMM_FAT="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/System/Library/Frameworks/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+OUT="$VZ_BUILD_ROOT/analysis/usb-restore-transport"+INPUTS="$OUT/inputs"+REPORTS="$OUT/reports"+PROJECT_DIR="$OUT/ghidra"+PROJECT_NAME="USBRestoreTransport"+KEXT="$INPUTS/AppleUSBUserHCI.arm64e"+VMM="$INPUTS/com.apple.Virtualization.VirtualMachine.arm64e"+if [[ -n "${VZ_LLVM_LIPO:-}" ]]; then+ LIPO="$VZ_LLVM_LIPO"+elif [[ -x /opt/homebrew/opt/llvm/bin/llvm-lipo ]]; then+ LIPO=/opt/homebrew/opt/llvm/bin/llvm-lipo+else+ LIPO="$(command -v llvm-lipo || command -v lipo || true)"+fi++need_command shasum+[[ -x "$LIPO" ]] || die "missing llvm-lipo or lipo"+need_file "$HEADLESS"+need_file "$KDK_KEXT"+need_file "$IOUSBHOST"+need_file "$VMM_FAT"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpNamedFunctions.java"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpAddressFunctions.java"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpStringReferenceFunctions.java"+mkdir -p "$INPUTS" "$REPORTS" "$PROJECT_DIR"++"$LIPO" "$KDK_KEXT" -thin arm64e -output "$KEXT"+"$LIPO" "$VMM_FAT" -thin arm64e -output "$VMM"+shasum -a 256 "$KEXT" "$IOUSBHOST" "$VMM" >"$OUT/sha256.txt"++if [[ ! -f "$PROJECT_DIR/$PROJECT_NAME.gpr" ]]; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$KEXT" "$IOUSBHOST" "$VMM" -overwrite \+ -analysisTimeoutPerFile 1800 -max-cpu 8+fi++run_named() {+ local program="$1"+ local report="$2"+ shift 2+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process "$program" -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpNamedFunctions.java "$REPORTS/$report" "$@"+}++run_strings() {+ local program="$1"+ local report="$2"+ shift 2+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process "$program" -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpStringReferenceFunctions.java \+ "$REPORTS/$report" "$@"+}++run_named AppleUSBUserHCI.arm64e apple-usb-user-hci.c \+ AppleUSBUserHCIResources AppleUSBUserHCIUserClient \+ AppleUSBUserHCICommandQueue AppleUSBUserHCI::commandWrite \+ AppleUSBUserHCI::doorbellWrite AppleUSBUserHCITransferQueue \+ AppleUSBUserHCIIsochronousTransferQueue++run_named IOUSBHost.macos.raw iousbhost-controller-interface.c \+ IOUSBHostControllerInterface IOUSBHostCIControllerStateMachine \+ IOUSBHostCIPortStateMachine IOUSBHostCIDeviceStateMachine \+ IOUSBHostCIEndpointStateMachine++run_strings com.apple.Virtualization.VirtualMachine.arm64e vmm-usb-xrefs.c \+ IOUSBHostControllerInterfaceUUID com.apple.virtualization.usb.hci \+ com.apple.virtualization.usb.xhci-host-controller \+ get_usb_controller_location_id AppleUSBUserHCIPort++"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process com.apple.Virtualization.VirtualMachine.arm64e -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpAddressFunctions.java "$REPORTS/vmm-usb-handlers.c" \+ usb_controller_create=0x10016aeb0 \+ usb_command_handler=0x100109e88 \+ usb_doorbell_handler=0x100109ef4 \+ usb_interest_handler=0x100109f94 \+ usb_controller_destroy=0x100109dac \+ get_usb_controller_location_id=0x1000306ac++"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process com.apple.Virtualization.VirtualMachine.arm64e -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpAddressFunctions.java "$REPORTS/vmm-usb-processors.c" \+ command_processor=0x10010a61c \+ doorbell_processor=0x100109f98 \+ location_worker=0x1000e0920++echo "USB restore transport analysis: $OUT"diff --git a/VirtualMac/scripts/research/analyze-ventura-input-abi.sh b/VirtualMac/scripts/research/analyze-ventura-input-abi.shnew file mode 100755index 0000000..4b3cfae--- /dev/null+++ b/VirtualMac/scripts/research/analyze-ventura-input-abi.sh@@ -0,0 +1,58 @@+#!/bin/bash++# Reproduce the input-device boundary analysis against the extracted Ventura+# Virtualization.framework. The generated reports are intentionally kept under+# build/ so they do not make the source tree depend on Ghidra output.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++GHIDRA_HOME="${VZ_GHIDRA_HOME:-/Applications/ghidra_12.1.2_PUBLIC}"+HEADLESS="$GHIDRA_HOME/support/analyzeHeadless"+PROJECT_DIR="$VZ_BUILD_ROOT/ghidra"+PROJECT_NAME="VirtualMac"+VIRTUALIZATION="$VZ_BUILD_ROOT/ipad-vm/payload/Frameworks/Virtualization.framework/Versions/A/Virtualization"+VMM="$VZ_BUILD_ROOT/ipad-vm/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+OUT="$VZ_BUILD_ROOT/analysis/ventura-input-abi"++need_file "$HEADLESS"+need_file "$PROJECT_DIR/$PROJECT_NAME.gpr"+need_file "$VIRTUALIZATION"+need_file "$VMM"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpNamedFunctions.java"+need_command strings+mkdir -p "$OUT"++"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process Virtualization -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpNamedFunctions.java \+ "$OUT/pointing-device.c" \+ '_VZPointingDevice::'++"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process Virtualization -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpNamedFunctions.java \+ "$OUT/device-construction.c" \+ 'VZMacTrackpadConfiguration::' \+ '_VZAppleTouchScreenConfiguration::' \+ '_VZMultiTouchDevice::'++strings -a "$VMM" | awk \+ '/^process_(symbolic_hot_key|zoom_toggle|scale|rotation|scroll_wheel)_events$/ { print }' \+ | sort -u >"$OUT/pointing-rpc-names.txt"++grep '^===== _VZPointingDevice::' "$OUT/pointing-device.c" \+ >"$OUT/pointing-methods.txt"++printf 'Ventura input ABI reports:\n'+printf ' %s\n' \+ "$OUT/pointing-methods.txt" \+ "$OUT/pointing-rpc-names.txt" \+ "$OUT/device-construction.c"+cat "$OUT/pointing-methods.txt"+printf '\nVMM pointing RPC names:\n'+cat "$OUT/pointing-rpc-names.txt"diff --git a/VirtualMac/scripts/research/analyze-vz-installation.sh b/VirtualMac/scripts/research/analyze-vz-installation.shnew file mode 100755index 0000000..19ffda3--- /dev/null+++ b/VirtualMac/scripts/research/analyze-vz-installation.sh@@ -0,0 +1,58 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++GHIDRA_HOME="${VZ_GHIDRA_HOME:-/Applications/ghidra_12.1.2_PUBLIC}"+HEADLESS="$GHIDRA_HOME/support/analyzeHeadless"+SOURCE_VZ="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/System/Library/Frameworks/Virtualization.framework/Versions/A"+INSTALLATION_XPC="$SOURCE_VZ/XPCServices/com.apple.Virtualization.Installation.xpc"+INSTALLATION_BINARY="$INSTALLATION_XPC/Contents/MacOS/com.apple.Virtualization.Installation"+OUTPUT="$VZ_BUILD_ROOT/analysis/vz-installation"+PROJECT_DIR="$VZ_BUILD_ROOT/ghidra-installation"+PROJECT_NAME="VZInstallation"+THIN_BINARY="$OUTPUT/com.apple.Virtualization.Installation.arm64e"+PROGRAM_NAME="$(basename "$THIN_BINARY")"++need_command codesign+need_command lipo+need_command otool+need_command plutil+need_file "$HEADLESS"+need_file "$INSTALLATION_BINARY"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpStringReferenceFunctions.java"+need_file "$VZ_REPO_ROOT/vz/development/ghidra/DumpTargetFunctions.java"+mkdir -p "$OUTPUT" "$PROJECT_DIR"++lipo "$INSTALLATION_BINARY" -thin arm64e -output "$THIN_BINARY"+plutil -p "$INSTALLATION_XPC/Contents/Info.plist" \+ >"$OUTPUT/info-plist.txt"+otool -L "$INSTALLATION_BINARY" >"$OUTPUT/linked-images.txt"+codesign -d --entitlements :- "$INSTALLATION_XPC" \+ >"$OUTPUT/entitlements.plist" 2>/dev/null || true+strings -a "$INSTALLATION_BINARY" | sort -u \+ >"$OUTPUT/strings.txt"++if [[ ! -f "$PROJECT_DIR/$PROJECT_NAME.gpr" ]]; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$THIN_BINARY" -overwrite \+ -analysisTimeoutPerFile 1800 -max-cpu 8+fi++"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process "$PROGRAM_NAME" -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpTargetFunctions.java "$OUTPUT"++"$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process "$PROGRAM_NAME" -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpStringReferenceFunctions.java \+ "$OUTPUT/string-reference-functions.c" \+ start_install load_restore_image request_mobile_device_update \+ AMRestorableDeviceRestoreWithError RestoreBundlePath IPSWExtractPath \+ CatalogV2URLs HostMobileDeviceVersion++echo "Virtualization installation analysis: $OUTPUT"diff --git a/VirtualMac/scripts/research/compare-hid-event-layouts.sh b/VirtualMac/scripts/research/compare-hid-event-layouts.shnew file mode 100755index 0000000..8d41283--- /dev/null+++ b/VirtualMac/scripts/research/compare-hid-event-layouts.sh@@ -0,0 +1,42 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SOURCE="$VZ_REPO_ROOT/vz/development/probes/hid_event_layout.m"+OUT="$VZ_BUILD_ROOT/hid-event-layout"+IOS_BIN="$OUT/hid-event-layout-ios"+MAC_BIN_REMOTE="/tmp/hid-event-layout-macos"+SOURCE_REMOTE="/tmp/hid_event_layout.m"+ENTS="$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements"++need_command ldid+need_command xcrun+need_file "$SOURCE"+need_file "$ENTS"+mkdir -p "$OUT"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=16.0 \+ -isysroot "$SDK" -framework CoreFoundation -framework IOKit \+ "$SOURCE" -o "$IOS_BIN"+ldid -S"$ENTS" "$IOS_BIN"+ios_hash="$(ldid -h "$IOS_BIN" | sed -n 's/^CDHash=//p')"++ensure_ipad_usb+ipad_scp "$IOS_BIN" "$IPAD_TARGET:/tmp/hid-event-layout"+ipad_ssh "chmod 755 /tmp/hid-event-layout; \+ jbctl trustcache add '$ios_hash'; /tmp/hid-event-layout" \+ >"$OUT/ipados.txt" 2>&1++real_mac_ssh_args+real_mac_scp "$SOURCE" "$REAL_MAC_TARGET:$SOURCE_REMOTE"+real_mac_ssh "xcrun clang -arch arm64 -framework CoreFoundation \+ -framework IOKit '$SOURCE_REMOTE' -o '$MAC_BIN_REMOTE'; \+ '$MAC_BIN_REMOTE'" >"$OUT/macos13.txt" 2>&1++echo "iPadOS layout: $OUT/ipados.txt"+echo "macOS 13 layout: $OUT/macos13.txt"+diff -u "$OUT/macos13.txt" "$OUT/ipados.txt" || truediff --git a/VirtualMac/scripts/research/compare-iouserethernet.sh b/VirtualMac/scripts/research/compare-iouserethernet.shnew file mode 100755index 0000000..c952f66--- /dev/null+++ b/VirtualMac/scripts/research/compare-iouserethernet.sh@@ -0,0 +1,66 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++MAC_KERNEL="${VZ_MAC_KERNELCACHE:-$VZ_BUILD_ROOT/inputs/macos/22D68__MacBookAir10,1/kernelcache.release.MacBookAir10,1_MacBookPro17,1_Macmini9,1_iMac21,1_2}"+IPAD_KERNEL="${VZ_IPAD_KERNELCACHE:-$VZ_BUILD_ROOT/inputs/ipados/20D67__iPad14,6/kernelcache.release.iPad14,3_4_5_6}"+OUT="$VZ_BUILD_ROOT/analysis/iouserethernet"+INPUTS="$OUT/inputs"+REPORTS="$OUT/reports"+PROJECT_DIR="$OUT/ghidra"+PROJECT_NAME="IOUserEthernetComparison"+HEADLESS="${VZ_GHIDRA_HOME:-/Applications/ghidra_12.1.2_PUBLIC}/support/analyzeHeadless"+GHIDRA_SCRIPT="$VZ_REPO_ROOT/vz/development/ghidra/DumpIOUserEthernetAuthorization.java"++IPSW="$VZ_BUILD_ROOT/toolchain/bin/ipsw-a2sb"+need_file "$IPSW"+need_file "$MAC_KERNEL"+need_file "$IPAD_KERNEL"+need_file "$HEADLESS"+need_file "$GHIDRA_SCRIPT"+mkdir -p "$OUT/macos" "$OUT/ipados" "$INPUTS" "$REPORTS" "$PROJECT_DIR"++"$IPSW" kernel extract "$MAC_KERNEL" com.apple.iokit.IOUserEthernet \+ --imports --force -o "$OUT/macos"+"$IPSW" kernel extract "$IPAD_KERNEL" com.apple.iokit.IOUserEthernet \+ --imports --force -o "$OUT/ipados"+cp "$OUT/macos/com.apple.iokit.IOUserEthernet" \+ "$INPUTS/IOUserEthernet.macos-22D68"+cp "$OUT/ipados/com.apple.iokit.IOUserEthernet" \+ "$INPUTS/IOUserEthernet.ipados-20D67"++for platform in macos-22D68 ipados-20D67; do+ binary="$INPUTS/IOUserEthernet.$platform"+ {+ echo "file: $binary"+ file "$binary"+ shasum -a 256 "$binary"+ echo "authorization imports and strings:"+ nm -nm "$binary" 2>/dev/null | \+ grep -E 'clientHasPrivilege|AMFIEntitlementGetBool' || true+ strings -a "$binary" | \+ grep -E 'ethernet.user-access|not entitled' || true+ } >"$REPORTS/$platform-summary.txt"+done++if [[ ! -f "$PROJECT_DIR/$PROJECT_NAME.gpr" ]]; then+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -import "$INPUTS/IOUserEthernet.macos-22D68" \+ "$INPUTS/IOUserEthernet.ipados-20D67" \+ -analysisTimeoutPerFile 1800 -max-cpu 8 \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpIOUserEthernetAuthorization.java "$REPORTS"+else+ for program in IOUserEthernet.macos-22D68 \+ IOUserEthernet.ipados-20D67; do+ "$HEADLESS" "$PROJECT_DIR" "$PROJECT_NAME" \+ -process "$program" -noanalysis \+ -scriptPath "$VZ_REPO_ROOT/vz/development/ghidra" \+ -postScript DumpIOUserEthernetAuthorization.java "$REPORTS"+ done+fi++echo "IOUserEthernet comparison reports: $REPORTS"diff --git a/VirtualMac/scripts/research/oracle-real-mac.sh b/VirtualMac/scripts/research/oracle-real-mac.shnew file mode 100755index 0000000..7a04ab6--- /dev/null+++ b/VirtualMac/scripts/research/oracle-real-mac.sh@@ -0,0 +1,62 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++need_command clang+need_command sshpass+need_command shasum++OUT_DIR="$VZ_BUILD_ROOT/oracle"+PROBE="$OUT_DIR/oracle-images"+REPORT="$OUT_DIR/real-mac.txt"+mkdir -p "$OUT_DIR"++clang \+ -arch arm64 \+ -mmacosx-version-min=13.0 \+ -fobjc-arc \+ -framework Foundation \+ "$VZ_REPO_ROOT/vz/development/probes/oracle_images.m" \+ -o "$PROBE"++REMOTE_DIR="/tmp/VirtualMac-oracle-${UID}"+real_mac_ssh "mkdir -p '$REMOTE_DIR'"+real_mac_scp "$PROBE" "$REAL_MAC_TARGET:$REMOTE_DIR/oracle-images" >/dev/null++real_mac_ssh "set -e+export LC_ALL=C+export LANG=C+VMM=/System/Library/Frameworks/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine+RES=/System/Library/Frameworks/Virtualization.framework/Versions/A/Resources+THIN=\$(mktemp /tmp/apple-vz-vmm-arm64e.XXXXXX)+trap 'rm -f \"\$THIN\"; rm -rf \"$REMOTE_DIR\"' EXIT+lipo \"\$VMM\" -thin arm64e -output \"\$THIN\"+echo 'ORACLE_FORMAT 1'+echo 'OS'+sw_vers+uname -a+echo 'HARDWARE'+/usr/sbin/sysctl -n hw.model hw.memsize hw.ncpu kern.osversion+echo 'SIP'+csrutil status 2>/dev/null || true+echo 'VMM'+file \"\$VMM\"+lipo -info \"\$VMM\"+dwarfdump --uuid \"\$VMM\"+printf 'arm64e-size '; stat -f %z \"\$THIN\"+printf 'arm64e-sha256 '; shasum -a 256 \"\$THIN\" | awk '{print \$1}'+codesign -d --entitlements :- \"\$VMM\" 2>&1+echo 'RESOURCES'+for f in AVPBooter.vmapple2.bin VZG11.fd VZG21.fd; do+ printf '%s ' \"\$f\"+ stat -f %z \"\$RES/\$f\"+ shasum -a 256 \"\$RES/\$f\" | awk '{print \$1}'+done+echo 'LOADED_IMAGES'+\"$REMOTE_DIR/oracle-images\"+" | tee "$REPORT"++echo "wrote $REPORT"diff --git a/VirtualMac/scripts/research/trace-network-sharing-real-mac.sh b/VirtualMac/scripts/research/trace-network-sharing-real-mac.shnew file mode 100755index 0000000..3488a72--- /dev/null+++ b/VirtualMac/scripts/research/trace-network-sharing-real-mac.sh@@ -0,0 +1,37 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+APP="$REMOTE_ROOT/DerivedData/Build/Products/Debug/macOSVirtualMachineSampleApp-Objective-C.app"+TRACE="$VZ_REPO_ROOT/vz/development/probes/trace_network_sharing_real_mac.lldb"+REMOTE_TRACE="$REMOTE_ROOT/trace_network_sharing_real_mac.lldb"++need_command sshpass+need_file "$TRACE"+real_mac_ssh_args+real_mac_scp "$TRACE" "$REAL_MAC_TARGET:$REMOTE_TRACE"++cat <<EOF+The trace fixture is installed on the Ventura Mac.++Terminal 1 (attach before starting the VM):+ ssh -p $VZ_REAL_MAC_PORT $VZ_REAL_MAC_USER@$VZ_REAL_MAC_HOST+ sudo launchctl kickstart -k system/com.apple.NetworkSharing+ sudo lldb -p \$(pgrep -x InternetSharing) -s $REMOTE_TRACE++Terminal 2 (trigger the known-good NAT path):+ ssh -p $VZ_REAL_MAC_PORT $VZ_REAL_MAC_USER@$VZ_REAL_MAC_HOST open -n $APP++At IOServiceOpen, save x3, finish, and inspect the result:+ register read x0 x1 x2 x3+ expr unsigned long long \$connect_out=(unsigned long long)\$x3+ thread backtrace+ finish+ register read x0 w0+ memory read --format x --size 4 --count 1 \$connect_out+EOFdiff --git a/VirtualMac/scripts/research/trace-real-mac-usb-restore.sh b/VirtualMac/scripts/research/trace-real-mac-usb-restore.shnew file mode 100755index 0000000..66ebf95--- /dev/null+++ b/VirtualMac/scripts/research/trace-real-mac-usb-restore.sh@@ -0,0 +1,52 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+: "${VZ_REAL_MAC_USB_BUNDLE:?set VZ_REAL_MAC_USB_BUNDLE to the VM bundle}"+REMOTE="$VZ_REAL_MAC_WORK"+BUNDLE="$VZ_REAL_MAC_USB_BUNDLE"+PYTHON_REMOTE="$REMOTE/trace_usb_hci_commands.py"+LLDB_COMMANDS_REMOTE="$REMOTE/trace-usb-hci.lldb"+LOCAL_PYTHON="$VZ_REPO_ROOT/vz/development/lldb/trace_usb_hci_commands.py"++need_file "$LOCAL_PYTHON"+real_mac_ssh_args+real_mac_scp "$LOCAL_PYTHON" "$REAL_MAC_TARGET:$PYTHON_REMOTE"++real_mac_ssh "+set -eu+pkill -f start-force-dfu 2>/dev/null || true+pkill -f com.apple.Virtualization.VirtualMachine 2>/dev/null || true+: >/tmp/vz-usb-command-trace.log+printf '%s\n' \+ 'settings set auto-confirm true' \+ 'process attach --name com.apple.Virtualization.VirtualMachine --waitfor' \+ 'command script import $PYTHON_REMOTE' \+ 'vz_usb_trace_install' \+ 'continue' >'$LLDB_COMMANDS_REMOTE'+{ printf '%s\n' '$VZ_REAL_MAC_PASSWORD' | \+ sudo -S lldb -s '$LLDB_COMMANDS_REMOTE'; } \+ >'$REMOTE/trace-usb-hci-lldb.log' 2>&1 &+echo \$! >'$REMOTE/trace-usb-hci-lldb.pid'+sleep 1+DYLD_FRAMEWORK_PATH='$REMOTE/usb-oracle-runtime' \+ nohup '$REMOTE/start-force-dfu' '$BUNDLE' \+ >'$REMOTE/trace-usb-hci-vm.log' 2>&1 &+echo \$! >'$REMOTE/trace-usb-hci-vm.pid'+echo TRACE_STARTED+"++for _ in {1..30}; do+ trace="$(real_mac_ssh 'cat /tmp/vz-usb-command-trace.log 2>/dev/null || true')"+ if [[ "$trace" == *"command type="* ]]; then+ printf '%s\n' "$trace"+ exit+ fi+ sleep 1+done++die "real-Mac USB trace did not observe a command"diff --git a/VirtualMac/scripts/research/trace-vz-installation-real-mac.sh b/VirtualMac/scripts/research/trace-vz-installation-real-mac.shnew file mode 100755index 0000000..9eb8946--- /dev/null+++ b/VirtualMac/scripts/research/trace-vz-installation-real-mac.sh@@ -0,0 +1,51 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+: "${VZ_REAL_MAC_VM:?set VZ_REAL_MAC_VM to the reference restore destination}"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+REMOTE_IPSW="${VZ_REAL_MAC_INSTALL_IPSW:-$REMOTE_ROOT/input/UniversalMac_13.6_22G120_Restore.ipsw}"+REMOTE_TOOL="$REMOTE_ROOT/DerivedData/Build/Products/Debug/InstallationTool-Objective-C"+LOCAL_LLDB="$VZ_REPO_ROOT/vz/development/probes/trace_vz_installation_real_mac.lldb"+REMOTE_LLDB="$REMOTE_ROOT/trace_vz_installation_real_mac.lldb"+LOCAL_LLDB_PY="$VZ_REPO_ROOT/vz/development/probes/trace_vz_installation_lldb.py"+REMOTE_LLDB_PY="$REMOTE_ROOT/trace_vz_installation_lldb.py"++need_command sshpass+need_file "$LOCAL_LLDB"+need_file "$LOCAL_LLDB_PY"+real_mac_ssh_args++case "${1:-}" in+ start)+ trace_id="$(date -u +%Y%m%dT%H%M%SZ)"+ remote_trace="$REMOTE_ROOT/traces/install-$trace_id"+ real_mac_scp "$LOCAL_LLDB" "$REAL_MAC_TARGET:$REMOTE_LLDB"+ real_mac_scp "$LOCAL_LLDB_PY" "$REAL_MAC_TARGET:$REMOTE_LLDB_PY"+ real_mac_ssh "test -f '$REMOTE_IPSW' && test -x '$REMOTE_TOOL'"+ real_mac_ssh "if test -d '$VZ_REAL_MAC_VM'; then rmdir '$VZ_REAL_MAC_VM'; fi; mkdir -p '$remote_trace'"++ real_mac_ssh "printf '%s\\n' '$VZ_REAL_MAC_PASSWORD' | sudo -S -b fs_usage -w -f pathname -t 7200 InstallationTool-Objective-C com.apple.Virtualization.Installation com.apple.Virtualization.VirtualMachine >'$remote_trace/fs-usage.log' 2>&1"+ real_mac_ssh "cd '$REMOTE_ROOT' && printf '%s\\n' '$VZ_REAL_MAC_PASSWORD' | sudo -S -b lldb -s '$REMOTE_LLDB' >'$remote_trace/lldb.log' 2>&1"+ real_mac_ssh "nohup /usr/bin/log stream --style compact --level debug --predicate '(process == \"InstallationTool-Objective-C\") || (process == \"com.apple.Virtualization.Installation\") || (process == \"com.apple.Virtualization.VirtualMachine\") || (subsystem BEGINSWITH \"com.apple.Virtualization\")' >'$remote_trace/unified.log' 2>&1 </dev/null & echo \$! >'$remote_trace/log-stream.pid'"+ sleep 3+ remote_vm_parent="$(dirname "$VZ_REAL_MAC_VM")"+ real_mac_ssh "cd '$remote_vm_parent' && nohup '$REMOTE_TOOL' '$REMOTE_IPSW' >'$remote_trace/installer.log' 2>&1 </dev/null & echo \$! >'$remote_trace/installer.pid'; printf '%s\\n' '$remote_trace' >'$REMOTE_ROOT/current-install-trace'"+ echo "Started Ventura reference restore trace: $remote_trace"+ ;;+ status)+ remote_vm_parent="$(dirname "$VZ_REAL_MAC_VM")"+ real_mac_ssh "trace=\$(cat '$REMOTE_ROOT/current-install-trace'); echo \"trace=\$trace\"; ls -lh '$REMOTE_IPSW'; pgrep -fl 'InstallationTool-Objective-C|com.apple.Virtualization.Installation|com.apple.Virtualization.VirtualMachine|lldb.*trace_vz_installation' || true; tail -30 \"\$trace/installer.log\" 2>/dev/null || true; df -h '$remote_vm_parent' | tail -1; du -sh '$VZ_REAL_MAC_VM' 2>/dev/null || true"+ ;;+ stop-trace)+ real_mac_ssh "trace=\$(cat '$REMOTE_ROOT/current-install-trace'); if test -f \"\$trace/log-stream.pid\"; then kill \$(cat \"\$trace/log-stream.pid\") 2>/dev/null || true; fi; printf '%s\\n' '$VZ_REAL_MAC_PASSWORD' | sudo -S pkill -f 'lldb.*trace_vz_installation_real_mac' 2>/dev/null || true; pids=\$(pgrep -f '^fs_usage .*InstallationTool-Objective-C' || true); if test -n \"\$pids\"; then printf '%s\\n' '$VZ_REAL_MAC_PASSWORD' | sudo -S kill \$pids 2>/dev/null || true; fi; echo \"Trace files: \$trace\""+ ;;+ *)+ echo "usage: $0 start | status | stop-trace" >&2+ exit 2+ ;;+esacdiff --git a/VirtualMac/scripts/tests/benchmark-ipad-guest-video.sh b/VirtualMac/scripts/tests/benchmark-ipad-guest-video.shnew file mode 100755index 0000000..b2b120c--- /dev/null+++ b/VirtualMac/scripts/tests/benchmark-ipad-guest-video.sh@@ -0,0 +1,84 @@+#!/bin/bash++# Exercise macOS VideoToolbox paravirtual device from a guest. It generates a+# 15-second 1080p H.264 source, converts it to HEVC with macOS avconvert, and+# verifies that the guest driver remains loaded after the workload.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck disable=SC1091+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_GUEST_HOST:?set VZ_GUEST_HOST to the guest address}"+: "${VZ_GUEST_USER:?set VZ_GUEST_USER to the guest SSH user}"+: "${VZ_GUEST_PASSWORD:?set VZ_GUEST_PASSWORD to the guest SSH password}"+GUEST_HOST="$VZ_GUEST_HOST"+GUEST_USER="$VZ_GUEST_USER"+GUEST_PORT="${VZ_GUEST_USB_PORT:-2208}"+GUEST_PASSWORD="$VZ_GUEST_PASSWORD"+SAMPLE="$VZ_BUILD_ROOT/video-benchmark-1080p.mp4"++need_command ffmpeg+need_command lsof+need_command ssh+need_command sshpass+ensure_ipad_usb+mkdir -p "$VZ_BUILD_ROOT"++if [[ ! -f "$SAMPLE" ]]; then+ ffmpeg -hide_banner -loglevel error \+ -f lavfi -i 'testsrc2=size=1920x1080:rate=30:duration=15' \+ -c:v libx264 -preset veryfast -pix_fmt yuv420p \+ -movflags +faststart -y "$SAMPLE"+fi++owned_tunnel=0+if ! lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1; then+ sshpass -p "$VZ_IPAD_PASSWORD" ssh "${IPAD_SSH_ARGS[@]}" \+ -o ControlMaster=no -o ControlPath=none \+ -N -L "127.0.0.1:$GUEST_PORT:$GUEST_HOST:22" "$IPAD_TARGET" &+ tunnel_pid=$!+ owned_tunnel=1+fi+cleanup() {+ if [[ "$owned_tunnel" == 1 ]]; then+ listener_pids="$(lsof -t -iTCP:"$GUEST_PORT" -sTCP:LISTEN 2>/dev/null || true)"+ if [[ -n "$listener_pids" ]]; then+ # shellcheck disable=SC2086+ kill $listener_pids 2>/dev/null || true+ fi+ kill "$tunnel_pid" 2>/dev/null || true+ wait "$tunnel_pid" 2>/dev/null || true+ fi+}+trap cleanup EXIT++for _ in {1..40}; do+ lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 && break+ sleep 0.25+done+lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 ||+ die "iPad guest SSH tunnel did not open"++guest_ssh=(sshpass -p "$GUEST_PASSWORD" ssh -p "$GUEST_PORT"+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10 -o PubkeyAuthentication=no+ -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1+ "[email protected]")+guest_scp=(sshpass -p "$GUEST_PASSWORD" scp -P "$GUEST_PORT"+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10 -o PubkeyAuthentication=no+ -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1)++"${guest_scp[@]}" "$SAMPLE" "[email protected]:/tmp/vz-video-input.mp4"+# shellcheck disable=SC2016+"${guest_ssh[@]}" 'set -eu+driver=com.apple.driver.AppleVideoToolboxParavirtualization+kmutil showloaded 2>/dev/null | grep -F "$driver"+rm -f /tmp/vz-video-output.mov+/usr/bin/time -p avconvert --source /tmp/vz-video-input.mp4 \+ --output /tmp/vz-video-output.mov \+ --preset PresetHEVCHighestQuality --replace+test -s /tmp/vz-video-output.mov+kmutil showloaded 2>/dev/null | grep -F "$driver"+ls -lh /tmp/vz-video-input.mp4 /tmp/vz-video-output.mov'diff --git a/VirtualMac/scripts/tests/check-ipad-guest-clock.sh b/VirtualMac/scripts/tests/check-ipad-guest-clock.shnew file mode 100755index 0000000..141c37d--- /dev/null+++ b/VirtualMac/scripts/tests/check-ipad-guest-clock.sh@@ -0,0 +1,68 @@+#!/bin/bash++# Verify that the virtual RTC advances independently of guest network time.+# The prior Network Time setting is restored before the script exits.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_GUEST_HOST:?set VZ_GUEST_HOST to the guest address}"+: "${VZ_GUEST_USER:?set VZ_GUEST_USER to the guest SSH user}"+GUEST_HOST="$VZ_GUEST_HOST"+GUEST_USER="$VZ_GUEST_USER"+GUEST_PORT="${VZ_GUEST_USB_PORT:-2208}"+: "${VZ_GUEST_PASSWORD:?set VZ_GUEST_PASSWORD in .env or the environment}"++need_command lsof+need_command ssh+need_command sshpass+ensure_ipad_usb++sshpass -p "$VZ_IPAD_PASSWORD" ssh "${IPAD_SSH_ARGS[@]}" \+ -o ControlMaster=no -o ControlPath=none \+ -N -L "127.0.0.1:$GUEST_PORT:$GUEST_HOST:22" "$IPAD_TARGET" &+tunnel_pid=$!+cleanup() {+ listener_pids="$(lsof -t -iTCP:"$GUEST_PORT" -sTCP:LISTEN 2>/dev/null || true)"+ if [[ -n "$listener_pids" ]]; then+ # shellcheck disable=SC2086+ kill $listener_pids 2>/dev/null || true+ fi+ kill "$tunnel_pid" 2>/dev/null || true+ wait "$tunnel_pid" 2>/dev/null || true+}+trap cleanup EXIT++for _ in {1..40}; do+ lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 && break+ sleep 0.25+done++guest_ssh() {+ sshpass -p "$VZ_GUEST_PASSWORD" ssh -p "$GUEST_PORT" \+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -o ConnectTimeout=10 -o PubkeyAuthentication=no \+ -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1 \+ "[email protected]" "$@"+}++guest_ssh "printf '%s\\n' '$VZ_GUEST_PASSWORD' | sudo -S systemsetup -setusingnetworktime off >/dev/null 2>&1 || true"+start_host="$(date +%s)"+start_guest="$(guest_ssh 'date +%s')"+sleep 5+end_host="$(date +%s)"+end_guest="$(guest_ssh 'date +%s')"+guest_ssh "printf '%s\\n' '$VZ_GUEST_PASSWORD' | sudo -S systemsetup -setusingnetworktime on >/dev/null 2>&1 || true"++host_delta=$((end_host - start_host))+guest_delta=$((end_guest - start_guest))+skew=$((start_guest - start_host))+(( skew < 0 )) && skew=$((-skew))+echo "host delta: $host_delta seconds"+echo "guest RTC delta with Network Time off: $guest_delta seconds"+echo "host/guest initial skew: $skew seconds"+(( guest_delta >= 4 && guest_delta <= 8 )) ||+ die "guest RTC did not advance at wall-clock speed"+(( skew <= 5 )) || die "guest RTC differs from host by more than five seconds"diff --git a/VirtualMac/scripts/tests/check-ipad-guest-network.sh b/VirtualMac/scripts/tests/check-ipad-guest-network.shnew file mode 100755index 0000000..c72bb92--- /dev/null+++ b/VirtualMac/scripts/tests/check-ipad-guest-network.sh@@ -0,0 +1,70 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_GUEST_HOST:?set VZ_GUEST_HOST to the guest address}"+: "${VZ_GUEST_USER:?set VZ_GUEST_USER to the guest SSH user}"+GUEST_HOST="$VZ_GUEST_HOST"+GUEST_USER="$VZ_GUEST_USER"+GUEST_PORT="${VZ_GUEST_USB_PORT:-2208}"+: "${VZ_GUEST_PASSWORD:?set VZ_GUEST_PASSWORD in .env or the environment}"++need_command curl+need_command lsof+need_command ssh+need_command sshpass+ensure_ipad_usb++if lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1; then+ die "local guest SSH port $GUEST_PORT is already in use"+fi++sshpass -p "$VZ_IPAD_PASSWORD" ssh \+ "${IPAD_SSH_ARGS[@]}" \+ -o ControlMaster=no -o ControlPath=none \+ -N -L "127.0.0.1:$GUEST_PORT:$GUEST_HOST:22" \+ "$IPAD_TARGET" &+tunnel_pid=$!+cleanup() {+ # sshpass exits after authentication and leaves ssh re-parented, so the+ # original background PID alone is not sufficient to close the tunnel.+ listener_pids="$(lsof -t -iTCP:"$GUEST_PORT" -sTCP:LISTEN 2>/dev/null || true)"+ if [[ -n "$listener_pids" ]]; then+ # shellcheck disable=SC2086+ kill $listener_pids 2>/dev/null || true+ fi+ kill "$tunnel_pid" 2>/dev/null || true+ wait "$tunnel_pid" 2>/dev/null || true+}+trap cleanup EXIT++for _ in {1..40}; do+ lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 && break+ kill -0 "$tunnel_pid" 2>/dev/null ||+ die "iPad guest SSH tunnel exited before opening"+ sleep 0.25+done+lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 ||+ die "iPad guest SSH tunnel did not open"++remote_check=$'set -eu\n'+remote_check+=$'address=$(ipconfig getifaddr en0)\n'+remote_check+=$'test -n "$address"\n'+remote_check+=$'echo "guest IPv4: $address"\n'+remote_check+=$'route -n get default | grep "gateway:"\n'+remote_check+=$'for url in https://google.com https://apple.com https://macrumors.com https://9to5mac.com; do\n'+remote_check+=$' curl -4 -ILsS --connect-timeout 8 --max-time 25 -o /dev/null -w "$url code=%{http_code} remote=%{remote_ip}\\n" "$url"\n'+remote_check+=$'done\n'++sshpass -p "$VZ_GUEST_PASSWORD" ssh \+ -p "$GUEST_PORT" \+ -o StrictHostKeyChecking=no \+ -o UserKnownHostsFile=/dev/null \+ -o ConnectTimeout=10 \+ -o PubkeyAuthentication=no \+ -o PreferredAuthentications=password \+ -o NumberOfPasswordPrompts=1 \+ "[email protected]" "$remote_check"diff --git a/VirtualMac/scripts/tests/check-ipad-vm-health.sh b/VirtualMac/scripts/tests/check-ipad-vm-health.shnew file mode 100755index 0000000..9c12c6f--- /dev/null+++ b/VirtualMac/scripts/tests/check-ipad-vm-health.sh@@ -0,0 +1,30 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++result="$(ipad_ssh '+set -eu+host_pattern=/VirtualMac.app/VirtualMac+vmm_pattern=/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine+ps ax | grep -F "$host_pattern" | grep -v grep >/dev/null+ps ax | grep -F "$vmm_pattern" | grep -v grep >/dev/null+health=$(grep "health state=" /tmp/VirtualMac.log | tail -1)+test -n "$health"+echo "$health" | grep -q "state=1"+test "$(grep -c "TASK_LOOKUP_MISS" /tmp/pvg-trace.log || true)" = 0+test "$(grep "TASK_RESERVE" /tmp/pvg-trace.log | grep -c "result=0x0" || true)" = 0+test "$(grep "TASK_MAP" /tmp/pvg-trace.log | grep -c "result=0" || true)" = 0+test "$(grep "TASK_MAP" /tmp/pvg-trace.log | grep -c "within=0" || true)" = 0+test "$(grep -c "METAL_COMMAND_BUFFER.*error=" /tmp/pvg-trace.log || true)" = 0+echo "$health"+grep "METAL_HEALTH" /tmp/pvg-trace.log | tail -1+printf "tasks=%s managed-textures=%s\n" \+ "$(grep -c "TASK_RESERVE" /tmp/pvg-trace.log || true)" \+ "$(grep -c "METAL_TEXTURE.*managed-to-shared" /tmp/pvg-trace.log || true)"+')"++printf '%s\n' "$result"+echo "native iPad VM health checks passed"diff --git a/VirtualMac/scripts/tests/test-extracted-vm-real-mac.sh b/VirtualMac/scripts/tests/test-extracted-vm-real-mac.shnew file mode 100755index 0000000..1b96f62--- /dev/null+++ b/VirtualMac/scripts/tests/test-extracted-vm-real-mac.sh@@ -0,0 +1,240 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+: "${VZ_REAL_MAC_VM:?set VZ_REAL_MAC_VM to the VM bundle on the reference Mac}"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+LOCAL_FRAMEWORKS="$VZ_BUILD_ROOT/frameworks/bundles/macos"+LOCAL_SHIM="$VZ_REPO_ROOT/vz/shims/pvg_metallib_shim.m"+REMOTE_FRAMEWORKS="$REMOTE_ROOT/frameworks"+REMOTE_TEST_ROOT="$REMOTE_ROOT/ExtractedFrameworkTest"+BUILT_APP="$REMOTE_ROOT/DerivedData/Build/Products/Debug/macOSVirtualMachineSampleApp-Objective-C.app"+TEST_APP="$REMOTE_TEST_ROOT/macOSVirtualMachineSampleApp-Objective-C.app"+APP_EXECUTABLE="$TEST_APP/Contents/MacOS/macOSVirtualMachineSampleApp-Objective-C"+VMM="$TEST_APP/Contents/XPCServices/com.apple.Virtualization.VirtualMachine.xpc"+APP_LOG="$REMOTE_ROOT/extracted-framework-app.log"+HOST_DYLD_LOG="$REMOTE_ROOT/host-dyld.log"+VMM_DYLD_LOG="$REMOTE_ROOT/vmm-dyld.log"+RESULT_DIR="$VZ_BUILD_ROOT/validation"+RESULT="$RESULT_DIR/extracted-vm-real-mac.txt"+FRAMEWORK_ARCHIVE="$(mktemp -t apple-vz-frameworks.XXXXXX.tar.gz)"+trap 'rm -f "$FRAMEWORK_ARCHIVE"' EXIT++need_command sshpass+need_command tar+need_file "$LOCAL_SHIM"+for name in Hypervisor ParavirtualizedGraphics Virtualization; do+ need_file "$LOCAL_FRAMEWORKS/$name.framework/Versions/A/$name"+done+need_file \+ "$LOCAL_FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/Resources/default.metallib"+need_file \+ "$LOCAL_FRAMEWORKS/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.EventTap.xpc/Contents/MacOS/com.apple.Virtualization.EventTap"+need_file \+ "$LOCAL_FRAMEWORKS/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"++mkdir -p "$RESULT_DIR"+tar -C "$LOCAL_FRAMEWORKS" -czf "$FRAMEWORK_ARCHIVE" \+ Hypervisor.framework \+ ParavirtualizedGraphics.framework \+ Virtualization.framework++active="$(real_mac_ssh \+ "pgrep -f '$APP_EXECUTABLE|$VMM/Contents/MacOS/com.apple.Virtualization.VirtualMachine' || true")"+[[ -z "$active" ]] ||+ die "the extracted-framework test VM is already active on the real Mac (PIDs: $active)"++real_mac_ssh \+ "mkdir -p '$REMOTE_ROOT' '$REMOTE_FRAMEWORKS'; rm -rf \+ '$REMOTE_FRAMEWORKS/Hypervisor.framework' \+ '$REMOTE_FRAMEWORKS/ParavirtualizedGraphics.framework' \+ '$REMOTE_FRAMEWORKS/Virtualization.framework' \+ '$REMOTE_TEST_ROOT'"+real_mac_ssh_args+real_mac_scp "$FRAMEWORK_ARCHIVE" \+ "$REAL_MAC_TARGET:$REMOTE_ROOT/frameworks.tar.gz"+real_mac_scp "$LOCAL_SHIM" \+ "$REAL_MAC_TARGET:$REMOTE_ROOT/pvg_metallib_shim.m"++prepare_script="$(cat <<EOF+set -eu+export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer+test -d '$VZ_REAL_MAC_VM'+test -d '$BUILT_APP'+test -x '$BUILT_APP/Contents/MacOS/macOSVirtualMachineSampleApp-Objective-C'+test "\$(xcodebuild -version | head -1)" = "Xcode 14.2"++tar -xzf '$REMOTE_ROOT/frameworks.tar.gz' -C '$REMOTE_FRAMEWORKS'+rm -f '$REMOTE_ROOT/frameworks.tar.gz'+codesign --verify --deep --strict '$REMOTE_FRAMEWORKS/Virtualization.framework'++mkdir -p '$REMOTE_TEST_ROOT'+ditto '$BUILT_APP' '$TEST_APP'+mkdir -p '$TEST_APP/Contents/XPCServices'+ditto \+ '$REMOTE_FRAMEWORKS/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.EventTap.xpc' \+ '$TEST_APP/Contents/XPCServices/com.apple.Virtualization.EventTap.xpc'+ditto \+ '$REMOTE_FRAMEWORKS/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.VirtualMachine.xpc' \+ '$VMM'++mkdir -p '$VMM/Contents/Frameworks' '$VMM/Contents/Resources'+ditto '$REMOTE_FRAMEWORKS/Hypervisor.framework' \+ '$VMM/Contents/Frameworks/Hypervisor.framework'+ditto '$REMOTE_FRAMEWORKS/ParavirtualizedGraphics.framework' \+ '$VMM/Contents/Frameworks/ParavirtualizedGraphics.framework'+cp \+ '$REMOTE_FRAMEWORKS/ParavirtualizedGraphics.framework/Versions/A/Resources/default.metallib' \+ '$VMM/Contents/Resources/default.metallib'++xcrun clang -arch arm64e -fobjc-arc -dynamiclib \+ -framework Foundation -framework Metal \+ '$REMOTE_ROOT/pvg_metallib_shim.m' \+ -o '$VMM/Contents/Frameworks/PVGMetallibShim.dylib'+codesign --force --sign - \+ '$VMM/Contents/Frameworks/PVGMetallibShim.dylib'+for framework in \+ '$VMM/Contents/Frameworks/Hypervisor.framework' \+ '$VMM/Contents/Frameworks/ParavirtualizedGraphics.framework'; do+ codesign --force --sign - "\$framework"+done++PLIST='$VMM/Contents/Info.plist'+/usr/libexec/PlistBuddy \+ -c 'Delete :XPCService:EnvironmentVariables' "\$PLIST" >/dev/null 2>&1 || true+/usr/libexec/PlistBuddy \+ -c 'Add :XPCService:EnvironmentVariables dict' "\$PLIST"+/usr/libexec/PlistBuddy \+ -c 'Add :XPCService:EnvironmentVariables:DYLD_FRAMEWORK_PATH string $VMM/Contents/Frameworks' "\$PLIST"+/usr/libexec/PlistBuddy \+ -c 'Add :XPCService:EnvironmentVariables:DYLD_INSERT_LIBRARIES string $VMM/Contents/Frameworks/PVGMetallibShim.dylib' "\$PLIST"+/usr/libexec/PlistBuddy \+ -c 'Add :XPCService:EnvironmentVariables:DYLD_PRINT_LIBRARIES string 1' "\$PLIST"+/usr/libexec/PlistBuddy \+ -c 'Add :XPCService:EnvironmentVariables:DYLD_PRINT_TO_FILE string $VMM_DYLD_LOG' "\$PLIST"+/usr/libexec/PlistBuddy \+ -c 'Add :XPCService:EnvironmentVariables:NSUnbufferedIO string YES' "\$PLIST"++codesign --force --sign - --deep \+ --preserve-metadata=entitlements,flags,runtime '$VMM'+codesign --force --sign - --deep \+ --preserve-metadata=entitlements,flags,runtime '$TEST_APP'+codesign --verify --deep --strict '$TEST_APP'+/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister \+ -f '$TEST_APP'+rm -f '$APP_LOG' '$HOST_DYLD_LOG' '$VMM_DYLD_LOG'+EOF+)"+real_mac_ssh "$prepare_script"++launch_script="$(cat <<EOF+set -eu+DYLD_FRAMEWORK_PATH='$REMOTE_FRAMEWORKS' \+DYLD_PRINT_LIBRARIES=1 \+DYLD_PRINT_TO_FILE='$HOST_DYLD_LOG' \+nohup '$APP_EXECUTABLE' >'$APP_LOG' 2>&1 </dev/null &+launched_pid=\$!+i=0+app_pid=+while test "\$i" -lt 30; do+ app_pid=\$(pgrep -n -f '$APP_EXECUTABLE' || true)+ test -n "\$app_pid" && break+ sleep 1+ i=\$((i + 1))+done+test -n "\$app_pid"+test "\$app_pid" = "\$launched_pid"+i=0+vmm_pid=+while test "\$i" -lt 60; do+ vmm_pid=\$(pgrep -n -f \+ '$VMM/Contents/MacOS/com.apple.Virtualization.VirtualMachine' || true)+ test -n "\$vmm_pid" && break+ test -e '$APP_LOG' && \+ grep -q 'Internal Virtualization error' '$APP_LOG' && exit 1+ sleep 1+ i=\$((i + 1))+done+test -n "\$vmm_pid"+sleep 20+kill -0 "\$app_pid"+kill -0 "\$vmm_pid"+test ! -s '$APP_LOG'+grep -Fq \+ '$REMOTE_FRAMEWORKS/Virtualization.framework/Versions/A/Virtualization' \+ '$HOST_DYLD_LOG'+grep -Fq \+ '$VMM/Contents/Frameworks/Hypervisor.framework/Versions/A/Hypervisor' \+ '$VMM_DYLD_LOG'+grep -Fq \+ '$VMM/Contents/Frameworks/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics' \+ '$VMM_DYLD_LOG'+grep -Fq \+ '$VMM/Contents/Frameworks/PVGMetallibShim.dylib' \+ '$VMM_DYLD_LOG'+printf 'APP_PID\\t%s\\nVMM_PID\\t%s\\n' "\$app_pid" "\$vmm_pid"+EOF+)"++set +e+real_mac_ssh "$launch_script" 2>&1 | tee "$RESULT"+status=${PIPESTATUS[0]}+set -e+[[ "$status" == 0 ]] ||+ die "the extracted-framework VM failed to remain alive"++app_pid="$(awk -F $'\t' '$1 == "APP_PID" { print $2 }' "$RESULT")"+vmm_pid="$(awk -F $'\t' '$1 == "VMM_PID" { print $2 }' "$RESULT")"+[[ -n "$app_pid" && -n "$vmm_pid" ]] ||+ die "failed to record the host and VMM PIDs"++inspect_script="$(cat <<EOF+set -eu+export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer+xcrun lldb --batch -p '$app_pid' \+ -o 'image list -t -f Virtualization' \+ -o detach+EOF+)"+echo "HOST_IMAGES" | tee -a "$RESULT"+set +e+real_mac_ssh "$inspect_script" 2>&1 | tee -a "$RESULT"+status=${PIPESTATUS[0]}+set -e+[[ "$status" == 0 ]] || die "LLDB inspection of the sample app failed"++echo "VMM_IMAGES" | tee -a "$RESULT"+set +e+printf '%s\n' "$VZ_REAL_MAC_PASSWORD" |+ real_mac_ssh \+ "sudo -S -p '' env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \+ xcrun lldb --batch -p '$vmm_pid' \+ -o 'image list -t -f Hypervisor ParavirtualizedGraphics' \+ -o 'image list -t -f PVGMetallibShim.dylib' \+ -o detach" 2>&1 | tee -a "$RESULT"+status=${PIPESTATUS[1]}+set -e+[[ "$status" == 0 ]] || die "root LLDB inspection of the Apple VMM failed"++grep -Fq "$REMOTE_FRAMEWORKS/Virtualization.framework" "$RESULT" ||+ die "host app did not load the extracted Virtualization framework"+grep -Fq "$VMM/Contents/Frameworks/Hypervisor.framework" "$RESULT" ||+ die "Apple VMM did not load the extracted Hypervisor framework"+grep -Fq "$VMM/Contents/Frameworks/ParavirtualizedGraphics.framework" "$RESULT" ||+ die "Apple VMM did not load the extracted ParavirtualizedGraphics framework"+grep -Fq "$VMM/Contents/Frameworks/PVGMetallibShim.dylib" "$RESULT" ||+ die "Apple VMM did not load the PVG metallib shim"+if grep -Eq \+ '/System/Library/Frameworks/(Virtualization|Hypervisor|ParavirtualizedGraphics)\.framework/' \+ "$RESULT"; then+ die "LLDB reported a system copy of a framework that must be extracted"+fi++real_mac_ssh "kill -0 '$app_pid'; kill -0 '$vmm_pid'"+echo "extracted 22D68 Apple virtualization stack is loaded and running"+echo "the real-Mac GUI was left open for visual confirmation"+echo "evidence: $RESULT"diff --git a/VirtualMac/scripts/tests/test-ipad-guest-audio.sh b/VirtualMac/scripts/tests/test-ipad-guest-audio.shnew file mode 100755index 0000000..266b1af--- /dev/null+++ b/VirtualMac/scripts/tests/test-ipad-guest-audio.sh@@ -0,0 +1,165 @@+#!/bin/bash++# Validate both directions of the native virtio-sound device:+# guest system sound -> iPad output sink+# iPad microphone -> guest input source+# The guest microphone TCC prompt is accepted through Virtual Mac's one-shot+# input command bridge, so the test remains repeatable over USB SSH.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck disable=SC1091+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_GUEST_HOST:?set VZ_GUEST_HOST to the guest address}"+: "${VZ_GUEST_USER:?set VZ_GUEST_USER to the guest SSH user}"+: "${VZ_GUEST_PASSWORD:?set VZ_GUEST_PASSWORD to the guest SSH password}"+GUEST_HOST="$VZ_GUEST_HOST"+GUEST_USER="$VZ_GUEST_USER"+GUEST_PORT="${VZ_GUEST_USB_PORT:-2208}"+GUEST_PASSWORD="$VZ_GUEST_PASSWORD"+PROBE_ROOT="$(mktemp -d -t vz-audio-probe.XXXXXX)"+REMOTE_ROOT="/tmp/vz-audio-probe-$$"++need_command codesign+need_command ldid+need_command lsof+need_command ssh+need_command sshpass+need_command xcrun+ensure_ipad_usb++owned_tunnel=0+if ! lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1; then+ sshpass -p "$VZ_IPAD_PASSWORD" ssh "${IPAD_SSH_ARGS[@]}" \+ -o ControlMaster=no -o ControlPath=none \+ -N -L "127.0.0.1:$GUEST_PORT:$GUEST_HOST:22" "$IPAD_TARGET" &+ tunnel_pid=$!+ owned_tunnel=1+fi+cleanup() {+ if [[ "$owned_tunnel" == 1 ]]; then+ listener_pids="$(lsof -t -iTCP:"$GUEST_PORT" -sTCP:LISTEN 2>/dev/null || true)"+ if [[ -n "$listener_pids" ]]; then+ # shellcheck disable=SC2086+ kill $listener_pids 2>/dev/null || true+ fi+ kill "$tunnel_pid" 2>/dev/null || true+ wait "$tunnel_pid" 2>/dev/null || true+ fi+ rm -rf "$PROBE_ROOT"+}+trap cleanup EXIT++for _ in {1..40}; do+ lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 && break+ sleep 0.25+done+lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1 ||+ die "iPad guest SSH tunnel did not open"++guest_ssh=(sshpass -p "$GUEST_PASSWORD" ssh -p "$GUEST_PORT"+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10 -o PubkeyAuthentication=no+ -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1+ "[email protected]")+guest_scp=(sshpass -p "$GUEST_PASSWORD" scp -P "$GUEST_PORT"+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=10 -o PubkeyAuthentication=no+ -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1)++APP="$PROBE_ROOT/AudioCaptureProbe.app"+mkdir -p "$APP/Contents/MacOS"+xcrun --sdk macosx clang -arch arm64 -mmacosx-version-min=13.0 -fblocks \+ "$VZ_REPO_ROOT/vz/development/probes/audio_capture_app.m" \+ -framework AppKit -framework AVFoundation \+ -o "$APP/Contents/MacOS/AudioCaptureProbe"+cp "$VZ_REPO_ROOT/vz/development/probes/AudioCaptureProbe-Info.plist" \+ "$APP/Contents/Info.plist"+codesign -s - --force --deep "$APP"+ditto -c -k --sequesterRsrc --keepParent "$APP" \+ "$PROBE_ROOT/AudioCaptureProbe.zip"++xcrun --sdk macosx clang -arch arm64 -mmacosx-version-min=13.0 -fobjc-arc \+ "$VZ_REPO_ROOT/vz/development/probes/window_list_probe.m" \+ -framework CoreGraphics -framework Foundation \+ -o "$PROBE_ROOT/window-list-probe"+codesign -s - --force "$PROBE_ROOT/window-list-probe"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=16.0 \+ -isysroot "$SDK" -fobjc-arc \+ "$VZ_REPO_ROOT/vz/development/probes/audio_tone_probe.m" \+ -framework AVFAudio -framework AudioToolbox -framework Foundation \+ -o "$PROBE_ROOT/audio-tone-probe"+ldid -S"$VZ_REPO_ROOT/vz/host/VirtualMac.entitlements" \+ "$PROBE_ROOT/audio-tone-probe"+tone_hash="$(ldid -h "$PROBE_ROOT/audio-tone-probe" |+ sed -n 's/^CDHash=//p')"+[[ -n "$tone_hash" ]] || die "could not read tone probe CDHash"++"${guest_ssh[@]}" "mkdir -p '$REMOTE_ROOT'"+"${guest_scp[@]}" "$PROBE_ROOT/AudioCaptureProbe.zip" \+ "$PROBE_ROOT/window-list-probe" \+ "[email protected]:$REMOTE_ROOT/"+ipad_scp "$PROBE_ROOT/audio-tone-probe" \+ "$IPAD_TARGET:/var/root/VirtualMac/audio-tone-probe"+ipad_ssh "chmod 755 /var/root/VirtualMac/audio-tone-probe; \+ jbctl trustcache add '$tone_hash'"++"${guest_ssh[@]}" "set -eu+pkill -f '/AudioCaptureProbe.*app/Contents/MacOS/AudioCaptureProbe' 2>/dev/null || true+chmod 755 '$REMOTE_ROOT/window-list-probe'+ditto -x -k '$REMOTE_ROOT/AudioCaptureProbe.zip' '$REMOTE_ROOT'+: >/tmp/vz-audio-capture-result.txt+open '$REMOTE_ROOT/AudioCaptureProbe.app'"++# A prompt is a UserNotificationCenter window on-screen. Compute the Allow+# button from its actual bounds instead of assuming a guest resolution.+for _ in {1..12}; do+ windows="$("${guest_ssh[@]}" "$REMOTE_ROOT/window-list-probe")"+ screen="$(printf '%s\n' "$windows" | sed -n 's/^screen //p')"+ alert="$(printf '%s\n' "$windows" |+ grep 'owner=UserNotificationCenter' | grep -E ' y=[0-9]' | head -1 || true)"+ if [[ -n "$alert" ]]; then+ read -r normalized_x normalized_y < <(awk -v screen="$screen" \+ -v alert="$alert" 'BEGIN {+ split(screen, s, /[ =]/); n=split(alert, a, /[ =]/);+ sw=s[2]; sh=s[4];+ for (i=1; i<=n; i++) {+ if (a[i] == "x") x=a[i+1];+ if (a[i] == "y") y=a[i+1];+ if (a[i] == "width") w=a[i+1];+ if (a[i] == "height") h=a[i+1];+ }+ printf "%.5f %.5f\n", (x + 0.75*w)/sw, (y + 0.83*h)/sh;+ }')+ ipad_ssh "printf 'click %s %s 1\n' '$normalized_x' '$normalized_y' \+ >/tmp/vz-input-command; chown mobile:mobile /tmp/vz-input-command"+ fi+ sleep 0.5+ [[ -z "$alert" ]] && break+done++# The guest beep exercises its virtual output stream. The iPad tone then gives+# the physical microphone a deterministic signal for the guest input stream.+"${guest_ssh[@]}" "osascript -e 'set volume output volume 75' -e 'beep 5'"+ipad_ssh "/var/root/VirtualMac/audio-tone-probe 3"+sleep 3++result="$("${guest_ssh[@]}" 'cat /tmp/vz-audio-capture-result.txt')"+printf '%s\n' "$result"+printf '%s\n' "$result" | grep -Fq 'permission=granted' ||+ die "guest microphone permission was not granted"+peak="$(printf '%s\n' "$result" | sed -n 's/.* peak=\([0-9.]*\).*/\1/p')"+[[ -n "$peak" ]] || die "guest microphone probe did not report a peak"+awk -v peak="$peak" 'BEGIN { exit !(peak > 0.00001) }' ||+ die "guest microphone stream contained only zeros"++"${guest_ssh[@]}" "printf '%s\n' '$GUEST_PASSWORD' | sudo -S \+ log show --last 2m --style compact 2>/dev/null | \+ grep -F 'setPlayState Started Output {AVIODevice' | tail -1"+ipad_ssh "ps ax | grep -F \+ '/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine' | \+ grep -v grep"+echo "iPad guest audio input/output validation passed"diff --git a/VirtualMac/scripts/tests/test-ipad-input.sh b/VirtualMac/scripts/tests/test-ipad-input.shnew file mode 100755index 0000000..53ca8ac--- /dev/null+++ b/VirtualMac/scripts/tests/test-ipad-input.sh@@ -0,0 +1,19 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++VZ_IPAD_INPUT_SELF_TEST=1 \+ "$VZ_REPO_ROOT/scripts/launch-ipad-app.sh" "${1:-7}"+sleep 3+ipad_ssh "+echo SELF_TEST+grep -E 'input self-test|input pointer|input key' /tmp/VirtualMac.log || true+echo KEYBOARD_CALLBACKS+grep -F 'process_keyboard_led_update' /tmp/vzxpchook.log \+ /tmp/vmmhook.log 2>/dev/null | tail -8 || true+echo VMM+ps axww | grep com.apple.Virtualization.VirtualMachine | grep -v grep || true+"diff --git a/VirtualMac/scripts/tests/test-ipad-vm-reservations.sh b/VirtualMac/scripts/tests/test-ipad-vm-reservations.shnew file mode 100755index 0000000..43f4ab3--- /dev/null+++ b/VirtualMac/scripts/tests/test-ipad-vm-reservations.sh@@ -0,0 +1,28 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++SDK="$(xcrun --sdk iphoneos --show-sdk-path)"+OUT="$VZ_BUILD_ROOT/vm-reserve-probe"+BIN="$OUT/vm-reserve-probe"+REMOTE="${VZ_IPAD_WORK:-/var/root/VirtualMac}/vm-reserve-probe"++need_command ldid+need_command xcrun+need_file "$VZ_REPO_ROOT/vz/development/probes/vm_reserve_probe.c"+need_file "$VZ_REPO_ROOT/vz/patches/vmm.ents.xml"+mkdir -p "$OUT"++xcrun --sdk iphoneos clang \+ -arch arm64 -miphoneos-version-min=16.0 -isysroot "$SDK" \+ "$VZ_REPO_ROOT/vz/development/probes/vm_reserve_probe.c" -o "$BIN"+ldid -S"$VZ_REPO_ROOT/vz/patches/vmm.ents.xml" "$BIN"+hash="$(ldid -h "$BIN" | sed -n 's/^CDHash=//p')"+test -n "$hash"++ensure_ipad_usb+ipad_scp "$BIN" "$IPAD_TARGET:$REMOTE"+ipad_ssh "chmod 755 '$REMOTE'; jbctl trustcache add '$hash'; '$REMOTE'"diff --git a/VirtualMac/scripts/tests/test-shared-folders-real-mac.sh b/VirtualMac/scripts/tests/test-shared-folders-real-mac.shnew file mode 100755index 0000000..077c5b0--- /dev/null+++ b/VirtualMac/scripts/tests/test-shared-folders-real-mac.sh@@ -0,0 +1,119 @@+#!/bin/bash++# Boot Ventura-hosted VM with macOS VirtioFS automount tag and+# prove that a host sentinel is visible inside the guest.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++: "${VZ_REAL_MAC_WORK:?set VZ_REAL_MAC_WORK on the reference Mac}"+: "${VZ_REAL_MAC_SHARED_VM:?set VZ_REAL_MAC_SHARED_VM to the test VM bundle}"+: "${VZ_REAL_MAC_GUEST_USER:?set VZ_REAL_MAC_GUEST_USER}"+: "${VZ_REAL_MAC_GUEST_PASSWORD:?set VZ_REAL_MAC_GUEST_PASSWORD}"+REMOTE_ROOT="$VZ_REAL_MAC_WORK"+REMOTE_VM="$VZ_REAL_MAC_SHARED_VM"+REMOTE_SHARE="$REMOTE_ROOT/shared-folder-oracle"+REMOTE_PROBE="$REMOTE_ROOT/vzmacboot-shared"+REMOTE_LOG="$REMOTE_ROOT/shared-folder-oracle-vm.log"+GUEST_USER="$VZ_REAL_MAC_GUEST_USER"+GUEST_PASSWORD="$VZ_REAL_MAC_GUEST_PASSWORD"+GUEST_PORT="${VZ_REAL_MAC_GUEST_PORT:-2211}"+GUEST_MAC="d6:a7:58:8e:78:d6"++need_command lsof+need_command sshpass+real_mac_ssh_args++local_source="$VZ_REPO_ROOT/vz/development/probes/vzmacboot.m"+local_entitlements="$VZ_REPO_ROOT/vz/development/probes/vz-macos.entitlements"+need_file "$local_source"+need_file "$local_entitlements"++runner_pid=+tunnel_pid=+cleanup() {+ if [[ -n "$tunnel_pid" ]]; then+ kill "$tunnel_pid" 2>/dev/null || true+ wait "$tunnel_pid" 2>/dev/null || true+ fi+ if [[ -n "$runner_pid" ]]; then+ real_mac_ssh "kill '$runner_pid' 2>/dev/null || true" || true+ fi+}+trap cleanup EXIT++[[ -z "$(real_mac_ssh "pgrep -f 'vzmacboot-shared|com.apple.Virtualization.VirtualMachine' || true")" ]] ||+ die "a real-Mac virtualization process is already running"+if lsof -nP -iTCP:"$GUEST_PORT" -sTCP:LISTEN >/dev/null 2>&1; then+ die "local guest SSH port $GUEST_PORT is already in use"+fi++real_mac_scp "$local_source" "$local_entitlements" \+ "$REAL_MAC_TARGET:$REMOTE_ROOT/"+runner_pid="$(real_mac_ssh "+set -eu+test -f '$REMOTE_VM/Disk.img'+mkdir -p '$REMOTE_SHARE'+printf 'ventura-virtiofs-oracle\n' >'$REMOTE_SHARE/host-sentinel.txt'+xcrun clang -fobjc-arc -framework AppKit -framework Virtualization \+ '$REMOTE_ROOT/vzmacboot.m' -o '$REMOTE_PROBE'+codesign --force --sign - --entitlements \+ '$REMOTE_ROOT/vz-macos.entitlements' '$REMOTE_PROBE' >/dev/null+VZ_SHARED_DIRECTORY='$REMOTE_SHARE' VZ_RUN_SECONDS=300 \+VZ_LOG_PATH='$REMOTE_LOG' nohup '$REMOTE_PROBE' '$REMOTE_VM' \+ >/dev/null 2>&1 &+echo \$!+")"++guest_ip=+for _ in {1..60}; do+ guest_ip="$(real_mac_ssh "arp -an | awk '+ / on bridge100 / && tolower(\$4) == \"$GUEST_MAC\" {+ gsub(/[()]/, \"\", \$2); print \$2; exit+ }'")"+ [[ -n "$guest_ip" ]] && break+ sleep 2+done+[[ -n "$guest_ip" ]] || die "could not discover the Ventura guest address"++sshpass -p "$VZ_REAL_MAC_PASSWORD" ssh "${REAL_MAC_SSH_ARGS[@]}" \+ -o ControlMaster=no -o ControlPath=none \+ -N -L "127.0.0.1:$GUEST_PORT:$guest_ip:22" \+ "$REAL_MAC_TARGET" &+tunnel_pid=$!+for _ in {1..60}; do+ if sshpass -p "$GUEST_PASSWORD" ssh -p "$GUEST_PORT" \+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -o ConnectTimeout=2 -o PubkeyAuthentication=no \+ -o PreferredAuthentications=password \+ "[email protected]" true 2>/dev/null; then+ break+ fi+ sleep 2+done++guest_ssh=(sshpass -p "$GUEST_PASSWORD" ssh -p "$GUEST_PORT"+ -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null+ -o ConnectTimeout=5 -o PubkeyAuthentication=no+ -o PreferredAuthentications=password "[email protected]")+"${guest_ssh[@]}" "+set -eu+mount | grep -F '/Volumes/My Shared Files (AppleVirtIOFS'+test \"\$(cat '/Volumes/My Shared Files/Host Share/host-sentinel.txt')\" = \+ ventura-virtiofs-oracle+"+"${guest_ssh[@]}" "+printf '%s\n' '$GUEST_PASSWORD' | sudo -S -p '' shutdown -h now+" || true++for _ in {1..30}; do+ if ! real_mac_ssh "kill -0 '$runner_pid' 2>/dev/null"; then+ runner_pid=+ break+ fi+ sleep 1+done++echo "Ventura guest automatically mounted the real-Mac shared folder"diff --git a/VirtualMac/scripts/tests/verify-ipad-videotoolbox-runtime.sh b/VirtualMac/scripts/tests/verify-ipad-videotoolbox-runtime.shnew file mode 100755index 0000000..387ad49--- /dev/null+++ b/VirtualMac/scripts/tests/verify-ipad-videotoolbox-runtime.sh@@ -0,0 +1,26 @@+#!/bin/bash++# Prove that a running iPad-hosted VM is using the bundled Ventura+# VideoToolbox host implementation. This briefly attaches LLDB and immediately+# detaches after listing images; the VM resumes before the command returns.++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=../lib/common.sh+source "$SCRIPT_DIR/../lib/common.sh"++ensure_ipad_usb+processes="$(ipad_ssh "ps ax | grep 'VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine' | grep -v grep")"+pid="$(printf '%s\n' "$processes" | awk 'NR == 1 { print $1 }')"+[[ -n "$pid" ]] || die "the iPad VirtualMachine process is not running"++images="$(ipad_ssh "printf 'process attach --pid $pid\\nimage list -b -o -f\\nprocess detach\\nquit\\n' | /var/jb/usr/bin/lldb 2>&1")"+printf '%s\n' "$images" | grep -E 'Process .* (stopped|detached)|VideoToolbox'++bundled='/VirtualMac/payload/Frameworks/VideoToolbox.framework/VideoToolbox'+printf '%s\n' "$images" | grep -F "$bundled" >/dev/null ||+ die "the VMM did not load the bundled macOS VideoToolbox framework"+printf '%s\n' "$images" | grep -F 'VideoToolboxParavirtualizationSupport.framework' >/dev/null ||+ die "the VMM did not load VideoToolboxParavirtualizationSupport"++printf 'IPAD_VIDEOTOOLBOX_RUNTIME_OK\tpid=%s\n' "$pid"diff --git a/VirtualMac/setup.sh b/VirtualMac/setup.shnew file mode 100755index 0000000..da0577e--- /dev/null+++ b/VirtualMac/setup.sh@@ -0,0 +1,284 @@+#!/bin/bash++# Build a complete Virtualization.framework-on-iPad package from a fresh+# checkout. With no arguments this is an interactive wizard; every choice is+# also available as an option or environment variable for unattended builds.++set -euo pipefail++REPO_ROOT="$(cd "$(dirname "$0")" && pwd)"+MACOS_NAME="UniversalMac_13.2.1_22D68_Restore.ipsw"+IPADOS_NAME="iPad14,3,iPad14,4,iPad14,5,iPad14,6_16.3.1_20D67_Restore.ipsw"+MACOS_URL="https://updates.cdn-apple.com/2023WinterFCS/fullrestores/032-48346/EFF99C1E-C408-4E7A-A448-12E1468AF06C/$MACOS_NAME"+IPADOS_URL="https://updates.cdn-apple.com/2023WinterFCS/fullrestores/032-50028/ACF197BE-D22C-49EC-94C5-C1B58D7708AC/$IPADOS_NAME"+MACOS_SHA256="0310220c8a540dc53a92ec9f9e0894db627d8f97fd18c3275eb96865a6e5fe04"+IPADOS_SHA256="a4d922f3fdc960fd5714b5d46c13b928c1249e072cb93301bd1f7bb66ec29cc0"+DEVICE_SUPPORT_NAME="DeviceSupport_macOS_27_beta.dmg"+DEVICE_SUPPORT_URL="https://github.com/nfzerox/DeviceSupportMirror/releases/download/1.0/$DEVICE_SUPPORT_NAME"+DEVICE_SUPPORT_SHA256="d02e14429a02a78d8bf9d84df8ae55f5a03f2a00dbf58767f451b68eda417ca1"++BUILD_ROOT="${VZ_BUILD_ROOT:-$REPO_ROOT/build}"+DOWNLOAD_ROOT="${VZ_DOWNLOAD_ROOT:-$BUILD_ROOT/downloads}"+MACOS_IPSW="${VZ_MACOS_IPSW:-}"+IPADOS_IPSW="${VZ_IPADOS_IPSW:-}"+DEVICE_SUPPORT_DMG="${VZ_DEVICE_SUPPORT_DMG:-}"+XCODE_PATH="${DEVELOPER_DIR:-${VZ_XCODE_PATH:-}}"+IPAD_UDID="${VZ_IPAD_UDID:-}"+IPAD_PORT="${VZ_IPAD_PORT:-2221}"+IPAD_PASSWORD_FILE=""+INTERACTIVE=-1+FULL_IPADOS_AUDIT=0+INSTALL_IPAD=0+LAUNCH_IPAD=0+SKIP_DEPENDENCIES=0++usage() {+ cat <<'EOF'+Usage: ./setup.sh [options]++Build options:+ --build-dir PATH Generated files (default: ./build)+ --download-dir PATH Downloaded restore images (default: BUILD/downloads)+ --macos-ipsw PATH Reuse macOS 13.2.1 (22D68) restore image+ --full-ipados-audit Extract 16.3.1 and 16.1 iPadOS caches and audit ABIs+ --ipados-ipsw PATH Reuse 16.3.1 image for --full-ipados-audit+ --device-support-dmg P Reuse the macOS 27 DeviceSupport disk image+ --xcode PATH Xcode.app or its Contents/Developer directory+ --skip-dependencies Do not install Homebrew or Brewfile dependencies+ --non-interactive Never prompt; download omitted restore images++Optional iPad deployment:+ --install Install the resulting deb over USB SSH+ --launch Install and then launch Virtual Mac+ --ipad-udid UDID Target device; auto-detected when exactly one is attached+ --ipad-port PORT Local iproxy port (default: 2221)+ --ipad-password-file P Read the SSH password from P++Environment equivalents are documented in .env.example. Passwords are never+accepted as command-line values because process arguments are observable.+EOF+}++die() {+ echo "error: $*" >&2+ exit 1+}++while (($#)); do+ case "$1" in+ --build-dir) BUILD_ROOT="${2:?missing path}"; shift 2 ;;+ --download-dir) DOWNLOAD_ROOT="${2:?missing path}"; shift 2 ;;+ --macos-ipsw) MACOS_IPSW="${2:?missing path}"; shift 2 ;;+ --ipados-ipsw) IPADOS_IPSW="${2:?missing path}"; FULL_IPADOS_AUDIT=1; shift 2 ;;+ --device-support-dmg) DEVICE_SUPPORT_DMG="${2:?missing path}"; shift 2 ;;+ --full-ipados-audit) FULL_IPADOS_AUDIT=1; shift ;;+ --xcode) XCODE_PATH="${2:?missing path}"; shift 2 ;;+ --skip-dependencies) SKIP_DEPENDENCIES=1; shift ;;+ --non-interactive) INTERACTIVE=0; shift ;;+ --install) INSTALL_IPAD=1; shift ;;+ --launch) INSTALL_IPAD=1; LAUNCH_IPAD=1; shift ;;+ --ipad-udid) IPAD_UDID="${2:?missing UDID}"; shift 2 ;;+ --ipad-port) IPAD_PORT="${2:?missing port}"; shift 2 ;;+ --ipad-password-file) IPAD_PASSWORD_FILE="${2:?missing path}"; shift 2 ;;+ -h|--help) usage; exit 0 ;;+ *) die "unknown option: $1 (run ./setup.sh --help)" ;;+ esac+done++# No explicit --non-interactive marker is retained after parsing, so enable+# the wizard whenever a terminal is attached and CI has not opted out.+if [[ "$INTERACTIVE" == -1 ]]; then+ if [[ -t 0 && "${CI:-}" != true && "${VZ_NONINTERACTIVE:-0}" != 1 ]]; then+ INTERACTIVE=1+ else+ INTERACTIVE=0+ fi+fi++prompt_default() {+ local prompt="$1" default_value="$2" answer+ read -r -p "$prompt [$default_value]: " answer+ printf '%s' "${answer:-$default_value}"+}++prompt_yes_no() {+ local prompt="$1" default_value="$2" answer suffix+ if [[ "$default_value" == 1 ]]; then suffix="Y/n"; else suffix="y/N"; fi+ read -r -p "$prompt [$suffix]: " answer+ case "${answer:-}" in+ y|Y|yes|YES) return 0 ;;+ n|N|no|NO) return 1 ;;+ '') [[ "$default_value" == 1 ]] ;;+ *) echo "Please answer yes or no." >&2; prompt_yes_no "$prompt" "$default_value" ;;+ esac+}++absolute_directory() {+ mkdir -p "$1"+ (cd "$1" && pwd -P)+}++absolute_file() {+ local directory basename+ directory="$(dirname "$1")"+ basename="$(basename "$1")"+ (cd "$directory" && printf '%s/%s\n' "$(pwd -P)" "$basename")+}++install_homebrew() {+ if command -v brew >/dev/null 2>&1; then return; fi+ command -v curl >/dev/null 2>&1 || die "curl is required to install Homebrew"+ echo "Installing Homebrew..."+ NONINTERACTIVE=1 /bin/bash -c \+ "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"+ if [[ -x /opt/homebrew/bin/brew ]]; then+ eval "$(/opt/homebrew/bin/brew shellenv)"+ elif [[ -x /usr/local/bin/brew ]]; then+ eval "$(/usr/local/bin/brew shellenv)"+ else+ die "Homebrew installation completed but brew is not on PATH"+ fi+}++select_xcode() {+ local developer_path="$XCODE_PATH"+ if [[ -n "$developer_path" && "$developer_path" == *.app ]]; then+ developer_path="$developer_path/Contents/Developer"+ fi+ if [[ -n "$developer_path" ]]; then+ [[ -d "$developer_path" ]] || die "Xcode developer directory not found: $developer_path"+ export DEVELOPER_DIR="$developer_path"+ fi++ if xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1; then return; fi++ if [[ "$INTERACTIVE" == 1 ]]; then+ echo "A full Xcode with an iPhoneOS SDK is required." >&2+ echo "Install Xcode now, then enter its path below." >&2+ developer_path="$(prompt_default "Xcode.app path" "/Applications/Xcode.app")"+ if [[ "$developer_path" == *.app ]]; then+ developer_path="$developer_path/Contents/Developer"+ fi+ [[ -d "$developer_path" ]] || die "Xcode developer directory not found: $developer_path"+ export DEVELOPER_DIR="$developer_path"+ else+ die "full Xcode is missing; install it or pass --xcode PATH"+ fi+ xcrun --sdk iphoneos --show-sdk-path >/dev/null ||+ die "selected Xcode has no iPhoneOS SDK"+}++find_existing_restore() {+ local requested="$1" filename="$2" candidate+ if [[ -n "$requested" ]]; then printf '%s' "$requested"; return; fi+ for candidate in "$DOWNLOAD_ROOT/$filename" "${HOME:-}/Downloads/$filename"; do+ if [[ -f "$candidate" ]]; then printf '%s' "$candidate"; return; fi+ done+}++obtain_verified_file() {+ local label="$1" current="$2" filename="$3" url="$4" expected="$5" choice actual+ choice="$(find_existing_restore "$current" "$filename")"+ if [[ "$INTERACTIVE" == 1 ]]; then+ if [[ -n "$choice" ]]; then+ choice="$(prompt_default "$label file (blank downloads it)" "$choice")"+ else+ read -r -p "$label file path (blank downloads it): " choice+ fi+ fi+ if [[ -z "$choice" ]]; then+ choice="$DOWNLOAD_ROOT/$filename"+ mkdir -p "$DOWNLOAD_ROOT"+ echo "Downloading $label to $choice" >&2+ curl --fail --location --continue-at - --output "$choice" "$url"+ fi+ [[ -f "$choice" ]] || die "$label file not found: $choice"+ choice="$(absolute_file "$choice")"+ echo "Verifying $label file..." >&2+ actual="$(shasum -a 256 "$choice" | awk '{print $1}')"+ [[ "$actual" == "$expected" ]] ||+ die "$label restore image SHA-256 mismatch: expected $expected, got $actual"+ printf '%s' "$choice"+}++BUILD_ROOT="$(absolute_directory "$BUILD_ROOT")"+DOWNLOAD_ROOT="$(absolute_directory "$DOWNLOAD_ROOT")"++if [[ "$INTERACTIVE" == 1 ]]; then+ echo "Virtual Mac on iPad clean build wizard"+ echo "Generated files will remain outside Git. Existing verified downloads are reused."+ BUILD_ROOT="$(absolute_directory "$(prompt_default "Build directory" "$BUILD_ROOT")")"+ DOWNLOAD_ROOT="$(absolute_directory "$(prompt_default "Restore-image directory" "$DOWNLOAD_ROOT")")"+fi++if [[ "$SKIP_DEPENDENCIES" == 0 ]]; then+ install_homebrew+ brew bundle install --file "$REPO_ROOT/Brewfile"+fi++command -v curl >/dev/null 2>&1 || die "missing command: curl"+command -v shasum >/dev/null 2>&1 || die "missing command: shasum"+select_xcode++MACOS_IPSW="$(obtain_verified_file macOS "$MACOS_IPSW" "$MACOS_NAME" "$MACOS_URL" "$MACOS_SHA256")"+DEVICE_SUPPORT_DMG="$(obtain_verified_file DeviceSupport "$DEVICE_SUPPORT_DMG" \+ "$DEVICE_SUPPORT_NAME" "$DEVICE_SUPPORT_URL" "$DEVICE_SUPPORT_SHA256")"+if [[ "$FULL_IPADOS_AUDIT" == 1 ]]; then+ IPADOS_IPSW="$(obtain_verified_file iPadOS "$IPADOS_IPSW" "$IPADOS_NAME" "$IPADOS_URL" "$IPADOS_SHA256")"+fi++export VZ_BUILD_ROOT="$BUILD_ROOT"+export VZ_MACOS_IPSW="$MACOS_IPSW"+export VZ_IPADOS_IPSW="$IPADOS_IPSW"+export VZ_DEVICE_SUPPORT_DMG="$DEVICE_SUPPORT_DMG"+export VZ_INCLUDE_IPADOS_AUDIT="$FULL_IPADOS_AUDIT"+export VZ_REQUIRE_IPADOS_COMPAT_DSC="$FULL_IPADOS_AUDIT"+export VZ_IGNORE_ENV_FILE=1++"$REPO_ROOT/scripts/bootstrap.sh"+"$REPO_ROOT/scripts/prepare-inputs.sh"+if [[ "$FULL_IPADOS_AUDIT" == 1 ]]; then+ "$REPO_ROOT/scripts/fetch-ipados-compat-cache.sh"+fi+"$REPO_ROOT/scripts/build-frameworks.sh"+"$REPO_ROOT/scripts/build-ipad-deb.sh"++DEB="$(find "$BUILD_ROOT/release" -maxdepth 1 -type f \+ -name 'VirtualMac_*.deb' -print0 |+ xargs -0 ls -1t | head -1)"+[[ -f "$DEB" ]] || die "build completed without a deb"++if [[ "$INTERACTIVE" == 1 && "$INSTALL_IPAD" == 0 ]]; then+ prompt_yes_no "Install the package on a USB-connected Dopamine iPad?" 0 && INSTALL_IPAD=1+fi++if [[ "$INSTALL_IPAD" == 1 ]]; then+ if [[ -z "$IPAD_UDID" ]]; then+ devices="$(idevice_id -l)"+ count="$(printf '%s\n' "$devices" | awk 'NF { count++ } END { print count+0 }')"+ [[ "$count" == 1 ]] || die "attach exactly one iPad or pass --ipad-udid"+ IPAD_UDID="$devices"+ fi+ if [[ -n "$IPAD_PASSWORD_FILE" ]]; then+ [[ -f "$IPAD_PASSWORD_FILE" ]] || die "password file not found: $IPAD_PASSWORD_FILE"+ VZ_IPAD_PASSWORD="$(<"$IPAD_PASSWORD_FILE")"+ elif [[ -z "${VZ_IPAD_PASSWORD:-}" && "$INTERACTIVE" == 1 ]]; then+ read -r -s -p "iPad SSH password: " VZ_IPAD_PASSWORD+ echo+ fi+ : "${VZ_IPAD_PASSWORD:?set VZ_IPAD_PASSWORD or use --ipad-password-file}"+ export VZ_IPAD_UDID="$IPAD_UDID" VZ_IPAD_PORT="$IPAD_PORT"+ export VZ_IPAD_PASSWORD+ export VZ_IPAD_DEB="$DEB"+ "$REPO_ROOT/scripts/install-ipad-deb.sh"+ if [[ "$LAUNCH_IPAD" == 1 ]]; then+ "$REPO_ROOT/scripts/launch-ipad-app.sh" 1+ fi+fi++cat <<EOF++Build complete.+ Package: $DEB+ Build: $BUILD_ROOT+EOFdiff --git a/VirtualMac/vendor/VirtualBuddy/NOTICE.md b/VirtualMac/vendor/VirtualBuddy/NOTICE.mdnew file mode 100644index 0000000..5d67977--- /dev/null+++ b/VirtualMac/vendor/VirtualBuddy/NOTICE.md@@ -0,0 +1,21 @@+Copyright (c) 2022 Guilherme Rambo++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++- Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.+- Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/VirtualMac/vendor/VirtualBuddy/ipsws_v2.json b/VirtualMac/vendor/VirtualBuddy/ipsws_v2.jsonnew file mode 100644index 0000000..292d38c--- /dev/null+++ b/VirtualMac/vendor/VirtualBuddy/ipsws_v2.json@@ -0,0 +1,2859 @@+{+ "apiVersion" : 2,+ "channels" : [+ {+ "icon" : "checkmark.seal",+ "id" : "regular",+ "name" : "Release",+ "note" : "Public, stable releases."+ },+ {+ "icon" : "wrench.and.screwdriver",+ "id" : "devbeta",+ "name" : "Developer Beta",+ "note" : "Betas meant for developer testing."+ }+ ],+ "deviceSupportVersions" : [+ {+ "id" : "device_support_macOS26_beta",+ "instructions" : "Your Mac needs an update to install virtual machines that use this version of macOS.\n\nHere’s how you can install the update:\n\n1. Head over to the [Apple Developer downloads page](https:\/\/developer.apple.com\/download\/).\n2. Under “Operating Systems”, find “Device Support for macOS 26”.\n3. Click the link below that item.\n4. Double-click the downloaded DMG and open the installer. Follow the instructions.\n5. Quit and relaunch VirtualBuddy. Then, try again.\n\nInstalling the latest Xcode beta will also install the required update.",+ "mobileDeviceMinVersion" : "1810.0.0",+ "osVersion" : "26.0.0",+ "title" : "Device Support Update Required"+ }+ ],+ "features" : [+ {+ "detail" : "For previous versions, you can enable file sharing in System Preferences > Sharing.",+ "id" : "file_sharing",+ "minVersionGuest" : "13.0.0",+ "minVersionHost" : "13.0.0",+ "name" : "File sharing",+ "unsupportedPlatform" : false+ },+ {+ "id" : "guest_app",+ "minVersionGuest" : "12.3.0",+ "minVersionHost" : "13.0.0",+ "name" : "VirtualBuddyGuest app",+ "unsupportedPlatform" : false+ },+ {+ "id" : "trackpad",+ "minVersionGuest" : "13.0.0",+ "minVersionHost" : "13.0.0",+ "name" : "Trackpad",+ "unsupportedPlatform" : false+ },+ {+ "id" : "mac_keyboard",+ "minVersionGuest" : "13.0.0",+ "minVersionHost" : "13.0.0",+ "name" : "Mac keyboard",+ "unsupportedPlatform" : false+ },+ {+ "id" : "state_restoration",+ "minVersionGuest" : "14.0.0",+ "minVersionHost" : "14.0.0",+ "name" : "State restoration",+ "unsupportedPlatform" : false+ },+ {+ "id" : "display_resize",+ "minVersionGuest" : "14.0.0",+ "minVersionHost" : "14.0.0",+ "name" : "Automatic display configuration",+ "unsupportedPlatform" : false+ },+ {+ "id" : "rosetta_sharing",+ "minVersionGuest" : "14.0.0",+ "minVersionHost" : "14.0.0",+ "name" : "Rosetta Sharing",+ "unsupportedPlatform" : true+ },+ {+ "id" : "provisioning",+ "minVersionGuest" : "27.0.0",+ "minVersionHost" : "27.0.0",+ "name" : "Skip Setup Assistant",+ "unsupportedPlatform" : false+ }+ ],+ "groups" : [+ {+ "darkImage" : {+ "id" : "goldengate",+ "thumbnail" : {+ "blurHash" : "U14U{d%3xx%5xxM^M_tTDzRhxwt8D|t9ogM^",+ "height" : 2048,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/goldengate-dark-thumbnail.heic",+ "width" : 2048+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/goldengate-dark.heic"+ },+ "id" : "goldengate",+ "image" : {+ "id" : "goldengate",+ "thumbnail" : {+ "blurHash" : "UKIh55=W%K?a}:NHM}%L4:R-t7-pNHxat6M{",+ "height" : 2048,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/goldengate-thumbnail.heic",+ "width" : 2048+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/goldengate.heic"+ },+ "majorVersion" : "27.0.0",+ "name" : "macOS Golden Gate"+ },+ {+ "darkImage" : {+ "id" : "tahoe",+ "thumbnail" : {+ "blurHash" : "[email protected]+S6jFt3EBIZt5oJ",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/tahoe-dark-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/tahoe-dark.heic"+ },+ "id" : "tahoe",+ "image" : {+ "id" : "tahoe",+ "thumbnail" : {+ "blurHash" : "[email protected]+S6jFt3EBIZt5oJ",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/tahoe-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/tahoe.heic"+ },+ "majorVersion" : "26.0.0",+ "name" : "macOS Tahoe"+ },+ {+ "darkImage" : {+ "id" : "sequoia",+ "thumbnail" : {+ "blurHash" : "eN86q8M1Hbyya7t-g$MpnTx,b;k9X8Vgr?osbHenWEeYoGj@aNaPah",+ "height" : 399,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sequoia-dark-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sequoia-dark.heic"+ },+ "id" : "sequoia",+ "image" : {+ "id" : "sequoia",+ "thumbnail" : {+ "blurHash" : "egK9[+5Y0:}iNe-S=rI^SixW$JoIwbNfOYocn$NeWXNfShfkS5S5WX",+ "height" : 399,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sequoia-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sequoia.heic"+ },+ "majorVersion" : "15.0.0",+ "name" : "macOS Sequoia"+ },+ {+ "darkImage" : {+ "id" : "sonoma",+ "thumbnail" : {+ "blurHash" : "ec8rzYaIWBj?a}iqosaxj?fkRFa2axayj[t%ofV[ayf6V]pGkBf5fi",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sonoma-dark-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sonoma-dark.heic"+ },+ "id" : "sonoma",+ "image" : {+ "id" : "sonoma",+ "thumbnail" : {+ "blurHash" : "e:Hx.{wFRlbFaxm#xToba{j?tmetnOjsa#J,tRsln$a#NINff+oIj?",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sonoma-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/sonoma.heic"+ },+ "majorVersion" : "14.0.0",+ "name" : "macOS Sonoma"+ },+ {+ "darkImage" : {+ "id" : "ventura",+ "thumbnail" : {+ "blurHash" : "enHk%=ocoeW:Nb-8xEODaya#1fWWJAWExDEjR-jGazoJWCagw^s-Wp",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/ventura-dark-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/ventura-dark.heic"+ },+ "id" : "ventura",+ "image" : {+ "id" : "ventura",+ "thumbnail" : {+ "blurHash" : "eqOd?[TcFgR.a}LM$yWFs+oJ2{N{Iuj[jZJrj]slS5a#NNafw@ocoI",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/ventura-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/ventura.heic"+ },+ "majorVersion" : "13.0.0",+ "name" : "macOS Ventura"+ },+ {+ "darkImage" : {+ "id" : "monterey",+ "thumbnail" : {+ "blurHash" : "eb6$?*bER}o3j?oToNjqa^jsS7oOoMa_axoOWqa}oNjrbJa~a#a}oM",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/monterey-dark-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/monterey-dark.heic"+ },+ "id" : "monterey",+ "image" : {+ "id" : "monterey",+ "thumbnail" : {+ "blurHash" : "euJi.3I.R6snaz~UjLa1fOafPQxBoLaiaeXVX4g2o0jZoaW?X9bXoL",+ "height" : 720,+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/monterey-thumbnail.heic",+ "width" : 720+ },+ "url" : "https:\/\/api.virtualbuddy.app\/v2\/images\/monterey.heic"+ },+ "majorVersion" : "12.0.0",+ "name" : "macOS Monterey"+ }+ ],+ "legacyGuestAppVersions" : [+ {+ "guestAppVersion" : "1.4.0",+ "id" : "VirtualBuddyGuest_minOS_12.3",+ "maxGuestVersion" : "12.99.99",+ "minGuestVersion" : "12.3.0",+ "sha384" : "8b4797ad33b40fc939a532c28d121c63bebcd7bb36c0fdd0de1db54174652c18fb3da4a2cea298a2efd1984ead37ac77",+ "url" : "https://raw.githubusercontent.com/insidegui/VirtualBuddy/refs/heads/legacy-guest-support/data/LegacyGuestApp/VirtualBuddyGuest_minOS_12.3.dmg"+ },+ {+ "guestAppVersion" : "2.1.0",+ "id" : "VirtualBuddyGuest_minOS_13.0",+ "maxGuestVersion" : "13.99.99",+ "minGuestVersion" : "13.0.0",+ "sha384" : "ccb6c968eff880dd2e2a1b91d9d1be373b95cfb3bb2072042c0af3be0fc0962fb22d56516d2ca2b05a51935ad5a63f8c",+ "url" : "https://raw.githubusercontent.com/insidegui/VirtualBuddy/refs/heads/legacy-guest-support/data/LegacyGuestApp/VirtualBuddyGuest_minOS_13.0.dmg"+ },+ {+ "guestAppVersion" : "2.2.0",+ "id" : "VirtualBuddyGuest_minOS_14.0",+ "maxGuestVersion" : "14.99.99",+ "minGuestVersion" : "14.0.0",+ "sha384" : "ccb6c968eff880dd2e2a1b91d9d1be373b95cfb3bb2072042c0af3be0fc0962fb22d56516d2ca2b05a51935ad5a63f8c",+ "url" : "https://raw.githubusercontent.com/insidegui/VirtualBuddy/refs/heads/legacy-guest-support/data/LegacyGuestApp/VirtualBuddyGuest_minOS_14.0.dmg"+ }+ ],+ "minAppVersion" : "2.0.0",+ "requirementSets" : [+ {+ "id" : "min_host_12",+ "minCPUCount" : 2,+ "minMemorySizeMB" : 4096,+ "minVersionHost" : "12.0.0",+ "virtualInstallationBackend" : false+ },+ {+ "id" : "min_host_13",+ "minCPUCount" : 2,+ "minMemorySizeMB" : 4096,+ "minVersionHost" : "13.0.0",+ "virtualInstallationBackend" : false+ },+ {+ "id" : "min_host_26",+ "minCPUCount" : 2,+ "minMemorySizeMB" : 4096,+ "minVersionHost" : "26.0.0",+ "virtualInstallationBackend" : false+ },+ {+ "id" : "min_host_27",+ "minCPUCount" : 2,+ "minMemorySizeMB" : 4096,+ "minVersionHost" : "27.0.0",+ "virtualInstallationBackend" : false+ },+ {+ "id" : "min_host_26_virtual_installation",+ "minCPUCount" : 2,+ "minMemorySizeMB" : 4096,+ "minVersionHost" : "26.0.0",+ "virtualInstallationBackend" : true+ }+ ],+ "restoreImages" : [+ {+ "build" : "26A5388g",+ "channel" : "devbeta",+ "downloadSize" : 22662343948,+ "group" : "goldengate",+ "id" : "26A5388g",+ "mobileDeviceMinVersion" : "1853.0.0",+ "name" : "macOS 27.0 Developer Beta 4",+ "requirements" : "min_host_26_virtual_installation",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerSeed\/fullrestores\/140-55718\/5809AFC6-1923-4590-AAFC-904A0283E659\/UniversalMac_27.0_26A5388g_Restore.ipsw",+ "version" : "27.0.0"+ },+ {+ "build" : "26A5378n",+ "channel" : "devbeta",+ "downloadSize" : 22590067379,+ "group" : "goldengate",+ "id" : "26A5378n",+ "mobileDeviceMinVersion" : "1853.0.0",+ "name" : "macOS 27.0 Developer Beta 3 v.2",+ "requirements" : "min_host_26_virtual_installation",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerSeed\/fullrestores\/140-37973\/1ACA049C-10F0-4F1D-8E38-E52B9168C4BC\/UniversalMac_27.0_26A5378n_Restore.ipsw",+ "version" : "27.0.0"+ },+ {+ "build" : "26A5378j",+ "channel" : "devbeta",+ "downloadSize" : 22567352533,+ "group" : "goldengate",+ "id" : "26A5378j",+ "mobileDeviceMinVersion" : "1853.0.0",+ "name" : "macOS 27.0 Developer Beta 3",+ "requirements" : "min_host_26_virtual_installation",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerSeed\/fullrestores\/140-36017\/0F8D2136-7924-4F3E-A9AA-99722A9EFB39\/UniversalMac_27.0_26A5378j_Restore.ipsw",+ "version" : "27.0.0"+ },+ {+ "build" : "26A5368g",+ "channel" : "devbeta",+ "downloadSize" : 22661410445,+ "group" : "goldengate",+ "id" : "26A5368g",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 27.0 Developer Beta 2",+ "requirements" : "min_host_26_virtual_installation",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerSeed\/fullrestores\/140-20108\/5D0C3865-B25E-4700-A8B0-A15D60451BF4\/UniversalMac_27.0_26A5368g_Restore.ipsw",+ "version" : "27.0.0"+ },+ {+ "build" : "26A5353q",+ "channel" : "devbeta",+ "downloadSize" : 22569026466,+ "group" : "goldengate",+ "id" : "26A5353q",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 27.0 Developer Beta 1",+ "requirements" : "min_host_26_virtual_installation",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerSeed\/fullrestores\/122-99636\/BB03A927-E303-44C1-BB94-6197F130A163\/UniversalMac_27.0_26A5353q_Restore.ipsw",+ "version" : "27.0.0"+ },+ {+ "build" : "25G72",+ "channel" : "regular",+ "downloadSize" : 19772077142,+ "group" : "tahoe",+ "id" : "25G72",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerFCS\/fullrestores\/140-65618\/10445B26-DE2C-43EC-9149-0A831602E74B\/UniversalMac_26.6_25G72_Restore.ipsw",+ "version" : "26.6.0"+ },+ {+ "build" : "25G70",+ "channel" : "devbeta",+ "downloadSize" : 19772219794,+ "group" : "tahoe",+ "id" : "25G70",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.6 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SummerFCS\/fullrestores\/140-56823\/1C29995E-8C11-4384-B9C0-B00145B84F51\/UniversalMac_26.6_25G70_Restore.ipsw",+ "version" : "26.6.0"+ },+ {+ "build" : "25G5065a",+ "channel" : "devbeta",+ "downloadSize" : 19769079764,+ "group" : "tahoe",+ "id" : "25G5065a",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.6 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/140-39234\/FAC2CC7B-4D0B-4522-A464-B0CD24A6E313\/UniversalMac_26.6_25G5065a_Restore.ipsw",+ "version" : "26.6.0"+ },+ {+ "build" : "25G5057c",+ "channel" : "devbeta",+ "downloadSize" : 19772261857,+ "group" : "tahoe",+ "id" : "25G5057c",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.6 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/140-31192\/A19E7612-3A2E-4716-82DD-39E624B1D4D8\/UniversalMac_26.6_25G5057c_Restore.ipsw",+ "version" : "26.6.0"+ },+ {+ "build" : "25G5043d",+ "channel" : "devbeta",+ "downloadSize" : 19906521059,+ "group" : "tahoe",+ "id" : "25G5043d",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.6 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/140-06140\/0C979E51-6B9F-4D2E-84E1-08718CAB38F5\/UniversalMac_26.6_25G5043d_Restore.ipsw",+ "version" : "26.6.0"+ },+ {+ "build" : "25G5028f",+ "channel" : "devbeta",+ "downloadSize" : 19906405222,+ "group" : "tahoe",+ "id" : "25G5028f",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.6 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/122-66788\/E1D3F6EB-514E-4A9B-833A-2A82621ACA18\/UniversalMac_26.6_25G5028f_Restore.ipsw",+ "version" : "26.6.0"+ },+ {+ "build" : "25F84",+ "channel" : "regular",+ "downloadSize" : 19769902281,+ "group" : "tahoe",+ "id" : "25F84",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringFCS\/fullrestores\/140-24263\/B95838F0-6815-4F0B-A039-156526C081AD\/UniversalMac_26.5.2_25F84_Restore.ipsw",+ "version" : "26.5.2"+ },+ {+ "build" : "25F80",+ "channel" : "regular",+ "downloadSize" : 19769808058,+ "group" : "tahoe",+ "id" : "25F80",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringFCS\/fullrestores\/122-88870\/E47EBB85-45F2-4E3C-B9E7-6FF7868C2FBA\/UniversalMac_26.5.1_25F80_Restore.ipsw",+ "version" : "26.5.1"+ },+ {+ "build" : "25F71",+ "channel" : "regular",+ "downloadSize" : 19769944180,+ "group" : "tahoe",+ "id" : "25F71",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringFCS\/fullrestores\/122-58869\/DFB1CEEF-5619-4591-9924-E20DB2C8FED0\/UniversalMac_26.5_25F71_Restore.ipsw",+ "version" : "26.5.0"+ },+ {+ "build" : "25F5068a",+ "channel" : "devbeta",+ "downloadSize" : 19766667567,+ "group" : "tahoe",+ "id" : "25F5068a",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/122-44487\/95D09FEF-E0D7-48A8-9832-C1E412C9851C\/UniversalMac_26.5_25F5068a_Restore.ipsw",+ "version" : "26.5.0"+ },+ {+ "build" : "25F5058e",+ "channel" : "devbeta",+ "downloadSize" : 19732467266,+ "group" : "tahoe",+ "id" : "25F5058e",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/122-41795\/940A7416-4256-449F-8170-E8B4E207602E\/UniversalMac_26.5_25F5058e_Restore.ipsw",+ "version" : "26.5.0"+ },+ {+ "build" : "25F5053d",+ "channel" : "devbeta",+ "downloadSize" : 19766937211,+ "group" : "tahoe",+ "id" : "25F5053d",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/122-40967\/D206B768-60B6-4527-9F32-2B5BBF1E5A2B\/UniversalMac_26.5_25F5053d_Restore.ipsw",+ "version" : "26.5.0"+ },+ {+ "build" : "25F5042g",+ "channel" : "devbeta",+ "downloadSize" : 19766440157,+ "group" : "tahoe",+ "id" : "25F5042g",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.5 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026SpringSeed\/fullrestores\/122-21852\/BDB79369-54B9-4326-A5A4-29328983BE3A\/UniversalMac_26.5_25F5042g_Restore.ipsw",+ "version" : "26.5.0"+ },+ {+ "build" : "25E253",+ "channel" : "regular",+ "downloadSize" : 19734779897,+ "group" : "tahoe",+ "id" : "25E253",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.4.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/122-28781\/DCB2FF13-06CB-44C2-BCA2-DFCAF3521D46\/UniversalMac_26.4.1_25E253_Restore.ipsw",+ "version" : "26.4.1"+ },+ {+ "build" : "25E246",+ "channel" : "regular",+ "downloadSize" : 19734835218,+ "group" : "tahoe",+ "id" : "25E246",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/122-00766\/062A6121-2ABE-45D7-BCB1-72B666B6D2C2\/UniversalMac_26.4_25E246_Restore.ipsw",+ "version" : "26.4.0"+ },+ {+ "build" : "25E243",+ "channel" : "devbeta",+ "downloadSize" : 19734806625,+ "group" : "tahoe",+ "id" : "25E243",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.4 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/122-08082\/B9E8695D-7851-435A-8897-6D84A80F4F84\/UniversalMac_26.4_25E243_Restore.ipsw",+ "version" : "26.4.0"+ },+ {+ "build" : "25E5233c",+ "channel" : "devbeta",+ "downloadSize" : 19731757690,+ "group" : "tahoe",+ "id" : "25E5233c",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.4 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterSeed\/fullrestores\/047-94466\/DDE04370-287E-4321-8FAB-8656591CAF70\/UniversalMac_26.4_25E5233c_Restore.ipsw",+ "version" : "26.4.0"+ },+ {+ "build" : "25E5223i",+ "channel" : "devbeta",+ "downloadSize" : 19222852846,+ "group" : "tahoe",+ "id" : "25E5223i",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.4 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterSeed\/fullrestores\/047-83754\/2EAF0D9F-ADAF-402B-9C29-874D9B1E6378\/UniversalMac_26.4_25E5223i_Restore.ipsw",+ "version" : "26.4.0"+ },+ {+ "build" : "25E5218f",+ "channel" : "devbeta",+ "downloadSize" : 19289481885,+ "group" : "tahoe",+ "id" : "25E5218f",+ "mobileDeviceMinVersion" : "1827.100.14",+ "name" : "macOS 26.4 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterSeed\/fullrestores\/047-83734\/6F2EB9BB-586D-4CCA-8C8D-28A02E38AAA2\/UniversalMac_26.4_25E5218f_Restore.ipsw",+ "version" : "26.4.0"+ },+ {+ "build" : "25E5207k",+ "channel" : "devbeta",+ "downloadSize" : 19289462929,+ "group" : "tahoe",+ "id" : "25E5207k",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.4 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterSeed\/fullrestores\/047-01191\/B8945931-E74E-43AC-9370-BFCA2E35392E\/UniversalMac_26.4_25E5207k_Restore.ipsw",+ "version" : "26.4.0"+ },+ {+ "build" : "25D2140",+ "channel" : "regular",+ "downloadSize" : 19330789958,+ "group" : "tahoe",+ "id" : "25D2140",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/047-94879\/40A2B65E-4E49-4EAA-8BEC-62A305007488\/UniversalMac_26.3.2_25D2140_Restore.ipsw",+ "version" : "26.3.2"+ },+ {+ "build" : "25D2128",+ "channel" : "regular",+ "downloadSize" : 19330833456,+ "group" : "tahoe",+ "id" : "25D2128",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/047-88313\/2E098049-1731-4415-A206-546D09301973\/UniversalMac_26.3.1_25D2128_Restore.ipsw",+ "version" : "26.3.1"+ },+ {+ "build" : "25D125",+ "channel" : "regular",+ "downloadSize" : 18877622182,+ "group" : "tahoe",+ "id" : "25D125",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/047-60229\/6D5DBEA5-75A0-4BEF-ACC9-5ACF9B8DF6B7\/UniversalMac_26.3_25D125_Restore.ipsw",+ "version" : "26.3.0"+ },+ {+ "build" : "25D122",+ "channel" : "devbeta",+ "downloadSize" : 18877545740,+ "group" : "tahoe",+ "id" : "25D122",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterFCS\/fullrestores\/082-57168\/EE47B566-E405-4A7C-B99E-5BBCA418BF73\/UniversalMac_26.3_25D122_Restore.ipsw",+ "version" : "26.3.0"+ },+ {+ "build" : "25D5112c",+ "channel" : "devbeta",+ "downloadSize" : 18873995756,+ "group" : "tahoe",+ "id" : "25D5112c",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterSeed\/fullrestores\/047-27561\/D17A405D-58FC-4CD3-9CBD-2FF572E5B45C\/UniversalMac_26.3_25D5112c_Restore.ipsw",+ "version" : "26.3.0"+ },+ {+ "build" : "25D5101c",+ "channel" : "devbeta",+ "downloadSize" : 18806520160,+ "group" : "tahoe",+ "id" : "25D5101c",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2026WinterSeed\/fullrestores\/047-11932\/34528828-0245-4624-9D72-AFB752B2BEA2\/UniversalMac_26.3_25D5101c_Restore.ipsw",+ "version" : "26.3.0"+ },+ {+ "build" : "25D5087f",+ "channel" : "devbeta",+ "downloadSize" : 18789116337,+ "group" : "tahoe",+ "id" : "25D5087f",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.3 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/089-61648\/B3DA1DA6-F227-4898-87F1-D6F07AEDC708\/UniversalMac_26.3_25D5087f_Restore.ipsw",+ "version" : "26.3.0"+ },+ {+ "build" : "25C56",+ "channel" : "regular",+ "downloadSize" : 18741508230,+ "group" : "tahoe",+ "id" : "25C56",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallFCS\/fullrestores\/093-37399\/E144C918-CF99-4BBC-B1D0-3E739B9A3F2D\/UniversalMac_26.2_25C56_Restore.ipsw",+ "version" : "26.2.0"+ },+ {+ "build" : "25C5048a",+ "channel" : "devbeta",+ "downloadSize" : 18721157967,+ "group" : "tahoe",+ "id" : "25C5048a",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.2 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/089-47061\/439CA6BD-EFD9-4FFF-9C04-6A63838AB6A9\/UniversalMac_26.2_25C5048a_Restore.ipsw",+ "version" : "26.2.0"+ },+ {+ "build" : "25C5037j",+ "channel" : "devbeta",+ "downloadSize" : 18720456518,+ "group" : "tahoe",+ "id" : "25C5037j",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.2 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/089-37244\/F3E98428-E443-4226-849D-48649C50B10B\/UniversalMac_26.2_25C5037j_Restore.ipsw",+ "version" : "26.2.0"+ },+ {+ "build" : "25C5031i",+ "channel" : "devbeta",+ "downloadSize" : 18688911675,+ "group" : "tahoe",+ "id" : "25C5031i",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.2 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/089-21529\/D038FF08-78B0-4FFE-9E39-2F5A64AE46AB\/UniversalMac_26.2_25C5031i_Restore.ipsw",+ "version" : "26.2.0"+ },+ {+ "build" : "25B78",+ "channel" : "regular",+ "downloadSize" : 18718884780,+ "group" : "tahoe",+ "id" : "25B78",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallFCS\/fullrestores\/089-04148\/791B6F00-A30B-4EB0-B2E3-257167F7715B\/UniversalMac_26.1_25B78_Restore.ipsw",+ "version" : "26.1.0"+ },+ {+ "build" : "25B77",+ "channel" : "devbeta",+ "downloadSize" : 18718876862,+ "group" : "tahoe",+ "id" : "25B77",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.1 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallFCS\/fullrestores\/082-71650\/9F912A37-12E8-4AC7-9ABE-F12B1A38D1B1\/UniversalMac_26.1_25B77_Restore.ipsw",+ "version" : "26.1.0"+ },+ {+ "build" : "25B5072a",+ "channel" : "devbeta",+ "downloadSize" : 18580910549,+ "group" : "tahoe",+ "id" : "25B5072a",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.1 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/093-85256\/C134DA7F-3E56-47A6-9E51-A83457E42A15\/UniversalMac_26.1_25B5072a_Restore.ipsw",+ "version" : "26.1.0"+ },+ {+ "build" : "25B5062e",+ "channel" : "devbeta",+ "downloadSize" : 18573497955,+ "group" : "tahoe",+ "id" : "25B5062e",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.1 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/093-84191\/18D74779-3C02-4F5B-AADC-77259C29ADA1\/UniversalMac_26.1_25B5062e_Restore.ipsw",+ "version" : "26.1.0"+ },+ {+ "build" : "25B5057f",+ "channel" : "devbeta",+ "downloadSize" : 18573453168,+ "group" : "tahoe",+ "id" : "25B5057f",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.1 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/093-73644\/970FD02E-AB88-4138-B23A-B8B490E7A2D6\/UniversalMac_26.1_25B5057f_Restore.ipsw",+ "version" : "26.1.0"+ },+ {+ "build" : "25B5042k",+ "channel" : "devbeta",+ "downloadSize" : 19012528170,+ "group" : "tahoe",+ "id" : "25B5042k",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.1 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallSeed\/fullrestores\/082-91406\/9745D030-E51F-497A-9E26-1B40A07FE9AE\/UniversalMac_26.1_25B5042k_Restore.ipsw",+ "version" : "26.1.0"+ },+ {+ "build" : "25A362",+ "channel" : "regular",+ "downloadSize" : 18267682409,+ "group" : "tahoe",+ "id" : "25A362",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallFCS\/fullrestores\/093-50898\/60AE7E97-3E60-441B-9B34-E603C694C5C1\/UniversalMac_26.0.1_25A362_Restore.ipsw",+ "version" : "26.0.1"+ },+ {+ "build" : "25A354",+ "channel" : "regular",+ "downloadSize" : 18267586270,+ "group" : "tahoe",+ "id" : "25A354",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallFCS\/fullrestores\/093-37622\/CE01FAB2-7F26-48EE-AEE4-5E57A7F6D8BB\/UniversalMac_26.0_25A354_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A353",+ "channel" : "devbeta",+ "downloadSize" : 18250895075,+ "group" : "tahoe",+ "id" : "25A353",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025FallFCS\/fullrestores\/093-37294\/119120C1-6306-4287-AC2B-0AF964CD0B3C\/UniversalMac_26.0_25A353_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5351b",+ "channel" : "devbeta",+ "downloadSize" : 18110649555,+ "group" : "tahoe",+ "id" : "25A5351b",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 9",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/093-28610\/036AE4A3-8A7D-44F1-A26F-ED754C346A74\/UniversalMac_26.0_25A5351b_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5349a",+ "channel" : "devbeta",+ "downloadSize" : 18110732600,+ "group" : "tahoe",+ "id" : "25A5349a",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 8",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/093-26148\/FDF54F82-98DF-4285-A0DB-CB30F4F93C71\/UniversalMac_26.0_25A5349a_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5346a",+ "channel" : "devbeta",+ "downloadSize" : 18110708260,+ "group" : "tahoe",+ "id" : "25A5346a",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 7",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/093-15545\/4C191A6F-E63B-4A9F-8597-6B1880EE09CC\/UniversalMac_26.0_25A5346a_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5338b",+ "channel" : "devbeta",+ "downloadSize" : 18110631556,+ "group" : "tahoe",+ "id" : "25A5338b",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/093-05416\/26D38526-AE12-4E87-8542-D71CA2EA1A0F\/UniversalMac_26.0_25A5338b_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5327h",+ "channel" : "devbeta",+ "downloadSize" : 17958910966,+ "group" : "tahoe",+ "id" : "25A5327h",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/093-03417\/C35F3BA3-6DCD-473C-9266-A3BF390520BE\/UniversalMac_26.0_25A5327h_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5316i",+ "channel" : "devbeta",+ "downloadSize" : 18615400612,+ "group" : "tahoe",+ "id" : "25A5316i",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/082-89871\/D95E6C0D-147C-4F0D-878B-A4534D9B4763\/UniversalMac_26.0_25A5316i_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5306g",+ "channel" : "devbeta",+ "downloadSize" : 18833175626,+ "group" : "tahoe",+ "id" : "25A5306g",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/082-72248\/F32F08F8-FC66-4D24-847B-F03C6CF7C410\/UniversalMac_26.0_25A5306g_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "24G90",+ "channel" : "regular",+ "downloadSize" : 16814137790,+ "group" : "sequoia",+ "id" : "24G90",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.6.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerFCS\/fullrestores\/093-10809\/CFD6DD38-DAF0-40DA-854F-31AAD1294C6F\/UniversalMac_15.6.1_24G90_Restore.ipsw",+ "version" : "15.6.1"+ },+ {+ "build" : "24G84",+ "channel" : "regular",+ "downloadSize" : 16814076831,+ "group" : "sequoia",+ "id" : "24G84",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerFCS\/fullrestores\/082-08674\/51294E4D-A273-44BE-A280-A69FC347FB87\/UniversalMac_15.6_24G84_Restore.ipsw",+ "version" : "15.6.0"+ },+ {+ "build" : "24G5074c",+ "channel" : "devbeta",+ "downloadSize" : 16877900839,+ "group" : "sequoia",+ "id" : "24G5074c",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.6 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/082-70173\/CA418AAE-B538-4B79-AA99-303369C6A512\/UniversalMac_15.6_24G5074c_Restore.ipsw",+ "version" : "15.6.0"+ },+ {+ "build" : "24G5065c",+ "channel" : "devbeta",+ "downloadSize" : 16877786738,+ "group" : "sequoia",+ "id" : "24G5065c",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.6 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/082-62583\/9DB8F3CA-FCE0-45B5-8C17-6A4BF5E5A706\/UniversalMac_15.6_24G5065c_Restore.ipsw",+ "version" : "15.6.0"+ },+ {+ "build" : "25A5295e",+ "channel" : "devbeta",+ "downloadSize" : 18740071846,+ "group" : "tahoe",+ "id" : "25A5295e",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/082-58035\/4434D4B0-E61D-483F-87A0-4643F9D4750D\/UniversalMac_26.0_25A5295e_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "25A5279m",+ "channel" : "devbeta",+ "downloadSize" : 18287329125,+ "group" : "tahoe",+ "id" : "25A5279m",+ "mobileDeviceMinVersion" : "1810.0.0",+ "name" : "macOS 26.0 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SummerSeed\/fullrestores\/082-55592\/95F6DA16-4116-491E-B332-7165C051E1C5\/UniversalMac_26.0_25A5279m_Restore.ipsw",+ "version" : "26.0.0"+ },+ {+ "build" : "24G5054d",+ "channel" : "devbeta",+ "downloadSize" : 16877678522,+ "group" : "sequoia",+ "id" : "24G5054d",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.6 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/082-29051\/6E674436-7F60-4CEC-B318-C0062D336517\/UniversalMac_15.6_24G5054d_Restore.ipsw",+ "version" : "15.6.0"+ },+ {+ "build" : "24F74",+ "channel" : "regular",+ "downloadSize" : 16879691985,+ "group" : "sequoia",+ "id" : "24F74",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringFCS\/fullrestores\/082-44534\/CE6C1054-99A3-4F67-A823-3EE9E6510CDE\/UniversalMac_15.5_24F74_Restore.ipsw",+ "version" : "15.5.0"+ },+ {+ "build" : "24F5068b",+ "channel" : "devbeta",+ "downloadSize" : 16876550506,+ "group" : "sequoia",+ "id" : "24F5068b",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.5 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/082-42002\/44CF75E3-7765-4356-A88C-5EEEC4471CA4\/UniversalMac_15.5_24F5068b_Restore.ipsw",+ "version" : "15.5.0"+ },+ {+ "build" : "24F5053j",+ "channel" : "devbeta",+ "downloadSize" : 16809364641,+ "group" : "sequoia",+ "id" : "24F5053j",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.5 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/072-92980\/8E6DFD3B-8438-423F-8FFE-A95234775E84\/UniversalMac_15.5_24F5053j_Restore.ipsw",+ "version" : "15.5.0"+ },+ {+ "build" : "24F5053f",+ "channel" : "devbeta",+ "downloadSize" : 16876267533,+ "group" : "sequoia",+ "id" : "24F5053f",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.5 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/082-24561\/B199D1B2-296D-43E5-A29A-5FC27796F36D\/UniversalMac_15.5_24F5053f_Restore.ipsw",+ "version" : "15.5.0"+ },+ {+ "build" : "24F5042g",+ "channel" : "devbeta",+ "downloadSize" : 16875810487,+ "group" : "sequoia",+ "id" : "24F5042g",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.5 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringSeed\/fullrestores\/072-94893\/B85463BB-3ED6-4A5A-BE78-92AD86B531D7\/UniversalMac_15.5_24F5042g_Restore.ipsw",+ "version" : "15.5.0"+ },+ {+ "build" : "24E263",+ "channel" : "regular",+ "downloadSize" : 16808445859,+ "group" : "sequoia",+ "id" : "24E263",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringFCS\/fullrestores\/082-23340\/61923341-EE73-4C6E-BB3E-DAB3069548BF\/UniversalMac_15.4.1_24E263_Restore.ipsw",+ "version" : "15.4.1"+ },+ {+ "build" : "24E248",+ "channel" : "regular",+ "downloadSize" : 16808408047,+ "group" : "sequoia",+ "id" : "24E248",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringFCS\/fullrestores\/082-16517\/AACDDC33-9683-4431-98AF-F04EF7C15EE3\/UniversalMac_15.4_24E248_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24E247",+ "channel" : "devbeta",+ "downloadSize" : 16808392577,+ "group" : "sequoia",+ "id" : "24E247",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4 RC 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringFCS\/fullrestores\/082-13483\/7D547A66-A1A6-48C1-A8E1-FE78559BDD34\/UniversalMac_15.4_24E247_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24E246",+ "channel" : "devbeta",+ "downloadSize" : 16808427372,+ "group" : "sequoia",+ "id" : "24E246",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025SpringFCS\/fullrestores\/082-13013\/C3CAC9AF-B139-4924-BE1B-10ED6EF931A4\/UniversalMac_15.4_24E246_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24E5238a",+ "channel" : "devbeta",+ "downloadSize" : 16805266642,+ "group" : "sequoia",+ "id" : "24E5238a",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterSeed\/fullrestores\/082-08323\/FD7D7539-514F-4F2E-AD3B-4D6D0D248706\/UniversalMac_15.4_24E5238a_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24E5228e",+ "channel" : "devbeta",+ "downloadSize" : 16805273503,+ "group" : "sequoia",+ "id" : "24E5228e",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterSeed\/fullrestores\/072-96972\/D76A7AE6-3A35-4295-B102-E5FC5C84B4DC\/UniversalMac_15.4_24E5228e_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24E5222f",+ "channel" : "devbeta",+ "downloadSize" : 16602610887,+ "group" : "sequoia",+ "id" : "24E5222f",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterSeed\/fullrestores\/072-90273\/76B9EE73-0836-47FB-8CBA-E3E902ACD21A\/UniversalMac_15.4_24E5222f_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24E5206s",+ "channel" : "devbeta",+ "downloadSize" : 16598479538,+ "group" : "sequoia",+ "id" : "24E5206s",+ "mobileDeviceMinVersion" : "1774.0.0",+ "name" : "macOS 15.4 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterSeed\/fullrestores\/072-92205\/1FCDCB29-B8A3-4461-A98A-270F1D1121C8\/UniversalMac_15.4_24E5206s_Restore.ipsw",+ "version" : "15.4.0"+ },+ {+ "build" : "24D81",+ "channel" : "regular",+ "downloadSize" : 16532705221,+ "group" : "sequoia",+ "id" : "24D81",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.3.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterFCS\/fullrestores\/082-01504\/828B8EF9-8134-49D5-B24A-0BA504FC5ECC\/UniversalMac_15.3.2_24D81_Restore.ipsw",+ "version" : "15.3.2"+ },+ {+ "build" : "24D70",+ "channel" : "regular",+ "downloadSize" : 16532837554,+ "group" : "sequoia",+ "id" : "24D70",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.3.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterFCS\/fullrestores\/072-70618\/42F1A8CC-7E07-4329-958A-757FF600C303\/UniversalMac_15.3.1_24D70_Restore.ipsw",+ "version" : "15.3.1"+ },+ {+ "build" : "24D60",+ "channel" : "regular",+ "downloadSize" : 16532796141,+ "group" : "sequoia",+ "id" : "24D60",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterFCS\/fullrestores\/072-08269\/7CAAB9F7-E970-428D-8764-4CD7BCD105CD\/UniversalMac_15.3_24D60_Restore.ipsw",+ "version" : "15.3.0"+ },+ {+ "build" : "24D5055b",+ "channel" : "devbeta",+ "downloadSize" : 16529416640,+ "group" : "sequoia",+ "id" : "24D5055b",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.3 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterSeed\/fullrestores\/072-61910\/64022727-D907-4A4F-963E-CADF5C74E1A7\/UniversalMac_15.3_24D5055b_Restore.ipsw",+ "version" : "15.3.0"+ },+ {+ "build" : "24D5040f",+ "channel" : "devbeta",+ "downloadSize" : 16529508256,+ "group" : "sequoia",+ "id" : "24D5040f",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.3 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2025WinterSeed\/fullrestores\/072-51416\/CB0B4DD0-1512-47FF-91B8-862ECB6CD2CF\/UniversalMac_15.3_24D5040f_Restore.ipsw",+ "version" : "15.3.0"+ },+ {+ "build" : "24D5034f",+ "channel" : "devbeta",+ "downloadSize" : 16528933369,+ "group" : "sequoia",+ "id" : "24D5034f",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.3 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/072-29298\/D5353B95-E6B5-42DA-8DC3-664A28FFB1B9\/UniversalMac_15.3_24D5034f_Restore.ipsw",+ "version" : "15.3.0"+ },+ {+ "build" : "24C101",+ "channel" : "regular",+ "downloadSize" : 16532456817,+ "group" : "sequoia",+ "id" : "24C101",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-44245\/E811A1B0-28A9-4FCD-AE32-322E796F0EB8\/UniversalMac_15.2_24C101_Restore.ipsw",+ "version" : "15.2.0"+ },+ {+ "build" : "24C100",+ "channel" : "devbeta",+ "downloadSize" : 16532519706,+ "group" : "sequoia",+ "id" : "24C100",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.2 RC 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-39903\/D467F0BB-9D59-4DCF-A355-DD200CE808A8\/UniversalMac_15.2_24C100_Restore.ipsw",+ "version" : "15.2.0"+ },+ {+ "build" : "24C98",+ "channel" : "devbeta",+ "downloadSize" : 16532504882,+ "group" : "sequoia",+ "id" : "24C98",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.2 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-38683\/C48192CB-7F42-4DD2-9EE6-0F6691DC088E\/UniversalMac_15.2_24C98_Restore.ipsw",+ "version" : "15.2.0"+ },+ {+ "build" : "24C5089c",+ "channel" : "devbeta",+ "downloadSize" : 16529207615,+ "group" : "sequoia",+ "id" : "24C5089c",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.2 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/072-35468\/AF95DCD4-137A-4E7D-A5D8-E12009F4B0EF\/UniversalMac_15.2_24C5089c_Restore.ipsw",+ "version" : "15.2.0"+ },+ {+ "build" : "24C5079e",+ "channel" : "devbeta",+ "downloadSize" : 16529245021,+ "group" : "sequoia",+ "id" : "24C5079e",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.2 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/072-18002\/44DBAF90-E56D-43E0-81F1-016B12E7FE27\/UniversalMac_15.2_24C5079e_Restore.ipsw",+ "version" : "15.2.0"+ },+ {+ "build" : "24C5073e",+ "channel" : "devbeta",+ "downloadSize" : 16529788046,+ "group" : "sequoia",+ "id" : "24C5073e",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.2 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/072-11046\/F7A6FD60-0556-437D-88B6-6F2DD2CD8B96\/UniversalMac_15.2_24C5073e_Restore.ipsw",+ "version" : "15.2.0"+ },+ {+ "build" : "24B2091",+ "channel" : "regular",+ "downloadSize" : 15516666958,+ "group" : "sequoia",+ "id" : "24B2091",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1.1 (24B2091)",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-29960\/5EEC3C20-D7CB-4DD1-9CE4-7C177F531A41\/UniversalMac_15.1.1_24B2091_Restore.ipsw",+ "version" : "15.1.1"+ },+ {+ "build" : "24B91",+ "channel" : "regular",+ "downloadSize" : 15755042223,+ "group" : "sequoia",+ "id" : "24B91",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-30094\/44BD016F-6EE3-4EE5-8890-6F9AA008C537\/UniversalMac_15.1.1_24B91_Restore.ipsw",+ "version" : "15.1.1"+ },+ {+ "build" : "24B2083",+ "channel" : "regular",+ "downloadSize" : 15516638342,+ "group" : "sequoia",+ "id" : "24B2083",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1 (24B2083)",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-12302\/3786987A-AD94-4BFB-81B8-56D3841CA81B\/UniversalMac_15.1_24B2083_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24B83",+ "channel" : "regular",+ "downloadSize" : 15738221177,+ "group" : "sequoia",+ "id" : "24B83",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-12340\/78D28AC4-CCFC-45D2-BD27-1E5D915E43F9\/UniversalMac_15.1_24B83_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24B82",+ "channel" : "devbeta",+ "downloadSize" : 15755058094,+ "group" : "sequoia",+ "id" : "24B82",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/062-24344\/4BBFA6BD-C58F-4C82-B793-6ECA98024379\/UniversalMac_15.1_24B82_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24B5070a",+ "channel" : "devbeta",+ "downloadSize" : 15734880172,+ "group" : "sequoia",+ "id" : "24B5070a",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1 Developer Beta 6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/072-00383\/7EB106DF-9B03-4C2A-ACD1-997B0BFF9364\/UniversalMac_15.1_24B5070a_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24B5055e",+ "channel" : "devbeta",+ "downloadSize" : 15734924985,+ "group" : "sequoia",+ "id" : "24B5055e",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/062-91081\/FADE991A-C188-4D32-8F97-313F57E27359\/UniversalMac_15.1_24B5055e_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24B5046f",+ "channel" : "devbeta",+ "downloadSize" : 15870172423,+ "group" : "sequoia",+ "id" : "24B5046f",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallSeed\/fullrestores\/062-80453\/61A07BD2-553D-425D-8B93-7E5A730AA4CA\/UniversalMac_15.1_24B5046f_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24B5035e",+ "channel" : "devbeta",+ "downloadSize" : 15869388891,+ "group" : "sequoia",+ "id" : "24B5035e",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.1 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-74506\/D50AC8F9-4795-4711-9C1A-907B6EB829A2\/UniversalMac_15.1_24B5035e_Restore.ipsw",+ "version" : "15.1.0"+ },+ {+ "build" : "24A348",+ "channel" : "regular",+ "downloadSize" : 15737037399,+ "group" : "sequoia",+ "id" : "24A348",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/072-01423\/566E5B4E-1100-4643-91B3-131247351844\/UniversalMac_15.0.1_24A348_Restore.ipsw",+ "version" : "15.0.1"+ },+ {+ "build" : "24A335",+ "channel" : "regular",+ "downloadSize" : 15736994120,+ "group" : "sequoia",+ "id" : "24A335",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024FallFCS\/fullrestores\/062-78489\/BDA44327-C79E-4608-A7E0-455A7E91911F\/UniversalMac_15.0_24A335_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5331b",+ "channel" : "devbeta",+ "downloadSize" : 15598810418,+ "group" : "sequoia",+ "id" : "24A5331b",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0 Developer Beta 8",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-71949\/A67919DD-2AAC-4324-99BF-70765065DD70\/UniversalMac_15.0_24A5331b_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5327a",+ "channel" : "devbeta",+ "downloadSize" : 15598903779,+ "group" : "sequoia",+ "id" : "24A5327a",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0 Developer Beta 7",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-64520\/F98C92F6-656A-46BB-A1DB-F447698DBB72\/UniversalMac_15.0_24A5327a_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5320a",+ "channel" : "devbeta",+ "downloadSize" : 15598703819,+ "group" : "sequoia",+ "id" : "24A5320a",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0 Developer Beta 6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-59123\/7B77FE01-E040-4D4A-8E93-64BBF212A351\/UniversalMac_15.0_24A5320a_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5309e",+ "channel" : "devbeta",+ "downloadSize" : 16020119097,+ "group" : "sequoia",+ "id" : "24A5309e",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-45756\/5B063A0C-5ECA-434B-A462-CD1F65737105\/UniversalMac_15.0_24A5309e_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5298h",+ "channel" : "devbeta",+ "downloadSize" : 15892020340,+ "group" : "sequoia",+ "id" : "24A5298h",+ "mobileDeviceMinVersion" : "1754.0.0",+ "name" : "macOS 15.0 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-39288\/8A58D88A-ED62-4E46-A406-13F0294EB4F5\/UniversalMac_15.0_24A5298h_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5289h",+ "channel" : "devbeta",+ "downloadSize" : 15756935317,+ "group" : "sequoia",+ "id" : "24A5289h",+ "mobileDeviceMinVersion" : "1742.0.0",+ "name" : "macOS 15.0 Developer Beta 3 (24A5289h)",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-36090\/83523325-6540-4A17-BA93-A5849E4E9AC2\/UniversalMac_15.0_24A5289h_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5289g",+ "channel" : "devbeta",+ "downloadSize" : 15756393703,+ "group" : "sequoia",+ "id" : "24A5289g",+ "mobileDeviceMinVersion" : "1742.0.0",+ "name" : "macOS 15.0 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-33928\/E22622FB-DAFC-4C64-8CC6-B7CAF89477F7\/UniversalMac_15.0_24A5289g_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5279h",+ "channel" : "devbeta",+ "downloadSize" : 16230968934,+ "group" : "sequoia",+ "id" : "24A5279h",+ "mobileDeviceMinVersion" : "1742.0.0",+ "name" : "macOS 15.0 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/062-22022\/AB066FFB-B7FE-4132-83AC-E58A323805C1\/UniversalMac_15.0_24A5279h_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "24A5264n",+ "channel" : "devbeta",+ "downloadSize" : 15824875957,+ "group" : "sequoia",+ "id" : "24A5264n",+ "mobileDeviceMinVersion" : "1742.0.0",+ "name" : "macOS 15.0 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerSeed\/fullrestores\/052-49083\/ED8F54D6-A7BF-488A-85E5-617E08C41383\/UniversalMac_15.0_24A5264n_Restore.ipsw",+ "version" : "15.0.0"+ },+ {+ "build" : "23G93",+ "channel" : "regular",+ "downloadSize" : 14790601661,+ "group" : "sonoma",+ "id" : "23G93",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.6.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerFCS\/fullrestores\/062-52859\/932E0A8F-6644-4759-82DA-F8FA8DEA806A\/UniversalMac_14.6.1_23G93_Restore.ipsw",+ "version" : "14.6.1"+ },+ {+ "build" : "23G80",+ "channel" : "regular",+ "downloadSize" : 14790718754,+ "group" : "sonoma",+ "id" : "23G80",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SummerFCS\/fullrestores\/052-69922\/F5DA2B64-25EB-4370-9E89-FA5689859796\/UniversalMac_14.6_23G80_Restore.ipsw",+ "version" : "14.6.0"+ },+ {+ "build" : "23G5075b",+ "channel" : "devbeta",+ "downloadSize" : 14634053502,+ "group" : "sonoma",+ "id" : "23G5075b",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.6 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/062-37092\/7D35E462-CD30-4B65-A1D6-D2AF0DA9AED8\/UniversalMac_14.6_23G5075b_Restore.ipsw",+ "version" : "14.6.0"+ },+ {+ "build" : "23G5066c",+ "channel" : "devbeta",+ "downloadSize" : 14631054851,+ "group" : "sonoma",+ "id" : "23G5066c",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.6 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/062-28262\/A4400A1D-9F38-41F7-B1CD-B3CB782DA2A3\/UniversalMac_14.6_23G5066c_Restore.ipsw",+ "version" : "14.6.0"+ },+ {+ "build" : "23G5061b",+ "channel" : "devbeta",+ "downloadSize" : 14647192213,+ "group" : "sonoma",+ "id" : "23G5061b",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.6 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/062-20934\/B03E5DE3-1484-489F-AC53-956AC17DB7F0\/UniversalMac_14.6_23G5061b_Restore.ipsw",+ "version" : "14.6.0"+ },+ {+ "build" : "23G5052d",+ "channel" : "devbeta",+ "downloadSize" : 14640728273,+ "group" : "sonoma",+ "id" : "23G5052d",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.6 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/052-91270\/121EBE77-A313-4250-9F8D-55F2AABBCD4C\/UniversalMac_14.6_23G5052d_Restore.ipsw",+ "version" : "14.6.0"+ },+ {+ "build" : "23F79",+ "channel" : "regular",+ "downloadSize" : 14801044197,+ "group" : "sonoma",+ "id" : "23F79",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringFCS\/fullrestores\/062-01897\/C874907B-9F82-4109-87EB-6B3C9BF1507D\/UniversalMac_14.5_23F79_Restore.ipsw",+ "version" : "14.5.0"+ },+ {+ "build" : "23F5074a",+ "channel" : "devbeta",+ "downloadSize" : 14631266856,+ "group" : "sonoma",+ "id" : "23F5074a",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.5 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/052-93222\/8E2C4935-6FAA-4624-88D5-008966BD1A4C\/UniversalMac_14.5_23F5074a_Restore.ipsw",+ "version" : "14.5.0"+ },+ {+ "build" : "23F5064f",+ "channel" : "devbeta",+ "downloadSize" : 14612241697,+ "group" : "sonoma",+ "id" : "23F5064f",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.5 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/052-86827\/74D9C6E6-396C-451B-8ACD-DB523D9FA93F\/UniversalMac_14.5_23F5064f_Restore.ipsw",+ "version" : "14.5.0"+ },+ {+ "build" : "23F5059e",+ "channel" : "devbeta",+ "downloadSize" : 14625397506,+ "group" : "sonoma",+ "id" : "23F5059e",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.5 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/052-84344\/599ECB0B-BF84-449F-B0D1-1428CFFAACC5\/UniversalMac_14.5_23F5059e_Restore.ipsw",+ "version" : "14.5.0"+ },+ {+ "build" : "23F5049f",+ "channel" : "devbeta",+ "downloadSize" : 14617671816,+ "group" : "sonoma",+ "id" : "23F5049f",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.5 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024SpringSeed\/fullrestores\/052-63630\/11AFEFAF-A420-4CAE-84E7-D66530A7E9CA\/UniversalMac_14.5_23F5049f_Restore.ipsw",+ "version" : "14.5.0"+ },+ {+ "build" : "23E224",+ "channel" : "regular",+ "downloadSize" : 14744062393,+ "group" : "sonoma",+ "id" : "23E224",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterFCS\/fullrestores\/052-77579\/4569734E-120C-4F31-AD08-FC1FF825D059\/UniversalMac_14.4.1_23E224_Restore.ipsw",+ "version" : "14.4.1"+ },+ {+ "build" : "23E214",+ "channel" : "regular",+ "downloadSize" : 14744505377,+ "group" : "sonoma",+ "id" : "23E214",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterFCS\/fullrestores\/052-61990\/47F0DD06-1106-4F2E-9CD6-AE6B361A0EC6\/UniversalMac_14.4_23E214_Restore.ipsw",+ "version" : "14.4.0"+ },+ {+ "build" : "23E5211a",+ "channel" : "devbeta",+ "downloadSize" : 14553892980,+ "group" : "sonoma",+ "id" : "23E5211a",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterSeed\/fullrestores\/052-59970\/42D9D34A-DD6E-40D5-AA2B-EEB8E65EE64E\/UniversalMac_14.4_23E5211a_Restore.ipsw",+ "version" : "14.4.0"+ },+ {+ "build" : "23E5205c",+ "channel" : "devbeta",+ "downloadSize" : 14556773482,+ "group" : "sonoma",+ "id" : "23E5205c",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterSeed\/fullrestores\/052-58286\/18DAC58E-4161-45D4-BE02-AE47B12B87B8\/UniversalMac_14.4_23E5205c_Restore.ipsw",+ "version" : "14.4.0"+ },+ {+ "build" : "23E5196e",+ "channel" : "devbeta",+ "downloadSize" : 14552980775,+ "group" : "sonoma",+ "id" : "23E5196e",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterSeed\/fullrestores\/052-51632\/C6A7A58A-3CB1-4271-9CED-1D5DAE9078CF\/UniversalMac_14.4_23E5196e_Restore.ipsw",+ "version" : "14.4.0"+ },+ {+ "build" : "23E5191e",+ "channel" : "devbeta",+ "downloadSize" : 14560421496,+ "group" : "sonoma",+ "id" : "23E5191e",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterSeed\/fullrestores\/052-45324\/985FEED9-1A9E-49EB-A904-467E5E7EEE9C\/UniversalMac_14.4_23E5191e_Restore.ipsw",+ "version" : "14.4.0"+ },+ {+ "build" : "23E5180j",+ "channel" : "devbeta",+ "downloadSize" : 14526761461,+ "group" : "sonoma",+ "id" : "23E5180j",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.4 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterSeed\/fullrestores\/052-42583\/F09F735D-D3C3-4AF7-9BEC-F9C5D3B84363\/UniversalMac_14.4_23E5180j_Restore.ipsw",+ "version" : "14.4.0"+ },+ {+ "build" : "23D60",+ "channel" : "regular",+ "downloadSize" : 14503964718,+ "group" : "sonoma",+ "id" : "23D60",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.3.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterFCS\/fullrestores\/052-40770\/72916BCC-D357-422D-A4A2-EF1DEDF6968C\/UniversalMac_14.3.1_23D60_Restore.ipsw",+ "version" : "14.3.1"+ },+ {+ "build" : "23D56",+ "channel" : "regular",+ "downloadSize" : 14505910832,+ "group" : "sonoma",+ "id" : "23D56",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2024WinterFCS\/fullrestores\/042-78241\/B45074EB-2891-4C05-BCA4-7463F3AC0982\/UniversalMac_14.3_23D56_Restore.ipsw",+ "version" : "14.3.0"+ },+ {+ "build" : "23D5051b",+ "channel" : "devbeta",+ "downloadSize" : 14345532149,+ "group" : "sonoma",+ "id" : "23D5051b",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.3 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/052-27952\/6B395980-45C8-4E7C-9252-9F4CE35C7EDB\/UniversalMac_14.3_23D5051b_Restore.ipsw",+ "version" : "14.3.0"+ },+ {+ "build" : "23D5043d",+ "channel" : "devbeta",+ "downloadSize" : 14354286748,+ "group" : "sonoma",+ "id" : "23D5043d",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.3 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/052-23267\/60655998-DD9A-40BF-BFAB-6D2A4442DE83\/UniversalMac_14.3_23D5043d_Restore.ipsw",+ "version" : "14.3.0"+ },+ {+ "build" : "23D5033f",+ "channel" : "devbeta",+ "downloadSize" : 14349582906,+ "group" : "sonoma",+ "id" : "23D5033f",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.3 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/052-04657\/4126C431-B3EA-42C2-BC36-ED83715B8700\/UniversalMac_14.3_23D5033f_Restore.ipsw",+ "version" : "14.3.0"+ },+ {+ "build" : "23C71",+ "channel" : "regular",+ "downloadSize" : 14489499738,+ "group" : "sonoma",+ "id" : "23C71",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/052-22662\/ECE59A41-DACC-4CA5-AB23-FDED1A4567DE\/UniversalMac_14.2.1_23C71_Restore.ipsw",+ "version" : "14.2.1"+ },+ {+ "build" : "23C64",+ "channel" : "regular",+ "downloadSize" : 14488791535,+ "group" : "sonoma",+ "id" : "23C64",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/052-15117\/DC2EE605-ABF3-41AE-9652-D137A8AA5907\/UniversalMac_14.2_23C64_Restore.ipsw",+ "version" : "14.2.0"+ },+ {+ "build" : "23C63",+ "channel" : "devbeta",+ "downloadSize" : 14489489499,+ "group" : "sonoma",+ "id" : "23C63",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/052-14744\/7215DBB4-BEAD-4A9C-9202-276ABA6832D5\/UniversalMac_14.2_23C63_Restore.ipsw",+ "version" : "14.2.0"+ },+ {+ "build" : "23C5055b",+ "channel" : "devbeta",+ "downloadSize" : 14332799879,+ "group" : "sonoma",+ "id" : "23C5055b",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterFCS\/fullrestores\/052-05962\/A8344C85-06CE-43C7-9FF6-7B477A4DB8BA\/UniversalMac_14.2_23C5055b_Restore.ipsw",+ "version" : "14.2.0"+ },+ {+ "build" : "23C5047e",+ "channel" : "devbeta",+ "downloadSize" : 14324106377,+ "group" : "sonoma",+ "id" : "23C5047e",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallSeed\/fullrestores\/042-99526\/0A9085CC-B36A-400A-86D8-B9FE23B1DA29\/UniversalMac_14.2_23C5047e_Restore.ipsw",+ "version" : "14.2.0"+ },+ {+ "build" : "23C5041e",+ "channel" : "devbeta",+ "downloadSize" : 14343066933,+ "group" : "sonoma",+ "id" : "23C5041e",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallSeed\/fullrestores\/042-92143\/F642F928-DEE0-4C3F-A416-85745C778855\/UniversalMac_14.2_23C5041e_Restore.ipsw",+ "version" : "14.2.0"+ },+ {+ "build" : "23C5030f",+ "channel" : "devbeta",+ "downloadSize" : 14015403903,+ "group" : "sonoma",+ "id" : "23C5030f",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.2 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallSeed\/fullrestores\/042-71093\/ECEFE157-E28B-40B4-9F21-CFD075129029\/UniversalMac_14.2_23C5030f_Restore.ipsw",+ "version" : "14.2.0"+ },+ {+ "build" : "23B92",+ "channel" : "regular",+ "downloadSize" : 13980816431,+ "group" : "sonoma",+ "id" : "23B92",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/052-09443\/E8752548-0B80-480C-9FB4-67246672C1B5\/UniversalMac_14.1.2_23B92_Restore.ipsw",+ "version" : "14.1.2"+ },+ {+ "build" : "23B81",+ "channel" : "regular",+ "downloadSize" : 13981156491,+ "group" : "sonoma",+ "id" : "23B81",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/042-89681\/55BD14DB-5535-4203-9359-E2C070E43FBE\/UniversalMac_14.1.1_23B81_Restore.ipsw",+ "version" : "14.1.1"+ },+ {+ "build" : "23B74",+ "channel" : "regular",+ "downloadSize" : 13981550665,+ "group" : "sonoma",+ "id" : "23B74",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/042-86430\/DBE44960-58A6-4715-948B-D64F33F769BD\/UniversalMac_14.1_23B74_Restore.ipsw",+ "version" : "14.1.0"+ },+ {+ "build" : "23B73",+ "channel" : "devbeta",+ "downloadSize" : 13981665474,+ "group" : "sonoma",+ "id" : "23B73",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/042-10900\/347B734E-BC0B-41FA-9671-8000FCB5B0BB\/UniversalMac_14.1_23B73_Restore.ipsw",+ "version" : "14.1.0"+ },+ {+ "build" : "23B5067a",+ "channel" : "devbeta",+ "downloadSize" : 13964726406,+ "group" : "sonoma",+ "id" : "23B5067a",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallSeed\/fullrestores\/042-73325\/B24FC9CF-34D1-44A6-B977-FA718FE83DEB\/UniversalMac_14.1_23B5067a_Restore.ipsw",+ "version" : "14.1.0"+ },+ {+ "build" : "23B5056e",+ "channel" : "devbeta",+ "downloadSize" : 13913662198,+ "group" : "sonoma",+ "id" : "23B5056e",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallSeed\/fullrestores\/042-65885\/0FA6C4A7-C21A-4A5F-84C8-8FEE0D98A153\/UniversalMac_14.1_23B5056e_Restore.ipsw",+ "version" : "14.1.0"+ },+ {+ "build" : "23B5046f",+ "channel" : "devbeta",+ "downloadSize" : 13909776599,+ "group" : "sonoma",+ "id" : "23B5046f",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.1 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallSeed\/fullrestores\/042-60177\/C4B6F5B3-8B66-461A-A048-4A9925F36FCD\/UniversalMac_14.1_23B5046f_Restore.ipsw",+ "version" : "14.1.0"+ },+ {+ "build" : "23A344",+ "channel" : "regular",+ "downloadSize" : 13905898651,+ "group" : "sonoma",+ "id" : "23A344",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/042-54934\/0E101AD6-3117-4B63-9BF1-143B6DB9270A\/UniversalMac_14.0_23A344_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A339",+ "channel" : "devbeta",+ "downloadSize" : 13905892847,+ "group" : "sonoma",+ "id" : "23A339",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/002-81996\/596571C1-9856-4BB3-B5BF-B5A48F4B406E\/UniversalMac_14.0_23A339_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5337a",+ "channel" : "devbeta",+ "downloadSize" : 13817165626,+ "group" : "sonoma",+ "id" : "23A5337a",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 7",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/042-41500\/D1789AEF-013B-4112-8A1E-401589023267\/UniversalMac_14.0_23A5337a_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5328b",+ "channel" : "devbeta",+ "downloadSize" : 13818265607,+ "group" : "sonoma",+ "id" : "23A5328b",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/042-37824\/AA6B32A0-3C2C-4BEB-95A1-64E601934330\/UniversalMac_14.0_23A5328b_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5312d",+ "channel" : "devbeta",+ "downloadSize" : 13902876317,+ "group" : "sonoma",+ "id" : "23A5312d",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/042-27168\/7E046825-8EBA-4AAE-8ECC-DDD51B9306D2\/UniversalMac_14.0_23A5312d_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5301h",+ "channel" : "devbeta",+ "downloadSize" : 13966115260,+ "group" : "sonoma",+ "id" : "23A5301h",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/042-25548\/9EA6EC3D-5A7D-4D53-A17C-70EE71393921\/UniversalMac_14.0_23A5301h_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5286i",+ "channel" : "devbeta",+ "downloadSize" : 14040882686,+ "group" : "sonoma",+ "id" : "23A5286i",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 3 (23A5286i)",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/042-13887\/3B4075C1-B695-49EA-82D9-4B720699D341\/UniversalMac_14.0_23A5286i_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5286g",+ "channel" : "devbeta",+ "downloadSize" : 14039361424,+ "group" : "sonoma",+ "id" : "23A5286g",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/042-06324\/379026FA-C14F-4095-99FD-19F607D10EBF\/UniversalMac_14.0_23A5286g_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5276g",+ "channel" : "devbeta",+ "downloadSize" : 14011239154,+ "group" : "sonoma",+ "id" : "23A5276g",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/032-95861\/67600C59-8516-4A46-B9D7-4007D395CEF5\/UniversalMac_14.0_23A5276g_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "23A5257q",+ "channel" : "devbeta",+ "downloadSize" : 14073497027,+ "group" : "sonoma",+ "id" : "23A5257q",+ "mobileDeviceMinVersion" : "1600.0.0",+ "name" : "macOS 14.0 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerSeed\/fullrestores\/032-94355\/CBE8CBE1-750D-487E-A393-B90FEF60CEBA\/UniversalMac_14.0_23A5257q_Restore.ipsw",+ "version" : "14.0.0"+ },+ {+ "build" : "22G120",+ "channel" : "regular",+ "downloadSize" : 12893555341,+ "group" : "ventura",+ "id" : "22G120",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.6",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023FallFCS\/fullrestores\/042-55833\/C0830847-A2F8-458F-B680-967991820931\/UniversalMac_13.6_22G120_Restore.ipsw",+ "version" : "13.6.0"+ },+ {+ "build" : "22G91",+ "channel" : "regular",+ "downloadSize" : 12892043230,+ "group" : "ventura",+ "id" : "22G91",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5.2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerFCS\/fullrestores\/042-43686\/945D434B-DA5D-48DB-A558-F6D18D11AD69\/UniversalMac_13.5.2_22G91_Restore.ipsw",+ "version" : "13.5.2"+ },+ {+ "build" : "22G90",+ "channel" : "regular",+ "downloadSize" : 12892897195,+ "group" : "ventura",+ "id" : "22G90",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerFCS\/fullrestores\/042-25658\/2D6BE8DB-5549-4F85-8C54-39FC23BABC68\/UniversalMac_13.5.1_22G90_Restore.ipsw",+ "version" : "13.5.1"+ },+ {+ "build" : "22G74",+ "channel" : "regular",+ "downloadSize" : 12893195726,+ "group" : "ventura",+ "id" : "22G74",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SummerFCS\/fullrestores\/032-69606\/D3E05CDF-E105-434C-A4A1-4E3DC7668DD0\/UniversalMac_13.5_22G74_Restore.ipsw",+ "version" : "13.5.0"+ },+ {+ "build" : "22G5072a",+ "channel" : "devbeta",+ "downloadSize" : 12876188620,+ "group" : "ventura",+ "id" : "22G5072a",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5 Developer Beta 5",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/042-09570\/8DA0B0AA-6FD4-42C4-A54E-BC0D53B92AC0\/UniversalMac_13.5_22G5072a_Restore.ipsw",+ "version" : "13.5.0"+ },+ {+ "build" : "22G5059d",+ "channel" : "devbeta",+ "downloadSize" : 12881087818,+ "group" : "ventura",+ "id" : "22G5059d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/042-03209\/55CBE04D-FD90-483B-A6D7-45E0FBC1C94F\/UniversalMac_13.5_22G5059d_Restore.ipsw",+ "version" : "13.5.0"+ },+ {+ "build" : "22G5048d",+ "channel" : "devbeta",+ "downloadSize" : 12874423585,+ "group" : "ventura",+ "id" : "22G5048d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-93679\/1D39F2AC-8FD4-46A3-A159-478C76472B16\/UniversalMac_13.5_22G5048d_Restore.ipsw",+ "version" : "13.5.0"+ },+ {+ "build" : "22G5038d",+ "channel" : "devbeta",+ "downloadSize" : 12727337348,+ "group" : "ventura",+ "id" : "22G5038d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-92523\/E476F5EC-D046-4A76-889B-F19DA354459E\/UniversalMac_13.5_22G5038d_Restore.ipsw",+ "version" : "13.5.0"+ },+ {+ "build" : "22G5027e",+ "channel" : "devbeta",+ "downloadSize" : 12729623010,+ "group" : "ventura",+ "id" : "22G5027e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.5 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-86178\/CE6C5645-C5C3-41A9-B986-D5F0BD7BB10B\/UniversalMac_13.5_22G5027e_Restore.ipsw",+ "version" : "13.5.0"+ },+ {+ "build" : "22F82",+ "channel" : "regular",+ "downloadSize" : 12739802320,+ "group" : "ventura",+ "id" : "22F82",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringFCS\/fullrestores\/042-01877\/2F49A9FE-7033-41D0-9D0C-64EFCE6B4C22\/UniversalMac_13.4.1_22F82_Restore.ipsw",+ "version" : "13.4.1"+ },+ {+ "build" : "22F66",+ "channel" : "regular",+ "downloadSize" : 12739995153,+ "group" : "ventura",+ "id" : "22F66",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringFCS\/fullrestores\/032-84884\/F97A22EE-9B5E-4FD5-94C1-B39DCEE8D80F\/UniversalMac_13.4_22F66_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22F63",+ "channel" : "devbeta",+ "downloadSize" : 12739473501,+ "group" : "ventura",+ "id" : "22F63",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4 RC 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringFCS\/fullrestores\/032-83954\/6E06237C-1B56-4932-A8E1-3A07A3EE03A8\/UniversalMac_13.4_22F63_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22F62",+ "channel" : "devbeta",+ "downloadSize" : 12738586980,+ "group" : "ventura",+ "id" : "22F62",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4 RC",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringFCS\/fullrestores\/032-44024\/731F1533-53BE-4CEB-AA05-74F333CA904A\/UniversalMac_13.4_22F62_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22F5059b",+ "channel" : "devbeta",+ "downloadSize" : 12721895514,+ "group" : "ventura",+ "id" : "22F5059b",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-79565\/BA9CBFB7-152C-4FB6-B0B3-47769997BFA1\/UniversalMac_13.4_22F5059b_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22F5049e",+ "channel" : "devbeta",+ "downloadSize" : 12720838737,+ "group" : "ventura",+ "id" : "22F5049e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-76661\/573284E7-4A4A-440C-AC01-6065C7A8E667\/UniversalMac_13.4_22F5049e_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22F5037d",+ "channel" : "devbeta",+ "downloadSize" : 12743516873,+ "group" : "ventura",+ "id" : "22F5037d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-69885\/ECFA1532-C633-4ACE-9D2C-3B5FD19510D4\/UniversalMac_13.4_22F5037d_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22F5027f",+ "channel" : "devbeta",+ "downloadSize" : 12728262691,+ "group" : "ventura",+ "id" : "22F5027f",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.4 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023SpringSeed\/fullrestores\/032-69187\/B11709E0-1CF5-4460-A069-D12E1243E2AD\/UniversalMac_13.4_22F5027f_Restore.ipsw",+ "version" : "13.4.0"+ },+ {+ "build" : "22E261",+ "channel" : "regular",+ "downloadSize" : 12726460903,+ "group" : "ventura",+ "id" : "22E261",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.3.1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterFCS\/fullrestores\/032-66602\/418BC37A-FCD9-400A-B4FA-022A19576CD4\/UniversalMac_13.3.1_22E261_Restore.ipsw",+ "version" : "13.3.1"+ },+ {+ "build" : "22E252",+ "channel" : "regular",+ "downloadSize" : 12727918028,+ "group" : "ventura",+ "id" : "22E252",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/002-75537\/8250FA0E-0962-46D6-8A90-57A390B9FFD7\/UniversalMac_13.3_22E252_Restore.ipsw",+ "version" : "13.3.0"+ },+ {+ "build" : "22E5246b",+ "channel" : "devbeta",+ "downloadSize" : 12713804212,+ "group" : "ventura",+ "id" : "22E5246b",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.3 Developer Beta 4",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/032-63669\/7C0F9BA8-35C0-457F-AF56-6943D58A2CDB\/UniversalMac_13.3_22E5246b_Restore.ipsw",+ "version" : "13.3.0"+ },+ {+ "build" : "22E5236f",+ "channel" : "devbeta",+ "downloadSize" : 12711164370,+ "group" : "ventura",+ "id" : "22E5236f",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.3 Developer Beta 3",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/032-60411\/1DDA996F-B620-4770-8FFE-87AB2043784D\/UniversalMac_13.3_22E5236f_Restore.ipsw",+ "version" : "13.3.0"+ },+ {+ "build" : "22E5230e",+ "channel" : "devbeta",+ "downloadSize" : 12702079514,+ "group" : "ventura",+ "id" : "22E5230e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.3 Developer Beta 2",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/032-54760\/AE02E378-FD59-474D-93AB-C52617103C72\/UniversalMac_13.3_22E5230e_Restore.ipsw",+ "version" : "13.3.0"+ },+ {+ "build" : "22E5219e",+ "channel" : "devbeta",+ "downloadSize" : 12690065479,+ "group" : "ventura",+ "id" : "22E5219e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.3 Developer Beta 1",+ "requirements" : "min_host_13",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/032-01932\/676E0981-4535-4942-A4AE-E14C604CE719\/UniversalMac_13.3_22E5219e_Restore.ipsw",+ "version" : "13.3.0"+ },+ {+ "build" : "22D68",+ "channel" : "regular",+ "downloadSize" : 12494476408,+ "group" : "ventura",+ "id" : "22D68",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.2.1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterFCS\/fullrestores\/032-48346\/EFF99C1E-C408-4E7A-A448-12E1468AF06C\/UniversalMac_13.2.1_22D68_Restore.ipsw",+ "version" : "13.2.1"+ },+ {+ "build" : "22D49",+ "channel" : "regular",+ "downloadSize" : 12494248692,+ "group" : "ventura",+ "id" : "22D49",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.2",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterFCS\/fullrestores\/032-35688\/0350BB21-2B4B-4850-BF77-70B830283B28\/UniversalMac_13.2_22D49_Restore.ipsw",+ "version" : "13.2.0"+ },+ {+ "build" : "22D5038i",+ "channel" : "devbeta",+ "downloadSize" : 12269915297,+ "group" : "ventura",+ "id" : "22D5038i",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.2 Developer Beta 2",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/032-33181\/62ECE236-5806-4136-AD08-EDC026FD80A5\/UniversalMac_13.2_22D5038i_Restore.ipsw",+ "version" : "13.2.0"+ },+ {+ "build" : "22D5027d",+ "channel" : "devbeta",+ "downloadSize" : 12278161108,+ "group" : "ventura",+ "id" : "22D5027d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.2 Developer Beta 1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2023WinterSeed\/fullrestores\/032-12640\/6B472BA3-E678-4251-92D1-7AA23B66F53E\/UniversalMac_13.2_22D5027d_Restore.ipsw",+ "version" : "13.2.0"+ },+ {+ "build" : "22C65",+ "channel" : "regular",+ "downloadSize" : 12279576859,+ "group" : "ventura",+ "id" : "22C65",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallFCS\/fullrestores\/012-60270\/0A7F49BA-FC31-4AD9-8E45-49B1FB9128A6\/UniversalMac_13.1_22C65_Restore.ipsw",+ "version" : "13.1.0"+ },+ {+ "build" : "22C5059b",+ "channel" : "devbeta",+ "downloadSize" : 12261527012,+ "group" : "ventura",+ "id" : "22C5059b",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.1 Developer Beta 4",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/032-08112\/957EA73A-7C95-4B3C-B99C-2C2C47555832\/UniversalMac_13.1_22C5059b_Restore.ipsw",+ "version" : "13.1.0"+ },+ {+ "build" : "22C5050e",+ "channel" : "devbeta",+ "downloadSize" : 12258951167,+ "group" : "ventura",+ "id" : "22C5050e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.1 Developer Beta 3",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/032-06252\/946CBF92-8F27-49B1-A692-81F54C73D2F0\/UniversalMac_13.1_22C5050e_Restore.ipsw",+ "version" : "13.1.0"+ },+ {+ "build" : "22C5044e",+ "channel" : "devbeta",+ "downloadSize" : 11918902102,+ "group" : "ventura",+ "id" : "22C5044e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.1 Developer Beta 2",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/032-02019\/670C9BA6-67EB-4AE6-A02E-88976F6F3118\/UniversalMac_13.1_22C5044e_Restore.ipsw",+ "version" : "13.1.0"+ },+ {+ "build" : "22C5033e",+ "channel" : "devbeta",+ "downloadSize" : 11886880578,+ "group" : "ventura",+ "id" : "22C5033e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.1 Developer Beta 1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/012-82062\/10E6B723-51B8-4B2C-BA3B-12A18ED4E719\/UniversalMac_13.1_22C5033e_Restore.ipsw",+ "version" : "13.1.0"+ },+ {+ "build" : "22A400",+ "channel" : "regular",+ "downloadSize" : 12197932579,+ "group" : "ventura",+ "id" : "22A400",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0.1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallFCS\/fullrestores\/012-93802\/A7270B0F-05F8-43D1-A9AD-40EF5699E82C\/UniversalMac_13.0.1_22A400_Restore.ipsw",+ "version" : "13.0.1"+ },+ {+ "build" : "22A380",+ "channel" : "regular",+ "downloadSize" : 12197669257,+ "group" : "ventura",+ "id" : "22A380",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallFCS\/fullrestores\/012-92188\/2C38BCD1-2BFF-4A10-B358-94E8E28BE805\/UniversalMac_13.0_22A380_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A379",+ "channel" : "devbeta",+ "downloadSize" : 12197156665,+ "group" : "ventura",+ "id" : "22A379",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 RC",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallFCS\/fullrestores\/071-08994\/1118ADF4-1CC9-4554-9333-B1F64CF0C820\/UniversalMac_13.0_22A379_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5373b",+ "channel" : "devbeta",+ "downloadSize" : 12173276873,+ "group" : "ventura",+ "id" : "22A5373b",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 11",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-84563\/2FC38C63-3213-4BB6-8E41-2B066332CBE6\/UniversalMac_13.0_22A5373b_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5365d",+ "channel" : "devbeta",+ "downloadSize" : 12175865747,+ "group" : "ventura",+ "id" : "22A5365d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 10",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-83054\/16ECAA12-3A1B-4663-B49B-B1563ECD4314\/UniversalMac_13.0_22A5365d_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5358e",+ "channel" : "devbeta",+ "downloadSize" : 12211984012,+ "group" : "ventura",+ "id" : "22A5358e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 9",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-71790\/AF5A04A6-FF20-44C1-9BFF-43081BDB4D8C\/UniversalMac_13.0_22A5358e_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5352e",+ "channel" : "devbeta",+ "downloadSize" : 12202491122,+ "group" : "ventura",+ "id" : "22A5352e",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 8",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-70113\/6F1F08B7-9A1B-48A9-93DB-55EE21121C87\/UniversalMac_13.0_22A5352e_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5342f",+ "channel" : "devbeta",+ "downloadSize" : 12036111685,+ "group" : "ventura",+ "id" : "22A5342f",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 7",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-66750\/108EF06D-FBEE-4910-BA83-56A5C9B54110\/UniversalMac_13.0_22A5342f_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5331f",+ "channel" : "devbeta",+ "downloadSize" : 12020352498,+ "group" : "ventura",+ "id" : "22A5331f",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 6",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-61458\/80300AD0-69E5-4429-AE3E-A936CA83B5FC\/UniversalMac_13.0_22A5331f_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5321d",+ "channel" : "devbeta",+ "downloadSize" : 12013062572,+ "group" : "ventura",+ "id" : "22A5321d",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 5",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-51397\/8EF0874D-388A-4F62-B58A-89F968DD3082\/UniversalMac_13.0_22A5321d_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5311f",+ "channel" : "devbeta",+ "downloadSize" : 12177142220,+ "group" : "ventura",+ "id" : "22A5311f",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 4",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-43316\/6CE4D83A-E44C-4DD1-B47F-DE168355662E\/UniversalMac_13.0_22A5311f_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5295i",+ "channel" : "devbeta",+ "downloadSize" : 12110805518,+ "group" : "ventura",+ "id" : "22A5295i",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 3 (22A5295i)",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-38309\/6EDC76A0-4432-4C64-83C5-F43C885A75D6\/UniversalMac_13.0_22A5295i_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5295h",+ "channel" : "devbeta",+ "downloadSize" : 12109750298,+ "group" : "ventura",+ "id" : "22A5295h",+ "mobileDeviceMinVersion" : "1400.0.0",+ "name" : "macOS 13.0 Developer Beta 3",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-34274\/130176F5-C4CB-4664-A2F0-F29CA1281694\/UniversalMac_13.0_22A5295h_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "22A5286j",+ "channel" : "devbeta",+ "downloadSize" : 12103954377,+ "group" : "ventura",+ "id" : "22A5286j",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 13.0 Developer Beta 2",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerSeed\/fullrestores\/012-30346\/9DD787A7-044B-4650-86D4-84E80B6B9C36\/UniversalMac_13.0_22A5286j_Restore.ipsw",+ "version" : "13.0.0"+ },+ {+ "build" : "21G217",+ "channel" : "regular",+ "downloadSize" : 14086558415,+ "group" : "monterey",+ "id" : "21G217",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.6.1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallFCS\/fullrestores\/012-66032\/8D8D90C6-A876-4FFF-BBF4-D158939B3841\/UniversalMac_12.6.1_21G217_Restore.ipsw",+ "version" : "12.6.1"+ },+ {+ "build" : "21G115",+ "channel" : "regular",+ "downloadSize" : 14081739387,+ "group" : "monterey",+ "id" : "21G115",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.6",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallFCS\/fullrestores\/012-40537\/0EC7C669-13E9-49FB-BD64-9EECC1D174B2\/UniversalMac_12.6_21G115_Restore.ipsw",+ "version" : "12.6.0"+ },+ {+ "build" : "21G83",+ "channel" : "regular",+ "downloadSize" : 14088266331,+ "group" : "monterey",+ "id" : "21G83",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5.1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerFCS\/fullrestores\/012-51674\/A7019DDB-3355-470F-A355-4162A187AB6C\/UniversalMac_12.5.1_21G83_Restore.ipsw",+ "version" : "12.5.1"+ },+ {+ "build" : "21G72",+ "channel" : "regular",+ "downloadSize" : 14084058716,+ "group" : "monterey",+ "id" : "21G72",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerFCS\/fullrestores\/012-42731\/BD9917E0-262C-41C5-A69F-AC316A534A39\/UniversalMac_12.5_21G72_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21G69",+ "channel" : "devbeta",+ "downloadSize" : 14085080132,+ "group" : "monterey",+ "id" : "21G69",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5 RC",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SummerFCS\/fullrestores\/012-40368\/5DD0A524-140A-46AF-91ED-5F28EA9DEC01\/UniversalMac_12.5_21G69_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21G5063a",+ "channel" : "devbeta",+ "downloadSize" : 13938297123,+ "group" : "monterey",+ "id" : "21G5063a",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5 Developer Beta 5",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/012-36748\/52342C55-6598-4A86-AAB8-8901145792C8\/UniversalMac_12.5_21G5063a_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21G5056b",+ "channel" : "devbeta",+ "downloadSize" : 13934172302,+ "group" : "monterey",+ "id" : "21G5056b",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5 Developer Beta 4",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/012-26441\/AE0AC638-2773-49D3-BF84-950B10BF39E9\/UniversalMac_12.5_21G5056b_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21G5046c",+ "channel" : "devbeta",+ "downloadSize" : 13868797741,+ "group" : "monterey",+ "id" : "21G5046c",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5 Developer Beta 3",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/012-18271\/FFF202B2-E4B6-4A3E-9681-42A0F3F81B11\/UniversalMac_12.5_21G5046c_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21G5037d",+ "channel" : "devbeta",+ "downloadSize" : 13829637373,+ "group" : "monterey",+ "id" : "21G5037d",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5 Developer Beta 2",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/012-10648\/1CC63FC5-5A22-4A5A-9A7B-C19C8C4A6731\/UniversalMac_12.5_21G5037d_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21G5027d",+ "channel" : "devbeta",+ "downloadSize" : 13831129170,+ "group" : "monterey",+ "id" : "21G5027d",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.5 Developer Beta 1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022FallSeed\/fullrestores\/002-93712\/5F234425-6096-43FC-B518-1E9D7B4D0254\/UniversalMac_12.5_21G5027d_Restore.ipsw",+ "version" : "12.5.0"+ },+ {+ "build" : "21F79",+ "channel" : "regular",+ "downloadSize" : 13837340777,+ "group" : "monterey",+ "id" : "21F79",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.4",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SpringFCS\/fullrestores\/012-06874\/9CECE956-D945-45E2-93E9-4FFDC81BB49A\/UniversalMac_12.4_21F79_Restore.ipsw",+ "version" : "12.4.0"+ },+ {+ "build" : "21F5071b",+ "channel" : "devbeta",+ "downloadSize" : 13819236155,+ "group" : "monterey",+ "id" : "21F5071b",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.4 Developer Beta 4",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SpringSeed\/fullrestores\/002-95106\/0F7A6388-C4B5-4B8E-B8B2-F62C030699D0\/UniversalMac_12.4_21F5071b_Restore.ipsw",+ "version" : "12.4.0"+ },+ {+ "build" : "21F5063e",+ "channel" : "devbeta",+ "downloadSize" : 13818052632,+ "group" : "monterey",+ "id" : "21F5063e",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.4 Developer Beta 3",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SpringSeed\/fullrestores\/002-90009\/DA6BD192-1698-48B3-AB6D-9D3A045ED1B1\/UniversalMac_12.4_21F5063e_Restore.ipsw",+ "version" : "12.4.0"+ },+ {+ "build" : "21F5058e",+ "channel" : "devbeta",+ "downloadSize" : 13832392408,+ "group" : "monterey",+ "id" : "21F5058e",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.4 Developer Beta 2",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SpringSeed\/fullrestores\/002-87587\/BC2EBE80-F0F4-4B56-BCDC-340E0AD8E985\/UniversalMac_12.4_21F5058e_Restore.ipsw",+ "version" : "12.4.0"+ },+ {+ "build" : "21F5048e",+ "channel" : "devbeta",+ "downloadSize" : 13812557221,+ "group" : "monterey",+ "id" : "21F5048e",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.4 Developer Beta 1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SpringSeed\/fullrestores\/002-85721\/A21FF659-8493-4A16-A989-2C3141F48D8C\/UniversalMac_12.4_21F5048e_Restore.ipsw",+ "version" : "12.4.0"+ },+ {+ "build" : "21E258",+ "channel" : "regular",+ "downloadSize" : 13875260060,+ "group" : "monterey",+ "id" : "21E258",+ "mobileDeviceMinVersion" : "1351.0.0",+ "name" : "macOS 12.3.1",+ "requirements" : "min_host_12",+ "url" : "https:\/\/updates.cdn-apple.com\/2022SpringFCS\/fullrestores\/002-79219\/851BEDF0-19DB-4040-B765-0F4089D1530D\/UniversalMac_12.3.1_21E258_Restore.ipsw",+ "version" : "12.3.1"+ }+ ]+}\ No newline at end of filediff --git a/VirtualMac/vz/development/ghidra/DumpAMFIEntitlements.java b/VirtualMac/vz/development/ghidra/DumpAMFIEntitlements.javanew file mode 100644index 0000000..5a20140--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpAMFIEntitlements.java@@ -0,0 +1,79 @@+// Decompile the iPadOS 16.3.1 AMFI entitlement-query overloads used by+// IOUserEthernet. Addresses are from the iPad14,3-6 20D67 kernelcache.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Function;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.LinkedHashMap;+import java.util.Map;++public class DumpAMFIEntitlements extends GhidraScript {+ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length != 1)+ throw new IllegalArgumentException("expected output directory");++ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("AMFIEntitlementGetBool_proc", 0xfffffe00092b5e34L);+ targets.put("AMFIEntitlementGetBool_OSEntitlements",+ 0xfffffe00092b5eb4L);+ targets.put("AMFIEntitlementGetBool_ucred", 0xfffffe00092b5fccL);+ targets.put("OSEntitlements_initWithValidationResult",+ 0xfffffe00092b1858L);+ targets.put("OSEntitlements_queryEntitlementsFor",+ 0xfffffe00092b1cbcL);+ targets.put("OSEntitlements_markAsCSPlatform",+ 0xfffffe00092b2318L);+ targets.put("OSEntitlements_isCSPlatform", 0xfffffe00092b235cL);+ targets.put("getEntitlements_ucred", 0xfffffe00092b2834L);+ targets.put("copyEntitlements_ucred", 0xfffffe00092b2860L);+ targets.put("copyEntitlements_proc", 0xfffffe00092b28dcL);+ targets.put("loadEntitlementsFromSignature",+ 0xfffffe00092ba44cL);+ targets.put("postValidation", 0xfffffe00092ba710L);++ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);+ StringBuilder report = new StringBuilder();+ for (Map.Entry<String, Long> target : targets.entrySet()) {+ Address address = toAddr(target.getValue());+ Function function = getFunctionAt(address);+ if (function == null)+ function = getFunctionContaining(address);+ report.append("===== ").append(target.getKey()).append(" @ ")+ .append(address).append(" =====\n");+ if (function == null) {+ report.append("No function found.\n\n");+ continue;+ }+ report.append("function: ").append(function.getName())+ .append(" entry=").append(function.getEntryPoint())+ .append("\n");+ DecompileResults result = decompiler.decompileFunction(+ function, 120, monitor);+ if (!result.decompileCompleted()) {+ report.append("Decompiler failed: ")+ .append(result.getErrorMessage()).append("\n\n");+ continue;+ }+ report.append(result.getDecompiledFunction().getC())+ .append("\n\n");+ }+ decompiler.dispose();++ File outputDir = new File(args[0]);+ outputDir.mkdirs();+ File output = new File(outputDir, "AMFIEntitlementGetBool.c");+ Files.writeString(output.toPath(), report.toString(),+ StandardCharsets.UTF_8);+ println("wrote " + output.getAbsolutePath());+ }+}diff --git a/VirtualMac/vz/development/ghidra/DumpAddressFunctions.java b/VirtualMac/vz/development/ghidra/DumpAddressFunctions.javanew file mode 100644index 0000000..19de4f1--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpAddressFunctions.java@@ -0,0 +1,61 @@+// Decompile functions containing requested addresses.+// Arguments after the output path are LABEL=ADDRESS pairs.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Function;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;++public class DumpAddressFunctions extends GhidraScript {+ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length < 2)+ throw new IllegalArgumentException(+ "expected output file followed by LABEL=ADDRESS pairs");+ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);+ StringBuilder report = new StringBuilder();+ report.append("program: ").append(currentProgram.getName())+ .append("\nsha256: ")+ .append(currentProgram.getExecutableSHA256()).append("\n\n");+ for (int index = 1; index < args.length; index++) {+ String[] pair = args[index].split("=", 2);+ if (pair.length != 2)+ throw new IllegalArgumentException("invalid target " + args[index]);+ Address address = toAddr(Long.decode(pair[1]));+ Function function = getFunctionAt(address);+ if (function == null)+ function = getFunctionContaining(address);+ report.append("===== ").append(pair[0]).append(" @ ")+ .append(address).append(" =====\n");+ if (function == null) {+ report.append("No function found.\n\n");+ continue;+ }+ report.append("function: ").append(function.getName(true))+ .append(" entry=").append(function.getEntryPoint())+ .append("\n");+ DecompileResults result =+ decompiler.decompileFunction(function, 300, monitor);+ if (result.decompileCompleted())+ report.append(result.getDecompiledFunction().getC());+ else+ report.append("Decompiler failed: ")+ .append(result.getErrorMessage()).append("\n");+ report.append("\n");+ }+ decompiler.dispose();+ File output = new File(args[0]);+ output.getParentFile().mkdirs();+ Files.writeString(output.toPath(), report.toString(),+ StandardCharsets.UTF_8);+ println("wrote " + output.getAbsolutePath());+ }+}diff --git a/VirtualMac/vz/development/ghidra/DumpIOUserEthernetAuthorization.java b/VirtualMac/vz/development/ghidra/DumpIOUserEthernetAuthorization.javanew file mode 100644index 0000000..6db964d--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpIOUserEthernetAuthorization.java@@ -0,0 +1,72 @@+// Decompile the IOUserEthernet entry points which authorize a new client.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.listing.Function;+import ghidra.program.model.listing.FunctionIterator;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.ArrayList;+import java.util.List;++public class DumpIOUserEthernetAuthorization extends GhidraScript {+ private boolean isAuthorizationTarget(Function function) {+ String name = function.getName(true);+ return (name.contains("IOUserEthernetResourceUserClient") &&+ name.contains("initWithTask")) ||+ (name.contains("IOUserEthernetResource") &&+ name.contains("newUserClient"));+ }++ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length != 1)+ throw new IllegalArgumentException("expected output directory");++ File outputDir = new File(args[0]);+ outputDir.mkdirs();+ List<Function> targets = new ArrayList<>();+ FunctionIterator functions =+ currentProgram.getFunctionManager().getFunctions(true);+ while (functions.hasNext()) {+ Function function = functions.next();+ if (isAuthorizationTarget(function))+ targets.add(function);+ }++ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);+ StringBuilder report = new StringBuilder();+ report.append("program: ").append(currentProgram.getName())+ .append("\nsha256: ")+ .append(currentProgram.getExecutableSHA256()).append("\n\n");++ for (Function function : targets) {+ report.append("===== ").append(function.getName(true))+ .append(" @ ").append(function.getEntryPoint())+ .append(" =====\n");+ DecompileResults result =+ decompiler.decompileFunction(function, 180, monitor);+ if (result.decompileCompleted())+ report.append(result.getDecompiledFunction().getC());+ else+ report.append("Decompiler failed: ")+ .append(result.getErrorMessage()).append("\n");+ report.append("\n");+ }+ decompiler.dispose();++ if (targets.isEmpty())+ report.append("No authorization functions found.\n");+ File output = new File(outputDir,+ currentProgram.getName() + "-authorization.c");+ Files.writeString(output.toPath(), report.toString(),+ StandardCharsets.UTF_8);+ println("wrote " + output.getAbsolutePath());+ }+}diff --git a/VirtualMac/vz/development/ghidra/DumpNamedFunctions.java b/VirtualMac/vz/development/ghidra/DumpNamedFunctions.javanew file mode 100644index 0000000..1a3edc9--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpNamedFunctions.java@@ -0,0 +1,51 @@+// Decompile functions whose Ghidra name contains the supplied text.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.listing.Function;+import ghidra.program.model.listing.FunctionIterator;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;++public class DumpNamedFunctions extends GhidraScript {+ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length != 2)+ throw new IllegalArgumentException("expected name text and output file");+ String needle = args[0];+ File output = new File(args[1]);+ StringBuilder report = new StringBuilder();+ report.append("program: ").append(currentProgram.getName())+ .append("\nfunction search: ").append(needle).append("\n\n");++ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);+ FunctionIterator functions = currentProgram.getFunctionManager()+ .getFunctions(true);+ while (functions.hasNext() && !monitor.isCancelled()) {+ Function function = functions.next();+ if (!function.getName().contains(needle))+ continue;+ report.append("===== ").append(function.getName()).append(" @ ")+ .append(function.getEntryPoint()).append(" =====\n");+ DecompileResults result = decompiler.decompileFunction(+ function, 180, monitor);+ if (result.decompileCompleted())+ report.append(result.getDecompiledFunction().getC());+ else+ report.append("Decompiler failed: ")+ .append(result.getErrorMessage()).append("\n");+ report.append("\n");+ }+ decompiler.dispose();+ output.getParentFile().mkdirs();+ Files.writeString(output.toPath(), report.toString(),+ StandardCharsets.UTF_8);+ println("wrote " + output.getAbsolutePath());+ }+}diff --git a/VirtualMac/vz/development/ghidra/DumpStringReferenceFunctions.java b/VirtualMac/vz/development/ghidra/DumpStringReferenceFunctions.javanew file mode 100644index 0000000..22a7c29--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpStringReferenceFunctions.java@@ -0,0 +1,65 @@+// Decompile every function referencing one of the requested string fragments.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.DataIterator;+import ghidra.program.model.listing.Function;+import ghidra.program.model.symbol.Reference;+import ghidra.program.model.symbol.ReferenceIterator;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.LinkedHashMap;+import java.util.Map;++public class DumpStringReferenceFunctions extends GhidraScript {+ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length < 2)+ throw new IllegalArgumentException(+ "expected output file followed by string fragments");+ Map<String, Function> functions = new LinkedHashMap<>();+ DataIterator data = currentProgram.getListing().getDefinedData(true);+ while (data.hasNext()) {+ Data item = data.next();+ Object value = item.getValue();+ if (!(value instanceof String))+ continue;+ String text = (String)value;+ boolean wanted = false;+ for (int i = 1; i < args.length; i++)+ wanted |= text.contains(args[i]);+ if (!wanted)+ continue;+ ReferenceIterator refs = currentProgram.getReferenceManager()+ .getReferencesTo(item.getMinAddress());+ while (refs.hasNext()) {+ Reference ref = refs.next();+ Function function = getFunctionContaining(ref.getFromAddress());+ if (function != null)+ functions.put(function.getEntryPoint().toString(), function);+ }+ }+ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);+ StringBuilder report = new StringBuilder();+ for (Map.Entry<String, Function> entry : functions.entrySet()) {+ Function function = entry.getValue();+ report.append("===== ").append(function.getName()).append(" @ ")+ .append(entry.getKey()).append(" =====\n");+ DecompileResults result = decompiler.decompileFunction(+ function, 120, monitor);+ report.append(result.decompileCompleted()+ ? result.getDecompiledFunction().getC()+ : result.getErrorMessage()).append("\n\n");+ }+ decompiler.dispose();+ Files.writeString(new File(args[0]).toPath(), report.toString(),+ StandardCharsets.UTF_8);+ }+}diff --git a/VirtualMac/vz/development/ghidra/DumpStringXrefs.java b/VirtualMac/vz/development/ghidra/DumpStringXrefs.javanew file mode 100644index 0000000..8e27fa4--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpStringXrefs.java@@ -0,0 +1,97 @@+// Decompile every function which references a string containing the supplied+// text. This is useful for frameworks whose stripped functions have no stable+// symbol name but do retain diagnostic exception strings.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.DataIterator;+import ghidra.program.model.listing.Function;+import ghidra.program.model.address.Address;+import ghidra.program.model.symbol.Reference;+import ghidra.program.model.symbol.ReferenceIterator;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.LinkedHashSet;+import java.util.Set;+import java.util.ArrayDeque;+import java.util.HashSet;++public class DumpStringXrefs extends GhidraScript {+ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length != 2)+ throw new IllegalArgumentException("expected search text and output file");++ String needle = args[0];+ File output = new File(args[1]);+ Set<Function> functions = new LinkedHashSet<>();+ StringBuilder report = new StringBuilder();+ report.append("program: ").append(currentProgram.getName())+ .append("\nsearch: ").append(needle).append("\n\n");++ DataIterator data = currentProgram.getListing().getDefinedData(true);+ while (data.hasNext() && !monitor.isCancelled()) {+ Data item = data.next();+ String value = item.getDefaultValueRepresentation();+ if (value == null || !value.contains(needle))+ continue;+ report.append("string ").append(item.getAddress()).append(" ")+ .append(value).append("\n");+ ArrayDeque<Address> pending = new ArrayDeque<>();+ Set<Address> visited = new HashSet<>();+ pending.add(item.getAddress());+ for (int depth = 0; depth < 4 && !pending.isEmpty(); depth++) {+ int count = pending.size();+ while (count-- > 0) {+ Address target = pending.remove();+ if (!visited.add(target))+ continue;+ ReferenceIterator references = currentProgram+ .getReferenceManager().getReferencesTo(target);+ while (references.hasNext()) {+ Reference reference = references.next();+ Address from = reference.getFromAddress();+ Function function = getFunctionContaining(from);+ report.append(" xref depth=").append(depth)+ .append(" ").append(from)+ .append(" function=").append(function).append("\n");+ if (function != null) {+ functions.add(function);+ continue;+ }+ Data container = currentProgram.getListing()+ .getDataContaining(from);+ pending.add(container != null+ ? container.getAddress() : from);+ }+ }+ }+ }++ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);+ for (Function function : functions) {+ report.append("\n===== ").append(function.getName()).append(" @ ")+ .append(function.getEntryPoint()).append(" =====\n");+ DecompileResults result = decompiler.decompileFunction(+ function, 180, monitor);+ if (result.decompileCompleted())+ report.append(result.getDecompiledFunction().getC());+ else+ report.append("Decompiler failed: ")+ .append(result.getErrorMessage()).append("\n");+ }+ decompiler.dispose();++ output.getParentFile().mkdirs();+ Files.writeString(output.toPath(), report.toString(),+ StandardCharsets.UTF_8);+ println("wrote " + output.getAbsolutePath());+ }+}diff --git a/VirtualMac/vz/development/ghidra/DumpTargetFunctions.java b/VirtualMac/vz/development/ghidra/DumpTargetFunctions.javanew file mode 100644index 0000000..3f53501--- /dev/null+++ b/VirtualMac/vz/development/ghidra/DumpTargetFunctions.java@@ -0,0 +1,241 @@+// Decompile the small set of extracted Virtualization/VMM functions involved+// in UIKit presentation, cursor rendering, input translation, and AVP HID.+// @category VirtualMac++import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;+import ghidra.app.script.GhidraScript;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Function;+import ghidra.program.model.listing.FunctionIterator;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.LinkedHashMap;+import java.util.Map;++public class DumpTargetFunctions extends GhidraScript {+ private Map<String, Long> virtualizationTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("keyboard_sendKeyEvents", 0x100072d70L);+ targets.put("pointer_sendPointerEvents", 0x1000a7888L);+ targets.put("framebuffer_cursor", 0x1000ab408L);+ targets.put("framebuffer_setCursor", 0x1000ab3fcL);+ targets.put("framebuffer_didUpdateCursor", 0x1000ab418L);+ targets.put("framebuffer_applyCursorUpdate", 0x1000ab60cL);+ targets.put("framebuffer_applyCursorUpdateAsync", 0x1000ab9acL);+ targets.put("framebuffer_updateCursorGeometry", 0x1000abab8L);+ targets.put("framebuffer_updateCursorVisibility", 0x1000abc7cL);+ targets.put("framebuffer_didUpdateFrame", 0x1000abed0L);+ targets.put("framebuffer_applyFrameUpdate", 0x1000ac0c4L);+ targets.put("framebuffer_applyFrameUpdateAsync", 0x1000ac200L);+ targets.put("framebuffer_layout", 0x1000ac868L);+ targets.put("framebuffer_setShowsCursor", 0x1000ac930L);+ targets.put("framebuffer_initWithFrame", 0x1000acd00L);+ targets.put("framebuffer_finishInit", 0x1000acbe0L);+ targets.put("host_platform_configuration", 0x100075ad4L);+ return targets;+ }++ private Map<String, Long> vmmTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("rpc_keyboard", 0x10002ece4L);+ targets.put("rpc_digitizer", 0x10002f7f8L);+ targets.put("rpc_keyboard_dispatch", 0x1000df65cL);+ targets.put("rpc_digitizer_dispatch", 0x1000df5a4L);+ targets.put("hid_digitizer_event", 0x1000414c4L);+ targets.put("avp_screen_digitizer_event", 0x100121e3cL);+ targets.put("avp_relative_pointer_event", 0x10012203cL);+ targets.put("avp_hid_submit_event", 0x100122fc0L);+ targets.put("avp_keyboard_event", 0x100063cbcL);+ targets.put("avp_hid_enqueue", 0x10012ddacL);+ targets.put("avp_hid_async_drain", 0x10012deb4L);+ targets.put("pci_device_registration", 0x100179d50L);+ targets.put("pvg_create_task_callback", 0x10011e854L);+ targets.put("pvg_map_memory_callback", 0x10011e8c0L);+ targets.put("pvg_read_memory_callback", 0x10011eac8L);+ targets.put("pvg_destroy_task_callback", 0x10011eba0L);+ return targets;+ }++ private Map<String, Long> pvgTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ // The first address is the helper which raises "Invalid task". The+ // second is the recovered NSException catch site observed in the VMM.+ targets.put("invalid_task_throw", 0x100010a00L);+ targets.put("invalid_task_catch", 0x10001eb34L);+ targets.put("invalid_task_command", 0x10001e9d8L);+ targets.put("create_task", 0x10001082cL);+ targets.put("delete_task", 0x100010aa8L);+ targets.put("cmd_define_task", 0x100020004L);+ targets.put("cmd_delete_task", 0x10001dc44L);+ // Include the neighboring task and IOSurface code so the decompiler+ // can expose the state which makes the task lookup fail.+ targets.put("task_lookup_before", 0x100010800L);+ targets.put("task_lookup_after", 0x100010c00L);+ targets.put("surface_catch_before", 0x10001e800L);+ targets.put("surface_catch_after", 0x10001ed00L);+ return targets;+ }++ private Map<String, Long> vmnetTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("vmnet_start_interface", 0x100004000L);+ targets.put("vmnet_start_register_interface", 0x1000048fcL);+ targets.put("vmnet_start_async", 0x1000049b8L);+ targets.put("vmnet_start_netrb", 0x100004b3cL);+ targets.put("vmnet_interface_set_event_callback", 0x100005480L);+ targets.put("vmnet_stop_interface", 0x100005f38L);+ return targets;+ }++ private Map<String, Long> netrbTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("NETRBXPCEndPointCreate", 0x1e90ed428L);+ targets.put("NETRBXPCCreate", 0x1e90ed668L);+ targets.put("NETRBXPCSetupAndSend", 0x1e90ed91cL);+ targets.put("NETRBClientCreate", 0x1e90eddbcL);+ targets.put("NETRBClientCreate_connection", 0x1e90ee010L);+ targets.put("NETRBClientCreate_response", 0x1e90ee28cL);+ return targets;+ }++ private Map<String, Long> netrbMacTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("NETRBXPCCreate", 0x1babd0bf0L);+ targets.put("NETRBXPCSetupAndSend", 0x1babd0ea4L);+ targets.put("NETRBClientCreate", 0x1babd1360L);+ targets.put("NETRBClientNewInterface", 0x1babd3c0cL);+ targets.put("NETRBClientNewInterface_send", 0x1babd40d0L);+ targets.put("NETRBClientNewInterface_reply", 0x1babd43c0L);+ targets.put("NETRBClientHandleReply", 0x1babd27d0L);+ targets.put("NETRBClientStartService", 0x1babd1dd8L);+ return targets;+ }++ private Map<String, Long> internetSharingTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("cleanup_and_exit", 0x1000032a4L);+ targets.put("main", 0x1000033bcL);+ targets.put("start_xpc_listener", 0x10000394cL);+ targets.put("xpc_message_dispatch", 0x100003f10L);+ targets.put("create_interface", 0x1000052d8L);+ targets.put("create_network_service", 0x100006380L);+ targets.put("destroy_network_service", 0x100006140L);+ targets.put("service_interface_create", 0x100007198L);+ targets.put("configure_network_service", 0x1000078e0L);+ targets.put("allocate_bridge_name", 0x10001b96cL);+ targets.put("ethernet_controller_create", 0x100009fe0L);+ targets.put("ethernet_bsd_attach_callback", 0x10000a334L);+ targets.put("interface_broadcast_create", 0x10000ef64L);+ targets.put("interface_direct_create", 0x100010580L);+ targets.put("launchd_job_load", 0x10000d7d4L);+ targets.put("mis_bcast_init", 0x1000183f0L);+ targets.put("mis_dns_init", 0x1000199acL);+ targets.put("mis_bridge_add_member", 0x10001b24cL);+ targets.put("mis_bridge_create", 0x10001bc5cL);+ targets.put("mis_dhcp_init", 0x10001dbb8L);+ targets.put("settings_init", 0x100015cc4L);+ targets.put("bootpd_configuration_init", 0x100017e64L);+ targets.put("bootpd_configuration_cleanup", 0x1000182dcL);+ targets.put("broadcast_init", 0x10000eeccL);+ targets.put("xpc_listener_init", 0x10001a78cL);+ targets.put("startup_prerequisite", 0x10001cc54L);+ targets.put("log_message", 0x10001cd48L);+ return targets;+ }++ private Map<String, Long> installationTargets() {+ Map<String, Long> targets = new LinkedHashMap<>();+ targets.put("mobile_device_notification", 0x1000046b4L);+ targets.put("mobile_device_progress", 0x1000054a8L);+ targets.put("start_install", 0x10000b394L);+ targets.put("set_usb_controller_location_id", 0x10000c760L);+ targets.put("request_mobile_device_update", 0x10000cda0L);+ targets.put("load_restore_image_catalog", 0x10000dce8L);+ targets.put("load_restore_image", 0x1000101f4L);+ targets.put("service_connection", 0x100010a90L);+ return targets;+ }++ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ if (args.length != 1)+ throw new IllegalArgumentException("expected output directory");+ File outputDir = new File(args[0]);+ outputDir.mkdirs();++ String programName = currentProgram.getName();+ Map<String, Long> targets;+ if (programName.equals("Virtualization"))+ targets = virtualizationTargets();+ else if (programName.equals("ParavirtualizedGraphics"))+ targets = pvgTargets();+ else if (programName.equals("vmnet"))+ targets = vmnetTargets();+ else if (programName.equals("Netrb"))+ targets = netrbTargets();+ else if (programName.startsWith("Netrb.macos"))+ targets = netrbMacTargets();+ else if (programName.equals("InternetSharing"))+ targets = internetSharingTargets();+ else if (programName.startsWith(+ "com.apple.Virtualization.Installation"))+ targets = installationTargets();+ else+ targets = vmmTargets();+ DecompInterface decompiler = new DecompInterface();+ decompiler.openProgram(currentProgram);++ StringBuilder report = new StringBuilder();+ report.append("program: ").append(programName).append("\n\n");+ if (programName.equals("ParavirtualizedGraphics")) {+ report.append("===== task-related-functions =====\n");+ FunctionIterator functions =+ currentProgram.getFunctionManager().getFunctions(true);+ while (functions.hasNext()) {+ Function function = functions.next();+ String name = function.getName();+ if (name.contains("TaskID") ||+ name.contains("DefineTask") ||+ name.contains("DeleteTask")) {+ report.append(function.getEntryPoint()).append(" ")+ .append(name).append("\n");+ }+ }+ report.append("\n");+ }+ for (Map.Entry<String, Long> target : targets.entrySet()) {+ Address address = toAddr(target.getValue());+ Function function = getFunctionAt(address);+ if (function == null)+ function = getFunctionContaining(address);+ report.append("===== ").append(target.getKey())+ .append(" @ ").append(address).append(" =====\n");+ if (function == null) {+ report.append("No function found.\n\n");+ continue;+ }+ report.append("function: ").append(function.getName())+ .append(" entry=").append(function.getEntryPoint())+ .append("\n");+ DecompileResults result = decompiler.decompileFunction(+ function, 120, monitor);+ if (!result.decompileCompleted()) {+ report.append("Decompiler failed: ")+ .append(result.getErrorMessage()).append("\n\n");+ continue;+ }+ report.append(result.getDecompiledFunction().getC())+ .append("\n\n");+ }+ decompiler.dispose();++ File output = new File(outputDir, programName + "-targets.c");+ Files.writeString(output.toPath(), report.toString(),+ StandardCharsets.UTF_8);+ println("wrote " + output.getAbsolutePath());+ }+}diff --git a/VirtualMac/vz/development/harness/build_test.sh b/VirtualMac/vz/development/harness/build_test.shnew file mode 100755index 0000000..6239f5f--- /dev/null+++ b/VirtualMac/vz/development/harness/build_test.sh@@ -0,0 +1,37 @@+#!/bin/bash++# Build a loadable iOS arm64e image and dlopen-test it on-device.+set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")/../scripts" && pwd)"+# shellcheck source=../scripts/lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++DSC="$VZ_BUILD_ROOT/inputs/macos/22D68__MacOS/dyld_shared_cache_arm64e"+PY="$VZ_BUILD_ROOT/toolchain/venv/bin/python3"+IMG="$1"; MODE="${2:-compact}"+NAME="$(basename "$IMG")"+OUTPUT_ROOT="$VZ_BUILD_ROOT/manual-load-test"+RE="$OUTPUT_ROOT/$NAME"+OUT="$OUTPUT_ROOT/$NAME.$MODE"+IOS="$OUT.ios" # stamped+signed+mkdir -p "$OUTPUT_ROOT"+need_file "$DSC"+need_file "$PY"+ensure_ipad_usb++[ -f "$RE" ] || "$VZ_BUILD_ROOT/toolchain/venv/bin/dyldex" -e "$IMG" -o "$RE" "$DSC" >/dev/null 2>&1+"$PY" "$VZ_REPO_ROOT/vz/uncache.py" "$DSC" "$IMG" "$RE" "$OUT" "$MODE" 2>&1 | grep -E 'rebases,|ADRP|objc relative|wrote'+cp "$OUT" "$IOS"+$PY - "$IOS" <<'PY'+import struct,sys+b=bytearray(open(sys.argv[1],"rb").read()); n=struct.unpack_from("<I",b,16)[0]; o=32+for _ in range(n):+ c,s=struct.unpack_from("<II",b,o)+ if c==0x32: struct.pack_into("<III",b,o+8,2,16<<16,16<<16|2); break+ o+=s+open(sys.argv[1],"wb").write(b)+PY+codesign -f -s - "$IOS" 2>/dev/null+HV=$(ldid -h "$IOS" 2>/dev/null | sed -n 's/^CDHash=//p')+ipad_scp "$IOS" "$IPAD_TARGET:/var/root/$NAME.test" >/dev/null 2>&1+ipad_ssh "jbctl trustcache add $HV >/dev/null; /var/root/hvload_e /var/root/$NAME.test; echo exit=\$?" 2>&1 | tail -8diff --git a/VirtualMac/vz/development/harness/ipad.sh b/VirtualMac/vz/development/harness/ipad.shnew file mode 100755index 0000000..f7f6bb0--- /dev/null+++ b/VirtualMac/vz/development/harness/ipad.sh@@ -0,0 +1,12 @@+#!/bin/bash++set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")/../scripts" && pwd)"+# shellcheck source=../scripts/lib/common.sh+source "$SCRIPT_DIR/lib/common.sh"++case "$1" in+ ssh) shift; ipad_ssh "$@";;+ scp) shift; ipad_scp "$@";;+ *) echo "usage: ipad.sh ssh '<cmd>' | scp <src> 127.0.0.1:<dst>"; exit 1;;+esacdiff --git a/VirtualMac/vz/development/harness/macbuild.sh b/VirtualMac/vz/development/harness/macbuild.shnew file mode 100755index 0000000..5875a05--- /dev/null+++ b/VirtualMac/vz/development/harness/macbuild.sh@@ -0,0 +1,16 @@+#!/bin/bash+# Extract a framework from the 13.2.1 cache, make it loadable (compact), and dlopen+# it on this Mac (deps resolve to host frameworks). Fast iteration + lldb for objc.+# Usage: macbuild.sh <image-path-in-cache> <basename>+set -e+cd "$(dirname "$0")/.."+DSC=build/rootfs_macOS/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e+PY=build/vz/venv/bin/python3+IMG="$1"; NAME="$2"+RE="build/vz/loadable/$NAME"+OUT="build/vz/loadable/$NAME.mac"+[ -f "$RE" ] || build/vz/venv/bin/dyldex -e "$IMG" -o "$RE" "$DSC" >/dev/null 2>&1+VZ_MAC=1 $PY build/vz/uncache.py "$DSC" "$IMG" "$RE" "$OUT" compact 2>&1 | grep -viE 'pkg_resources|UserWarning|import pkg|Slide|^[/\\|-]$|building all'+codesign -f -s - "$OUT" 2>/dev/null+echo -n "dlopen on Mac: "+build/vz/macload "$OUT" 2>&1 | tr '\n' ' '; echodiff --git a/VirtualMac/vz/development/harness/vm.sh b/VirtualMac/vz/development/harness/vm.shnew file mode 100755index 0000000..ae79294--- /dev/null+++ b/VirtualMac/vz/development/harness/vm.sh@@ -0,0 +1,17 @@+#!/bin/bash+# Helper for the matching macOS guest VM.+# Keeps the whole ssh/scp command in one script (zsh won't word-split a $VAR of -o flags).+# vz/development/harness/vm.sh ssh '<remote command>'+# vz/development/harness/vm.sh scp <src> mac@<guest-address>:<dst>+: "${VZ_GUEST_HOST:?set VZ_GUEST_HOST}"+: "${VZ_GUEST_USER:?set VZ_GUEST_USER}"+HOST="$VZ_GUEST_HOST"+USER="$VZ_GUEST_USER"+PASSWORD="${VZ_GUEST_PASSWORD:?set VZ_GUEST_PASSWORD}"+OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10+ -o PubkeyAuthentication=no -o PreferredAuthentications=password -o NumberOfPasswordPrompts=1)+case "$1" in+ ssh) shift; exec sshpass -p "$PASSWORD" ssh "${OPTS[@]}" "$USER@$HOST" "$@";;+ scp) shift; exec sshpass -p "$PASSWORD" scp "${OPTS[@]}" "$@";;+ *) echo "usage: vm.sh ssh '<cmd>' | scp <src> USER@$HOST:<dst>"; exit 1;;+esacdiff --git a/VirtualMac/vz/development/lldb/trace_installation_restore.lldb b/VirtualMac/vz/development/lldb/trace_installation_restore.lldbnew file mode 100644index 0000000..49c5881--- /dev/null+++ b/VirtualMac/vz/development/lldb/trace_installation_restore.lldb@@ -0,0 +1,25 @@+# File-address breakpoints for the exact Ventura 22D68 Installation helper+# and MobileDevice 1857 packaged by build-ipad-installation.sh. Every+# breakpoint auto-continues so the VZ ten-second DFU watchdog remains viable.+settings set stop-disassembly-count 0++# Installation receives the VMM's USB controller location ID and registers+# its MobileDevice notification callback.+breakpoint set -s com.apple.Virtualization.Installation -a 0x100004324 -N vz_location_set -G true -C 'register read x0 x1'++# MobileDevice is loaded after LLDB attaches. A pending symbol breakpoint+# arms the exact file-address sites as soon as any deviceWithService variant+# first runs; setting unloaded-module file addresses directly is not deferred+# by the iPad LLDB build.+breakpoint set -s MobileDevice -n deviceWithService -K false -N md_arm -G true -C 'breakpoint set -s MobileDevice -a 0x255af0 -N md_dfu_object -G true -C "register read x0 x20 x21"' -C 'breakpoint set -s MobileDevice -a 0x255b08 -N md_dfu_callback -G true -C "register read x0 x20 x21 x22"' -C 'breakpoint set -s MobileDevice -a 0xc6cd0 -N md_trackable_location -G true -C "register read x0 x19"' -C 'breakpoint set -s MobileDevice -a 0xc6cdc -N md_trackable_ecid -G true -C "register read x0 x19"' -C 'breakpoint set -s MobileDevice -a 0xc7c24 -N md_trackable_result -G true -C "register read x0 x20 x21"' -C 'breakpoint set -s MobileDevice -a 0xb6730 -N md_restore_worker -G true -C "register read x0" -C "memory read -fx -c 5 \`\$x0\`"'+breakpoint set -s MobileDevice -n usbDFU_servicesAdded -K false -N md_usb_dfu_added -G true -C 'register read x0 x1'+breakpoint set -s MobileDevice -n taDFU_AppleKIS_servicesAdded -K false -N md_kis_added -G true -C 'register read x0 x1'+breakpoint set -s MobileDevice -n tadfu_discovery_callback -K false -N md_tad_callback -G true -C 'register read x0'++# MobileDevice calls the Installation callback, which dispatches the final+# restore-start worker onto the Installer queue.+breakpoint set -s com.apple.Virtualization.Installation -a 0x1000045f8 -N vz_device_callback -G true -C 'register read x0 x1 x2 x3'+breakpoint set -s com.apple.Virtualization.Installation -a 0x1000046b4 -N vz_device_worker -G true -C 'register read x0' -C 'memory read -fx -c 3 `$x0`'++# The watchdog firing means no matching-location callback reached the worker.+breakpoint set -s com.apple.Virtualization.Installation -a 0x10000347c -N vz_install_timeout -G true -C 'register read x0'diff --git a/VirtualMac/vz/development/lldb/trace_iousblib_descriptors.py b/VirtualMac/vz/development/lldb/trace_iousblib_descriptors.pynew file mode 100644index 0000000..1ed5398--- /dev/null+++ b/VirtualMac/vz/development/lldb/trace_iousblib_descriptors.py@@ -0,0 +1,88 @@+"""Trace IOUSBLib associated-descriptor results in a restore process.++Attach LLDB to com.apple.Virtualization.Installation, import this file, run+``vz_iousb_descriptor_trace_install``, and continue. Ventura's arm64e+IOUSBHostFamily IOUSBLib has a single return at entry + 0x78 for this method.+"""++import lldb+++LOG = "/tmp/vz-iousblib-descriptor-trace.log"+SYMBOL = "_ZN19IOUSBInterfaceClass28FindNextAssociatedDescriptorEPKvh"+CALLS = {}+RETURN_BREAKPOINT = None+++def _append(line):+ with open(LOG, "a", encoding="utf-8") as output:+ output.write(line + "\n")+++def _reg(frame, name):+ return frame.FindRegister(name).GetValueAsUnsigned()+++def _read(process, address, size):+ if not address:+ return b""+ error = lldb.SBError()+ data = process.ReadMemory(address, size, error)+ return data if error.Success() else b""+++def _hex(data):+ return " ".join(f"{byte:02x}" for byte in data)+++def entry_hit(frame, _location, _dictionary):+ global RETURN_BREAKPOINT+ thread = frame.GetThread()+ process = thread.GetProcess()+ descriptor_type = _reg(frame, "x2") & 0xFF+ CALLS[thread.id] = descriptor_type+ if RETURN_BREAKPOINT is None:+ target = process.GetTarget()+ return_address = frame.GetPC() + 0x78+ RETURN_BREAKPOINT = target.BreakpointCreateByAddress(return_address)+ RETURN_BREAKPOINT.SetScriptCallbackFunction(+ "trace_iousblib_descriptors.return_hit"+ )+ _append(f"return-breakpoint=0x{return_address:x}")+ return False+++def return_hit(frame, _location, _dictionary):+ thread = frame.GetThread()+ descriptor_type = CALLS.pop(thread.id, None)+ if descriptor_type is None:+ return False+ result = _reg(frame, "x0")+ data = _read(thread.GetProcess(), result, 32)+ _append(+ f"type=0x{descriptor_type:02x} result=0x{result:x} bytes={_hex(data)}"+ )+ return False+++def install(debugger, _command, result, _dictionary):+ global RETURN_BREAKPOINT+ CALLS.clear()+ RETURN_BREAKPOINT = None+ with open(LOG, "w", encoding="utf-8") as output:+ output.write("trace-started\n")+ target = debugger.GetSelectedTarget()+ breakpoint = target.BreakpointCreateByName(SYMBOL)+ breakpoint.SetScriptCallbackFunction(+ "trace_iousblib_descriptors.entry_hit"+ )+ result.AppendMessage(+ f"IOUSBLib descriptor trace installed; log={LOG}"+ )+++def __lldb_init_module(debugger, _dictionary):+ debugger.HandleCommand(+ "command script add -f trace_iousblib_descriptors.install "+ "vz_iousb_descriptor_trace_install"+ )diff --git a/VirtualMac/vz/development/lldb/trace_mobiledevice_dfu.py b/VirtualMac/vz/development/lldb/trace_mobiledevice_dfu.pynew file mode 100644index 0000000..c88a886--- /dev/null+++ b/VirtualMac/vz/development/lldb/trace_mobiledevice_dfu.py@@ -0,0 +1,100 @@+"""Auto-continuing MobileDevice DFU construction trace for iPad LLDB.++Usage after attaching to com.apple.Virtualization.Installation:+ command script import /var/root/VirtualMac/lldb/trace_mobiledevice_dfu.py+ trace-mobiledevice-dfu+ continue+"""++import lldb+import time++LOG = "/tmp/mobiledevice-dfu-trace.log"+DESIRED_FILE_ADDRESS = 0x255620++MILESTONES = [+ (0x120, "create-plugin"),+ (0x180, "query-interface"),+ (0x1AC, "location"),+ (0x1C0, "vendor"),+ (0x1D4, "product"),+ (0x1EC, "manufacturer-index"),+ (0x218, "product-index"),+ (0x244, "serial-index"),+ (0x260, "strings-complete"),+ (0x280, "configuration"),+ (0x390, "descriptors-parsed"),+ (0x3BC, "device-accepted"),+ (0x3D0, "return"),+ (0x3F0, "device-rejected"),+]++_installed_addresses = set()+++def _log(message):+ with open(LOG, "a", encoding="utf-8") as stream:+ stream.write(f"[{time.time():.6f}] {message}\n")+++def _register(frame, name):+ value = frame.FindRegister(name)+ return value.GetValueAsUnsigned() if value.IsValid() else 0+++def milestone_callback(frame, bp_loc, _dict):+ thread = frame.GetThread()+ process = thread.GetProcess()+ label = bp_loc.GetBreakpoint().GetName() or "milestone"+ x19 = _register(frame, "x19")+ w0 = _register(frame, "w0")+ detail = ""+ if x19:+ error = lldb.SBError()+ data = process.ReadMemory(x19 + 0x20, 16, error)+ if error.Success():+ detail = " object20=" + data.hex()+ _log(+ f"pid={process.GetProcessID()} {label} pc=0x{frame.GetPC():x} "+ f"w0=0x{w0:x} x19=0x{x19:x}{detail}"+ )+ return False+++def entry_callback(frame, _bp_loc, _dict):+ address = frame.GetPCAddress()+ if address.GetFileAddress() != DESIRED_FILE_ADDRESS:+ return False+ target = frame.GetThread().GetProcess().GetTarget()+ base = address.GetLoadAddress(target)+ _log(f"pid={frame.GetThread().GetProcess().GetProcessID()} device-entry "+ f"load=0x{base:x}")+ for offset, label in MILESTONES:+ load_address = base + offset+ if load_address in _installed_addresses:+ continue+ breakpoint = target.BreakpointCreateByAddress(load_address)+ breakpoint.AddName(label)+ breakpoint.SetScriptCallbackFunction(+ "trace_mobiledevice_dfu.milestone_callback")+ _installed_addresses.add(load_address)+ return False+++def trace_mobiledevice_dfu(debugger, _command, result, _dict):+ target = debugger.GetSelectedTarget()+ breakpoint = target.BreakpointCreateByName(+ "deviceWithService", "MobileDevice")+ breakpoint.AddName("dfu-device-entry")+ breakpoint.SetScriptCallbackFunction(+ "trace_mobiledevice_dfu.entry_callback")+ _log(f"armed entry breakpoint id={breakpoint.GetID()}")+ result.PutCString(+ f"MobileDevice DFU trace armed; log: {LOG}")+++def __lldb_init_module(debugger, _dict):+ debugger.HandleCommand(+ "command script add -f trace_mobiledevice_dfu.trace_mobiledevice_dfu "+ "trace-mobiledevice-dfu")+diff --git a/VirtualMac/vz/development/lldb/trace_usb_hci_commands.py b/VirtualMac/vz/development/lldb/trace_usb_hci_commands.pynew file mode 100644index 0000000..b66cc81--- /dev/null+++ b/VirtualMac/vz/development/lldb/trace_usb_hci_commands.py@@ -0,0 +1,135 @@+"""Trace Ventura VMM USB controller commands at the reconstructed handlers.++Usage after attaching LLDB before VMM initialization:+ command script import trace_usb_hci_commands.py+ vz_usb_trace_install+ continue+"""++import lldb+import struct+++LOG = "/tmp/vz-usb-command-trace.log"+VMM_NAME = "com.apple.Virtualization.VirtualMachine"+COMMAND_HANDLER_OFFSET = 0x109E88+DOORBELL_HANDLER_OFFSET = 0x109EF4+ENDPOINT_RINGS = {}+++def _append(line):+ with open(LOG, "a", encoding="utf-8") as output:+ output.write(line + "\n")+++def _register(frame, name):+ return frame.FindRegister(name).GetValueAsUnsigned()+++def _read(process, address, size):+ error = lldb.SBError()+ data = process.ReadMemory(address, size, error)+ return data if error.Success() else b""+++def _hex(data):+ return " ".join(f"{value:02x}" for value in data)+++def _dump_ring(process, address, prefix):+ visited = set()+ current = address+ for segment in range(8):+ if not current or current in visited:+ break+ visited.add(current)+ ring = _read(process, current, 16 * 16)+ followed = 0+ for index in range(len(ring) // 16):+ item_control, item_data0, item_data1 = struct.unpack_from(+ "<IIQ", ring, index * 16+ )+ _append(+ f"{prefix}.segment{segment}[{index}] "+ f"type=0x{item_control & 0x3f:02x} "+ f"control=0x{item_control:08x} data0=0x{item_data0:08x} "+ f"data1=0x{item_data1:016x}"+ )+ if (item_control & 0x3F) == 0x3C:+ if item_control & 0x8000:+ followed = item_data1+ break+ current = followed+++def command_hit(frame, _location, _dictionary):+ process = frame.GetThread().GetProcess()+ packed = _register(frame, "x2")+ data1 = _register(frame, "x3")+ control = packed & 0xFFFFFFFF+ data0 = packed >> 32+ message_type = control & 0x3F+ _append(+ f"command type=0x{message_type:02x} control=0x{control:08x} "+ f"data0=0x{data0:08x} data1=0x{data1:016x}"+ )+ if message_type in (0x24, 0x28, 0x2C) and data1:+ _append(f"descriptor {_hex(_read(process, data1, 64))}")+ if message_type == 0x2E and data1:+ ENDPOINT_RINGS[data0] = data1+ _dump_ring(process, data1, "set-ring")+ return False+++def doorbell_hit(frame, _location, _dictionary):+ process = frame.GetThread().GetProcess()+ address = _register(frame, "x2")+ count = _register(frame, "x3") & 0xFFFFFFFF+ data = _read(process, address, min(count, 64) * 4)+ values = [+ struct.unpack_from("<I", data, index * 4)[0]+ for index in range(len(data) // 4)+ ]+ _append("doorbell " + " ".join(f"0x{value:08x}" for value in values))+ for value in values:+ ring = ENDPOINT_RINGS.get(value)+ if ring:+ _dump_ring(process, ring, f"doorbell-0x{value:08x}")+ return False+++def install(debugger, _command, result, _dictionary):+ target = debugger.GetSelectedTarget()+ process = target.GetProcess()+ module = next(+ (module for module in target.modules if module.file.basename == VMM_NAME),+ None,+ )+ if module is None:+ result.SetError("VMM module is not loaded")+ return+ base = module.GetObjectFileHeaderAddress().GetLoadAddress(target)+ with open(LOG, "w", encoding="utf-8") as output:+ output.write(f"pid={process.id} base=0x{base:x}\n")+ command_breakpoint = target.BreakpointCreateByAddress(+ base + COMMAND_HANDLER_OFFSET+ )+ command_breakpoint.SetScriptCallbackFunction(+ "trace_usb_hci_commands.command_hit"+ )+ doorbell_breakpoint = target.BreakpointCreateByAddress(+ base + DOORBELL_HANDLER_OFFSET+ )+ doorbell_breakpoint.SetScriptCallbackFunction(+ "trace_usb_hci_commands.doorbell_hit"+ )+ result.AppendMessage(+ f"USB trace installed at base 0x{base:x}; log={LOG}"+ )+++def __lldb_init_module(debugger, _dictionary):+ debugger.HandleCommand(+ "command script add -f trace_usb_hci_commands.install "+ "vz_usb_trace_install"+ )diff --git a/VirtualMac/vz/development/probes/AudioCaptureProbe-Info.plist b/VirtualMac/vz/development/probes/AudioCaptureProbe-Info.plistnew file mode 100644index 0000000..4ec1459--- /dev/null+++ b/VirtualMac/vz/development/probes/AudioCaptureProbe-Info.plist@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleExecutable</key>+ <string>AudioCaptureProbe</string>+ <key>CFBundleIdentifier</key>+ <string>com.mac.virtual.AudioCaptureProbe</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Audio Capture Probe</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>NSMicrophoneUsageDescription</key>+ <string>Verify microphone input from the iPad virtualization host.</string>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/amfi_entitlement_probe.c b/VirtualMac/vz/development/probes/amfi_entitlement_probe.cnew file mode 100644index 0000000..1ec4cda--- /dev/null+++ b/VirtualMac/vz/development/probes/amfi_entitlement_probe.c@@ -0,0 +1,214 @@+#include <errno.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>++#include "info.h"++extern int jbclient_initialize_primitives(void);+#ifdef __arm64e__+extern int jbclient_get_fugu14_kcall(void);+#else+extern int arm64_kcall_init(void);+#endif+extern _Bool is_kcall_available(void);+extern uint64_t proc_find(pid_t pid);+extern int proc_rele(uint64_t proc);+extern uint64_t proc_task(uint64_t proc);+extern uint64_t proc_ucred(uint64_t proc);+extern uint32_t proc_getcsflags(uint64_t proc);+extern uint64_t kread64(uint64_t address);+extern uint64_t kread_ptr(uint64_t address);+extern uint32_t kread32(uint64_t address);+extern uint8_t kread8(uint64_t address);+extern int kreadbuf(uint64_t address, void *output, size_t size);+extern uint64_t mac_label_get(uint64_t label, int slot);+extern int kalloc(uint64_t *address, uint64_t size);+extern int kfree(uint64_t address, uint64_t size);+extern int kwritebuf(uint64_t address, const void *input, size_t size);+extern uint8_t kread8(uint64_t address);+extern int kcall(uint64_t *result, uint64_t function, int argc,+ const uint64_t *arguments);++static const uint64_t amfiEntitlementGetBoolUnslid =+ 0xfffffe00092b5e34ULL; // iPadOS 16.3.1 20D67, iPad14,3-6+static const uint64_t amfiMacSlotUnslid =+ 0xfffffe0007bb91d0ULL; // _amfi_mac_slot in the same kernelcache++static uint32_t readBigEndian32(const uint8_t *bytes) {+ return ((uint32_t)bytes[0] << 24) | ((uint32_t)bytes[1] << 16) |+ ((uint32_t)bytes[2] << 8) | bytes[3];+}++static _Bool containsBytes(const uint8_t *haystack, size_t haystackLength,+ const char *needle) {+ size_t needleLength = strlen(needle);+ if (needleLength > haystackLength)+ return 0;+ for (size_t i = 0; i <= haystackLength - needleLength; i++) {+ if (memcmp(haystack + i, needle, needleLength) == 0)+ return 1;+ }+ return 0;+}++static void inspect(uint64_t process) {+ uint64_t task = proc_task(process);+ uint64_t map = task ? kread_ptr(task + koffsetof(task, map)) : 0;+ uint64_t pmap = map ? kread_ptr(map + koffsetof(vm_map, pmap)) : 0;+ uint64_t region = pmap ?+ kread_ptr(pmap + koffsetof(pmap, pmap_cs_main)) : 0;+ uint64_t codeDirectory = region ?+ kread_ptr(region + koffsetof(pmap_cs_region, cd_entry)) : 0;+ uint32_t trust = codeDirectory ?+ kread32(codeDirectory + koffsetof(pmap_cs_code_directory, trust)) : 0;+ uint64_t credential = proc_ucred(process);+ uint64_t label = credential ?+ kread_ptr(credential + koffsetof(ucred, label)) : 0;+ int32_t slot = (int32_t)kread32(amfiMacSlotUnslid ++ gSystemInfo.kernelConstant.slide);+ uint64_t entitlements = label && slot >= 0 ?+ mac_label_get(label, slot) : 0;++ printf("csflags=0x%08x task=0x%llx map=0x%llx pmap=0x%llx\n",+ proc_getcsflags(process),+ (unsigned long long)task, (unsigned long long)map,+ (unsigned long long)pmap);+ printf("pmap_cs_region=0x%llx code_directory=0x%llx trust=%u\n",+ (unsigned long long)region, (unsigned long long)codeDirectory,+ trust);+ printf("ucred=0x%llx label=0x%llx amfi_slot=%d "+ "OSEntitlements=0x%llx\n",+ (unsigned long long)credential, (unsigned long long)label, slot,+ (unsigned long long)entitlements);+ if (entitlements) {+ printf("OSEntitlements words:");+ for (uint64_t offset = 0; offset < 0x60; offset += 8)+ printf(" %016llx", (unsigned long long)+ kread64(entitlements + offset));+ putchar('\n');+ uint64_t state = kread_ptr(entitlements + 0x10);+ printf("OSEntitlements state=0x%llx is_cs_platform=%u words:",+ (unsigned long long)state,+ state ? kread8(state + 0x69) : 0);+ for (uint64_t offset = 0; state && offset < 0x80; offset += 8)+ printf(" %016llx", (unsigned long long)+ kread64(state + offset));+ putchar('\n');++ uint64_t der = state ? kread_ptr(state + 0x60) : 0;+ if (der) {+ uint8_t prefix[64] = { 0 };+ kreadbuf(der, prefix, sizeof(prefix));+ uint32_t blobLength = readBigEndian32(prefix + 4);+ printf("DER pointer=0x%llx prefix=",+ (unsigned long long)der);+ for (size_t i = 0; i < sizeof(prefix); i++)+ printf("%02x", prefix[i]);+ putchar('\n');+ if (blobLength >= 8 && blobLength <= 0x20008) {+ uint8_t *blob = malloc(blobLength);+ if (blob && kreadbuf(der, blob, blobLength) == 0) {+ const char *ethernet =+ "com.apple.networking.ethernet.user-access";+ printf("DER length=%u contains_ethernet_key=%u\n",+ blobLength,+ containsBytes(blob, blobLength, ethernet));+ }+ free(blob);+ }+ }+ }+}++static int query(uint64_t process, const char *key) {+ uint64_t kernelKey = 0;+ uint64_t kernelBool = 0;+ uint64_t result = 0;+ int error = kalloc(&kernelKey, 256);+ if (error != 0)+ return fprintf(stderr, "kalloc(key) failed: %d\n", error), 1;+ error = kalloc(&kernelBool, 8);+ if (error != 0) {+ kfree(kernelKey, 256);+ return fprintf(stderr, "kalloc(bool) failed: %d\n", error), 1;+ }++ uint8_t zero = 0;+ kwritebuf(kernelKey, key, strlen(key) + 1);+ kwritebuf(kernelBool, &zero, sizeof(zero));+ uint64_t arguments[] = { process, kernelKey, kernelBool };+ error = kcall(&result,+ amfiEntitlementGetBoolUnslid ++ gSystemInfo.kernelConstant.slide,+ 3, arguments);+ uint8_t granted = kread8(kernelBool);+ printf("key=%s kcall=%d amfi=0x%llx granted=%u\n", key, error,+ (unsigned long long)result, granted);++ kfree(kernelBool, 8);+ kfree(kernelKey, 256);+ return error != 0;+}++int main(int argc, char **argv) {+ if (argc < 2) {+ fprintf(stderr, "usage: %s PID [ENTITLEMENT ...]\n", argv[0]);+ return 2;+ }+ pid_t pid = (pid_t)strtol(argv[1], NULL, 10);+ int error = jbclient_initialize_primitives();+ if (error != 0) {+ fprintf(stderr, "jbclient_initialize_primitives failed: %d\n", error);+ return 1;+ }+ uint64_t process = proc_find(pid);+ if (process == 0) {+ fprintf(stderr, "proc_find(%d) failed\n", pid);+ return 1;+ }+ printf("pid=%d proc=0x%llx slide=0x%llx amfi=0x%llx\n", pid,+ (unsigned long long)process,+ (unsigned long long)gSystemInfo.kernelConstant.slide,+ (unsigned long long)(amfiEntitlementGetBoolUnslid ++ gSystemInfo.kernelConstant.slide));+ inspect(process);++ if (!is_kcall_available()) {+#ifdef __arm64e__+ error = jbclient_get_fugu14_kcall();+ fprintf(stderr, "jbclient_get_fugu14_kcall=%d available=%d\n",+ error, is_kcall_available());+#else+ error = arm64_kcall_init();+ fprintf(stderr, "arm64_kcall_init=%d available=%d\n", error,+ is_kcall_available());+#endif+ }+ if (!is_kcall_available()) {+ fprintf(stderr, "kernel call primitive unavailable; "+ "credential inspection above is still valid\n");+ proc_rele(process);+ return 0;+ }++ int failed = 0;+ if (argc == 2) {+ const char *keys[] = {+ "com.apple.networking.ethernet.user-access",+ "com.apple.pf.allow",+ "platform-application",+ "com.apple.private.security.no-sandbox",+ "com.mac.virtual.does-not-exist",+ };+ for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); i++)+ failed |= query(process, keys[i]);+ } else {+ for (int i = 2; i < argc; i++)+ failed |= query(process, argv[i]);+ }+ proc_rele(process);+ return failed ? 1 : 0;+}diff --git a/VirtualMac/vz/development/probes/audio_capture_app.m b/VirtualMac/vz/development/probes/audio_capture_app.mnew file mode 100644index 0000000..a770cb5--- /dev/null+++ b/VirtualMac/vz/development/probes/audio_capture_app.m@@ -0,0 +1,120 @@+#import <AppKit/AppKit.h>+#import <AVFoundation/AVFoundation.h>+#include <math.h>++@interface AudioCaptureDelegate : NSObject <NSApplicationDelegate>+@property(nonatomic, retain) AVAudioEngine *engine;+@property(nonatomic, retain) NSWindow *window;+@property(nonatomic) uint64_t samples;+@property(nonatomic) double sumSquares;+@property(nonatomic) float peak;+@end++@implementation AudioCaptureDelegate++- (void)writeResult:(NSString *)result status:(int)status+{+ [result writeToFile:@"/tmp/vz-audio-capture-result.txt"+ atomically:YES encoding:NSUTF8StringEncoding error:nil];+ fputs(result.UTF8String, stdout);+ fflush(stdout);+ [NSApp terminate:@(status)];+}++- (void)beginCapture+{+ self.engine = [[[AVAudioEngine alloc] init] autorelease];+ AVAudioInputNode *input = self.engine.inputNode;+ AVAudioFormat *format = [input outputFormatForBus:0];+ if (!input || !format || format.channelCount == 0) {+ [self writeResult:@"permission=granted error=no-input\n" status:2];+ return;+ }+ [input installTapOnBus:0 bufferSize:1024 format:format+ block:^(AVAudioPCMBuffer *buffer, AVAudioTime *when) {+ (void)when;+ float *const *channels = buffer.floatChannelData;+ for (AVAudioChannelCount channel = 0;+ channels && channel < buffer.format.channelCount; channel++) {+ for (AVAudioFrameCount frame = 0; frame < buffer.frameLength;+ frame++) {+ float value = fabsf(channels[channel][frame]);+ self.sumSquares += (double)value * value;+ self.peak = MAX(self.peak, value);+ self.samples++;+ }+ }+ }];+ NSError *error = nil;+ if (![self.engine startAndReturnError:&error]) {+ [self writeResult:[NSString stringWithFormat:+ @"permission=granted error=%@\n", error] status:2];+ return;+ }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ [self.engine stop];+ [input removeTapOnBus:0];+ double rms = self.samples+ ? sqrt(self.sumSquares / (double)self.samples) : 0;+ NSString *result = [NSString stringWithFormat:+ @"permission=granted samples=%llu rms=%.8f peak=%.8f\n",+ (unsigned long long)self.samples, rms, self.peak];+ [self writeResult:result status:self.peak > 0.00001f ? 0 : 1];+ });+}++- (void)applicationDidFinishLaunching:(NSNotification *)notification+{+ (void)notification;+ [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];+ self.window = [[[NSWindow alloc]+ initWithContentRect:NSMakeRect(0, 0, 420, 120)+ styleMask:NSWindowStyleMaskTitled+ backing:NSBackingStoreBuffered defer:NO] autorelease];+ self.window.title = @"Virtual Mac Microphone Test";+ // The virtual display can report an empty/negative visibleFrame before+ // WindowServer finishes its first display transaction. An explicit point+ // keeps both this window and its TCC sheet on the 1366x1024 desktop.+ [self.window setFrameOrigin:NSMakePoint(473, 400)];+ [self.window makeKeyAndOrderFront:nil];+ [NSApp activateIgnoringOtherApps:YES];+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio+ completionHandler:^(BOOL granted) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (!granted) {+ [self writeResult:@"permission=denied\n" status:1];+ return;+ }+ [self beginCapture];+ });+ }];+}++- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender+{+ (void)sender;+ return NO;+}++- (void)dealloc+{+ [_engine release];+ [_window release];+ [super dealloc];+}++@end++int main(int argc, const char *argv[]) {+ (void)argc;+ (void)argv;+ @autoreleasepool {+ NSApplication *application = NSApplication.sharedApplication;+ AudioCaptureDelegate *delegate = [[AudioCaptureDelegate alloc] init];+ application.delegate = delegate;+ [application run];+ [delegate release];+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/audio_capture_probe.c b/VirtualMac/vz/development/probes/audio_capture_probe.cnew file mode 100644index 0000000..bf0c5b2--- /dev/null+++ b/VirtualMac/vz/development/probes/audio_capture_probe.c@@ -0,0 +1,98 @@+#include <AudioToolbox/AudioToolbox.h>+#include <CoreFoundation/CoreFoundation.h>+#include <math.h>+#include <signal.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>++static AudioQueueRef queue;+static volatile sig_atomic_t finished;+static uint64_t frames;+static double sum_squares;+static float peak;++static void capture(void *context, AudioQueueRef audio_queue,+ AudioQueueBufferRef buffer,+ const AudioTimeStamp *start_time,+ UInt32 packet_count,+ const AudioStreamPacketDescription *descriptions) {+ (void)context;+ (void)start_time;+ (void)packet_count;+ (void)descriptions;+ const float *samples = buffer->mAudioData;+ size_t count = buffer->mAudioDataByteSize / sizeof(*samples);+ for (size_t index = 0; index < count; index++) {+ float value = fabsf(samples[index]);+ sum_squares += (double)value * value;+ if (value > peak)+ peak = value;+ }+ frames += count / 2;+ if (!finished)+ AudioQueueEnqueueBuffer(audio_queue, buffer, 0, NULL);+}++static void stop_capture(int signal_number) {+ (void)signal_number;+ finished = 1;+}++static void check(OSStatus status, const char *operation) {+ if (status == noErr)+ return;+ fprintf(stderr, "%s failed: %d (0x%08x)\n", operation,+ (int)status, (unsigned int)status);+ exit(2);+}++int main(int argc, char **argv) {+ double duration = argc > 1 ? strtod(argv[1], NULL) : 5.0;+ AudioStreamBasicDescription format = {+ .mSampleRate = 48000,+ .mFormatID = kAudioFormatLinearPCM,+ .mFormatFlags = kAudioFormatFlagIsFloat |+ kAudioFormatFlagIsPacked |+ kAudioFormatFlagsNativeEndian,+ .mBytesPerPacket = 2 * sizeof(float),+ .mFramesPerPacket = 1,+ .mBytesPerFrame = 2 * sizeof(float),+ .mChannelsPerFrame = 2,+ .mBitsPerChannel = 8 * sizeof(float),+ };++ signal(SIGINT, stop_capture);+ signal(SIGTERM, stop_capture);+ check(AudioQueueNewInput(&format, capture, NULL, NULL,+ kCFRunLoopCommonModes, 0, &queue),+ "AudioQueueNewInput");+ for (unsigned int index = 0; index < 4; index++) {+ AudioQueueBufferRef buffer;+ check(AudioQueueAllocateBuffer(queue, 48000 * format.mBytesPerFrame / 10,+ &buffer),+ "AudioQueueAllocateBuffer");+ check(AudioQueueEnqueueBuffer(queue, buffer, 0, NULL),+ "AudioQueueEnqueueBuffer");+ }+ check(AudioQueueStart(queue, NULL), "AudioQueueStart");++ CFAbsoluteTime deadline = CFAbsoluteTimeGetCurrent() + duration;+ while (!finished && CFAbsoluteTimeGetCurrent() < deadline)+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, false);+ finished = 1;+ AudioQueueStop(queue, true);+ AudioQueueDispose(queue, true);++ double rms = frames ? sqrt(sum_squares / (double)(frames * 2)) : 0;+ char result[160];+ snprintf(result, sizeof(result), "frames=%llu rms=%.8f peak=%.8f\n",+ (unsigned long long)frames, rms, peak);+ fputs(result, stdout);+ FILE *result_file = fopen("/tmp/vz-audio-capture-result.txt", "w");+ if (result_file) {+ fputs(result, result_file);+ fclose(result_file);+ }+ return frames && peak > 0.00001f ? 0 : 1;+}diff --git a/VirtualMac/vz/development/probes/audio_tone_probe.m b/VirtualMac/vz/development/probes/audio_tone_probe.mnew file mode 100644index 0000000..61d2402--- /dev/null+++ b/VirtualMac/vz/development/probes/audio_tone_probe.m@@ -0,0 +1,88 @@+#import <AVFAudio/AVFAudio.h>+#import <AudioToolbox/AudioToolbox.h>+#include <math.h>+#include <stdio.h>++static double phase;+static const double frequency = 880.0;+static const double sampleRate = 48000.0;++static void renderTone(void *context, AudioQueueRef queue,+ AudioQueueBufferRef buffer) {+ (void)context;+ float *samples = buffer->mAudioData;+ UInt32 frames = buffer->mAudioDataBytesCapacity /+ (2 * (UInt32)sizeof(float));+ for (UInt32 frame = 0; frame < frames; frame++) {+ float sample = (float)(sin(phase) * 0.35);+ samples[frame * 2] = sample;+ samples[frame * 2 + 1] = sample;+ phase += 2.0 * M_PI * frequency / sampleRate;+ if (phase >= 2.0 * M_PI)+ phase -= 2.0 * M_PI;+ }+ buffer->mAudioDataByteSize = frames * 2 * sizeof(float);+ AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);+}++static void check(OSStatus status, const char *operation) {+ if (status == noErr)+ return;+ fprintf(stderr, "%s failed: %d (0x%08x)\n", operation,+ (int)status, (unsigned int)status);+ exit(2);+}++int main(int argc, char **argv) {+ @autoreleasepool {+ double duration = argc > 1 ? strtod(argv[1], NULL) : 4.0;+ AVAudioSession *session = AVAudioSession.sharedInstance;+ NSError *error = nil;+ AVAudioSessionCategoryOptions options =+ AVAudioSessionCategoryOptionMixWithOthers |+ AVAudioSessionCategoryOptionDefaultToSpeaker;+ if (![session setCategory:AVAudioSessionCategoryPlayAndRecord+ mode:AVAudioSessionModeDefault+ options:options error:&error] ||+ ![session setActive:YES error:&error]) {+ fprintf(stderr, "AVAudioSession setup failed: %s\n",+ error.localizedDescription.UTF8String);+ return 2;+ }++ AudioStreamBasicDescription format = {+ .mSampleRate = sampleRate,+ .mFormatID = kAudioFormatLinearPCM,+ .mFormatFlags = kAudioFormatFlagIsFloat |+ kAudioFormatFlagIsPacked |+ kAudioFormatFlagsNativeEndian,+ .mBytesPerPacket = 2 * sizeof(float),+ .mFramesPerPacket = 1,+ .mBytesPerFrame = 2 * sizeof(float),+ .mChannelsPerFrame = 2,+ .mBitsPerChannel = 8 * sizeof(float),+ };+ AudioQueueRef queue;+ check(AudioQueueNewOutput(&format, renderTone, NULL, NULL, NULL, 0,+ &queue),+ "AudioQueueNewOutput");+ for (unsigned int index = 0; index < 4; index++) {+ AudioQueueBufferRef buffer;+ check(AudioQueueAllocateBuffer(queue,+ 4800 * format.mBytesPerFrame,+ &buffer),+ "AudioQueueAllocateBuffer");+ renderTone(NULL, queue, buffer);+ }+ check(AudioQueueStart(queue, NULL), "AudioQueueStart");+ printf("playing %.0f Hz for %.1f seconds\n", frequency, duration);+ NSRunLoop *runLoop = NSRunLoop.currentRunLoop;+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:duration];+ while ([deadline timeIntervalSinceNow] > 0)+ [runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];+ AudioQueueStop(queue, true);+ AudioQueueDispose(queue, true);+ [session setActive:NO error:nil];+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/epprobe.m b/VirtualMac/vz/development/probes/epprobe.mnew file mode 100644index 0000000..637942d--- /dev/null+++ b/VirtualMac/vz/development/probes/epprobe.m@@ -0,0 +1,69 @@+// (1) extract the mach send-right backing an anonymous xpc_endpoint (confirmed at +0x18).+// (2) validate the rendezvous primitive in-process:+// xpc_connection_create_from_endpoint(E) -> the listener L receives a PEER connection and a+// message flows. (3) validate reconstruction-by-port-swap: clone an endpoint object and+// overwrite its +0x18 port with a copy of L's port -> still reaches L (this is how the+// spawned child will rebuild the endpoint from just the inherited mach port).+#include <xpc/xpc.h>+#include <mach/mach.h>+#include <dispatch/dispatch.h>+#include <stdio.h>+#include <string.h>++extern xpc_object_t xpc_endpoint_create(xpc_connection_t connection);+extern xpc_connection_t xpc_connection_create_from_endpoint(xpc_endpoint_t endpoint);++#define PORT_OFF 0x18++static uint32_t ep_port(xpc_object_t E) { return *(uint32_t *)((char *)E + PORT_OFF); }++int main(void) {+ setvbuf(stdout, NULL, _IONBF, 0);+ dispatch_queue_t q = dispatch_queue_create("L", DISPATCH_QUEUE_SERIAL);+ xpc_connection_t L = xpc_connection_create(NULL, q);+ xpc_connection_set_event_handler(L, ^(xpc_object_t peer) {+ if (xpc_get_type(peer) != XPC_TYPE_CONNECTION) {+ printf(">>> L: non-connection event (%s)\n", xpc_copy_description(peer)); return;+ }+ printf(">>> L received PEER %p — accepting\n", (void *)peer);+ xpc_connection_set_event_handler(peer, ^(xpc_object_t m) {+ if (xpc_get_type(m) == XPC_TYPE_DICTIONARY) {+ const char *s = xpc_dictionary_get_string(m, "hello");+ printf(">>> L PEER got message: hello=%s *** RENDEZVOUS WORKS ***\n", s ? s : "(nil)");+ }+ });+ xpc_connection_resume(peer);+ });+ xpc_connection_resume(L);++ xpc_object_t E = xpc_endpoint_create(L);+ printf("L=%p E=%p E.port=0x%x\n", (void *)L, (void *)E, ep_port(E));++ // (2) connect from the endpoint in-process+ xpc_connection_t c = xpc_connection_create_from_endpoint((xpc_endpoint_t)E);+ xpc_connection_set_event_handler(c, ^(xpc_object_t e) {+ if (xpc_get_type(e) == XPC_TYPE_ERROR)+ printf(" c error: %s\n", xpc_dictionary_get_string(e, XPC_ERROR_KEY_DESCRIPTION));+ });+ xpc_connection_resume(c);+ xpc_object_t msg = xpc_dictionary_create(NULL, NULL, 0);+ xpc_dictionary_set_string(msg, "hello", "from-endpoint");+ xpc_connection_send_message(c, msg);++ // (3) reconstruction-by-port-swap: a fresh endpoint object whose port we overwrite+ xpc_object_t E2 = xpc_endpoint_create(L); // same listener (clone shape)+ mach_port_t copy = ep_port(E); // reuse L's send right+ *(uint32_t *)((char *)E2 + PORT_OFF) = copy;+ xpc_connection_t c2 = xpc_connection_create_from_endpoint((xpc_endpoint_t)E2);+ xpc_connection_set_event_handler(c2, ^(xpc_object_t e) {});+ xpc_connection_resume(c2);+ xpc_object_t msg2 = xpc_dictionary_create(NULL, NULL, 0);+ xpc_dictionary_set_string(msg2, "hello", "from-portswap");+ xpc_connection_send_message(c2, msg2);++ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3LL * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ printf(">>> done\n"); exit(0);+ });+ dispatch_main();+ return 0;+}diff --git a/VirtualMac/vz/development/probes/hid_event_layout.m b/VirtualMac/vz/development/probes/hid_event_layout.mnew file mode 100644index 0000000..db4d385--- /dev/null+++ b/VirtualMac/vz/development/probes/hid_event_layout.m@@ -0,0 +1,52 @@+#import <CoreFoundation/CoreFoundation.h>+#include <dlfcn.h>+#include <malloc/malloc.h>+#include <stdint.h>+#include <stdio.h>++typedef CFTypeRef (*CreateKeyboardEventFn)(+ CFAllocatorRef, uint64_t, uint32_t, uint32_t, Boolean, uint32_t);+typedef uint32_t (*GetEventTypeFn)(CFTypeRef);++static void dumpBytes(const char *label, const void *object, size_t limit) {+ size_t allocationSize = malloc_size(object);+ size_t dumpSize = allocationSize < limit ? allocationSize : limit;+ printf("%s=%p allocation=%zu dump=%zu\n",+ label, object, allocationSize, dumpSize);+ const uint8_t *bytes = (const uint8_t *)object;+ for (size_t offset = 0; offset < dumpSize; offset += 16) {+ printf("%04zx:", offset);+ size_t lineEnd = offset + 16 < dumpSize ? offset + 16 : dumpSize;+ for (size_t i = offset; i < lineEnd; i++)+ printf(" %02x", bytes[i]);+ putchar('\n');+ }+}++int main(void) {+ CreateKeyboardEventFn createKeyboardEvent =+ (CreateKeyboardEventFn)dlsym(RTLD_DEFAULT,+ "IOHIDEventCreateKeyboardEvent");+ GetEventTypeFn getEventType =+ (GetEventTypeFn)dlsym(RTLD_DEFAULT, "IOHIDEventGetType");+ if (!createKeyboardEvent || !getEventType) {+ fprintf(stderr, "IOHID event functions unavailable: %s\n", dlerror());+ return 1;+ }++ CFTypeRef event = createKeyboardEvent(+ kCFAllocatorDefault, 0, 0x07, 0x04, true, 0);+ if (!event) {+ fprintf(stderr, "IOHIDEventCreateKeyboardEvent returned NULL\n");+ return 1;+ }++ printf("type=%u\n", getEventType(event));+ dumpBytes("event", event, 512);+ const void *payload = *(const void *const *)((const uint8_t *)event + 0x68);+ if (payload)+ dumpBytes("payload", payload, 1024);+ CFShow(event);+ CFRelease(event);+ return 0;+}diff --git a/VirtualMac/vz/development/probes/hv.entitlements b/VirtualMac/vz/development/probes/hv.entitlementsnew file mode 100644index 0000000..71f3180--- /dev/null+++ b/VirtualMac/vz/development/probes/hv.entitlements@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.private.hypervisor</key>+ <true/>+ <key>com.apple.private.memorystatus</key>+ <true/>+ <key>platform-application</key>+ <true/>+ <key>com.apple.private.amfi.can-execute-cdhash</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/hvfeatures.c b/VirtualMac/vz/development/probes/hvfeatures.cnew file mode 100644index 0000000..0d81008--- /dev/null+++ b/VirtualMac/vz/development/probes/hvfeatures.c@@ -0,0 +1,19 @@+#include <Hypervisor/Hypervisor.h>+#include <inttypes.h>+#include <stdio.h>++int main(void) {+ hv_vcpu_config_t config = hv_vcpu_config_create();+ if (!config) {+ fprintf(stderr, "hv_vcpu_config_create returned NULL\n");+ return 1;+ }+ for (uint64_t reg = 0; reg <= 16; reg++) {+ uint64_t value = 0;+ hv_return_t rc = hv_vcpu_config_get_feature_reg(+ config, (hv_feature_reg_t)reg, &value);+ printf("reg=%" PRIu64 " rc=%d value=0x%016" PRIx64 "\n",+ reg, rc, value);+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/hvload.c b/VirtualMac/vz/development/probes/hvload.cnew file mode 100644index 0000000..48bf6f6--- /dev/null+++ b/VirtualMac/vz/development/probes/hvload.c@@ -0,0 +1,24 @@+// dlopen-load test for an extracted+stamped Hypervisor.framework on-device.+// Tells us exactly what dyld thinks of the reconstructed image.+#include <stdio.h>+#include <dlfcn.h>++int main(int argc, char **argv) {+ setvbuf(stdout, NULL, _IONBF, 0); // unbuffered: survive a crash over ssh+ const char *p = argc > 1 ? argv[1] : "/var/root/Hypervisor.ios";+ printf("dlopen(%s)...\n", p);+ void *h = dlopen(p, RTLD_NOW | RTLD_LOCAL);+ if (!h) {+ printf("dlopen FAILED: %s\n", dlerror());+ return 1;+ }+ printf("dlopen OK: handle=%p\n", h);+ void *f = dlsym(h, "hv_vm_create");+ printf("dlsym(hv_vm_create) = %p\n", f);+ if (f) {+ typedef int (*fn_t)(void *);+ int r = ((fn_t)f)(NULL); // real framework call → expect arg-validation err, not crash+ printf("hv_vm_create(NULL) = 0x%x\n", r);+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/hvprobe.c b/VirtualMac/vz/development/probes/hvprobe.cnew file mode 100644index 0000000..8e45349--- /dev/null+++ b/VirtualMac/vz/development/probes/hvprobe.c@@ -0,0 +1,35 @@+// hvprobe: confirm the iPad 16.3.1 kernel grants the host hypervisor to our signed binary.+// Mirrors UTM's Services/UTMJailbreak.m hv_trap (mach trap #-5). If this returns+// != HV_UNSUPPORTED, macOS Hypervisor (which funnels all hv_* through the+// same trap) will likely work on this device with com.apple.private.hypervisor.+#include <stdio.h>+#include <stdint.h>++#define HV_CALL_VM_GET_CAPABILITIES 0+#define HV_CALL_VM_CREATE 1+#define HV_UNSUPPORTED ((int32_t)0xfae9400f)++__attribute__((naked)) static uint64_t hv_trap(unsigned int hv_call, void *hv_arg) {+ __asm__ volatile(+ "mov x16, #-0x5\n" // mach trap #-5 (hv_trap)+ "svc #0x80\n"+ "ret\n");+}++int main(void) {+ int64_t caps = hv_trap(HV_CALL_VM_GET_CAPABILITIES, NULL); // exact UTM check+ printf("hv_trap(VM_GET_CAPABILITIES) = 0x%llx\n", (unsigned long long)caps);+ printf("HV_UNSUPPORTED = 0x%llx\n", (unsigned long long)(uint32_t)HV_UNSUPPORTED);++ if ((int32_t)caps == HV_UNSUPPORTED) {+ printf("RESULT: HV UNSUPPORTED — kernel denied the hypervisor to this process.\n");+ return 2;+ }+ printf("RESULT: HV AVAILABLE — kernel granted the hypervisor.\n");++ // Bonus: try to actually create a VM. Non-zero/!=UNSUPPORTED here = even stronger signal.+ int64_t vm = hv_trap(HV_CALL_VM_CREATE, NULL);+ printf("hv_trap(VM_CREATE, NULL) = 0x%llx (errno-ish; arg=NULL so may EINVAL, but not UNSUPPORTED)\n",+ (unsigned long long)vm);+ return 0;+}diff --git a/VirtualMac/vz/development/probes/hwprobe.m b/VirtualMac/vz/development/probes/hwprobe.mnew file mode 100644index 0000000..3b0c742--- /dev/null+++ b/VirtualMac/vz/development/probes/hwprobe.m@@ -0,0 +1,129 @@+// Diagnostic: replicate vzboot's exact config-build sequence step by step with per-step+// logging, to find which step turns subsequent VZMac* inits nil (vzboot crashes at @[disp]+// with supported=0, yet these inits work in isolation). Also verifies the protoref fix lets+// VZVirtualMachine init run past the old conformsToProtocol: crash.+#include <stdio.h>+#include <dlfcn.h>+#include <objc/runtime.h>+#include <objc/message.h>+#import <Foundation/Foundation.h>++static id CLS(const char *n) { return (id)objc_getClass(n); }+static id msg(id s, const char *sel) { return ((id(*)(id, SEL))objc_msgSend)(s, sel_registerName(sel)); }+static id alloc(const char *n) { return msg(CLS(n), "alloc"); }+static id NEW(const char *n) { return msg(alloc(n), "init"); }+static void setObj(id o, const char *sel, id v) { ((void(*)(id, SEL, id))objc_msgSend)(o, sel_registerName(sel), v); }+static id initData(const char *cls, NSData *d) {+ return ((id(*)(id, SEL, id))objc_msgSend)(alloc(cls), sel_registerName("initWithDataRepresentation:"), d);+}+static id fileURL(NSString *p) { return [NSURL fileURLWithPath:p]; }++#define B @"/var/root/VM.bundle"+#define P(name, val) printf("%-34s = %p\n", name, (void *)(val))++int main(int argc, char **argv) {+ setvbuf(stdout, NULL, _IONBF, 0);+ const char *fw[] = {"/var/root/Hypervisor.ios", "/var/root/ParavirtualizedGraphics.ios", "/var/root/Virtualization.ios"};+ for (int i = 0; i < 3; i++)+ if (!dlopen(fw[i], RTLD_NOW | RTLD_GLOBAL)) { printf("dlopen %s FAIL: %s\n", fw[i], dlerror()); return 1; }+ printf("frameworks loaded; +[VZVirtualMachine isSupported]=%d\n",+ ((BOOL(*)(id, SEL))objc_msgSend)(CLS("VZVirtualMachine"), sel_registerName("isSupported")));++ id platform = NEW("VZMacPlatformConfiguration"); P("platform", platform);+ id aux = ((id(*)(id, SEL, id))objc_msgSend)(alloc("VZMacAuxiliaryStorage"),+ sel_registerName("initWithContentsOfURL:"), fileURL([B stringByAppendingPathComponent:@"AuxiliaryStorage"]));+ P("aux (VZMacAuxiliaryStorage)", aux);+ setObj(platform, "setAuxiliaryStorage:", aux);++ NSData *hmData = [NSData dataWithContentsOfFile:[B stringByAppendingPathComponent:@"HardwareModel"]];+ id hwModel = initData("VZMacHardwareModel", hmData);+ printf("hwModel=%p supported=%d (hmData.len=%lu)\n", (void *)hwModel,+ hwModel ? ((BOOL(*)(id, SEL))objc_msgSend)(hwModel, sel_registerName("isSupported")) : 0,+ (unsigned long)hmData.length);+ setObj(platform, "setHardwareModel:", hwModel);+ id mid = initData("VZMacMachineIdentifier", [NSData dataWithContentsOfFile:[B stringByAppendingPathComponent:@"MachineIdentifier"]]);+ P("machineIdentifier", mid);+ setObj(platform, "setMachineIdentifier:", mid);++ id config = NEW("VZVirtualMachineConfiguration"); P("config", config);+ setObj(config, "setPlatform:", platform);+ ((void(*)(id, SEL, NSUInteger))objc_msgSend)(config, sel_registerName("setCPUCount:"), 2);+ ((void(*)(id, SEL, unsigned long long))objc_msgSend)(config, sel_registerName("setMemorySize:"), 4ULL << 30);+ setObj(config, "setBootLoader:", NEW("VZMacOSBootLoader"));++ // VZ_NO_GFX=1 drops the graphics device so the VMM doesn't look up the+ // "com.apple.virtualization.avp.paravirtualized-graphics-gpu-arm" device-type+ // (which ParavirtualizedGraphics.ios doesn't register on iPad — see vz-start-progress+ // memo). Without gfx the guest boots headless; useful for proving the VM otherwise runs.+ if (!getenv("VZ_NO_GFX")) {+ id gfx = NEW("VZMacGraphicsDeviceConfiguration"); P("gfx", gfx);+ id disp = ((id(*)(id, SEL, NSInteger, NSInteger, NSInteger))objc_msgSend)(alloc("VZMacGraphicsDisplayConfiguration"),+ sel_registerName("initWithWidthInPixels:heightInPixels:pixelsPerInch:"), 1920, 1200, 80);+ P("disp", disp);+ if (disp) setObj(gfx, "setDisplays:", @[disp]); else printf(" !! disp nil -> would crash @[disp]\n");+ if (gfx) setObj(config, "setGraphicsDevices:", @[gfx]);+ } else {+ printf(">>> VZ_NO_GFX=1 -> skipping VZMacGraphicsDeviceConfiguration (headless test)\n");+ }++ NSError *err = nil;+ id diskAtt = ((id(*)(id, SEL, id, BOOL, NSError **))objc_msgSend)(alloc("VZDiskImageStorageDeviceAttachment"),+ sel_registerName("initWithURL:readOnly:error:"), fileURL([B stringByAppendingPathComponent:@"Disk.img"]), NO, &err);+ P("diskAtt", diskAtt);+ if (diskAtt) {+ id block = ((id(*)(id, SEL, id))objc_msgSend)(alloc("VZVirtioBlockDeviceConfiguration"),+ sel_registerName("initWithAttachment:"), diskAtt);+ setObj(config, "setStorageDevices:", @[block]);+ } else printf(" disk err: %s\n", [[err localizedDescription] UTF8String]);++ id kbd = NEW("VZUSBKeyboardConfiguration"); if (kbd) setObj(config, "setKeyboards:", @[kbd]);+ id pdev = NEW("VZUSBScreenCoordinatePointingDeviceConfiguration"); if (pdev) setObj(config, "setPointingDevices:", @[pdev]);+ P("kbd", kbd); P("pdev", pdev);++ printf(">>> validateWithError: (exercises config validation)...\n");+ NSError *verr = nil;+ BOOL ok = ((BOOL(*)(id, SEL, NSError **))objc_msgSend)(config, sel_registerName("validateWithError:"), &verr);+ printf(" validate ok=%d%s\n", ok, ok ? "" : [[NSString stringWithFormat:@" -- %@", [verr localizedDescription]] UTF8String]);++ printf(">>> creating VZVirtualMachine with a real queue (exercises the protoref/conformsToProtocol path)...\n");+ dispatch_queue_t q = dispatch_queue_create("vm.q", DISPATCH_QUEUE_SERIAL);+ id vm = ((id(*)(id, SEL, id, dispatch_queue_t))objc_msgSend)(alloc("VZVirtualMachine"),+ sel_registerName("initWithConfiguration:queue:"), config, q);+ P("VZVirtualMachine vm", vm);+ printf(">>> DONE (reached past VZVirtualMachine init — protoref/conformsToProtocol survived)\n");++ if (getenv("VZ_START")) {+ // [vm start] reaches the VMM via xpc_connection_create("com.apple.Virtualization.+ // VirtualMachine"); with DYLD_INSERT_LIBRARIES=vzxpchook.ios that's redirected to the+ // launchd MachService org.jb.vmmservice (the rebooted-in VMM daemon).+ __block BOOL canStart = NO; // VZ asserts queue affinity: all vm methods must run on q+ dispatch_sync(q, ^{ canStart = ((BOOL(*)(id, SEL))objc_msgSend)(vm, sel_registerName("canStart")); });+ printf(">>> canStart=%d ; calling startWithCompletionHandler: on the VM queue...\n", canStart);+ dispatch_semaphore_t done = dispatch_semaphore_create(0);+ void (^h)(id) = ^(id err) {+ if (err) {+ id d = ((id(*)(id, SEL))objc_msgSend)(err, sel_registerName("localizedDescription"));+ printf(">>> START COMPLETION: FAILED: %s\n", d ? [(NSString *)d UTF8String] : "(no description)");+ } else {+ printf(">>> START COMPLETION: SUCCESS — VM started\n");+ }+ dispatch_semaphore_signal(done);+ };+ dispatch_async(q, ^{+ ((void(*)(id, SEL, id))objc_msgSend)(vm, sel_registerName("startWithCompletionHandler:"), h);+ });+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 30LL * NSEC_PER_SEC)))+ printf(">>> start completion did NOT fire within 30s (hung in the VMM connection?)\n");+ dispatch_sync(q, ^{+ long st = ((long(*)(id, SEL))objc_msgSend)(vm, sel_registerName("state"));+ printf(">>> vm.state = %ld (0=stopped 1=running 2=paused 3=error 4=starting 7=stopping)\n", st);+ });+ printf(">>> letting the guest run for 15s...\n");+ sleep(15);+ dispatch_sync(q, ^{+ long st = ((long(*)(id, SEL))objc_msgSend)(vm, sel_registerName("state"));+ printf(">>> vm.state after 15s = %ld\n", st);+ });+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/internet_sharing_startup.lldb b/VirtualMac/vz/development/probes/internet_sharing_startup.lldbnew file mode 100644index 0000000..cb973f2--- /dev/null+++ b/VirtualMac/vz/development/probes/internet_sharing_startup.lldb@@ -0,0 +1,6 @@+settings set target.inline-breakpoint-strategy always+breakpoint set -a 0x10001cd48 -s InternetSharing -i 1+continue+register read x0 x1+memory read --format c --size 1 --count 96 $x1+thread backtracediff --git a/VirtualMac/vz/development/probes/macload.c b/VirtualMac/vz/development/probes/macload.cnew file mode 100644index 0000000..d244142--- /dev/null+++ b/VirtualMac/vz/development/probes/macload.c@@ -0,0 +1,13 @@+#include <stdio.h>+#include <dlfcn.h>+extern void* objc_getClass(const char*);+int main(int c,char**v){+ setvbuf(stdout,0,_IONBF,0);+ void*h=dlopen(v[1], RTLD_NOW|RTLD_LOCAL);+ if(!h){printf("FAIL: %s\n",dlerror());return 1;}+ printf("dlopen OK\n");+ const char*names[]={"OS_hv_vm_config","OS_hv_vcpu_config","OS_hv_vm_space_config"};+ for(int i=0;i<3;i++){ void*cls=objc_getClass(names[i]); printf(" class %s = %p\n",names[i],cls); }+ void*f=dlsym(h,"hv_vm_create"); printf("hv_vm_create=%p\n",f);+ return 0;+}diff --git a/VirtualMac/vz/development/probes/metal-bc-probe.m b/VirtualMac/vz/development/probes/metal-bc-probe.mnew file mode 100644index 0000000..ab754b4--- /dev/null+++ b/VirtualMac/vz/development/probes/metal-bc-probe.m@@ -0,0 +1,21 @@+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>++int main(void)+{+ @autoreleasepool {+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();+ MTLTextureDescriptor *descriptor = [[MTLTextureDescriptor alloc] init];+ descriptor.textureType = MTLTextureType2D;+ descriptor.pixelFormat = (MTLPixelFormat)152; // BC7 RGBA, Mac only+ descriptor.width = 64;+ descriptor.height = 64;+ descriptor.mipmapLevelCount = 1;+ descriptor.usage = MTLTextureUsageShaderRead;+ id<MTLTexture> texture = [device newTextureWithDescriptor:descriptor];+ fprintf(stderr, "metal-bc-probe device=%s format=%lu texture=%p\n",+ device.name.UTF8String, (unsigned long)descriptor.pixelFormat,+ texture);+ return texture ? 0 : 1;+ }+}diff --git a/VirtualMac/vz/development/probes/metal_library.m b/VirtualMac/vz/development/probes/metal_library.mnew file mode 100644index 0000000..827a209--- /dev/null+++ b/VirtualMac/vz/development/probes/metal_library.m@@ -0,0 +1,43 @@+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>++int main(int argc, const char *argv[]) {+ @autoreleasepool {+ if (argc != 2) {+ fprintf(stderr, "usage: metal-library /path/to/default.metallib\n");+ return 2;+ }++ NSString *path = [NSString stringWithUTF8String:argv[1]];+ NSURL *url = [NSURL fileURLWithPath:path];+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();+ if (device == nil) {+ fprintf(stderr, "METAL_DEVICE\t(null)\n");+ return 1;+ }++ NSError *error = nil;+ id<MTLLibrary> library = [device newLibraryWithURL:url error:&error];+ printf("METAL_DEVICE\t%s\n", device.name.UTF8String);+ printf("METALLIB_PATH\t%s\n", url.path.UTF8String);+ printf("METALLIB_RESULT\t%s\n", library != nil ? "loaded" : "failed");+ if (error != nil) {+ printf("METALLIB_ERROR_DOMAIN\t%s\n", error.domain.UTF8String);+ printf("METALLIB_ERROR_CODE\t%ld\n", (long)error.code);+ printf("METALLIB_ERROR\t%s\n", error.description.UTF8String);+ }+ if (library == nil) {+ return 1;+ }++ NSArray<NSString *> *names = [library.functionNames sortedArrayUsingSelector:@selector(compare:)];+ printf("METALLIB_FUNCTION_COUNT\t%lu\n", (unsigned long)names.count);+ for (NSString *name in names) {+ id<MTLFunction> function = [library newFunctionWithName:name];+ printf("METALLIB_FUNCTION\t%s\t%s\n",+ name.UTF8String,+ function != nil ? "loaded" : "failed");+ }+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/net_interfaces.c b/VirtualMac/vz/development/probes/net_interfaces.cnew file mode 100644index 0000000..c4b04c1--- /dev/null+++ b/VirtualMac/vz/development/probes/net_interfaces.c@@ -0,0 +1,31 @@+#include <arpa/inet.h>+#include <ifaddrs.h>+#include <net/if.h>+#include <stdio.h>+#include <stdlib.h>+#include <sys/socket.h>++int main(void) {+ struct ifaddrs *interfaces = NULL;+ if (getifaddrs(&interfaces) != 0) {+ perror("getifaddrs");+ return 1;+ }+ for (const struct ifaddrs *item = interfaces; item; item = item->ifa_next) {+ if (!item->ifa_addr)+ continue;+ int family = item->ifa_addr->sa_family;+ if (family != AF_INET && family != AF_INET6)+ continue;+ char address[INET6_ADDRSTRLEN] = {0};+ const void *bytes = family == AF_INET+ ? (const void *)&((const struct sockaddr_in *)item->ifa_addr)->sin_addr+ : (const void *)&((const struct sockaddr_in6 *)item->ifa_addr)->sin6_addr;+ if (!inet_ntop(family, bytes, address, sizeof(address)))+ continue;+ printf("%s\t%s\tflags=0x%x\n", item->ifa_name, address,+ item->ifa_flags);+ }+ freeifaddrs(interfaces);+ return 0;+}diff --git a/VirtualMac/vz/development/probes/netrb-native-probe-launchd.plist b/VirtualMac/vz/development/probes/netrb-native-probe-launchd.plistnew file mode 100644index 0000000..c66af74--- /dev/null+++ b/VirtualMac/vz/development/probes/netrb-native-probe-launchd.plist@@ -0,0 +1,20 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.mac.virtual.netrb-native-probe</string>+ <key>ProgramArguments</key>+ <array>+ <string>/var/jb/usr/local/bin/netrb-native-interface-probe</string>+ </array>+ <key>RunAtLoad</key>+ <true/>+ <key>StandardOutPath</key>+ <string>/tmp/netrb-native-interface-probe.log</string>+ <key>StandardErrorPath</key>+ <string>/tmp/netrb-native-interface-probe.log</string>+ <key>ProcessType</key>+ <string>Interactive</string>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/netrb-native-probe.ents.xml b/VirtualMac/vz/development/probes/netrb-native-probe.ents.xmlnew file mode 100644index 0000000..9616869--- /dev/null+++ b/VirtualMac/vz/development/probes/netrb-native-probe.ents.xml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>platform-application</key>+ <true/>+ <key>get-task-allow</key>+ <true/>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.MobileInternetSharing.allow</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/netrb_native_interface_probe.c b/VirtualMac/vz/development/probes/netrb_native_interface_probe.cnew file mode 100644index 0000000..87c18f7--- /dev/null+++ b/VirtualMac/vz/development/probes/netrb_native_interface_probe.c@@ -0,0 +1,79 @@+#include <dispatch/dispatch.h>+#include <dlfcn.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <unistd.h>+#include <xpc/xpc.h>++typedef void *(*client_create_fn)(dispatch_queue_t, void (^)(xpc_object_t),+ uint64_t);+typedef void (*client_destroy_fn)(void *);+typedef bool (*setup_and_send_fn)(dispatch_queue_t, xpc_object_t,+ void (^)(xpc_object_t));++int main(void) {+ setbuf(stdout, NULL);+ setbuf(stderr, NULL);+ void *image = dlopen(+ "/System/Library/PrivateFrameworks/Netrb.framework/Netrb",+ RTLD_NOW | RTLD_LOCAL);+ if (!image) {+ fprintf(stderr, "native Netrb dlopen failed: %s\n", dlerror());+ return 1;+ }+ client_create_fn create = (client_create_fn)dlsym(+ image, "_NETRBClientCreate");+ client_destroy_fn destroy = (client_destroy_fn)dlsym(+ image, "_NETRBClientDestroy");+ setup_and_send_fn send = (setup_and_send_fn)dlsym(+ image, "NETRBXPCSetupAndSend");+ if (!create || !destroy || !send) {+ fprintf(stderr, "native Netrb symbols unavailable create=%p "+ "destroy=%p send=%p\n", create, destroy, send);+ return 2;+ }+ dispatch_queue_t queue = dispatch_queue_create(+ "com.mac.virtual.netrb-native-probe", DISPATCH_QUEUE_SERIAL);+ void *client = create(queue, ^(xpc_object_t notification) {+ char *text = notification ? xpc_copy_description(notification) : NULL;+ printf("native Netrb notification: %s\n", text ?: "(null)");+ free(text);+ }, 0);+ if (!client) {+ fprintf(stderr, "native Netrb client create failed\n");+ return 3;+ }+ const char *clientID = (const char *)client + 0x20;+ printf("native Netrb client=%p id=%s\n", client, clientID);++ xpc_object_t request = xpc_dictionary_create(NULL, NULL, 0);+ xpc_dictionary_set_uint64(request, "xpcKey", 1014);+ xpc_dictionary_set_uint64(request, "opMode", 201);+ xpc_dictionary_set_string(request, "clientid", clientID);+ __block xpc_object_t reply = NULL;+ bool sent = send(NULL, request, ^(xpc_object_t response) {+ if (response)+ reply = xpc_retain(response);+ });+ char *requestText = xpc_copy_description(request);+ char *replyText = reply ? xpc_copy_description(reply) : NULL;+ printf("native Netrb operation 1014 sent=%d\nrequest=%s\nreply=%s\n",+ sent, requestText ?: "(null)", replyText ?: "(null)");+ free(requestText);+ free(replyText);+ uint64_t responseCode = reply+ ? xpc_dictionary_get_uint64(reply, "response") : 0;+ int interfaceFD = reply+ ? xpc_dictionary_dup_fd(reply, "interface_socket") : -1;+ printf("native Netrb response=%llu interface_socket=%d\n",+ (unsigned long long)responseCode, interfaceFD);+ if (interfaceFD >= 0)+ close(interfaceFD);+ if (reply)+ xpc_release(reply);+ xpc_release(request);+ destroy(client);+ return responseCode == 2001 && interfaceFD >= 0 ? 0 : 4;+}diff --git a/VirtualMac/vz/development/probes/ns.entitlements b/VirtualMac/vz/development/probes/ns.entitlementsnew file mode 100644index 0000000..d0ff293--- /dev/null+++ b/VirtualMac/vz/development/probes/ns.entitlements@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>com.apple.private.hypervisor</key><true/>+<key>com.apple.private.memorystatus</key><true/>+<key>com.apple.private.security.no-sandbox</key><true/>+<key>com.apple.private.security.no-container</key><true/>+<key>platform-application</key><true/>+<key>com.apple.private.amfi.can-execute-cdhash</key><true/>+</dict></plist>diff --git a/VirtualMac/vz/development/probes/objc_methods.m b/VirtualMac/vz/development/probes/objc_methods.mnew file mode 100644index 0000000..e95cef1--- /dev/null+++ b/VirtualMac/vz/development/probes/objc_methods.m@@ -0,0 +1,99 @@+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#import <UIKit/UIKit.h>+#import "../../host/NSViewShim.h"+#import <dlfcn.h>+#import <objc/runtime.h>+#import <objc/message.h>++int main(int argc, const char *argv[])+{+ @autoreleasepool {+ if (argc < 3) {+ fprintf(stderr, "usage: %s /path/to/image [...] ClassName\n", argv[0]);+ return 2;+ }++ printf("FAKE_CLASS\tNSView\tsuperclass=%s\tinstance-size=%zu\n",+ class_getName(class_getSuperclass([NSView class])),+ class_getInstanceSize([NSView class]));+ for (int i = 1; i < argc - 1; i++) {+ void *image = dlopen(argv[i], RTLD_NOW | RTLD_GLOBAL);+ if (!image) {+ fprintf(stderr, "dlopen %s failed: %s\n", argv[i], dlerror());+ return 1;+ }+ }++ const char *className = argv[argc - 1];+ Class cls = objc_getClass(className);+ const char *metalDevice = getenv("VZ_METAL_DEVICE");+ if (metalDevice && metalDevice[0] && metalDevice[0] != '0') {+ id device = MTLCreateSystemDefaultDevice();+ printf("METAL_DEVICE\t%s\t%p\n",+ device ? class_getName(object_getClass(device)) : "-",+ device);+ if (device) {+ cls = object_getClass(device);+ }+ }+ if (!cls) {+ fprintf(stderr, "class not found: %s\n", className);+ return 1;+ }++ printf("CLASS\t%s\tinstance-size=%zu\tsuperclass=%s\n",+ class_getName(cls),+ class_getInstanceSize(cls),+ class_getSuperclass(cls) ? class_getName(class_getSuperclass(cls)) : "-");++ unsigned int count = 0;+ Method *methods = class_copyMethodList(cls, &count);+ for (unsigned int i = 0; i < count; i++) {+ SEL selector = method_getName(methods[i]);+ IMP implementation = method_getImplementation(methods[i]);+ Dl_info info = {0};+ dladdr((const void *)implementation, &info);+ uintptr_t offset = (uintptr_t)implementation - (uintptr_t)info.dli_fbase;+ printf("METHOD\t%s\t0x%llx\t%s\n",+ sel_getName(selector),+ (unsigned long long)offset,+ info.dli_fname ?: "?");+ }+ free(methods);++ Ivar *ivars = class_copyIvarList(cls, &count);+ for (unsigned int i = 0; i < count; i++) {+ printf("IVAR\t%s\t%s\t%td\n",+ ivar_getName(ivars[i]),+ ivar_getTypeEncoding(ivars[i]),+ ivar_getOffset(ivars[i]));+ }+ free(ivars);++ objc_property_t *properties = class_copyPropertyList(cls, &count);+ for (unsigned int i = 0; i < count; i++) {+ printf("PROPERTY\t%s\t%s\n",+ property_getName(properties[i]),+ property_getAttributes(properties[i]));+ }+ free(properties);++ const char *instantiate = getenv("VZ_INSTANTIATE");+ if (instantiate && instantiate[0] && instantiate[0] != '0') {+ @try {+ id object = ((id(*)(id, SEL, CGRect))objc_msgSend)(+ [cls alloc], sel_registerName("initWithFrame:"),+ CGRectMake(0, 0, 1024, 768));+ printf("INSTANCE\t%s\t%p\t%s\n",+ className, object, [[object description] UTF8String]);+ } @catch (NSException *exception) {+ printf("INSTANCE_EXCEPTION\t%s\t%s\n",+ [[exception name] UTF8String],+ [[exception reason] UTF8String]);+ return 1;+ }+ }+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/oracle_images.m b/VirtualMac/vz/development/probes/oracle_images.mnew file mode 100644index 0000000..ad20500--- /dev/null+++ b/VirtualMac/vz/development/probes/oracle_images.m@@ -0,0 +1,106 @@+#include <dlfcn.h>+#include <mach-o/dyld.h>+#include <mach-o/loader.h>+#include <objc/message.h>+#include <objc/runtime.h>+#include <stdint.h>+#include <stdio.h>+#include <string.h>++static void print_uuid(const struct mach_header_64 *mh)+{+ const uint8_t *p = (const uint8_t *)(mh + 1);+ for (uint32_t i = 0; i < mh->ncmds; i++) {+ const struct load_command *lc = (const struct load_command *)p;+ if (lc->cmd == LC_UUID) {+ const struct uuid_command *uc = (const struct uuid_command *)p;+ for (unsigned j = 0; j < sizeof(uc->uuid); j++) {+ printf("%02X", uc->uuid[j]);+ if (j == 3 || j == 5 || j == 7 || j == 9)+ putchar('-');+ }+ return;+ }+ p += lc->cmdsize;+ }+ printf("none");+}++static void print_build_version(const struct mach_header_64 *mh)+{+ const uint8_t *p = (const uint8_t *)(mh + 1);+ for (uint32_t i = 0; i < mh->ncmds; i++) {+ const struct load_command *lc = (const struct load_command *)p;+ if (lc->cmd == LC_BUILD_VERSION) {+ const struct build_version_command *bc =+ (const struct build_version_command *)p;+ printf("%u\t%u.%u.%u\t%u.%u.%u",+ bc->platform,+ bc->minos >> 16, (bc->minos >> 8) & 0xff, bc->minos & 0xff,+ bc->sdk >> 16, (bc->sdk >> 8) & 0xff, bc->sdk & 0xff);+ return;+ }+ p += lc->cmdsize;+ }+ printf("none\tnone\tnone");+}++static int inspect(const char *label, const char *path, const char *symbol)+{+ dlerror();+ void *handle = dlopen(path, RTLD_NOW | RTLD_GLOBAL);+ if (!handle) {+ printf("LOAD\t%s\tFAIL\t%s\n", label, dlerror());+ return 1;+ }++ void *address = dlsym(handle, symbol);+ if (!address) {+ printf("LOAD\t%s\tNOSYMBOL\t%s\n", label, symbol);+ return 1;+ }++ Dl_info info = {0};+ if (!dladdr(address, &info) || !info.dli_fbase) {+ printf("LOAD\t%s\tNODLADDR\t%s\n", label, symbol);+ return 1;+ }++ const struct mach_header_64 *mh =+ (const struct mach_header_64 *)info.dli_fbase;+ printf("IMAGE\t%s\t%s\t", label, info.dli_fname ?: "(unknown)");+ print_uuid(mh);+ putchar('\t');+ print_build_version(mh);+ printf("\t%s\t%p\n", symbol, address);+ return 0;+}++int main(void)+{+ setvbuf(stdout, NULL, _IONBF, 0);++ int failures = 0;+ failures += inspect(+ "Hypervisor",+ "/System/Library/Frameworks/Hypervisor.framework/Versions/A/Hypervisor",+ "hv_vm_create");+ failures += inspect(+ "ParavirtualizedGraphics",+ "/System/Library/Frameworks/ParavirtualizedGraphics.framework/Versions/A/ParavirtualizedGraphics",+ "PGNewDeviceWithDescriptor");+ failures += inspect(+ "Virtualization",+ "/System/Library/Frameworks/Virtualization.framework/Versions/A/Virtualization",+ "VZErrorDomain");++ Class vm = objc_getClass("VZVirtualMachine");+ BOOL supported = NO;+ if (vm != Nil) {+ SEL sel = sel_registerName("isSupported");+ supported = ((BOOL (*)(id, SEL))objc_msgSend)((id)vm, sel);+ }+ printf("VZ\tclass=%p\tisSupported=%d\n", vm, supported);+ return failures ? 1 : 0;+}+diff --git a/VirtualMac/vz/development/probes/prepare_vm.m b/VirtualMac/vz/development/probes/prepare_vm.mnew file mode 100644index 0000000..f89c130--- /dev/null+++ b/VirtualMac/vz/development/probes/prepare_vm.m@@ -0,0 +1,92 @@+#import <Foundation/Foundation.h>+#import <Virtualization/Virtualization.h>++static void fail(NSString *message)+{+ fprintf(stderr, "error: %s\n", message.UTF8String);+ exit(1);+}++int main(int argc, const char *argv[])+{+ @autoreleasepool {+ if (argc != 3) {+ fprintf(stderr, "usage: prepare-vm <restore.ipsw> <VM.bundle>\n");+ return 2;+ }++ NSURL *restoreURL = [NSURL fileURLWithPath:@(argv[1])];+ NSURL *bundleURL = [NSURL fileURLWithPath:@(argv[2]) isDirectory:YES];+ NSFileManager *fm = NSFileManager.defaultManager;+ NSError *error = nil;+ if (![fm createDirectoryAtURL:bundleURL+ withIntermediateDirectories:YES attributes:nil error:&error])+ fail(error.localizedDescription);++ dispatch_semaphore_t loaded = dispatch_semaphore_create(0);+ __block VZMacOSRestoreImage *image = nil;+ __block NSError *loadError = nil;+ [VZMacOSRestoreImage loadFileURL:restoreURL+ completionHandler:^(VZMacOSRestoreImage *value, NSError *valueError) {+ image = value;+ loadError = valueError;+ dispatch_semaphore_signal(loaded);+ }];+ dispatch_semaphore_wait(loaded, DISPATCH_TIME_FOREVER);+ if (!image)+ fail([NSString stringWithFormat:@"restore image load failed: %@", loadError]);++ VZMacOSConfigurationRequirements *requirements =+ image.mostFeaturefulSupportedConfiguration;+ if (!requirements)+ fail(@"restore image has no configuration supported by this Mac");++ VZMacHardwareModel *hardwareModel = requirements.hardwareModel;+ VZMacMachineIdentifier *machineIdentifier =+ [[VZMacMachineIdentifier alloc] init];+ NSURL *hardwareURL =+ [bundleURL URLByAppendingPathComponent:@"HardwareModel"];+ NSURL *identifierURL =+ [bundleURL URLByAppendingPathComponent:@"MachineIdentifier"];+ NSURL *auxiliaryURL =+ [bundleURL URLByAppendingPathComponent:@"AuxiliaryStorage"];++ if (![hardwareModel.dataRepresentation writeToURL:hardwareURL+ options:NSDataWritingAtomic+ error:&error])+ fail(error.localizedDescription);+ if (![machineIdentifier.dataRepresentation writeToURL:identifierURL+ options:NSDataWritingAtomic+ error:&error])+ fail(error.localizedDescription);++ if (![fm fileExistsAtPath:auxiliaryURL.path]) {+ VZMacAuxiliaryStorage *auxiliaryStorage =+ [[VZMacAuxiliaryStorage alloc]+ initCreatingStorageAtURL:auxiliaryURL+ hardwareModel:hardwareModel+ options:0+ error:&error];+ if (!auxiliaryStorage)+ fail([NSString stringWithFormat:+ @"auxiliary storage creation failed: %@", error]);+ printf("AUXILIARY_STORAGE\tcreated\t%s\n",+ auxiliaryURL.path.UTF8String);+ } else {+ printf("AUXILIARY_STORAGE\texisting\t%s\n",+ auxiliaryURL.path.UTF8String);+ }++ printf("RESTORE\t%s\t%s\n",+ image.buildVersion.UTF8String,+ image.isSupported ? "supported" : "unsupported");+ printf("REQUIREMENTS\tcpu=%lu\tmemory=%llu\n",+ (unsigned long)requirements.minimumSupportedCPUCount,+ requirements.minimumSupportedMemorySize);+ printf("HARDWARE_MODEL\tbytes=%lu\tsupported=%d\n",+ (unsigned long)hardwareModel.dataRepresentation.length,+ hardwareModel.isSupported);+ printf("VM_METADATA_READY\t%s\n", bundleURL.path.UTF8String);+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/pvg_trace_lldb.py b/VirtualMac/vz/development/probes/pvg_trace_lldb.pynew file mode 100644index 0000000..39bcfdd--- /dev/null+++ b/VirtualMac/vz/development/probes/pvg_trace_lldb.py@@ -0,0 +1,207 @@+import lldb+++PVG_OFFSETS = {+ "init-entry": 0xE94C,+ "first-setup-result": 0xEC20,+ "second-setup-result": 0xEC2C,+ "init-failure": 0xEC3C,+ "init-success": 0xEC48,+ "blit-entry": 0xECD4,+ "blit-bundle": 0xED1C,+ "display-bundle": 0xE6D0,+ "blit-library-call": 0xED24,+ "blit-library-result": 0xED2C,+ "blit-in-function-result": 0xED44,+ "blit-in-pipeline-result": 0xED58,+ "blit-out-function-result": 0xED70,+ "blit-out-pipeline-result": 0xED84,+ "blit-in-error": 0xED90,+ "blit-out-error": 0xEDB8,+ "blit-result": 0xEDD4,+ "reporting-entry": 0xEE04,+ "reporting-result": 0xEEE0,+ "library-selector-stub": 0x3E6C8,+}++BREAKPOINT_NAMES = {}+USE_SYSTEM_RESOURCE_BUNDLE = False+USE_MAIN_RESOURCE_BUNDLE = False+++def _register(frame, name):+ value = frame.FindRegister(name)+ return value.GetValue() if value.IsValid() else "?"+++def trace_callback(frame, bp_loc, _internal_dict):+ bp_id = bp_loc.GetBreakpoint().GetID()+ name = BREAKPOINT_NAMES.get(bp_id, "unknown")+ print(+ "PVG_BREAK\t{}\tpc={}\tx0={}\tx2={}\tx19={}\tx20={}\tsp={}".format(+ name,+ _register(frame, "pc"),+ _register(frame, "x0"),+ _register(frame, "x2"),+ _register(frame, "x19"),+ _register(frame, "x20"),+ _register(frame, "sp"),+ ),+ flush=True,+ )+ if name in {+ "blit-bundle-and-device",+ "blit-library-result",+ "blit-in-pipeline-result",+ "blit-out-pipeline-result",+ "blit-in-error",+ "blit-out-error",+ }:+ error = frame.EvaluateExpression(+ "(id)*(void **)($sp + 8)",+ lldb.SBExpressionOptions(),+ )+ print(+ "PVG_ERROR\t{}\tvalue={}\tdescription={}".format(+ name,+ error.GetValue() or "?",+ error.GetObjectDescription() or "?",+ ),+ flush=True,+ )+ if name in {"blit-bundle", "blit-bundle-and-device", "blit-device"}:+ device = frame.EvaluateExpression("(id)$x0")+ bundle = frame.EvaluateExpression("(id)$x2")+ bundle_path = frame.EvaluateExpression("[(id)$x2 bundlePath]")+ print(+ "PVG_OBJECTS\tdevice={}\tbundle={}\tbundlePath={}".format(+ device.GetObjectDescription() or "?",+ bundle.GetObjectDescription() or "?",+ bundle_path.GetObjectDescription() or "?",+ ),+ flush=True,+ )+ if name == "blit-device":+ cls = frame.EvaluateExpression("(void *)[(id)$x0 class]")+ implementation = frame.EvaluateExpression(+ "(void *)[(id)$x0 "+ "methodForSelector:@selector(newDefaultLibraryWithBundle:error:)]"+ )+ print(+ "PVG_DEVICE\tclass={}\timplementation={}".format(+ cls.GetValue() or "?",+ implementation.GetValue() or "?",+ ),+ flush=True,+ )+ if name in {"blit-bundle", "display-bundle"} and USE_SYSTEM_RESOURCE_BUNDLE:+ system_bundle = frame.EvaluateExpression(+ "(void *)[NSBundle bundleWithPath:"+ '@"/System/Library/Frameworks/ParavirtualizedGraphics.framework"]'+ )+ pointer = system_bundle.GetValue()+ changed = frame.FindRegister("x2").SetValueFromCString(pointer)+ print(+ "PVG_OVERRIDE\tsystem-resource-bundle={}\tchanged={}".format(+ pointer,+ changed,+ ),+ flush=True,+ )+ if name in {"blit-bundle", "display-bundle"} and USE_MAIN_RESOURCE_BUNDLE:+ main_bundle = frame.EvaluateExpression("(void *)[NSBundle mainBundle]")+ pointer = main_bundle.GetValue()+ changed = frame.FindRegister("x2").SetValueFromCString(pointer)+ print(+ "PVG_OVERRIDE\tmain-resource-bundle={}\tchanged={}".format(+ pointer,+ changed,+ ),+ flush=True,+ )+ if name == "library-selector-stub":+ selector_name = frame.EvaluateExpression("(const char *)sel_getName((SEL)$x1)")+ implementation = frame.EvaluateExpression(+ "(void *)[(id)$x0 methodForSelector:(SEL)$x1]"+ )+ print(+ "PVG_SELECTOR\tx1={}\tname={}\timplementation={}".format(+ _register(frame, "x1"),+ selector_name.GetSummary() or selector_name.GetValue() or "?",+ implementation.GetValue() or "?",+ ),+ flush=True,+ )+ if name == "blit-library-call":+ process = frame.GetThread().GetProcess()+ error = lldb.SBError()+ pc = int(_register(frame, "pc"), 16)+ instruction = process.ReadUnsignedFromMemory(pc, 4, error)+ immediate = instruction & 0x03FFFFFF+ if immediate & 0x02000000:+ immediate -= 0x04000000+ target = pc + immediate * 4+ print(+ "PVG_CALL\tinstruction=0x{:08x}\ttarget=0x{:x}\terror={}".format(+ instruction,+ target,+ error.GetCString() or "none",+ ),+ flush=True,+ )+ return False+++def install_pvg_breakpoints(debugger, _command, result, _internal_dict):+ target = debugger.GetSelectedTarget()+ process = target.GetProcess()+ module = None+ debugger.SetAsync(False)+ debugger.HandleCommand(+ "settings set target.process.stop-on-sharedlibrary-events true"+ )++ for _ in range(512):+ for candidate in target.module_iter():+ if candidate.GetFileSpec().GetFilename() == "ParavirtualizedGraphics":+ module = candidate+ break+ if module is not None:+ break+ if process.GetState() != lldb.eStateStopped:+ result.SetError("VMM stopped before ParavirtualizedGraphics loaded")+ return+ process.Continue()++ if module is None:+ result.SetError("ParavirtualizedGraphics did not load")+ return++ header = module.GetObjectFileHeaderAddress().GetLoadAddress(target)+ print("PVG_MODULE\tbase=0x{:x}\tpath={}".format(header, module.GetFileSpec()), flush=True)+ for name, offset in PVG_OFFSETS.items():+ breakpoint = target.BreakpointCreateByAddress(header + offset)+ breakpoint.SetScriptCallbackFunction(+ "pvg_trace_lldb.trace_callback"+ )+ BREAKPOINT_NAMES[breakpoint.GetID()] = name+ print(+ "PVG_BP\t{}\tid={}\taddress=0x{:x}\tlocations={}".format(+ name,+ breakpoint.GetID(),+ header + offset,+ breakpoint.GetNumLocations(),+ ),+ flush=True,+ )++ debugger.HandleCommand(+ "settings set target.process.stop-on-sharedlibrary-events false"+ )+ result.AppendMessage("PVG breakpoints installed")+++def __lldb_init_module(debugger, _internal_dict):+ debugger.HandleCommand(+ "command script add -f pvg_trace_lldb.install_pvg_breakpoints install-pvg-breakpoints"+ )diff --git a/VirtualMac/vz/development/probes/restore_image_probe.m b/VirtualMac/vz/development/probes/restore_image_probe.mnew file mode 100644index 0000000..eb4b7db--- /dev/null+++ b/VirtualMac/vz/development/probes/restore_image_probe.m@@ -0,0 +1,120 @@+#import <Foundation/Foundation.h>+#import <objc/message.h>+#import <objc/runtime.h>+#include <dlfcn.h>+#import "../../host/NSViewShim.h"++static BOOL loadImage(NSString *path)+{+ void *image = dlopen(path.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);+ if (!image) {+ fprintf(stderr, "DLOPEN_FAILED\t%s\t%s\n",+ path.fileSystemRepresentation, dlerror());+ return NO;+ }+ printf("DLOPEN_OK\t%s\n", path.fileSystemRepresentation);+ return YES;+}++int main(int argc, const char *argv[])+{+ @autoreleasepool {+ setlinebuf(stdout);+ setlinebuf(stderr);+ if (argc != 2) {+ fprintf(stderr, "usage: restore-image-probe <restore.ipsw>\n");+ return 2;+ }++ // Realize the AppKit ABI shim before dyld registers Virtualization's+ // Objective-C classes. Several display classes inherit from NSView;+ // leaving this lazy makes objc reject the image's complete class set,+ // including unrelated restore-image classes.+ printf("FAKE_CLASS\tNSView\tsuperclass=%s\tinstance-size=%zu\n",+ class_getName(class_getSuperclass([NSView class])),+ class_getInstanceSize([NSView class]));++ NSString *root = @"/var/root/VirtualMac";+ NSString *installer = [root stringByAppendingPathComponent:+ @"payload/Installation.xpc/Contents/MacOS/"+ "com.apple.Virtualization.Installation"];+ setenv("VZ_INSTALLATION_BIN", installer.fileSystemRepresentation, 1);++ NSArray<NSString *> *images = @[+ [root stringByAppendingPathComponent:+ @"install/VZHostCompat.dylib"],+ [root stringByAppendingPathComponent:+ @"payload/Frameworks/Hypervisor.framework/Hypervisor"],+ [root stringByAppendingPathComponent:+ @"payload/Frameworks/ParavirtualizedGraphics.framework/"+ "ParavirtualizedGraphics"],+ [root stringByAppendingPathComponent:+ @"payload/Frameworks/Virtualization.framework/Virtualization"],+ ];+ for (NSString *image in images)+ if (!loadImage(image))+ return 1;++ Class virtualMachineClass = objc_getClass("VZVirtualMachine");+ Method startMethod = class_getInstanceMethod(+ virtualMachineClass,+ sel_registerName("startWithCompletionHandler:"));+ Dl_info virtualizationInfo = {0};+ if (!startMethod ||+ !dladdr((const void *)method_getImplementation(startMethod),+ &virtualizationInfo) ||+ !virtualizationInfo.dli_fbase) {+ fprintf(stderr, "VZ_IMAGE_BASE_UNAVAILABLE\n");+ return 1;+ }+ int (*rebindVirtualization)(void *) =+ (int (*)(void *))dlsym(RTLD_DEFAULT, "vz_rebind_virtualization");+ int rebindResult = rebindVirtualization+ ? rebindVirtualization(virtualizationInfo.dli_fbase) : -1;+ printf("VZ_REBIND\tbase=%p\tresult=%d\n",+ virtualizationInfo.dli_fbase, rebindResult);+ if (rebindResult != 0)+ return 1;++ Class restoreImageClass = objc_getClass("VZMacOSRestoreImage");+ SEL loadSelector = sel_registerName("loadFileURL:completionHandler:");+ if (!restoreImageClass ||+ !class_getClassMethod(restoreImageClass, loadSelector)) {+ fprintf(stderr, "RESTORE_CLASS_UNAVAILABLE\n");+ return 1;+ }++ NSURL *url = [NSURL fileURLWithPath:@(argv[1])];+ printf("RESTORE_LOAD_BEGIN\t%s\n", url.path.UTF8String);+ void (^completion)(id, NSError *) = ^(id image, NSError *error) {+ if (!image) {+ fprintf(stderr, "RESTORE_LOAD_FAILED\t%s\n",+ error.description.UTF8String ?: "(unknown)");+ fflush(NULL);+ exit(1);+ }+ NSString *build = [image valueForKey:@"buildVersion"];+ NSNumber *supported = [image valueForKey:@"supported"];+ id requirements =+ [image valueForKey:@"mostFeaturefulSupportedConfiguration"];+ id model = [requirements valueForKey:@"hardwareModel"];+ NSData *modelData = [model valueForKey:@"dataRepresentation"];+ NSNumber *minimumCPU =+ [requirements valueForKey:@"minimumSupportedCPUCount"];+ NSNumber *minimumMemory =+ [requirements valueForKey:@"minimumSupportedMemorySize"];+ printf("RESTORE_LOAD_OK\tbuild=%s\tsupported=%d\n",+ build.UTF8String ?: "(unknown)", supported.boolValue);+ printf("RESTORE_REQUIREMENTS\tcpu=%llu\tmemory=%llu\t"+ "hardware-model-bytes=%llu\n",+ minimumCPU.unsignedLongLongValue,+ minimumMemory.unsignedLongLongValue,+ (unsigned long long)modelData.length);+ fflush(NULL);+ exit(requirements && modelData.length ? 0 : 1);+ };+ ((void (*)(id, SEL, NSURL *, id))objc_msgSend)(+ restoreImageClass, loadSelector, url, completion);+ dispatch_main();+ }+}diff --git a/VirtualMac/vz/development/probes/start_force_dfu.m b/VirtualMac/vz/development/probes/start_force_dfu.mnew file mode 100644index 0000000..ccbd145--- /dev/null+++ b/VirtualMac/vz/development/probes/start_force_dfu.m@@ -0,0 +1,105 @@+#import <Foundation/Foundation.h>+#import <Virtualization/Virtualization.h>++@interface VZMacOSVirtualMachineStartOptions (ForceDFUPrivate)+@property(assign, setter=_setForceDFU:) BOOL _forceDFU;+@end++@interface VZVirtualMachine (USBLocationPrivate)+- (void)_getUSBControllerLocationIDWithCompletionHandler:+ (void (^)(id value))completionHandler;+@end++static VZVirtualMachine *gVirtualMachine;+static dispatch_source_t gLocationTimer;++static void Fail(NSString *stage, NSError *error)+{+ fprintf(stderr, "FORCE_DFU_FAILED\tstage=%s\terror=%s\n",+ stage.UTF8String, error.description.UTF8String);+ exit(1);+}++int main(int argc, const char *argv[])+{+ @autoreleasepool {+ setlinebuf(stdout);+ if (argc < 2) {+ fprintf(stderr, "usage: start-force-dfu VM.bundle\n");+ return 2;+ }+ NSString *bundlePath = @(argv[1]);+ NSURL *(^URL)(NSString *) = ^NSURL *(NSString *name) {+ return [NSURL fileURLWithPath:+ [bundlePath stringByAppendingPathComponent:name]];+ };++ NSData *hardwareData = [NSData dataWithContentsOfURL:URL(@"HardwareModel")];+ NSData *identifierData = [NSData dataWithContentsOfURL:URL(@"MachineIdentifier")];+ VZMacHardwareModel *hardwareModel =+ [[VZMacHardwareModel alloc] initWithDataRepresentation:hardwareData];+ VZMacMachineIdentifier *machineIdentifier =+ [[VZMacMachineIdentifier alloc]+ initWithDataRepresentation:identifierData];+ VZMacAuxiliaryStorage *auxiliaryStorage =+ [[VZMacAuxiliaryStorage alloc]+ initWithContentsOfURL:URL(@"AuxiliaryStorage")];+ if (!hardwareModel || !machineIdentifier || !auxiliaryStorage) {+ Fail(@"metadata", [NSError errorWithDomain:@"ForceDFU" code:1+ userInfo:nil]);+ }++ VZMacPlatformConfiguration *platform =+ [[VZMacPlatformConfiguration alloc] init];+ platform.hardwareModel = hardwareModel;+ platform.machineIdentifier = machineIdentifier;+ platform.auxiliaryStorage = auxiliaryStorage;++ NSError *error = nil;+ VZDiskImageStorageDeviceAttachment *attachment =+ [[VZDiskImageStorageDeviceAttachment alloc]+ initWithURL:URL(@"Disk.img") readOnly:NO error:&error];+ if (!attachment)+ Fail(@"disk", error);+ VZVirtioBlockDeviceConfiguration *blockDevice =+ [[VZVirtioBlockDeviceConfiguration alloc]+ initWithAttachment:attachment];++ VZVirtualMachineConfiguration *configuration =+ [VZVirtualMachineConfiguration new];+ configuration.platform = platform;+ configuration.CPUCount = 4;+ configuration.memorySize = 4ULL << 30;+ configuration.bootLoader = [[VZMacOSBootLoader alloc] init];+ configuration.storageDevices = @[ blockDevice ];+ if (![configuration validateWithError:&error])+ Fail(@"validation", error);++ gVirtualMachine = [[VZVirtualMachine alloc]+ initWithConfiguration:configuration];+ VZMacOSVirtualMachineStartOptions *options =+ [VZMacOSVirtualMachineStartOptions new];+ options._forceDFU = YES;+ printf("FORCE_DFU_START\tbundle=%s\n", bundlePath.UTF8String);+ [gVirtualMachine startWithOptions:options+ completionHandler:^(NSError *startError) {+ if (startError)+ Fail(@"start", startError);+ printf("FORCE_DFU_STARTED\n");+ gLocationTimer = dispatch_source_create(+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());+ dispatch_source_set_timer(gLocationTimer,+ dispatch_time(DISPATCH_TIME_NOW, 0), NSEC_PER_SEC,+ NSEC_PER_MSEC * 50);+ dispatch_source_set_event_handler(gLocationTimer, ^{+ [gVirtualMachine+ _getUSBControllerLocationIDWithCompletionHandler:^(id value) {+ printf("FORCE_DFU_LOCATION\t%s\n",+ value ? [[value description] UTF8String] : "none");+ }];+ });+ dispatch_resume(gLocationTimer);+ }];+ dispatch_main();+ }+}diff --git a/VirtualMac/vz/development/probes/trace_network_sharing_real_mac.lldb b/VirtualMac/vz/development/probes/trace_network_sharing_real_mac.lldbnew file mode 100644index 0000000..7b8463f--- /dev/null+++ b/VirtualMac/vz/development/probes/trace_network_sharing_real_mac.lldb@@ -0,0 +1,5 @@+settings set target.inline-breakpoint-strategy always+breakpoint set -n IOEthernetControllerCreate+breakpoint set -n IOServiceOpen+breakpoint list+continuediff --git a/VirtualMac/vz/development/probes/trace_vz_installation_lldb.py b/VirtualMac/vz/development/probes/trace_vz_installation_lldb.pynew file mode 100644index 0000000..5cd8631--- /dev/null+++ b/VirtualMac/vz/development/probes/trace_vz_installation_lldb.py@@ -0,0 +1,82 @@+import lldb+++def _register(frame, name):+ return frame.FindRegister(name).GetValueAsUnsigned()+++def _backtrace(frame, count):+ thread = frame.GetThread()+ for index in range(min(thread.GetNumFrames(), count)):+ item = thread.GetFrameAtIndex(index)+ module = item.GetModule().GetFileSpec().GetFilename() or "?"+ function = item.GetFunctionName() or item.GetDisplayFunctionName() or "?"+ print(f" #{index} {module}`{function} @ {item.GetPCAddress()}")+++def _cstring(frame, register):+ address = _register(frame, register)+ error = lldb.SBError()+ value = frame.GetThread().GetProcess().ReadCStringFromMemory(+ address, 1024, error+ )+ return value if error.Success() else f"<unreadable 0x{address:x}: {error}>"+++def _object(frame, register):+ address = _register(frame, register)+ value = frame.EvaluateExpression(f"(id)0x{address:x}")+ return value.GetObjectDescription() or value.GetSummary() or str(value)+++def dlsym(frame, _location, _dict):+ print(f"=== dlsym {_cstring(frame, 'x1')} ===")+ _backtrace(frame, 5)+ return False+++def register_notifications(frame, _location, _dict):+ print("=== AMRestorableDeviceRegisterForNotifications ===")+ _backtrace(frame, 12)+ return False+++def get_location(frame, _location, _dict):+ print("=== AMRestorableDeviceGetLocationID ===")+ _backtrace(frame, 8)+ return False+++def default_restore_options(frame, _location, _dict):+ print("=== AMRestorableDeviceCopyDefaultRestoreOptions ===")+ _backtrace(frame, 8)+ return False+++def restore(frame, _location, _dict):+ print("=== AMRestorableDeviceRestoreWithError ===")+ print(f"options: {_object(frame, 'x1')}")+ _backtrace(frame, 16)+ return False+++def matching_services(frame, _location, _dict):+ print("=== IOServiceGetMatchingServices ===")+ print(f"matching: {_object(frame, 'x1')}")+ _backtrace(frame, 8)+ return False+++def service_open(frame, _location, _dict):+ values = " ".join(+ f"{name}=0x{_register(frame, name):x}" for name in ("x0", "x1", "x2", "x3")+ )+ print(f"=== IOServiceOpen {values} ===")+ _backtrace(frame, 8)+ return False+++def spawn(frame, _location, _dict):+ print(f"=== posix_spawn {_cstring(frame, 'x1')} ===")+ _backtrace(frame, 8)+ return Falsediff --git a/VirtualMac/vz/development/probes/trace_vz_installation_real_mac.lldb b/VirtualMac/vz/development/probes/trace_vz_installation_real_mac.lldbnew file mode 100644index 0000000..51d126a--- /dev/null+++ b/VirtualMac/vz/development/probes/trace_vz_installation_real_mac.lldb@@ -0,0 +1,30 @@+settings set auto-confirm true+settings set target.inline-breakpoint-strategy always+process attach --name com.apple.Virtualization.Installation --waitfor+command script import ./trace_vz_installation_lldb.py++breakpoint set --name dlsym+breakpoint command add -F trace_vz_installation_lldb.dlsym 1++breakpoint set --name AMRestorableDeviceRegisterForNotifications+breakpoint command add -F trace_vz_installation_lldb.register_notifications 2++breakpoint set --name AMRestorableDeviceGetLocationID+breakpoint command add -F trace_vz_installation_lldb.get_location 3++breakpoint set --name AMRestorableDeviceCopyDefaultRestoreOptions+breakpoint command add -F trace_vz_installation_lldb.default_restore_options 4++breakpoint set --name AMRestorableDeviceRestoreWithError+breakpoint command add -F trace_vz_installation_lldb.restore 5++breakpoint set --name IOServiceGetMatchingServices+breakpoint command add -F trace_vz_installation_lldb.matching_services 6++breakpoint set --name IOServiceOpen+breakpoint command add -F trace_vz_installation_lldb.service_open 7++breakpoint set --name posix_spawn+breakpoint command add -F trace_vz_installation_lldb.spawn 8++continuediff --git a/VirtualMac/vz/development/probes/usb_bridge_probe.c b/VirtualMac/vz/development/probes/usb_bridge_probe.cnew file mode 100644index 0000000..dcc1e37--- /dev/null+++ b/VirtualMac/vz/development/probes/usb_bridge_probe.c@@ -0,0 +1,163 @@+#include <errno.h>+#include <pthread.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/socket.h>+#include <sys/un.h>+#include <unistd.h>++#include "../../host/usb_restore_bridge.h"++static int write_full(int fd, const void *buffer, size_t length) {+ const unsigned char *bytes = buffer;+ while (length) {+ ssize_t count = write(fd, bytes, length);+ if (count <= 0)+ return errno ?: EIO;+ bytes += count;+ length -= (size_t)count;+ }+ return 0;+}++static int read_full(int fd, void *buffer, size_t length) {+ unsigned char *bytes = buffer;+ while (length) {+ ssize_t count = read(fd, bytes, length);+ if (count <= 0)+ return errno ?: EIO;+ bytes += count;+ length -= (size_t)count;+ }+ return 0;+}++static int bridge_request(const struct vz_usb_bridge_request *request,+ const void *payload,+ struct vz_usb_bridge_response *response,+ void *response_payload,+ size_t response_capacity) {+ struct sockaddr_un address = { .sun_family = AF_UNIX };+ strlcpy(address.sun_path, VZ_USB_BRIDGE_SOCKET,+ sizeof(address.sun_path));+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);+ if (fd < 0 || connect(fd, (struct sockaddr *)&address,+ sizeof(address)) < 0) {+ perror("connect");+ return 1;+ }+ int error = write_full(fd, request, sizeof(*request));+ if (!error && request->payload_length)+ error = write_full(fd, payload, request->payload_length);+ if (!error)+ error = read_full(fd, response, sizeof(*response));+ if (!error && response->payload_length) {+ if (!response_payload || response->payload_length > response_capacity)+ error = EOVERFLOW;+ else+ error = read_full(fd, response_payload,+ response->payload_length);+ }+ close(fd);+ return error;+}++static int bulk_transfer(uint8_t endpoint, void *buffer, uint32_t length,+ uint32_t timeout_ms, uint32_t *actual) {+ bool input = (endpoint & 0x80U) != 0;+ struct vz_usb_bridge_request request = {+ .magic = VZ_USB_BRIDGE_MAGIC,+ .version = VZ_USB_BRIDGE_VERSION,+ .operation = VZ_USB_BRIDGE_BULK,+ .payload_length = input ? 0 : length,+ .timeout_ms = timeout_ms,+ .endpoint = endpoint,+ .transfer_length = length,+ };+ struct vz_usb_bridge_response response = {0};+ int error = bridge_request(&request, input ? NULL : buffer, &response,+ input ? buffer : NULL,+ input ? length : 0);+ if (!error && response.status)+ error = response.status;+ if (actual)+ *actual = error ? 0 : (input ? response.payload_length : length);+ return error;+}++struct read_context {+ uint8_t buffer[32768];+ uint32_t actual;+ int error;+};++static void *read_handshake(void *opaque) {+ struct read_context *context = opaque;+ context->error = bulk_transfer(0x81, context->buffer,+ sizeof(context->buffer), 10000,+ &context->actual);+ return NULL;+}++static int probe_usbmux_handshake(void) {+ static const uint8_t greeting[20] = {+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08,+ 0x00, 0x00, 0x00, 0x00,+ };+ struct read_context context = {0};+ pthread_t reader;+ int error = pthread_create(&reader, NULL, read_handshake, &context);+ if (error)+ return error;+ usleep(20000);+ uint32_t actual = 0;+ error = bulk_transfer(0x01, NULL, 0, 5000, &actual);+ if (!error)+ error = bulk_transfer(0x01, (void *)greeting, sizeof(greeting),+ 5000, &actual);+ pthread_join(reader, NULL);+ if (!error)+ error = context.error;+ if (error) {+ fprintf(stderr, "USBMUX_HANDSHAKE_FAILED\terror=%d (%s)\n",+ error, strerror(error));+ return 1;+ }+ printf("USBMUX_HANDSHAKE_OK\tactual=%u\tbytes=", context.actual);+ for (uint32_t index = 0; index < context.actual; index++)+ printf("%02x%s", context.buffer[index],+ index + 1 == context.actual ? "" : " ");+ putchar('\n');+ return 0;+}++int main(int argc, char **argv) {+ if (argc == 2 && strcmp(argv[1], "usbmux-handshake") == 0)+ return probe_usbmux_handshake();++ static const char command[] = "getenv ota-uuid";+ struct vz_usb_bridge_request request = {+ .magic = VZ_USB_BRIDGE_MAGIC,+ .version = VZ_USB_BRIDGE_VERSION,+ .operation = VZ_USB_BRIDGE_CONTROL,+ .payload_length = sizeof(command),+ .timeout_ms = 30000,+ .request_type = 0x40,+ .request = 0,+ .length = sizeof(command),+ };+ struct vz_usb_bridge_response response = {0};+ int error = bridge_request(&request, command, &response, NULL, 0);+ if (error) {+ fprintf(stderr, "transport error: %s\n", strerror(error));+ return 1;+ }+ printf("status=%d generation=%u vid=%04x pid=%04x ready=%u\n",+ response.status, response.device_generation, response.vendor_id,+ response.product_id, response.ready);+ return response.status ? 1 : 0;+}diff --git a/VirtualMac/vz/development/probes/usb_hci_oracle.m b/VirtualMac/vz/development/probes/usb_hci_oracle.mnew file mode 100644index 0000000..0c51bf8--- /dev/null+++ b/VirtualMac/vz/development/probes/usb_hci_oracle.m@@ -0,0 +1,216 @@+#import <Foundation/Foundation.h>+#import <objc/message.h>+#import <objc/runtime.h>+#include <stdarg.h>+#include <stdio.h>+#include <unistd.h>++typedef struct __attribute__((packed)) {+ uint32_t control;+ uint32_t data0;+ uint64_t data1;+} VZUSBHCIMessage;++typedef id (*InitIMP)(id, SEL, id, id, NSUInteger, id *, id, id, void *);+typedef BOOL (*EnqueueOneIMP)(id, SEL, const VZUSBHCIMessage *, id *);+typedef BOOL (*EnqueueOneExpediteIMP)(id, SEL, const VZUSBHCIMessage *, BOOL,+ id *);+typedef BOOL (*EnqueueManyIMP)(id, SEL, const VZUSBHCIMessage *, NSUInteger,+ id *);+typedef BOOL (*EnqueueManyExpediteIMP)(id, SEL, const VZUSBHCIMessage *,+ NSUInteger, BOOL, id *);+typedef BOOL (*CommandCallbackIMP)(id, SEL, int, id *);+typedef BOOL (*DoorbellCallbackIMP)(id, SEL, int, uint64_t, id *);++static InitIMP gInit;+static EnqueueOneIMP gEnqueueOne;+static EnqueueOneExpediteIMP gEnqueueOneExpedite;+static EnqueueManyIMP gEnqueueMany;+static EnqueueManyExpediteIMP gEnqueueManyExpedite;+static CommandCallbackIMP gCommandCallback;+static DoorbellCallbackIMP gDoorbellCallback;+static uint64_t gSequence;++static void Log(const char *format, ...)+{+ FILE *file = fopen("/tmp/usb-hci-oracle.log", "a");+ if (!file)+ return;+ va_list arguments;+ va_start(arguments, format);+ fprintf(file, "pid=%d ", getpid());+ vfprintf(file, format, arguments);+ va_end(arguments);+ fputc('\n', file);+ fclose(file);+}++static void LogMessages(const char *direction, const VZUSBHCIMessage *messages,+ NSUInteger count, BOOL expedite)+{+ if (!messages)+ return;+ for (NSUInteger index = 0; index < count; index++) {+ const VZUSBHCIMessage *message = &messages[index];+ uint64_t sequence = __atomic_add_fetch(&gSequence, 1, __ATOMIC_RELAXED);+ Log("%s sequence=%llu index=%llu/%llu expedite=%d control=0x%08x "+ "type=0x%02x status=0x%x data0=0x%08x data1=0x%016llx",+ direction, sequence, (uint64_t)index + 1, (uint64_t)count,+ expedite, message->control, message->control & 0x3f,+ (message->control >> 8) & 0xf, message->data0, message->data1);+ }+}++static id TraceInit(id self, SEL selector, NSData *capabilities, id queue,+ NSUInteger rate, id *error,+ void (^commandHandler)(id, VZUSBHCIMessage),+ void (^doorbellHandler)(id, uint32_t *, uint32_t),+ void *interestHandler)+{+ Log("init self=%p capability-bytes=%llu rate=%llu command=%p "+ "doorbell=%p interest=%p", self, capabilities.length, rate,+ commandHandler, doorbellHandler, interestHandler);+ void (^wrappedCommand)(id, VZUSBHCIMessage) =+ ^(id controller, VZUSBHCIMessage command) {+ LogMessages("kernel-command", &command, 1, NO);+ commandHandler(controller, command);+ };+ void (^wrappedDoorbell)(id, uint32_t *, uint32_t) =+ ^(id controller, uint32_t *doorbells, uint32_t count) {+ for (uint32_t index = 0; index < count; index++)+ Log("kernel-doorbell index=%u/%u value=0x%08x", index + 1,+ count, doorbells[index]);+ doorbellHandler(controller, doorbells, count);+ };+ return gInit(self, selector, capabilities, queue, rate, error,+ wrappedCommand, wrappedDoorbell, interestHandler);+}++static BOOL TraceEnqueueOne(id self, SEL selector,+ const VZUSBHCIMessage *message, id *error)+{+ LogMessages("controller-interrupt", message, 1, NO);+ return gEnqueueOne(self, selector, message, error);+}++static BOOL TraceEnqueueOneExpedite(id self, SEL selector,+ const VZUSBHCIMessage *message,+ BOOL expedite, id *error)+{+ LogMessages("controller-interrupt", message, 1, expedite);+ return gEnqueueOneExpedite(self, selector, message, expedite, error);+}++static BOOL TraceEnqueueMany(id self, SEL selector,+ const VZUSBHCIMessage *messages,+ NSUInteger count, id *error)+{+ LogMessages("controller-interrupt", messages, count, NO);+ return gEnqueueMany(self, selector, messages, count, error);+}++static BOOL TraceEnqueueManyExpedite(id self, SEL selector,+ const VZUSBHCIMessage *messages,+ NSUInteger count, BOOL expedite,+ id *error)+{+ LogMessages("controller-interrupt", messages, count, expedite);+ return gEnqueueManyExpedite(self, selector, messages, count, expedite,+ error);+}++static BOOL TraceCommandCallback(id self, SEL selector, int result, id *error)+{+ Ivar commandIvar = class_getInstanceVariable(object_getClass(self),+ "_command");+ if (!commandIvar)+ commandIvar = class_getInstanceVariable([self class], "_command");+ if (commandIvar) {+ const VZUSBHCIMessage *message =+ (const void *)((const uint8_t *)(__bridge const void *)self ++ ivar_getOffset(commandIvar));+ Log("command-callback result=0x%x error=%p self=%p", result,+ error ? *error : nil, self);+ LogMessages("kernel-command", message, 1, NO);+ } else {+ Log("command-callback result=0x%x missing-command-ivar self=%p",+ result, self);+ }+ return gCommandCallback(self, selector, result, error);+}++static BOOL TraceDoorbellCallback(id self, SEL selector, int result,+ uint64_t length, id *error)+{+ Ivar doorbellsIvar = class_getInstanceVariable([self class], "_doorbells");+ id doorbells = doorbellsIvar ? object_getIvar(self, doorbellsIvar) : nil;+ const uint32_t *bytes = [doorbells respondsToSelector:@selector(bytes)]+ ? [doorbells bytes] : NULL;+ NSUInteger byteLength =+ [doorbells respondsToSelector:@selector(length)] ? [doorbells length] : 0;+ NSUInteger count = MIN((NSUInteger)length, byteLength) / sizeof(uint32_t);+ Log("doorbell-callback result=0x%x length=%llu bytes=%llu error=%p self=%p",+ result, length, (uint64_t)byteLength, error ? *error : nil, self);+ for (NSUInteger index = 0; index < count; index++)+ Log("kernel-doorbell index=%llu/%llu value=0x%08x",+ (uint64_t)index + 1, (uint64_t)count, bytes[index]);+ return gDoorbellCallback(self, selector, result, length, error);+}++static IMP Replace(Class controller, const char *name, IMP replacement)+{+ Method method = class_getInstanceMethod(controller, sel_registerName(name));+ return method ? method_setImplementation(method, replacement) : NULL;+}++__attribute__((constructor)) static void InstallTrace(void)+{+ @autoreleasepool {+ Class controller = objc_getClass("IOUSBHostControllerInterface");+ if (!controller) {+ Log("IOUSBHostControllerInterface unavailable process=%s",+ NSProcessInfo.processInfo.processName.UTF8String);+ return;+ }+ Method commandCallback = class_getInstanceMethod(+ controller,+ sel_registerName("commandAsyncCallbackWithResult:error:"));+ Method doorbellCallback = class_getInstanceMethod(+ controller,+ sel_registerName("doorbellAsyncCallbacKWithResult:length:error:"));+ Ivar commandIvar = class_getInstanceVariable(controller, "_command");+ Ivar doorbellsIvar = class_getInstanceVariable(controller,+ "_doorbells");+ Log("callback-types command=%s doorbell=%s command-ivar=%s@%llu "+ "doorbells-ivar=%s@%llu",+ commandCallback ? method_getTypeEncoding(commandCallback) : "?",+ doorbellCallback ? method_getTypeEncoding(doorbellCallback) : "?",+ commandIvar ? ivar_getTypeEncoding(commandIvar) : "?",+ commandIvar ? (uint64_t)ivar_getOffset(commandIvar) : 0,+ doorbellsIvar ? ivar_getTypeEncoding(doorbellsIvar) : "?",+ doorbellsIvar ? (uint64_t)ivar_getOffset(doorbellsIvar) : 0);+ gInit = (InitIMP)Replace(+ controller,+ "initWithCapabilities:queue:interruptRateHz:error:commandHandler:"+ "doorbellHandler:interestHandler:", (IMP)TraceInit);+ gEnqueueOne = (EnqueueOneIMP)Replace(+ controller, "enqueueInterrupt:error:", (IMP)TraceEnqueueOne);+ gEnqueueOneExpedite = (EnqueueOneExpediteIMP)Replace(+ controller, "enqueueInterrupt:expedite:error:",+ (IMP)TraceEnqueueOneExpedite);+ gEnqueueMany = (EnqueueManyIMP)Replace(+ controller, "enqueueInterrupts:count:error:",+ (IMP)TraceEnqueueMany);+ gEnqueueManyExpedite = (EnqueueManyExpediteIMP)Replace(+ controller, "enqueueInterrupts:count:expedite:error:",+ (IMP)TraceEnqueueManyExpedite);+ gCommandCallback = (CommandCallbackIMP)Replace(+ controller, "commandAsyncCallbackWithResult:error:",+ (IMP)TraceCommandCallback);+ gDoorbellCallback = (DoorbellCallbackIMP)Replace(+ controller, "doorbellAsyncCallbacKWithResult:length:error:",+ (IMP)TraceDoorbellCallback);+ Log("trace installed process=%s init=%p",+ NSProcessInfo.processInfo.processName.UTF8String, gInit);+ }+}diff --git a/VirtualMac/vz/development/probes/vm_reserve_probe.c b/VirtualMac/vz/development/probes/vm_reserve_probe.cnew file mode 100644index 0000000..803ec78--- /dev/null+++ b/VirtualMac/vz/development/probes/vm_reserve_probe.c@@ -0,0 +1,51 @@+#include <errno.h>+#include <mach/mach.h>+#include <stdint.h>+#include <stdio.h>+#include <sys/mman.h>++enum { kReservationCount = 8 };+typedef uint64_t mach_vm_address_t;+typedef uint64_t mach_vm_size_t;+extern kern_return_t mach_vm_allocate(+ vm_map_t target, mach_vm_address_t *address,+ mach_vm_size_t size, int flags);+extern kern_return_t mach_vm_deallocate(+ vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);+static const mach_vm_size_t kReservationSize = 16ULL << 30;++int main(void) {+ mach_vm_address_t vm[kReservationCount] = {0};+ void *sparse[kReservationCount] = {0};++ puts("mach_vm_allocate reservations:");+ for (unsigned index = 0; index < kReservationCount; index++) {+ kern_return_t result = mach_vm_allocate(+ mach_task_self(), &vm[index], kReservationSize,+ VM_FLAGS_ANYWHERE);+ printf(" %u: result=%d address=0x%llx\n", index, result,+ (unsigned long long)vm[index]);+ if (result != KERN_SUCCESS)+ break;+ }+ for (unsigned index = 0; index < kReservationCount; index++) {+ if (vm[index] != 0)+ mach_vm_deallocate(mach_task_self(), vm[index],+ kReservationSize);+ }++ puts("mmap PROT_NONE reservations:");+ for (unsigned index = 0; index < kReservationCount; index++) {+ errno = 0;+ sparse[index] = mmap(NULL, (size_t)kReservationSize, PROT_NONE,+ MAP_PRIVATE | MAP_ANON, -1, 0);+ printf(" %u: address=%p errno=%d\n", index, sparse[index], errno);+ if (sparse[index] == MAP_FAILED)+ break;+ }+ for (unsigned index = 0; index < kReservationCount; index++) {+ if (sparse[index] != NULL && sparse[index] != MAP_FAILED)+ munmap(sparse[index], (size_t)kReservationSize);+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/vmm_factory_lldb.py b/VirtualMac/vz/development/probes/vmm_factory_lldb.pynew file mode 100644index 0000000..fdf0d07--- /dev/null+++ b/VirtualMac/vz/development/probes/vmm_factory_lldb.py@@ -0,0 +1,87 @@+import lldb+++FACTORY_RESULT_OFFSET = 0x154F14+SEQUENCE = 0+++def _register(frame, name):+ value = frame.FindRegister(name)+ text = value.GetValue()+ return int(text, 0) if text else 0+++def _possible_strings(process, sp):+ found = []+ error = lldb.SBError()+ for offset in range(0x20, 0x120, 8):+ pointer = process.ReadUnsignedFromMemory(sp + offset, 8, error)+ if error.Fail() or pointer < 0x100000000:+ error.Clear()+ continue+ text = process.ReadCStringFromMemory(pointer, 160, error)+ if error.Success() and text and all(+ character.isprintable() or character in "\t\r\n"+ for character in text+ ):+ found.append("+0x{:x}=0x{:x}={!r}".format(offset, pointer, text))+ error.Clear()+ return found+++def factory_result_callback(frame, _bp_loc, _internal_dict):+ global SEQUENCE+ SEQUENCE += 1+ process = frame.GetThread().GetProcess()+ sp = _register(frame, "sp")+ success = _register(frame, "x0")+ error = lldb.SBError()+ device = process.ReadUnsignedFromMemory(sp + 0xC0, 8, error)+ strings = _possible_strings(process, sp)+ print(+ "VMM_FACTORY\tsequence={}\tsuccess={}\tdevice=0x{:x}\tsp=0x{:x}"+ "\tstrings={}".format(+ SEQUENCE,+ success,+ device if error.Success() else 0,+ sp,+ " | ".join(strings) if strings else "-",+ ),+ flush=True,+ )+ return False+++def install_factory_trace(debugger, _command, result, _internal_dict):+ target = debugger.GetSelectedTarget()+ module = None+ for candidate in target.module_iter():+ if (+ candidate.GetFileSpec().GetFilename()+ == "com.apple.Virtualization.VirtualMachine"+ ):+ module = candidate+ break+ if module is None:+ result.SetError("VMM image is not loaded")+ return++ base = module.GetObjectFileHeaderAddress().GetLoadAddress(target)+ breakpoint = target.BreakpointCreateByAddress(+ base + FACTORY_RESULT_OFFSET+ )+ breakpoint.SetScriptCallbackFunction(+ "vmm_factory_lldb.factory_result_callback"+ )+ result.AppendMessage(+ "VMM factory trace installed at 0x{:x}".format(+ base + FACTORY_RESULT_OFFSET+ )+ )+++def __lldb_init_module(debugger, _internal_dict):+ debugger.HandleCommand(+ "command script add -f "+ "vmm_factory_lldb.install_factory_trace install-vmm-factory-trace"+ )diff --git a/VirtualMac/vz/development/probes/vmnet-probe-launchd.plist b/VirtualMac/vz/development/probes/vmnet-probe-launchd.plistnew file mode 100644index 0000000..a07b4e8--- /dev/null+++ b/VirtualMac/vz/development/probes/vmnet-probe-launchd.plist@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.mac.virtual.vmnet-probe</string>+ <key>ProgramArguments</key>+ <array>+ <string>/var/jb/usr/local/bin/vmnet-probe</string>+ </array>+ <key>UserName</key>+ <string>root</string>+ <key>RunAtLoad</key>+ <true/>+ <key>StandardOutPath</key>+ <string>/tmp/vmnet-probe-launchd.log</string>+ <key>StandardErrorPath</key>+ <string>/tmp/vmnet-probe-launchd.log</string>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/vmnet_probe.c b/VirtualMac/vz/development/probes/vmnet_probe.cnew file mode 100644index 0000000..2b6de4d--- /dev/null+++ b/VirtualMac/vz/development/probes/vmnet_probe.c@@ -0,0 +1,105 @@+#include <dispatch/dispatch.h>+#include <dlfcn.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include <CoreFoundation/CoreFoundation.h>+#include <xpc/xpc.h>++typedef struct vmnet_interface *interface_ref;+typedef interface_ref (*start_interface_fn)(xpc_object_t, dispatch_queue_t,+ void (^)(uint32_t, xpc_object_t));+typedef void (*stop_interface_fn)(interface_ref, dispatch_queue_t,+ void (^)(uint32_t));+typedef CFTypeRef (*dynamic_store_create_fn)(CFAllocatorRef, CFStringRef,+ void *, const void *);+typedef int (*sc_error_fn)(void);+typedef const char *(*sc_error_string_fn)(int);++int main(void) {+ void *systemConfiguration = dlopen(+ "/System/Library/Frameworks/SystemConfiguration.framework/"+ "SystemConfiguration", RTLD_NOW | RTLD_LOCAL);+ dynamic_store_create_fn createStore = (dynamic_store_create_fn)dlsym(+ systemConfiguration, "SCDynamicStoreCreate");+ sc_error_fn getSCError =+ (sc_error_fn)dlsym(systemConfiguration, "SCError");+ sc_error_string_fn getSCErrorString =+ (sc_error_string_fn)dlsym(systemConfiguration, "SCErrorString");+ CFTypeRef store = createStore ? createStore(+ NULL, CFSTR("com.apple.NetworkSharing"), NULL, NULL) : NULL;+ int storeError = getSCError ? getSCError() : -1;+ printf("vmnet probe: dynamic store=%p error=%d (%s)\n", store,+ storeError, getSCErrorString ? getSCErrorString(storeError) : "?");+ if (store)+ CFRelease(store);++ const char *framework =+ "/var/jb/usr/local/lib/vmnet.framework/vmnet";+ void *image = dlopen(framework, RTLD_NOW | RTLD_LOCAL);+ if (!image) {+ fprintf(stderr, "vmnet probe: dlopen failed: %s\n", dlerror());+ return 1;+ }++ start_interface_fn start =+ (start_interface_fn)dlsym(image, "vmnet_start_interface");+ stop_interface_fn stop =+ (stop_interface_fn)dlsym(image, "vmnet_stop_interface");+ const char *const *operationModeKey =+ (const char *const *)dlsym(image, "vmnet_operation_mode_key");+ if (!start || !operationModeKey || !*operationModeKey) {+ fprintf(stderr, "vmnet probe: required symbols unavailable\n");+ return 1;+ }++ xpc_object_t description = xpc_dictionary_create(NULL, NULL, 0);+ xpc_dictionary_set_uint64(description, *operationModeKey, 1001);+ dispatch_queue_t queue = dispatch_queue_create(+ "com.mac.virtual.vmnet-probe", DISPATCH_QUEUE_SERIAL);+ dispatch_semaphore_t started = dispatch_semaphore_create(0);+ __block uint32_t startStatus = UINT32_MAX;+ __block interface_ref interface = NULL;++ interface = start(description, queue, ^(uint32_t status,+ xpc_object_t parameters) {+ startStatus = status;+ char *text = parameters ? xpc_copy_description(parameters) : NULL;+ printf("vmnet probe: start status=%u parameters=%s\n", status,+ text ? text : "(null)");+ free(text);+ fflush(stdout);+ dispatch_semaphore_signal(started);+ });+ xpc_release(description);+ if (!interface) {+ fprintf(stderr, "vmnet probe: start returned NULL\n");+ return 2;+ }+ if (dispatch_semaphore_wait(+ started, dispatch_time(DISPATCH_TIME_NOW, 120 * NSEC_PER_SEC))) {+ fprintf(stderr, "vmnet probe: start timed out\n");+ return 3;+ }+ if (startStatus != 1000)+ return 4;+ if (!stop)+ return 0;++ dispatch_semaphore_t stopped = dispatch_semaphore_create(0);+ __block uint32_t stopStatus = UINT32_MAX;+ stop(interface, queue, ^(uint32_t status) {+ stopStatus = status;+ printf("vmnet probe: stop status=%u\n", status);+ fflush(stdout);+ dispatch_semaphore_signal(stopped);+ });+ if (dispatch_semaphore_wait(+ stopped, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC))) {+ fprintf(stderr, "vmnet probe: stop timed out\n");+ return 5;+ }+ return stopStatus == 1000 ? 0 : 6;+}diff --git a/VirtualMac/vz/development/probes/vmnet_probe.lldb b/VirtualMac/vz/development/probes/vmnet_probe.lldbnew file mode 100644index 0000000..42da5f4--- /dev/null+++ b/VirtualMac/vz/development/probes/vmnet_probe.lldb@@ -0,0 +1,10 @@+settings set auto-confirm true+settings set target.process.stop-on-sharedlibrary-events false+target create /var/jb/usr/local/bin/vmnet-probe+run+register read x0 x1 x2 x15 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 fp lr sp pc+memory read --format s --count 1 '$sp+0x10'+bt all+image list -o -f+disassemble --frame --mixed+quitdiff --git a/VirtualMac/vz/development/probes/vmnet_probe_create.lldb b/VirtualMac/vz/development/probes/vmnet_probe_create.lldbnew file mode 100644index 0000000..a0554e9--- /dev/null+++ b/VirtualMac/vz/development/probes/vmnet_probe_create.lldb@@ -0,0 +1,9 @@+settings set auto-confirm true+settings set target.process.stop-on-sharedlibrary-events false+target create /var/jb/usr/local/bin/vmnet-probe+breakpoint set --name NETRBXPCCreate+run+register read x0 x1 x2 x8 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 fp lr sp pc+disassemble --name NETRBXPCCreate+image list -o -f Netrb+quitdiff --git a/VirtualMac/vz/development/probes/vmnet_probe_send.lldb b/VirtualMac/vz/development/probes/vmnet_probe_send.lldbnew file mode 100644index 0000000..4fd00ca--- /dev/null+++ b/VirtualMac/vz/development/probes/vmnet_probe_send.lldb@@ -0,0 +1,11 @@+settings set auto-confirm true+settings set target.process.stop-on-sharedlibrary-events false+target create /var/jb/usr/local/bin/vmnet-probe+breakpoint set --name xpc_connection_send_message_with_reply_sync+run+register read x0 x1 x2 x19 x20 x21 x22 fp lr sp pc+memory read --format x --size 8 --count 8 $x0+memory read --format x --size 8 --count 16 $x1+disassemble --name NETRBXPCSetupAndSend+bt+quitdiff --git a/VirtualMac/vz/development/probes/vmnet_probe_type.lldb b/VirtualMac/vz/development/probes/vmnet_probe_type.lldbnew file mode 100644index 0000000..5ec366d--- /dev/null+++ b/VirtualMac/vz/development/probes/vmnet_probe_type.lldb@@ -0,0 +1,13 @@+settings set auto-confirm true+settings set target.process.stop-on-sharedlibrary-events false+target create /var/jb/usr/local/bin/vmnet-probe+breakpoint set --name NETRBXPCCreate+run+breakpoint set --address '$pc+112'+continue+register read x0 x8 x9 x19 x20 x21 fp lr sp pc+image lookup --address $x8+image lookup --address $x9+memory read --format x --size 8 --count 8 $x0+disassemble --frame+quitdiff --git a/VirtualMac/vz/development/probes/vt_pv_probe.c b/VirtualMac/vz/development/probes/vt_pv_probe.cnew file mode 100644index 0000000..f835637--- /dev/null+++ b/VirtualMac/vz/development/probes/vt_pv_probe.c@@ -0,0 +1,39 @@+#include <dlfcn.h>+#include <mach-o/dyld.h>+#include <stdio.h>+#include <string.h>++static void report_symbol(void *image, const char *name) {+ void *symbol = dlsym(image, name);+ printf("SYMBOL\t%s\t%p\n", name, symbol);+}++int main(int argc, char **argv) {+ const char *videoToolbox = argc > 1+ ? argv[1]+ : "/System/Library/Frameworks/VideoToolbox.framework/VideoToolbox";+ const char *support =+ "/System/Library/PrivateFrameworks/"+ "VideoToolboxParavirtualizationSupport.framework/"+ "VideoToolboxParavirtualizationSupport";+ void *vt = dlopen(videoToolbox, RTLD_NOW | RTLD_GLOBAL);+ printf("DLOPEN\tVideoToolbox\t%p\t%s\n", vt, vt ? "ok" : dlerror());+ void *pv = dlopen(support, RTLD_NOW | RTLD_GLOBAL);+ printf("DLOPEN\tPVSupport\t%p\t%s\n", pv, pv ? "ok" : dlerror());++ const char *symbols[] = {+ "VTParavirtualizationHostSessionCreate",+ "VTParavirtualizationHostSessionDeliverMessageFromGuest",+ "VTParavirtualizationHostSessionInvalidate",+ };+ for (size_t i = 0; i < sizeof(symbols) / sizeof(symbols[0]); ++i)+ report_symbol(RTLD_DEFAULT, symbols[i]);++ for (uint32_t i = 0; i < _dyld_image_count(); ++i) {+ const char *name = _dyld_get_image_name(i);+ if (name && (strstr(name, "VideoToolbox") || strstr(name, "AppleVXE") ||+ strstr(name, "AppleAVD")))+ printf("IMAGE\t%s\n", name);+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/vz-macos.entitlements b/VirtualMac/vz/development/probes/vz-macos.entitlementsnew file mode 100644index 0000000..7a489c7--- /dev/null+++ b/VirtualMac/vz/development/probes/vz-macos.entitlements@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.virtualization</key>+ <true/>+ <key>com.apple.security.hypervisor</key>+ <true/>+ <key>get-task-allow</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/vz.entitlements b/VirtualMac/vz/development/probes/vz.entitlementsnew file mode 100644index 0000000..fa05c63--- /dev/null+++ b/VirtualMac/vz/development/probes/vz.entitlements@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.private.hypervisor</key>+ <true/>+ <key>com.apple.private.memorystatus</key>+ <true/>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>platform-application</key>+ <true/>+ <key>com.apple.private.amfi.can-execute-cdhash</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/development/probes/vzcfg.m b/VirtualMac/vz/development/probes/vzcfg.mnew file mode 100644index 0000000..a8f09a9--- /dev/null+++ b/VirtualMac/vz/development/probes/vzcfg.m@@ -0,0 +1,50 @@+// Minimal VZ dispatch probe: chain-load, create config, check respondsToSelector for a+// spread of methods. With the extractor's selref pool + cleared fixed_up flag, objc should+// linear-search and resolve all of them.+#include <stdio.h>+#include <dlfcn.h>+#include <objc/runtime.h>+#include <objc/message.h>++static id msg(id s, const char *sel) { return ((id(*)(id, SEL))objc_msgSend)(s, sel_registerName(sel)); }++int main(int argc, char **argv) {+ setvbuf(stdout, NULL, _IONBF, 0);+ for (int i = 1; i < argc; i++) {+ void *h = dlopen(argv[i], RTLD_NOW | RTLD_GLOBAL);+ if (!h) { printf("dlopen %s FAIL: %s\n", argv[i], dlerror()); return 1; }+ printf("loaded %s\n", argv[i]);+ }+ Class C = objc_getClass("VZVirtualMachineConfiguration");+ id cfg = msg(msg((id)C, "alloc"), "init");+ printf("config = %p\n", (void *)cfg);+ const char *sels[] = {"setCPUCount:", "CPUCount", "setMemorySize:", "memorySize",+ "platform", "setPlatform:", "validateWithError:", "audioDevices", "keyboards"};+ int ok = 1;+ for (unsigned i = 0; i < sizeof(sels)/sizeof(sels[0]); i++) {+ BOOL r = ((BOOL(*)(id,SEL,SEL))objc_msgSend)(cfg, sel_registerName("respondsToSelector:"), sel_registerName(sels[i]));+ printf(" responds(%s)=%d\n", sels[i], r);+ if (!r) ok = 0;+ }+ printf(ok ? "ALL RESOLVE\n" : "some unresolved\n");++ // Exercise real method calls (not just respondsToSelector): set/get round-trip + validate.+ ((void(*)(id,SEL,unsigned long))objc_msgSend)(cfg, sel_registerName("setCPUCount:"), 2);+ unsigned long n = ((unsigned long(*)(id,SEL))objc_msgSend)(cfg, sel_registerName("CPUCount"));+ printf("setCPUCount:2 -> CPUCount=%lu %s\n", n, n == 2 ? "OK" : "MISMATCH");+ ((void(*)(id,SEL,unsigned long long))objc_msgSend)(cfg, sel_registerName("setMemorySize:"), 4ULL<<30);+ unsigned long long mem = ((unsigned long long(*)(id,SEL))objc_msgSend)(cfg, sel_registerName("memorySize"));+ printf("setMemorySize:4G -> memorySize=%llu\n", mem);+ // validateWithError: on an incomplete config should DISPATCH into VZ's validator and return+ // an NSError (not crash) -- proves real IMP execution through the framework's own logic.+ id err = nil;+ BOOL valid = ((BOOL(*)(id,SEL,id*))objc_msgSend)(cfg, sel_registerName("validateWithError:"), &err);+ printf("validateWithError: -> valid=%d, err=%p\n", valid, (void*)err);+ if (err) {+ id desc = ((id(*)(id,SEL))objc_msgSend)(err, sel_registerName("localizedDescription"));+ const char *s = ((const char*(*)(id,SEL))objc_msgSend)(desc, sel_registerName("UTF8String"));+ printf(" error: %s\n", s ? s : "(nil)");+ }+ printf("DISPATCH OK\n");+ return 0;+}diff --git a/VirtualMac/vz/development/probes/vzload.c b/VirtualMac/vz/development/probes/vzload.cnew file mode 100644index 0000000..df8b8da--- /dev/null+++ b/VirtualMac/vz/development/probes/vzload.c@@ -0,0 +1,24 @@+// Chain-dlopen harness: load several extracted+stamped frameworks in order, then+// probe ObjC class realization. Used to load our Hypervisor first (so dyld satisfies+// Virtualization's strong LC_LOAD_DYLIB by install-name match) then Virtualization.+#include <stdio.h>+#include <dlfcn.h>+extern void *objc_getClass(const char *);++int main(int argc, char **argv) {+ setvbuf(stdout, NULL, _IONBF, 0); // unbuffered: survive a crash over ssh+ for (int i = 1; i < argc; i++) {+ printf("dlopen(%s)...\n", argv[i]);+ void *h = dlopen(argv[i], RTLD_NOW | RTLD_GLOBAL); // GLOBAL: later loads + flat binds see these symbols+ if (!h) { printf(" FAILED: %s\n", dlerror()); return 1; }+ printf(" OK handle=%p\n", h);+ }+ const char *cls[] = {+ "VZVirtualMachineConfiguration", "VZVirtualMachine",+ "VZMacOSBootLoader", "VZVirtioBlockDeviceConfiguration",+ "VZMacPlatformConfiguration", "VZMacGraphicsDeviceConfiguration",+ };+ for (int i = 0; i < (int)(sizeof(cls)/sizeof(cls[0])); i++)+ printf("class %-40s = %p\n", cls[i], objc_getClass(cls[i]));+ return 0;+}diff --git a/VirtualMac/vz/development/probes/vzmacboot.m b/VirtualMac/vz/development/probes/vzmacboot.mnew file mode 100644index 0000000..2da4433--- /dev/null+++ b/VirtualMac/vz/development/probes/vzmacboot.m@@ -0,0 +1,266 @@+#import <AppKit/AppKit.h>+#import <Foundation/Foundation.h>+#import <Virtualization/Virtualization.h>+#include <mach-o/dyld.h>+#include <signal.h>++static VZVirtualMachine *machine;+static NSWindow *vmWindow;+static BOOL stopping;++static void printError(NSString *label, NSError *error)+{+ for (unsigned depth = 0; error && depth < 8; depth++) {+ printf("%s_ERROR\tdepth=%u\tdomain=%s\tcode=%ld\tdescription=%s\n",+ label.UTF8String, depth, error.domain.UTF8String,+ (long)error.code, error.localizedDescription.UTF8String);+ printf("%s_USERINFO\t%s\n", label.UTF8String,+ error.userInfo.description.UTF8String);+ error = error.userInfo[NSUnderlyingErrorKey];+ }+}++static void printLoadedFrameworks(void)+{+ uint32_t count = _dyld_image_count();+ for (uint32_t i = 0; i < count; i++) {+ const char *name = _dyld_get_image_name(i);+ if (name && (strstr(name, "Hypervisor.framework") ||+ strstr(name, "ParavirtualizedGraphics.framework") ||+ strstr(name, "Virtualization.framework")))+ printf("LOADED_IMAGE\t%s\n", name);+ }+}++static void finishStop(void)+{+ if (stopping)+ return;+ stopping = YES;+ NSError *error = nil;+ if (machine.canRequestStop && [machine requestStopWithError:&error]) {+ printf("REQUEST_STOP\taccepted\n");+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ if (machine.canStop) {+ [machine stopWithCompletionHandler:^(NSError *stopError) {+ printf("FORCED_STOP\t%s\n",+ stopError ? stopError.localizedDescription.UTF8String : "ok");+ exit(stopError ? 1 : 0);+ }];+ } else {+ exit(0);+ }+ });+ } else if (machine.canStop) {+ printf("REQUEST_STOP\tfailed\t%s\n",+ error ? error.localizedDescription.UTF8String : "unavailable");+ [machine stopWithCompletionHandler:^(NSError *stopError) {+ printf("FORCED_STOP\t%s\n",+ stopError ? stopError.localizedDescription.UTF8String : "ok");+ exit(stopError ? 1 : 0);+ }];+ } else {+ exit(0);+ }+}++@interface VMDelegate : NSObject <VZVirtualMachineDelegate>+@end++@implementation VMDelegate+- (void)guestDidStopVirtualMachine:(VZVirtualMachine *)virtualMachine+{+ (void)virtualMachine;+ printf("GUEST_STOPPED\n");+ exit(0);+}++- (void)virtualMachine:(VZVirtualMachine *)virtualMachine+ didStopWithError:(NSError *)error+{+ (void)virtualMachine;+ printf("VM_STOP_ERROR\t%s\n", error.localizedDescription.UTF8String);+ exit(1);+}+@end++static VZVirtualMachineConfiguration *configuration(NSURL *bundleURL)+{+ NSError *error = nil;+ NSData *hardwareData = [NSData dataWithContentsOfURL:+ [bundleURL URLByAppendingPathComponent:@"HardwareModel"]];+ NSData *identifierData = [NSData dataWithContentsOfURL:+ [bundleURL URLByAppendingPathComponent:@"MachineIdentifier"]];+ if (!hardwareData || !identifierData)+ return nil;++ VZMacHardwareModel *hardwareModel =+ [[VZMacHardwareModel alloc] initWithDataRepresentation:hardwareData];+ VZMacMachineIdentifier *identifier =+ [[VZMacMachineIdentifier alloc] initWithDataRepresentation:identifierData];+ VZMacAuxiliaryStorage *auxiliaryStorage =+ [[VZMacAuxiliaryStorage alloc] initWithURL:+ [bundleURL URLByAppendingPathComponent:@"AuxiliaryStorage"]];++ VZMacPlatformConfiguration *platform =+ [[VZMacPlatformConfiguration alloc] init];+ platform.hardwareModel = hardwareModel;+ platform.machineIdentifier = identifier;+ platform.auxiliaryStorage = auxiliaryStorage;++ VZVirtualMachineConfiguration *config =+ [[VZVirtualMachineConfiguration alloc] init];+ config.platform = platform;+ config.CPUCount = 4;+ config.memorySize = 4ULL << 30;+ config.bootLoader = [[VZMacOSBootLoader alloc] init];++ VZDiskImageStorageDeviceAttachment *attachment =+ [[VZDiskImageStorageDeviceAttachment alloc]+ initWithURL:[bundleURL URLByAppendingPathComponent:@"Disk.img"]+ readOnly:NO+ error:&error];+ if (!attachment) {+ fprintf(stderr, "disk attachment: %s\n", error.localizedDescription.UTF8String);+ return nil;+ }+ config.storageDevices = @[+ [[VZVirtioBlockDeviceConfiguration alloc] initWithAttachment:attachment]+ ];++ if (!getenv("VZ_NO_GRAPHICS")) {+ VZMacGraphicsDisplayConfiguration *display =+ [[VZMacGraphicsDisplayConfiguration alloc]+ initWithWidthInPixels:1280 heightInPixels:800 pixelsPerInch:80];+ VZMacGraphicsDeviceConfiguration *graphics =+ [[VZMacGraphicsDeviceConfiguration alloc] init];+ graphics.displays = @[display];+ config.graphicsDevices = @[graphics];+ }+ if (!getenv("VZ_NO_INPUT")) {+ config.keyboards = @[[[VZUSBKeyboardConfiguration alloc] init]];+ config.pointingDevices = @[+ [[VZUSBScreenCoordinatePointingDeviceConfiguration alloc] init]+ ];+ }+ if (!getenv("VZ_NO_NETWORK")) {+ VZVirtioNetworkDeviceConfiguration *network =+ [[VZVirtioNetworkDeviceConfiguration alloc] init];+ network.MACAddress = [[VZMACAddress alloc]+ initWithString:@"d6:a7:58:8e:78:d6"];+ network.attachment = [[VZNATNetworkDeviceAttachment alloc] init];+ config.networkDevices = @[network];+ }+ const char *sharedPath = getenv("VZ_SHARED_DIRECTORY");+ if (sharedPath && sharedPath[0]) {+ NSURL *sharedURL = [NSURL fileURLWithPath:@(sharedPath)+ isDirectory:YES];+ VZSharedDirectory *directory = [[VZSharedDirectory alloc]+ initWithURL:sharedURL readOnly:NO];+ VZMultipleDirectoryShare *share = [[VZMultipleDirectoryShare alloc]+ initWithDirectories:@{@"Host Share": directory}];+ VZVirtioFileSystemDeviceConfiguration *fileSystem =+ [[VZVirtioFileSystemDeviceConfiguration alloc]+ initWithTag:[VZVirtioFileSystemDeviceConfiguration+ macOSGuestAutomountTag]];+ fileSystem.share = share;+ config.directorySharingDevices = @[fileSystem];+ printf("SHARED_DIRECTORY\t%s\ttag=%s\n", sharedPath,+ fileSystem.tag.UTF8String);+ }+ return config;+}++int main(int argc, const char *argv[])+{+ @autoreleasepool {+ const char *logPath = getenv("VZ_LOG_PATH");+ if (logPath) {+ freopen(logPath, "w", stdout);+ freopen(logPath, "a", stderr);+ }+ setvbuf(stdout, NULL, _IONBF, 0);+ if (argc != 2) {+ fprintf(stderr, "usage: vzmacboot <VM.bundle>\n");+ return 2;+ }++ NSURL *bundleURL = [NSURL fileURLWithPath:@(argv[1]) isDirectory:YES];+ VZVirtualMachineConfiguration *config = configuration(bundleURL);+ if (!config) {+ fprintf(stderr, "error: could not construct VM configuration\n");+ return 1;+ }+ NSError *error = nil;+ BOOL valid = [config validateWithError:&error];+ printf("CONFIG_VALID\t%d\t%s\n", valid,+ error ? error.localizedDescription.UTF8String : "ok");+ printLoadedFrameworks();+ if (!valid)+ return 1;++ static VMDelegate *delegate;+ delegate = [[VMDelegate alloc] init];+ machine = [[VZVirtualMachine alloc] initWithConfiguration:config];+ machine.delegate = delegate;+ printf("VM_CREATED\t%p\tcanStart=%d\n", machine, machine.canStart);++ BOOL gui = getenv("VZ_GUI") != NULL;+ if (gui) {+ [NSApplication sharedApplication];+ [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];+ NSRect frame = NSMakeRect(0, 0, 1280, 800);+ vmWindow = [[NSWindow alloc]+ initWithContentRect:frame+ styleMask:(NSWindowStyleMaskTitled |+ NSWindowStyleMaskClosable |+ NSWindowStyleMaskMiniaturizable |+ NSWindowStyleMaskResizable)+ backing:NSBackingStoreBuffered+ defer:NO];+ vmWindow.title = @"macOS 13.2.1 — Virtual Mac extraction control";+ VZVirtualMachineView *view =+ [[VZVirtualMachineView alloc] initWithFrame:frame];+ view.virtualMachine = machine;+ view.capturesSystemKeys = YES;+ vmWindow.contentView = view;+ [vmWindow center];+ [vmWindow makeKeyAndOrderFront:nil];+ [NSApp activateIgnoringOtherApps:YES];+ printf("GUI_WINDOW\tvisible=1\tframe=1280x800\n");+ }++ [machine startWithCompletionHandler:^(NSError *startError) {+ printf("START_COMPLETION\t%s\tstate=%ld\n",+ startError ? startError.localizedDescription.UTF8String : "ok",+ (long)machine.state);+ if (startError) {+ printError(@"START", startError);+ exit(1);+ }+ }];++ __block unsigned ticks = 0;+ dispatch_source_t timer =+ dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,+ dispatch_get_main_queue());+ dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0),+ 5 * NSEC_PER_SEC, NSEC_PER_SEC / 10);+ dispatch_source_set_event_handler(timer, ^{+ ticks++;+ printf("VM_STATE\tseconds=%u\tstate=%ld\n", ticks * 5,+ (long)machine.state);+ const char *limit = getenv("VZ_RUN_SECONDS");+ unsigned seconds = limit ? (unsigned)strtoul(limit, NULL, 10) : 300;+ if (ticks * 5 >= seconds)+ finishStop();+ });+ dispatch_resume(timer);+ if (gui)+ [NSApp run];+ else+ dispatch_main();+ }+ return 0;+}diff --git a/VirtualMac/vz/development/probes/window_list_probe.m b/VirtualMac/vz/development/probes/window_list_probe.mnew file mode 100644index 0000000..12bc010--- /dev/null+++ b/VirtualMac/vz/development/probes/window_list_probe.m@@ -0,0 +1,32 @@+#import <CoreGraphics/CoreGraphics.h>+#import <Foundation/Foundation.h>++int main(void) {+ @autoreleasepool {+ CGRect screen = CGDisplayBounds(CGMainDisplayID());+ printf("screen width=%.0f height=%.0f\n",+ screen.size.width, screen.size.height);+ NSArray *windows = CFBridgingRelease(CGWindowListCopyWindowInfo(+ kCGWindowListOptionOnScreenOnly, kCGNullWindowID));+ for (NSDictionary *window in windows) {+ NSString *owner = window[(id)kCGWindowOwnerName];+ NSString *name = window[(id)kCGWindowName];+ NSDictionary *boundsDictionary = window[(id)kCGWindowBounds];+ CGRect bounds = CGRectZero;+ CGRectMakeWithDictionaryRepresentation(+ (CFDictionaryRef)boundsDictionary, &bounds);+ NSNumber *layer = window[(id)kCGWindowLayer];+ NSNumber *windowID = window[(id)kCGWindowNumber];+ if (owner.length || name.length)+ printf("id=%s layer=%s owner=%s name=%s "+ "x=%.0f y=%.0f width=%.0f height=%.0f\n",+ windowID.stringValue.UTF8String,+ layer.stringValue.UTF8String,+ owner.UTF8String ?: "",+ name.UTF8String ?: "",+ bounds.origin.x, bounds.origin.y,+ bounds.size.width, bounds.size.height);+ }+ }+ return 0;+}diff --git a/VirtualMac/vz/fixup_enum.py b/VirtualMac/vz/fixup_enum.pynew file mode 100644index 0000000..30e5324--- /dev/null+++ b/VirtualMac/vz/fixup_enum.py@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""Enumerate the slide-info-v3 fixups for one image in an arm64e dyld cache.++Reuses DyldExtractor's cache parsing + V3 page-chain walk, but RECORDS each+fixup (target + auth: key/diversity/authenticated) instead of discarding it+(which is all DyldExtractor does). Classifies in-image (rebase) vs external+(bind) and tallies authenticated pointers.++Usage: python3 fixup_enum.py <main-cache> <image-path-substring>+"""+import sys, struct, logging+import progressbar++from DyldExtractor.extraction_context import ExtractionContext+from DyldExtractor.macho.macho_context import MachOContext+from DyldExtractor.dyld.dyld_context import DyldContext+from DyldExtractor.dyld.dyld_structs import dyld_cache_slide_pointer3+from DyldExtractor.dyld.dyld_constants import DYLD_CACHE_SLIDE_V3_PAGE_ATTR_NO_REBASE+from DyldExtractor.converter import slide_info+++def enumerate_fixups(dsc_path, image_substr):+ logger = logging.getLogger()+ logging.basicConfig(level=100)+ statusBar = progressbar.ProgressBar(+ prefix="{variables.unit} >> {variables.status} :: [",+ variables={"unit": "--", "status": "--"},+ widgets=[progressbar.widgets.AnimatedMarker(), "]"], redirect_stdout=True)++ with open(dsc_path, "rb") as f:+ dyldCtx = DyldContext(f)+ subs = dyldCtx.addSubCaches(__import__("pathlib").Path(dsc_path))+ try:+ # locate the image+ target_img = None+ for imageData in dyldCtx.images:+ p = dyldCtx.readString(imageData.pathFileOffset)[:-1].decode("utf-8")+ if image_substr in p:+ target_img = imageData+ target_path = p+ break+ if not target_img:+ print("image not found"); return+ print(f"image: {target_path}")++ machoOffset, context = dyldCtx.convertAddr(target_img.address)+ machoCtx = MachOContext(context.fileObject, machoOffset, True)+ if dyldCtx.hasSubCaches():+ mappings = dyldCtx.mappings+ mainFileMap = next(m[0] for m in mappings if m[1] == context)+ machoCtx.addSubfiles(mainFileMap, ((m, c.makeCopy(copyMode=True)) for m, c in mappings))+ extractionCtx = ExtractionContext(dyldCtx, machoCtx, statusBar, logger)++ # image segment vmaddr ranges (for in-image classification)+ seg_ranges = []+ for seg in machoCtx.segmentsI:+ s = seg.seg+ seg_ranges.append((s.vmaddr, s.vmaddr + s.vmsize, bytes(s.segname).rstrip(b"\0").decode()))+ in_image = lambda a: any(lo <= a < hi for lo, hi, _ in seg_ranges)+ print("segments:")+ for lo, hi, nm in seg_ranges:+ print(f" {nm:16} {lo:#014x} - {hi:#014x}")++ # collector subclass of the V3 rebaser+ recs = [] # (addr, target, authenticated, key, diversity)++ class Collector(slide_info._V3Rebaser):+ def _rebasePage(self, ctx, pageOffset, delta):+ locOff = pageOffset+ while True:+ locOff += delta+ li = dyld_cache_slide_pointer3(self.dyldCtx.file, locOff)+ delta = li.plain.offsetToNextPointer * 8+ addr = self.mapping.address + (locOff - self.mapping.fileOffset)+ if not in_image(addr):+ # shared 16KB cache page: skip fixups belonging to neighbor images+ if delta == 0:+ break+ continue+ if li.auth.authenticated:+ tgt = li.auth.offsetFromSharedCacheBase + self.slideInfo.auth_value_add+ recs.append((addr, tgt, 1, int(li.auth.key), int(li.auth.diversityData)))+ else:+ v = li.plain.pointerValue+ tgt = ((v & 0x0007F80000000000) << 13) | (v & 0x000007FFFFFFFFFF)+ recs.append((addr, tgt, 0, 0, 0))+ if delta == 0:+ break++ for info in slide_info._getMappingInfo(extractionCtx):+ if info.slideInfo.version == 3:+ Collector(extractionCtx, info).run()++ auth = sum(r[2] for r in recs)+ rebases = [r for r in recs if in_image(r[1])]+ binds = [r for r in recs if not in_image(r[1])]+ print(f"\n=== {len(recs)} fixups in image ===")+ print(f" authenticated : {auth}")+ print(f" non-auth : {len(recs)-auth}")+ print(f" in-image (REBASE): {len(rebases)}")+ print(f" external (BIND) : {len(binds)}")+ print(" sample binds (addr -> target):")+ for r in binds[:8]:+ print(f" {r[0]:#014x} -> {r[1]:#014x} auth={r[2]} key={r[3]} div={r[4]}")+ print(" sample rebases:")+ for r in rebases[:6]:+ print(f" {r[0]:#014x} -> {r[1]:#014x} auth={r[2]} key={r[3]} div={r[4]}")+ finally:+ for sf in subs:+ sf.close()+++if __name__ == "__main__":+ enumerate_fixups(sys.argv[1], sys.argv[2])diff --git a/VirtualMac/vz/host/CoreUtils-iOS.tbd b/VirtualMac/vz/host/CoreUtils-iOS.tbdnew file mode 100644index 0000000..33abac4--- /dev/null+++ b/VirtualMac/vz/host/CoreUtils-iOS.tbd@@ -0,0 +1,10 @@+--- !tapi-tbd+tbd-version: 4+targets: [ arm64-ios ]+install-name: '/System/Library/PrivateFrameworks/CoreUtils.framework/CoreUtils'+current-version: 1+compatibility-version: 1+exports:+ - targets: [ arm64-ios ]+ symbols: [ _CryptoHKDF, _kCryptoHashDescriptor_SHA512 ]+...diff --git a/VirtualMac/vz/host/DiskArbitration-iOS.tbd b/VirtualMac/vz/host/DiskArbitration-iOS.tbdnew file mode 100644index 0000000..95e97ca--- /dev/null+++ b/VirtualMac/vz/host/DiskArbitration-iOS.tbd@@ -0,0 +1,11 @@+--- !tapi-tbd+tbd-version: 4+targets: [ arm64-ios ]+install-name: '/System/Library/PrivateFrameworks/DiskArbitration.framework/DiskArbitration'+current-version: 1+compatibility-version: 1+exports:+ - targets: [ arm64-ios ]+ symbols: [ _DADiskCreateFromBSDName, _DADiskMountWithArguments,+ _DASessionCreate, _DASessionSetDispatchQueue ]+...diff --git a/VirtualMac/vz/host/DiskImages-iOS.tbd b/VirtualMac/vz/host/DiskImages-iOS.tbdnew file mode 100644index 0000000..1278b00--- /dev/null+++ b/VirtualMac/vz/host/DiskImages-iOS.tbd@@ -0,0 +1,10 @@+--- !tapi-tbd+tbd-version: 4+targets: [ arm64-ios ]+install-name: '/System/Library/PrivateFrameworks/DiskImages.framework/DiskImages'+current-version: 1+compatibility-version: 1+exports:+ - targets: [ arm64-ios ]+ symbols: [ _DICopyStrError, _DIHLDiskImageAttach, _DIInitialize ]+...diff --git a/VirtualMac/vz/host/NSViewShim.h b/VirtualMac/vz/host/NSViewShim.hnew file mode 100644index 0000000..ec19ea2--- /dev/null+++ b/VirtualMac/vz/host/NSViewShim.h@@ -0,0 +1,30 @@+#import <UIKit/UIKit.h>++// The extracted macOS Virtualization framework weak-links AppKit. Providing the+// NSView class symbol lets dyld register VZVirtualMachineView and+// _VZFramebufferView on iOS. UIView supplies geometry, hierarchy, window, and+// a backing CALayer; these additions cover the AppKit layer-backed view API.+@interface NSView : UIView+{+ CALayer *_appKitLayer;+}+@property(nonatomic) BOOL wantsLayer;+@property(nonatomic, retain) CALayer *layer;+@end++@interface UIWindow (VZAppKitOcclusion)+- (NSUInteger)occlusionState;+@end++// Weak AppKit globals referenced by VZVirtualMachineView and+// _VZFramebufferView. Export matching NSString constants before the extracted+// framework is loaded so its flat-namespace bindings are non-null.+FOUNDATION_EXPORT NSString *const NSApplicationWillTerminateNotification;+FOUNDATION_EXPORT NSString *const NSWindowDidBecomeKeyNotification;+FOUNDATION_EXPORT NSString *const NSWindowDidChangeOcclusionStateNotification;+FOUNDATION_EXPORT NSString *const NSWindowDidResignKeyNotification;++// A framebuffer observer must be registered before VZ finishes wiring its XPC+// handlers, but the shim window reports itself occluded until the VM starts so+// that registration does not request frames prematurely.+void VZSetNSViewFrameRequestsSuppressed(BOOL suppressed);diff --git a/VirtualMac/vz/host/NSViewShim.m b/VirtualMac/vz/host/NSViewShim.mnew file mode 100644index 0000000..cae2176--- /dev/null+++ b/VirtualMac/vz/host/NSViewShim.m@@ -0,0 +1,109 @@+#import "NSViewShim.h"++NSString *const NSApplicationWillTerminateNotification =+ @"NSApplicationWillTerminateNotification";+NSString *const NSWindowDidBecomeKeyNotification =+ @"NSWindowDidBecomeKeyNotification";+NSString *const NSWindowDidChangeOcclusionStateNotification =+ @"NSWindowDidChangeOcclusionStateNotification";+NSString *const NSWindowDidResignKeyNotification =+ @"NSWindowDidResignKeyNotification";++static BOOL gVZSuppressFrameRequests;++// VZ's macOS trackpad haptic callback asks CoreGraphics Services to actuate+// the host trackpad. iPadOS has no CGS connection or equivalent host haptic+// device, and the extracted weak imports otherwise remain null and crash on+// the first guest click. A successful no-op preserves input semantics.+uint32_t CGSMainConnectionID(void)+{+ return 0;+}++int CGSActuateDeviceWithPattern(uint32_t connection,+ uint64_t device,+ uint32_t pattern,+ uint64_t options)+{+ (void)connection;+ (void)device;+ (void)pattern;+ (void)options;+ return 0;+}++void VZSetNSViewFrameRequestsSuppressed(BOOL suppressed)+{+ gVZSuppressFrameRequests = suppressed;+}++@implementation NSView+- (void)setWantsLayer:(BOOL)wantsLayer+{+ // UIView is always layer-backed.+ (void)wantsLayer;+}++- (BOOL)wantsLayer+{+ return YES;+}++- (void)setLayer:(CALayer *)layer+{+ if (_appKitLayer == layer)+ return;+ [_appKitLayer removeFromSuperlayer];+ [_appKitLayer release];+ _appKitLayer = [layer retain];+ _appKitLayer.frame = self.bounds;+ [[super layer] addSublayer:_appKitLayer];+}++- (CALayer *)layer+{+ return _appKitLayer ?: [super layer];+}++- (UIWindow *)window+{+ UIWindow *window = [super window];+ if (window)+ return window;+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {+ if (![scene isKindOfClass:[UIWindowScene class]])+ continue;+ for (UIWindow *candidate in ((UIWindowScene *)scene).windows)+ if (candidate.isKeyWindow)+ return candidate;+ }+ return nil;+}++- (void)layoutSubviews+{+ [super layoutSubviews];+ _appKitLayer.frame = self.bounds;+ if ([self respondsToSelector:@selector(layout)])+ [self performSelector:@selector(layout)];+}++- (void)layout+{+ // AppKit layout hook; UIView drives layout through layoutSubviews.+}++- (void)dealloc+{+ [_appKitLayer release];+ [super dealloc];+}+@end++@implementation UIWindow (VZAppKitOcclusion)+- (NSUInteger)occlusionState+{+ // NSWindowOcclusionStateVisible.+ return self.hidden || gVZSuppressFrameRequests ? 0 : 2;+}+@enddiff --git a/VirtualMac/vz/host/Security-iOS.tbd b/VirtualMac/vz/host/Security-iOS.tbdnew file mode 100644index 0000000..f313a24--- /dev/null+++ b/VirtualMac/vz/host/Security-iOS.tbd@@ -0,0 +1,10 @@+--- !tapi-tbd+tbd-version: 4+targets: [ arm64-ios ]+install-name: '/System/Library/Frameworks/Security.framework/Security'+current-version: 1+compatibility-version: 1+exports:+ - targets: [ arm64-ios ]+ symbols: [ _SecItemCopyMatching ]+...diff --git a/VirtualMac/vz/host/VZAppSettings.h b/VirtualMac/vz/host/VZAppSettings.hnew file mode 100644index 0000000..2425302--- /dev/null+++ b/VirtualMac/vz/host/VZAppSettings.h@@ -0,0 +1,28 @@+#import <Foundation/Foundation.h>++NS_ASSUME_NONNULL_BEGIN++FOUNDATION_EXPORT NSString * const VZSettingsDidChangeNotification;+FOUNDATION_EXPORT NSString * const VZLibraryLayoutKey;+FOUNDATION_EXPORT NSString * const VZAutoBootVMPathKey;+FOUNDATION_EXPORT NSString * const VZAutoBootVMIdentifierKey;+FOUNDATION_EXPORT NSString * const VZKeyboardShortcutCaptureKey;+FOUNDATION_EXPORT NSString * const VZSystemGestureSuppressionKey;+FOUNDATION_EXPORT NSString * const VZMultitaskingGestureSuppressionKey;+FOUNDATION_EXPORT NSString * const VZHomeIndicatorSuppressionKey;+FOUNDATION_EXPORT NSString * const VZShowStatusLabelKey;+FOUNDATION_EXPORT NSString * const VZAutoDeleteRestoreImageKey;+FOUNDATION_EXPORT NSString * const VZHUDVisibilityKey;+FOUNDATION_EXPORT NSString * const VZHUDCornerKey;+FOUNDATION_EXPORT NSString * const VZDisplayScalingKey;++@interface VZAppSettings : NSObject++ (instancetype)sharedSettings;+- (BOOL)boolForKey:(NSString *)key;+- (nullable NSString *)stringForKey:(NSString *)key;+- (void)setBool:(BOOL)value forKey:(NSString *)key;+- (void)setString:(nullable NSString *)value forKey:(NSString *)key;+- (NSDictionary *)dictionaryRepresentation;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VirtualMac/vz/host/VZAppSettings.m b/VirtualMac/vz/host/VZAppSettings.mnew file mode 100644index 0000000..3053f0f--- /dev/null+++ b/VirtualMac/vz/host/VZAppSettings.m@@ -0,0 +1,118 @@+#import "VZAppSettings.h"++NSString * const VZSettingsDidChangeNotification = @"VZSettingsDidChange";+NSString * const VZLibraryLayoutKey = @"LibraryLayout";+NSString * const VZAutoBootVMPathKey = @"AutoBootVMPath";+NSString * const VZAutoBootVMIdentifierKey = @"AutoBootVMIdentifier";+NSString * const VZKeyboardShortcutCaptureKey = @"KeyboardShortcutCapture";+NSString * const VZSystemGestureSuppressionKey = @"SystemGestureSuppression";+NSString * const VZMultitaskingGestureSuppressionKey = @"MultitaskingGestureSuppression";+NSString * const VZHomeIndicatorSuppressionKey = @"HomeIndicatorSuppression";+NSString * const VZShowStatusLabelKey = @"ShowStatusLabel";+NSString * const VZAutoDeleteRestoreImageKey = @"AutoDeleteRestoreImage";+NSString * const VZHUDVisibilityKey = @"HUDVisibility";+NSString * const VZHUDCornerKey = @"HUDCorner";+NSString * const VZDisplayScalingKey = @"DisplayScaling";++static NSString * const VZSettingsPath = @"/var/mobile/Media/VirtualMac/Settings.plist";+static CFStringRef const VZSettingsDarwinNotification =+ CFSTR("com.mac.virtual.settings-changed");++@interface VZAppSettings ()+@property(nonatomic, retain) NSMutableDictionary *values;+@end++@implementation VZAppSettings+++ (instancetype)sharedSettings+{+ static VZAppSettings *settings;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ settings = [[self alloc] init]; });+ return settings;+}++- (instancetype)init+{+ if ((self = [super init])) {+ NSDictionary *saved = [NSDictionary dictionaryWithContentsOfFile:VZSettingsPath];+ _values = [[NSMutableDictionary alloc] initWithDictionary:+ [saved isKindOfClass:NSDictionary.class] ? saved : @{}];+ }+ return self;+}++- (NSDictionary *)defaults+{+ return @{+ VZLibraryLayoutKey: @"grid",+ VZKeyboardShortcutCaptureKey: @YES,+ VZSystemGestureSuppressionKey: @NO,+ VZMultitaskingGestureSuppressionKey: @NO,+ VZHomeIndicatorSuppressionKey: @YES,+ VZShowStatusLabelKey: @NO,+ VZAutoDeleteRestoreImageKey: @YES,+ VZHUDVisibilityKey: @"automatic",+ VZHUDCornerKey: @"top-right",+ VZDisplayScalingKey: @"fit",+ };+}++- (id)valueForSettingKey:(NSString *)key+{+ return self.values[key] ?: [self defaults][key];+}++- (BOOL)boolForKey:(NSString *)key+{+ return [[self valueForSettingKey:key] boolValue];+}++- (NSString *)stringForKey:(NSString *)key+{+ id value = [self valueForSettingKey:key];+ return [value isKindOfClass:NSString.class] ? value : nil;+}++- (void)save+{+ NSString *directory = VZSettingsPath.stringByDeletingLastPathComponent;+ [NSFileManager.defaultManager createDirectoryAtPath:directory+ withIntermediateDirectories:YES attributes:nil error:nil];+ [self.values writeToFile:VZSettingsPath atomically:YES];+ CFNotificationCenterPostNotification(+ CFNotificationCenterGetDarwinNotifyCenter(),+ VZSettingsDarwinNotification, NULL, NULL, YES);+ [NSNotificationCenter.defaultCenter postNotificationName:+ VZSettingsDidChangeNotification object:self];+}++- (void)setBool:(BOOL)value forKey:(NSString *)key+{+ self.values[key] = @(value);+ [self save];+}++- (void)setString:(NSString *)value forKey:(NSString *)key+{+ if (value.length)+ self.values[key] = value;+ else+ [self.values removeObjectForKey:key];+ [self save];+}++- (NSDictionary *)dictionaryRepresentation+{+ NSMutableDictionary *result = [NSMutableDictionary dictionaryWithDictionary:[self defaults]];+ [result addEntriesFromDictionary:self.values];+ return result;+}++- (void)dealloc+{+ [_values release];+ [super dealloc];+}++@enddiff --git a/VirtualMac/vz/host/VZNewVMViewController.h b/VirtualMac/vz/host/VZNewVMViewController.hnew file mode 100644index 0000000..182aa17--- /dev/null+++ b/VirtualMac/vz/host/VZNewVMViewController.h@@ -0,0 +1,16 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++@class VZNewVMViewController;+@protocol VZNewVMViewControllerDelegate <NSObject>+- (void)newVMControllerChooseLocalRestoreImage:(VZNewVMViewController *)controller;+- (void)newVMController:(VZNewVMViewController *)controller+ downloadRestoreImage:(NSDictionary *)image;+@end++@interface VZNewVMViewController : UITableViewController+@property(nonatomic, assign) id<VZNewVMViewControllerDelegate> delegate;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VirtualMac/vz/host/VZNewVMViewController.m b/VirtualMac/vz/host/VZNewVMViewController.mnew file mode 100644index 0000000..1e8d095--- /dev/null+++ b/VirtualMac/vz/host/VZNewVMViewController.m@@ -0,0 +1,170 @@+#import "VZNewVMViewController.h"+#import "VZRestoreCatalog.h"++@interface VZRestoreCatalogViewController : UITableViewController+@property(nonatomic, retain) NSArray<NSDictionary *> *images;+@property(nonatomic, retain) NSArray<NSString *> *groups;+@property(nonatomic, copy) void (^selection)(NSDictionary *image);+@property(nonatomic, assign) BOOL showMinorReleases;+@property(nonatomic, assign) BOOL showDeveloperBetas;+@end++@implementation VZRestoreCatalogViewController+- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { (void)tableView; return self.groups.count; }+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ (void)tableView; NSString *group = self.groups[section];+ return [[self imagesForGroup:group] count];+}+- (void)viewDidLoad {+ [super viewDidLoad];+ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]+ initWithImage:[UIImage systemImageNamed:@"ellipsis.circle"]+ menu:[self filterMenu]] autorelease];+}+- (UIMenu *)filterMenu {+ UIAction *minor = [UIAction actionWithTitle:@"Show Minor Releases"+ image:nil identifier:nil handler:^(__kindof UIAction *action) {+ (void)action; self.showMinorReleases = !self.showMinorReleases;+ self.navigationItem.rightBarButtonItem.menu = [self filterMenu];+ [self.tableView reloadData];+ }];+ minor.state = self.showMinorReleases ? UIMenuElementStateOn : UIMenuElementStateOff;+ UIAction *betas = [UIAction actionWithTitle:@"Show Developer Betas"+ image:nil identifier:nil handler:^(__kindof UIAction *action) {+ (void)action; self.showDeveloperBetas = !self.showDeveloperBetas;+ self.navigationItem.rightBarButtonItem.menu = [self filterMenu];+ [self.tableView reloadData];+ }];+ betas.state = self.showDeveloperBetas ? UIMenuElementStateOn : UIMenuElementStateOff;+ return [UIMenu menuWithTitle:@"Available Restore Images"+ children:@[minor, betas]];+}+- (NSArray *)imagesForGroup:(NSString *)group {+ if ([group isEqualToString:@"recommended"]) {+ NSDictionary *recommended = [VZRestoreCatalog+ recommendedImageFromImages:self.images];+ return recommended ? @[recommended] : @[];+ }+ NSArray *matches = [self.images filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:+ ^BOOL(NSDictionary *image, NSDictionary *bindings) {+ (void)bindings;+ NSDictionary *recommended = [VZRestoreCatalog+ recommendedImageFromImages:self.images];+ return [image[@"group"] isEqualToString:group] &&+ ![image[@"url"] isEqualToString:recommended[@"url"]];+ }]];+ NSArray *sorted = [matches sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {+ BOOL leftRelease = [left[@"channel"] isEqualToString:@"regular"];+ BOOL rightRelease = [right[@"channel"] isEqualToString:@"regular"];+ if (leftRelease != rightRelease) return leftRelease ? NSOrderedAscending : NSOrderedDescending;+ return [right[@"version"] compare:left[@"version"] options:NSNumericSearch];+ }];+ NSMutableArray *releases = [NSMutableArray array];+ NSMutableArray *betas = [NSMutableArray array];+ for (NSDictionary *image in sorted) {+ NSMutableArray *bucket = [image[@"channel"] isEqualToString:@"regular"] ? releases : betas;+ [bucket addObject:image];+ }+ NSMutableArray *visible = [NSMutableArray array];+ if (self.showMinorReleases)+ [visible addObjectsFromArray:releases];+ else if (releases.count)+ [visible addObject:releases.firstObject];+ if (self.showDeveloperBetas)+ [visible addObjectsFromArray:betas];+ else if (!releases.count && betas.count)+ [visible addObject:betas.firstObject];+ return visible;+}+- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {+ (void)tableView; NSString *group = self.groups[section];+ if ([group isEqualToString:@"recommended"])+ return @"Recommended";+ NSDictionary *names = @{@"sequoia":@"macOS Sequoia", @"sonoma":@"macOS Sonoma",+ @"ventura":@"macOS Ventura", @"monterey":@"macOS Monterey",+ @"tahoe":@"macOS Tahoe — Experimental", @"goldengate":@"macOS Golden Gate — Experimental"};+ return names[group] ?: group.capitalizedString;+}+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"image"];+ if (!cell) cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"image"] autorelease];+ NSDictionary *image = [self imagesForGroup:self.groups[indexPath.section]][indexPath.row];+ cell.imageView.image = nil;+ cell.textLabel.text = image[@"name"];+ NSByteCountFormatter *formatter = [[[NSByteCountFormatter alloc] init] autorelease];+ formatter.countStyle = NSByteCountFormatterCountStyleFile;+ NSString *channel = [image[@"channel"] isEqualToString:@"regular"] ? @"Release" : @"Developer Beta";+ cell.detailTextLabel.text = [NSString stringWithFormat:@"Build %@ · %@ · %@", image[@"build"], channel,+ [formatter stringFromByteCount:[image[@"downloadSize"] longLongValue]]];+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ return cell;+}+- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+ NSDictionary *image = [self imagesForGroup:self.groups[indexPath.section]][indexPath.row];+ if (self.selection) self.selection(image);+}+- (void)dealloc { [_images release]; [_groups release]; [_selection release]; [super dealloc]; }+@end++@interface VZNewVMViewController ()+@property(nonatomic, retain) NSArray<NSDictionary *> *catalog;+@property(nonatomic, retain) UIActivityIndicatorView *activity;+@end++@implementation VZNewVMViewController+- (instancetype)init { return [super initWithStyle:UITableViewStyleInsetGrouped]; }+- (void)viewDidLoad {+ [super viewDidLoad];+ self.title = @"New Virtual Mac";+ self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:+ UIBarButtonSystemItemCancel target:self action:@selector(cancel:)] autorelease];+ self.activity = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium] autorelease];+ [self.activity startAnimating];+ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:self.activity] autorelease];+ [VZRestoreCatalog loadWithCompletion:^(NSArray<NSDictionary *> *images, NSError *error) {+ self.catalog = images;+ [self.activity stopAnimating];+ self.navigationItem.rightBarButtonItem = nil;+ [self.tableView reloadData];+ if (error) NSLog(@"Virtual Mac restore catalog fallback failed: %@", error);+ }];+}+- (void)cancel:(id)sender { (void)sender; [self dismissViewControllerAnimated:YES completion:nil]; }+- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { (void)tableView; return 1; }+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { (void)tableView;(void)section; return 3; }+- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {+ (void)tableView; (void)section;+ return @"You can also copy an existing Virtual Mac bundle to /var/mobile/Media/VirtualMac using an app such as iMazing or Filza.";+}+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"choice"];+ if (!cell) cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"choice"] autorelease];+ NSArray *titles = @[@"Install Recommended macOS", @"Install macOS", @"Choose an IPSW"];+ NSArray *details = @[@"Download and install the latest macOS Sequoia release",+ @"Choose a macOS release or developer beta", @"Use an IPSW on this iPad"];+ NSArray *icons = @[@"checkmark.seal.fill", @"arrow.down.circle", @"doc.badge.plus"];+ cell.textLabel.text = titles[indexPath.row]; cell.detailTextLabel.text = details[indexPath.row];+ cell.imageView.image = [UIImage systemImageNamed:icons[indexPath.row]];+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ cell.selectionStyle = (indexPath.row < 2 && !self.catalog.count) ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleDefault;+ cell.textLabel.enabled = cell.selectionStyle != UITableViewCellSelectionStyleNone;+ return cell;+}+- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+ if (indexPath.row == 0) {+ NSDictionary *recommended = [VZRestoreCatalog recommendedImageFromImages:self.catalog];+ if (recommended) [self.delegate newVMController:self downloadRestoreImage:recommended];+ } else if (indexPath.row == 1 && self.catalog.count) {+ VZRestoreCatalogViewController *catalog = [[[VZRestoreCatalogViewController alloc] initWithStyle:UITableViewStyleInsetGrouped] autorelease];+ catalog.title = @"Install macOS"; catalog.images = self.catalog;+ NSMutableArray *groups = [NSMutableArray arrayWithObject:@"recommended"];+ [groups addObjectsFromArray:[VZRestoreCatalog orderedGroupsForImages:self.catalog]];+ catalog.groups = groups;+ catalog.selection = ^(NSDictionary *image) { [self.delegate newVMController:self downloadRestoreImage:image]; };+ [self.navigationController pushViewController:catalog animated:YES];+ } else if (indexPath.row == 2) [self.delegate newVMControllerChooseLocalRestoreImage:self];+}+- (void)dealloc { [_catalog release]; [_activity release]; [super dealloc]; }+@enddiff --git a/VirtualMac/vz/host/VZProgressViewController.h b/VirtualMac/vz/host/VZProgressViewController.hnew file mode 100644index 0000000..a60a6f3--- /dev/null+++ b/VirtualMac/vz/host/VZProgressViewController.h@@ -0,0 +1,16 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++@interface VZProgressViewController : UIViewController+@property(nonatomic, copy) NSString *statusText;+@property(nonatomic, copy, nullable) NSString *detailText;+@property(nonatomic, copy, nullable) NSString *consoleText;+@property(nonatomic, copy, nullable) dispatch_block_t cancellationHandler;+@property(nonatomic, assign) float progress;+@property(nonatomic, assign, getter=isIndeterminate) BOOL indeterminate;+@property(nonatomic, assign) BOOL consoleHidden;+- (instancetype)initWithTitle:(NSString *)title;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VirtualMac/vz/host/VZProgressViewController.m b/VirtualMac/vz/host/VZProgressViewController.mnew file mode 100644index 0000000..6392d56--- /dev/null+++ b/VirtualMac/vz/host/VZProgressViewController.m@@ -0,0 +1,124 @@+#import "VZProgressViewController.h"++@interface VZProgressViewController ()+@property(nonatomic, retain) UILabel *statusLabel;+@property(nonatomic, retain) UILabel *detailLabel;+@property(nonatomic, retain) UIProgressView *progressView;+@property(nonatomic, retain) UIActivityIndicatorView *activity;+@property(nonatomic, retain) UITextView *consoleView;+@end++@implementation VZProgressViewController++- (instancetype)initWithTitle:(NSString *)title+{+ if ((self = [super init])) {+ self.title = title;+ _statusText = [@"Preparing…" copy];+ _indeterminate = YES;+ }+ return self;+}++- (void)viewDidLoad+{+ [super viewDidLoad];+ self.view.backgroundColor = UIColor.systemBackgroundColor;+ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]+ initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self+ action:@selector(cancel:)] autorelease];++ self.statusLabel = [[[UILabel alloc] init] autorelease];+ self.statusLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];+ self.statusLabel.numberOfLines = 0;+ self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;+ self.detailLabel = [[[UILabel alloc] init] autorelease];+ self.detailLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];+ self.detailLabel.textColor = UIColor.secondaryLabelColor;+ self.detailLabel.numberOfLines = 0;+ self.detailLabel.translatesAutoresizingMaskIntoConstraints = NO;+ self.progressView = [[[UIProgressView alloc]+ initWithProgressViewStyle:UIProgressViewStyleDefault] autorelease];+ self.progressView.translatesAutoresizingMaskIntoConstraints = NO;+ self.activity = [[[UIActivityIndicatorView alloc]+ initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium] autorelease];+ self.activity.translatesAutoresizingMaskIntoConstraints = NO;+ self.consoleView = [[[UITextView alloc] init] autorelease];+ self.consoleView.translatesAutoresizingMaskIntoConstraints = NO;+ self.consoleView.editable = NO;+ self.consoleView.selectable = YES;+ self.consoleView.alwaysBounceVertical = YES;+ self.consoleView.backgroundColor = UIColor.secondarySystemBackgroundColor;+ self.consoleView.textColor = UIColor.labelColor;+ self.consoleView.font = [UIFont monospacedSystemFontOfSize:10+ weight:UIFontWeightRegular];+ self.consoleView.layer.cornerRadius = 10;+ self.consoleView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);+ for (UIView *view in @[self.statusLabel, self.detailLabel, self.progressView,+ self.activity, self.consoleView])+ [self.view addSubview:view];+ UILayoutGuide *guide = self.view.safeAreaLayoutGuide;+ [NSLayoutConstraint activateConstraints:@[+ [self.statusLabel.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor constant:24],+ [self.statusLabel.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor constant:-24],+ [self.statusLabel.topAnchor constraintEqualToAnchor:guide.topAnchor constant:24],+ [self.detailLabel.leadingAnchor constraintEqualToAnchor:self.statusLabel.leadingAnchor],+ [self.detailLabel.trailingAnchor constraintEqualToAnchor:self.statusLabel.trailingAnchor],+ [self.detailLabel.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:8],+ [self.progressView.leadingAnchor constraintEqualToAnchor:self.statusLabel.leadingAnchor],+ [self.progressView.trailingAnchor constraintEqualToAnchor:self.statusLabel.trailingAnchor],+ [self.progressView.topAnchor constraintEqualToAnchor:self.detailLabel.bottomAnchor constant:18],+ [self.activity.centerXAnchor constraintEqualToAnchor:self.progressView.centerXAnchor],+ [self.activity.centerYAnchor constraintEqualToAnchor:self.progressView.centerYAnchor],+ [self.consoleView.leadingAnchor constraintEqualToAnchor:self.statusLabel.leadingAnchor],+ [self.consoleView.trailingAnchor constraintEqualToAnchor:self.statusLabel.trailingAnchor],+ [self.consoleView.topAnchor constraintEqualToAnchor:self.progressView.bottomAnchor constant:18],+ [self.consoleView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor constant:-20],+ ]];+ self.preferredContentSize = CGSizeMake(620, 560);+ [self refresh];+}++- (void)cancel:(id)sender+{+ (void)sender;+ if (self.cancellationHandler) self.cancellationHandler();+}++- (void)refresh+{+ if (!self.isViewLoaded) return;+ self.statusLabel.text = self.statusText;+ self.detailLabel.text = self.detailText;+ self.detailLabel.hidden = !self.detailText.length;+ self.progressView.hidden = self.isIndeterminate;+ self.activity.hidden = !self.isIndeterminate;+ if (self.isIndeterminate) [self.activity startAnimating];+ else [self.activity stopAnimating];+ [self.progressView setProgress:self.progress animated:YES];+ self.consoleView.hidden = self.consoleHidden;+ if (![self.consoleView.text isEqualToString:self.consoleText]) {+ BOOL followsTail = self.consoleView.contentSize.height <= self.consoleView.bounds.size.height + 1 ||+ self.consoleView.contentOffset.y + self.consoleView.bounds.size.height >=+ self.consoleView.contentSize.height - 24;+ self.consoleView.text = self.consoleText ?: @"";+ if (followsTail && self.consoleText.length)+ [self.consoleView scrollRangeToVisible:NSMakeRange(self.consoleText.length - 1, 1)];+ }+}++- (void)setStatusText:(NSString *)value { if (_statusText != value) { [_statusText release]; _statusText = [value copy]; [self refresh]; } }+- (void)setDetailText:(NSString *)value { if (_detailText != value) { [_detailText release]; _detailText = [value copy]; [self refresh]; } }+- (void)setConsoleText:(NSString *)value { if (_consoleText != value) { [_consoleText release]; _consoleText = [value copy]; [self refresh]; } }+- (void)setProgress:(float)value { _progress = value; [self refresh]; }+- (void)setIndeterminate:(BOOL)value { _indeterminate = value; [self refresh]; }+- (void)setConsoleHidden:(BOOL)value { _consoleHidden = value; [self refresh]; }++- (void)dealloc+{+ [_statusText release]; [_detailText release]; [_consoleText release];+ [_cancellationHandler release]; [_statusLabel release]; [_detailLabel release];+ [_progressView release]; [_activity release]; [_consoleView release];+ [super dealloc];+}+@enddiff --git a/VirtualMac/vz/host/VZRestoreCatalog.h b/VirtualMac/vz/host/VZRestoreCatalog.hnew file mode 100644index 0000000..0ad766b--- /dev/null+++ b/VirtualMac/vz/host/VZRestoreCatalog.h@@ -0,0 +1,12 @@+#import <Foundation/Foundation.h>++NS_ASSUME_NONNULL_BEGIN++@interface VZRestoreCatalog : NSObject++ (void)loadWithCompletion:(void (^)(NSArray<NSDictionary *> *images,+ NSError *_Nullable error))completion;++ (nullable NSDictionary *)recommendedImageFromImages:(NSArray<NSDictionary *> *)images;++ (NSArray<NSString *> *)orderedGroupsForImages:(NSArray<NSDictionary *> *)images;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VirtualMac/vz/host/VZRestoreCatalog.m b/VirtualMac/vz/host/VZRestoreCatalog.mnew file mode 100644index 0000000..f589168--- /dev/null+++ b/VirtualMac/vz/host/VZRestoreCatalog.m@@ -0,0 +1,59 @@+#import "VZRestoreCatalog.h"++static NSString * const VZCatalogURL =+ @"https://api.virtualbuddy.app/v2/restore/mac?apiKey=15A25D48-4A34-4EE4-A293-C22B0DE1B54E";++@implementation VZRestoreCatalog+++ (NSArray *)imagesFromData:(NSData *)data error:(NSError **)error+{+ if (!data.length) return nil;+ NSDictionary *root = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];+ NSArray *images = [root isKindOfClass:NSDictionary.class] ? root[@"restoreImages"] : nil;+ return [images isKindOfClass:NSArray.class] ? images : nil;+}+++ (void)loadWithCompletion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion+{+ NSURL *url = [NSURL URLWithString:VZCatalogURL];+ [[[NSURLSession sharedSession] dataTaskWithURL:url+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSError *parseError = nil;+ NSArray *images = [self imagesFromData:data error:&parseError];+ if (!images.count) {+ NSString *fallback = [NSBundle.mainBundle pathForResource:@"ipsws_v2" ofType:@"json"];+ NSData *fallbackData = [NSData dataWithContentsOfFile:fallback];+ images = [self imagesFromData:fallbackData error:&parseError];+ }+ NSArray *result = images ?: @[];+ dispatch_async(dispatch_get_main_queue(), ^{+ completion(result, result.count ? nil : (error ?: parseError));+ });+ }] resume];+}+++ (NSDictionary *)recommendedImageFromImages:(NSArray<NSDictionary *> *)images+{+ NSArray *matches = [images filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:+ ^BOOL(NSDictionary *image, NSDictionary *bindings) {+ (void)bindings;+ return [image[@"group"] isEqualToString:@"sequoia"] &&+ [image[@"channel"] isEqualToString:@"regular"];+ }]];+ return [matches sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {+ return [right[@"version"] compare:left[@"version"] options:NSNumericSearch];+ }].firstObject;+}+++ (NSArray<NSString *> *)orderedGroupsForImages:(NSArray<NSDictionary *> *)images+{+ NSArray *preferred = @[@"goldengate", @"tahoe", @"sequoia",+ @"sonoma", @"ventura", @"monterey"];+ NSMutableArray *result = [NSMutableArray array];+ NSSet *present = [NSSet setWithArray:[images valueForKey:@"group"]];+ for (NSString *group in preferred) if ([present containsObject:group]) [result addObject:group];+ for (NSString *group in present) if (![result containsObject:group]) [result addObject:group];+ return result;+}++@enddiff --git a/VirtualMac/vz/host/VZSettingsViewController.h b/VirtualMac/vz/host/VZSettingsViewController.hnew file mode 100644index 0000000..7925e2a--- /dev/null+++ b/VirtualMac/vz/host/VZSettingsViewController.h@@ -0,0 +1,9 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++@interface VZSettingsViewController : UITableViewController+- (instancetype)initWithMachines:(NSArray<NSDictionary *> *)machines;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VirtualMac/vz/host/VZSettingsViewController.m b/VirtualMac/vz/host/VZSettingsViewController.mnew file mode 100644index 0000000..942c518--- /dev/null+++ b/VirtualMac/vz/host/VZSettingsViewController.m@@ -0,0 +1,280 @@+#import "VZSettingsViewController.h"+#import "VZAppSettings.h"+#import "VZVMLibraryViewController.h"++@interface VZSettingsViewController ()+@property(nonatomic, retain) NSArray<NSDictionary *> *machines;+@end++@implementation VZSettingsViewController++- (instancetype)initWithMachines:(NSArray<NSDictionary *> *)machines+{+ if ((self = [super initWithStyle:UITableViewStyleInsetGrouped]))+ _machines = [machines copy];+ return self;+}++- (void)viewDidLoad+{+ [super viewDidLoad];+ self.title = @"Settings";+ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]+ initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self+ action:@selector(done:)] autorelease];+}++- (void)done:(id)sender+{+ (void)sender;+ [self dismissViewControllerAnimated:YES completion:nil];+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView+{+ (void)tableView;+ return 4;+}++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section+{+ (void)tableView;+ return section == 0 ? 3 : section == 1 ? 5 : section == 2 ? 1 : 3;+}++- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section+{+ (void)tableView;+ return @[@"General", @"Input While a Virtual Mac Is Running", @"Diagnostics", @"Storage"][section];+}++- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section+{+ (void)tableView;+ if (section == 0)+ return [NSString stringWithFormat:@"Virtual Mac devices are stored in %@.", VZVMLibraryPath()];+ if (section == 1)+ return @"These options affect iPadOS only while Virtual Mac is frontmost and a virtual Mac is running.";+ return nil;+}++- (UITableViewCell *)baseCellForTableView:(UITableView *)tableView identifier:(NSString *)identifier+{+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];+ if (!cell)+ cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1+ reuseIdentifier:identifier] autorelease];+ cell.accessoryView = nil;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ cell.textLabel.textColor = UIColor.labelColor;+ cell.textLabel.textAlignment = NSTextAlignmentNatural;+ cell.detailTextLabel.text = nil;+ cell.imageView.image = nil;+ return cell;+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath+{+ VZAppSettings *settings = VZAppSettings.sharedSettings;+ UITableViewCell *cell = [self baseCellForTableView:tableView identifier:@"setting"];+ if (indexPath.section == 0 && indexPath.row == 0) {+ cell.textLabel.text = @"Start on Launch";+ NSString *path = [settings stringForKey:VZAutoBootVMPathKey];+ NSString *identifier = [settings stringForKey:VZAutoBootVMIdentifierKey];+ NSDictionary *selected = nil;+ for (NSDictionary *machine in self.machines)+ if ([machine[@"path"] isEqualToString:path] ||+ (identifier.length && [VZVMStableIdentifier(machine[@"path"])+ isEqualToString:identifier])) selected = machine;+ cell.detailTextLabel.text = selected[@"name"] ?: @"Show Library";+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ } else if (indexPath.section == 0 && indexPath.row == 1) {+ cell.textLabel.text = @"Virtual Mac Display";+ cell.detailTextLabel.text = [[settings stringForKey:VZDisplayScalingKey]+ isEqualToString:@"fill"] ? @"Fill Window" : @"Fit in Window";+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ } else if (indexPath.section == 0) {+ cell.textLabel.text = @"Copy Library Path";+ cell.imageView.image = [UIImage systemImageNamed:@"doc.on.doc"];+ } else if (indexPath.section == 1 && indexPath.row < 4) {+ NSArray *titles = @[@"Mac Keyboard Shortcuts", @"Suppress iPadOS System Edge Gestures",+ @"Suppress iPadOS Multitasking Gestures", @"Suppress iPadOS Home Indicator"];+ NSArray *keys = @[VZKeyboardShortcutCaptureKey, VZSystemGestureSuppressionKey,+ VZMultitaskingGestureSuppressionKey, VZHomeIndicatorSuppressionKey];+ cell.textLabel.text = titles[indexPath.row];+ UISwitch *toggle = [[[UISwitch alloc] init] autorelease];+ toggle.tag = indexPath.row;+ toggle.on = [settings boolForKey:keys[indexPath.row]];+ [toggle addTarget:self action:@selector(inputToggleChanged:)+ forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = toggle;+ cell.selectionStyle = UITableViewCellSelectionStyleNone;+ } else if (indexPath.section == 1) {+ cell.textLabel.text = @"Virtual Mac Controls";+ NSDictionary *names = @{@"automatic": @"Automatic", @"always": @"Always Visible",+ @"hidden": @"Always Hidden"};+ cell.detailTextLabel.text = names[[settings stringForKey:VZHUDVisibilityKey]] ?: @"Automatic";+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ } else if (indexPath.section == 2) {+ cell.textLabel.text = @"Show Virtual Mac Status Overlay";+ UISwitch *toggle = [[[UISwitch alloc] init] autorelease];+ toggle.on = [settings boolForKey:VZShowStatusLabelKey];+ [toggle addTarget:self action:@selector(statusToggleChanged:)+ forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = toggle;+ cell.selectionStyle = UITableViewCellSelectionStyleNone;+ } else if (indexPath.row == 0) {+ cell.textLabel.text = @"Delete IPSW After Installation";+ UISwitch *toggle = [[[UISwitch alloc] init] autorelease];+ toggle.on = [settings boolForKey:VZAutoDeleteRestoreImageKey];+ [toggle addTarget:self action:@selector(autoDeleteToggleChanged:)+ forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = toggle;+ cell.selectionStyle = UITableViewCellSelectionStyleNone;+ } else {+ NSArray *paths = indexPath.row == 1 ? VZInstallationArtifactPaths()+ : VZCachedRestoreImagePaths();+ cell.textLabel.text = indexPath.row == 1 ? @"Delete Installation Artifacts"+ : @"Delete Cached Restore Images";+ cell.detailTextLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)paths.count];+ cell.textLabel.textColor = paths.count ? UIColor.systemRedColor : UIColor.secondaryLabelColor;+ cell.selectionStyle = paths.count ? UITableViewCellSelectionStyleDefault+ : UITableViewCellSelectionStyleNone;+ }+ return cell;+}++- (void)inputToggleChanged:(UISwitch *)sender+{+ NSArray *keys = @[VZKeyboardShortcutCaptureKey, VZSystemGestureSuppressionKey,+ VZMultitaskingGestureSuppressionKey, VZHomeIndicatorSuppressionKey];+ [VZAppSettings.sharedSettings setBool:sender.on forKey:keys[sender.tag]];+}++- (void)chooseDisplayScalingFrom:(UITableViewCell *)cell+{+ UIAlertController *picker = [UIAlertController+ alertControllerWithTitle:@"Virtual Mac Display"+ message:@"Fit in Window shows the entire display. Fill Window crops its edges when the window has a different shape."+ preferredStyle:UIAlertControllerStyleActionSheet];+ NSArray *titles = @[@"Fit in Window", @"Fill Window"];+ NSArray *values = @[@"fit", @"fill"];+ for (NSUInteger index = 0; index < titles.count; index++) {+ [picker addAction:[UIAlertAction actionWithTitle:titles[index]+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ [VZAppSettings.sharedSettings setString:values[index]+ forKey:VZDisplayScalingKey];+ [self.tableView reloadData];+ }]];+ }+ [picker addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ picker.popoverPresentationController.sourceView = cell;+ picker.popoverPresentationController.sourceRect = cell.bounds;+ [self presentViewController:picker animated:YES completion:nil];+}++- (void)statusToggleChanged:(UISwitch *)sender+{+ [VZAppSettings.sharedSettings setBool:sender.on forKey:VZShowStatusLabelKey];+}++- (void)autoDeleteToggleChanged:(UISwitch *)sender+{+ [VZAppSettings.sharedSettings setBool:sender.on forKey:VZAutoDeleteRestoreImageKey];+}++- (void)chooseHUDVisibilityFrom:(UITableViewCell *)cell+{+ UIAlertController *picker = [UIAlertController alertControllerWithTitle:@"Virtual Mac Controls"+ message:@"Automatic hides the controls when an external keyboard and pointing device are connected."+ preferredStyle:UIAlertControllerStyleActionSheet];+ NSArray *titles = @[@"Automatic", @"Always Visible", @"Always Hidden"];+ NSArray *values = @[@"automatic", @"always", @"hidden"];+ for (NSUInteger index = 0; index < titles.count; index++) {+ [picker addAction:[UIAlertAction actionWithTitle:titles[index]+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ [VZAppSettings.sharedSettings setString:values[index] forKey:VZHUDVisibilityKey];+ [self.tableView reloadData];+ }]];+ }+ [picker addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ picker.popoverPresentationController.sourceView = cell;+ picker.popoverPresentationController.sourceRect = cell.bounds;+ [self presentViewController:picker animated:YES completion:nil];+}++- (void)chooseAutoBootFrom:(UITableViewCell *)cell+{+ UIAlertController *picker = [UIAlertController alertControllerWithTitle:@"Start on Launch"+ message:@"Choose whether Virtual Mac opens its library or starts a virtual Mac."+ preferredStyle:UIAlertControllerStyleActionSheet];+ [picker addAction:[UIAlertAction actionWithTitle:@"Show Library"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ [VZAppSettings.sharedSettings setString:nil forKey:VZAutoBootVMPathKey];+ [VZAppSettings.sharedSettings setString:nil forKey:VZAutoBootVMIdentifierKey];+ [self.tableView reloadData];+ }]];+ for (NSDictionary *machine in self.machines) {+ [picker addAction:[UIAlertAction actionWithTitle:machine[@"name"]+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ [VZAppSettings.sharedSettings setString:machine[@"path"] forKey:VZAutoBootVMPathKey];+ [VZAppSettings.sharedSettings setString:VZVMStableIdentifier(machine[@"path"])+ forKey:VZAutoBootVMIdentifierKey];+ [self.tableView reloadData];+ }]];+ }+ [picker addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ picker.popoverPresentationController.sourceView = cell;+ picker.popoverPresentationController.sourceRect = cell.bounds;+ [self presentViewController:picker animated:YES completion:nil];+}++- (void)confirmDeletePaths:(NSArray<NSString *> *)paths title:(NSString *)title+{+ if (!paths.count) return;+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:title+ message:@"Complete virtual Mac devices and restore images outside Virtual Mac are not removed."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive+ handler:^(UIAlertAction *action) {+ (void)action;+ VZRemovePaths(paths);+ [self.tableView reloadData];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath+{+ UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+ if (indexPath.section == 0 && indexPath.row == 0)+ [self chooseAutoBootFrom:cell];+ else if (indexPath.section == 0 && indexPath.row == 1)+ [self chooseDisplayScalingFrom:cell];+ else if (indexPath.section == 0 && indexPath.row == 2) {+ UIPasteboard.generalPasteboard.string = VZVMLibraryPath();+ UINotificationFeedbackGenerator *feedback = [[[UINotificationFeedbackGenerator alloc] init] autorelease];+ [feedback notificationOccurred:UINotificationFeedbackTypeSuccess];+ } else if (indexPath.section == 1 && indexPath.row == 4)+ [self chooseHUDVisibilityFrom:cell];+ else if (indexPath.section == 3 && indexPath.row == 1)+ [self confirmDeletePaths:VZInstallationArtifactPaths() title:@"Delete Installation Artifacts?"];+ else if (indexPath.section == 3 && indexPath.row == 2)+ [self confirmDeletePaths:VZCachedRestoreImagePaths() title:@"Delete Cached Restore Images?"];+}++- (void)dealloc+{+ [_machines release];+ [super dealloc];+}++@enddiff --git a/VirtualMac/vz/host/VZVMLibraryViewController.h b/VirtualMac/vz/host/VZVMLibraryViewController.hnew file mode 100644index 0000000..78272d3--- /dev/null+++ b/VirtualMac/vz/host/VZVMLibraryViewController.h@@ -0,0 +1,49 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++FOUNDATION_EXPORT NSString * const VZVMConfigurationFileName;++NSDictionary *VZVMDefaultOptions(void);+NSDictionary *VZVMOptionsForBundle(NSString *bundlePath);+BOOL VZRestoreImageUsesMontereyProfile(NSString *path);+BOOL VZWriteVMOptions(NSDictionary *options, NSString *bundlePath,+ NSError **error);+BOOL VZIsValidVMBundle(NSString *path);+NSString *_Nullable VZVMStableIdentifier(NSString *path);+NSArray<NSDictionary *> *VZDiscoverVirtualMachines(void);+NSArray<NSString *> *VZInstallationArtifactPaths(void);+NSArray<NSString *> *VZCachedRestoreImagePaths(void);+void VZRemovePaths(NSArray<NSString *> *paths);+NSString *VZVMLibraryPath(void);+NSString *VZVMSupportPath(void);+NSString *VZRestoreImagesPath(void);+NSString *VZInstallationsPath(void);++@class VZVMLibraryViewController;++@protocol VZVMLibraryViewControllerDelegate <NSObject>+- (void)vmLibrary:(VZVMLibraryViewController *)library+ bootBundleAtPath:(NSString *)path+ options:(NSDictionary *)options;+- (void)vmLibrary:(VZVMLibraryViewController *)library+ installRestoreImageAtURL:(NSURL *)url+ name:(NSString *)name+ options:(NSDictionary *)options;+@optional+- (nullable NSString *)activeVMBundlePathForLibrary:+ (VZVMLibraryViewController *)library;+- (void)vmLibraryResumeActiveVM:(VZVMLibraryViewController *)library;+- (void)vmLibraryForceShutdownActiveVM:+ (VZVMLibraryViewController *)library;+@end++@interface VZVMLibraryViewController : UIViewController+ <UIDocumentPickerDelegate>+@property(nonatomic, assign) id<VZVMLibraryViewControllerDelegate> delegate;+- (void)reloadLibrary;+- (void)presentNewVMFlow;+- (void)presentSettings;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VirtualMac/vz/host/VZVMLibraryViewController.m b/VirtualMac/vz/host/VZVMLibraryViewController.mnew file mode 100644index 0000000..99392dd--- /dev/null+++ b/VirtualMac/vz/host/VZVMLibraryViewController.m@@ -0,0 +1,2069 @@+#import "VZVMLibraryViewController.h"+#import "VZAppSettings.h"+#import "VZSettingsViewController.h"+#import "VZNewVMViewController.h"+#import "VZProgressViewController.h"+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>++#include <ifaddrs.h>+#include <errno.h>+#include <netinet/in.h>+#include <net/if.h>+#include <limits.h>+#include <spawn.h>+#include <stdlib.h>+#include <sys/sysctl.h>+#include <sys/wait.h>++extern char **environ;++NSString * const VZVMConfigurationFileName = @"VirtualMac.plist";++static NSString * const VZCPUCountKey = @"CPUCount";+static NSString * const VZMemorySizeKey = @"MemorySize";+static NSString * const VZStorageSizeKey = @"StorageSize";+static NSString * const VZNetworkModeKey = @"NetworkMode";+static NSString * const VZBridgeInterfaceKey = @"BridgeInterface";+static NSString * const VZBootRecoveryKey = @"BootRecovery";+static NSString * const VZSharedDirectoriesKey = @"SharedDirectories";+static NSString * const VZPointingDeviceKey = @"PointingDevice";+static NSString * const VZKeyboardDeviceKey = @"KeyboardDevice";+static NSString * const VZAudioOutputEnabledKey = @"AudioOutputEnabled";+static NSString * const VZAudioInputEnabledKey = @"AudioInputEnabled";+static NSString * const VZVideoToolboxEnabledKey = @"VideoToolboxEnabled";+static NSString * const VZDisplayModeKey = @"DisplayMode";+static NSString * const VZDisplayWidthKey = @"DisplayWidth";+static NSString * const VZDisplayHeightKey = @"DisplayHeight";+static NSString * const VZDisplayPPIKey = @"DisplayPixelsPerInch";+static NSString * const VZMACAddressKey = @"MACAddress";+static NSString * const VZVMNameKey = @"VMName";++static uint64_t GiB(uint64_t value)+{+ return value << 30;+}++NSString *VZVMLibraryPath(void)+{+ return VZVMSupportPath();+}++NSString *VZVMSupportPath(void)+{+ return @"/var/mobile/Media/VirtualMac";+}++NSString *VZRestoreImagesPath(void)+{+ return [VZVMSupportPath() stringByAppendingPathComponent:@"Restore Images"];+}++NSString *VZInstallationsPath(void)+{+ return [VZVMSupportPath() stringByAppendingPathComponent:@"Installations"];+}++static uint64_t VZDeviceMemoryLimit(void)+{+ uint64_t physical = NSProcessInfo.processInfo.physicalMemory;+ return physical >= GiB(12) ? GiB(8) : GiB(4);+}++static uint64_t VZDefaultStorageSize(void)+{+ NSDictionary *attributes = [NSFileManager.defaultManager+ attributesOfFileSystemForPath:VZVMLibraryPath() error:nil];+ uint64_t total = [attributes[NSFileSystemSize] unsignedLongLongValue];+ return total && total <= GiB(64) ? GiB(32) : GiB(64);+}++static uint64_t VZAvailableStorageSize(void)+{+ NSDictionary *attributes = [NSFileManager.defaultManager+ attributesOfFileSystemForPath:VZVMLibraryPath() error:nil];+ return [attributes[NSFileSystemFreeSize] unsignedLongLongValue];+}++static NSString *VZMACStringFromBytes(const uint8_t bytes[6])+{+ return [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x",+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]];+}++static NSString *VZRandomMACAddress(void)+{+ uint8_t bytes[6];+ arc4random_buf(bytes, sizeof(bytes));+ bytes[0] = (bytes[0] | 0x02) & 0xfe;+ return VZMACStringFromBytes(bytes);+}++static NSString *VZMACAddressForBundle(NSString *bundlePath)+{+ NSData *identifier = [NSData dataWithContentsOfFile:+ [bundlePath stringByAppendingPathComponent:@"MachineIdentifier"]];+ const uint8_t *contents = identifier.bytes;+ uint64_t hash = UINT64_C(1469598103934665603);+ for (NSUInteger index = 0; index < identifier.length; index++) {+ hash ^= contents[index];+ hash *= UINT64_C(1099511628211);+ }+ if (!identifier.length) {+ const char *path = bundlePath.fileSystemRepresentation;+ for (; path && *path; path++) {+ hash ^= (uint8_t)*path;+ hash *= UINT64_C(1099511628211);+ }+ }+ uint8_t bytes[6];+ for (NSUInteger index = 0; index < sizeof(bytes); index++)+ bytes[index] = (uint8_t)(hash >> (index * 8));+ bytes[0] = (bytes[0] | 0x02) & 0xfe;+ return VZMACStringFromBytes(bytes);+}++static NSArray *VZBridgeInterfaceNames(void)+{+ NSMutableSet *names = [NSMutableSet set];+ struct ifaddrs *interfaces = NULL;+ if (getifaddrs(&interfaces) == 0) {+ for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) {+ if (!item->ifa_name || !(item->ifa_flags & IFF_UP) ||+ (item->ifa_flags & IFF_LOOPBACK))+ continue;+ NSString *name = [NSString stringWithUTF8String:item->ifa_name];+ if ([name hasPrefix:@"en"] || [name hasPrefix:@"bridge"])+ [names addObject:name];+ }+ freeifaddrs(interfaces);+ }+ if (!names.count)+ [names addObject:@"en0"];+ return [names.allObjects sortedArrayUsingSelector:+ @selector(localizedStandardCompare:)];+}++static NSString *VZInterfaceDisplayName(NSString *interface)+{+ if ([interface isEqualToString:@"en0"])+ return @"Wi-Fi";+ if ([interface hasPrefix:@"pdp_ip"])+ return @"Cellular";+ if ([interface hasPrefix:@"bridge"])+ return [NSString stringWithFormat:@"Network Bridge (%@)", interface];+ if ([interface hasPrefix:@"en"])+ return [NSString stringWithFormat:@"Ethernet (%@)", interface];+ return interface;+}++static NSString *VZActiveInternetDisplayName(void)+{+ NSString *candidate = nil;+ struct ifaddrs *interfaces = NULL;+ if (getifaddrs(&interfaces) == 0) {+ for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) {+ if (!item->ifa_name || !item->ifa_addr ||+ item->ifa_addr->sa_family != AF_INET ||+ !(item->ifa_flags & IFF_UP) ||+ (item->ifa_flags & IFF_LOOPBACK))+ continue;+ NSString *name = [NSString stringWithUTF8String:item->ifa_name];+ if ([name isEqualToString:@"en0"]) {+ candidate = name;+ break;+ }+ if (!candidate && ([name hasPrefix:@"pdp_ip"] ||+ [name hasPrefix:@"utun"]))+ candidate = name;+ }+ freeifaddrs(interfaces);+ }+ if ([candidate hasPrefix:@"utun"])+ return @"VPN";+ return candidate ? VZInterfaceDisplayName(candidate)+ : @"iPad Internet Connection";+}++BOOL VZRestoreImageUsesMontereyProfile(NSString *path)+{+ // Match both friendly bundle names and Apple's restore-image convention,+ // for example UniversalMac_12.6_21G115_Restore.ipsw. Requiring a+ // non-digit boundary avoids treating 112.x as Monterey.+ NSString *name = path.lastPathComponent.lowercaseString ?: @"";+ if ([name containsString:@"monterey"] ||+ [name containsString:@"macos 12"] ||+ [name containsString:@"macos_12"] ||+ [name containsString:@"macos-12"])+ return YES;+ NSRange search = NSMakeRange(0, name.length);+ while (search.length) {+ NSRange version = [name rangeOfString:@"12." options:0 range:search];+ if (version.location == NSNotFound)+ break;+ BOOL leftBoundary = version.location == 0 ||+ ![NSCharacterSet.decimalDigitCharacterSet+ characterIsMember:[name characterAtIndex:version.location - 1]];+ NSUInteger digitIndex = NSMaxRange(version);+ BOOL hasMinor = digitIndex < name.length &&+ [NSCharacterSet.decimalDigitCharacterSet+ characterIsMember:[name characterAtIndex:digitIndex]];+ if (leftBoundary && hasMinor)+ return YES;+ NSUInteger next = NSMaxRange(version);+ search = NSMakeRange(next, name.length - next);+ }+ return NO;+}++static NSString *VZDefaultPointingDeviceForPath(NSString *path)+{+ return VZRestoreImageUsesMontereyProfile(path) ? @"USBMouse" : @"MacTrackpad";+}++static NSString *VZDefaultKeyboardDeviceForPath(NSString *path)+{+ return VZRestoreImageUsesMontereyProfile(path) ? @"USBKeyboard" : @"MacKeyboard";+}++NSDictionary *VZVMDefaultOptions(void)+{+ NSUInteger processors = MAX((NSUInteger)2,+ MIN((NSUInteger)4, NSProcessInfo.processInfo.activeProcessorCount));+ return @{+ VZCPUCountKey: @(processors),+ VZMemorySizeKey: @(VZDeviceMemoryLimit()),+ VZStorageSizeKey: @(VZDefaultStorageSize()),+ VZNetworkModeKey: @"NAT",+ VZBridgeInterfaceKey: @"en0",+ VZBootRecoveryKey: @NO,+ VZSharedDirectoriesKey: @[],+ VZPointingDeviceKey: @"MacTrackpad",+ VZKeyboardDeviceKey: @"MacKeyboard",+ VZAudioOutputEnabledKey: @YES,+ VZAudioInputEnabledKey: @YES,+ VZVideoToolboxEnabledKey: @YES,+ VZDisplayModeKey: @"NativeRetina",+ VZDisplayWidthKey: @1920,+ VZDisplayHeightKey: @1200,+ VZDisplayPPIKey: @264,+ VZMACAddressKey: VZRandomMACAddress(),+ };+}++NSDictionary *VZVMOptionsForBundle(NSString *bundlePath)+{+ NSMutableDictionary *options =+ [NSMutableDictionary dictionaryWithDictionary:VZVMDefaultOptions()];+ NSDictionary *saved = [NSDictionary dictionaryWithContentsOfFile:+ [bundlePath stringByAppendingPathComponent:VZVMConfigurationFileName]];+ if ([saved isKindOfClass:NSDictionary.class])+ [options addEntriesFromDictionary:saved];+ if (![saved[VZPointingDeviceKey] isKindOfClass:NSString.class])+ options[VZPointingDeviceKey] =+ VZDefaultPointingDeviceForPath(bundlePath);+ if (![saved[VZKeyboardDeviceKey] isKindOfClass:NSString.class])+ options[VZKeyboardDeviceKey] =+ VZDefaultKeyboardDeviceForPath(bundlePath);+ NSString *savedMAC = saved[VZMACAddressKey];+ if (![savedMAC isKindOfClass:NSString.class] ||+ [savedMAC isEqualToString:@"d6:a7:58:8e:78:d5"])+ options[VZMACAddressKey] = VZMACAddressForBundle(bundlePath);+ return options;+}++BOOL VZWriteVMOptions(NSDictionary *options, NSString *bundlePath,+ NSError **error)+{+ NSString *path =+ [bundlePath stringByAppendingPathComponent:VZVMConfigurationFileName];+ NSData *data = [NSPropertyListSerialization+ dataWithPropertyList:options format:NSPropertyListXMLFormat_v1_0+ options:0 error:error];+ return data && [data writeToFile:path options:NSDataWritingAtomic error:error];+}++BOOL VZIsValidVMBundle(NSString *path)+{+ NSFileManager *manager = NSFileManager.defaultManager;+ BOOL directory = NO;+ if (![manager fileExistsAtPath:path isDirectory:&directory] || !directory)+ return NO;+ for (NSString *name in @[@"Disk.img", @"AuxiliaryStorage",+ @"HardwareModel", @"MachineIdentifier"]) {+ BOOL itemDirectory = NO;+ if (![manager fileExistsAtPath:[path stringByAppendingPathComponent:name]+ isDirectory:&itemDirectory] || itemDirectory)+ return NO;+ }+ return YES;+}++NSString *VZVMStableIdentifier(NSString *path)+{+ NSData *identifier = [NSData dataWithContentsOfFile:+ [path stringByAppendingPathComponent:@"MachineIdentifier"]];+ return identifier.length ? [identifier base64EncodedStringWithOptions:0] : nil;+}++NSArray<NSDictionary *> *VZDiscoverVirtualMachines(void)+{+ NSFileManager *manager = NSFileManager.defaultManager;+ NSString *library = VZVMLibraryPath();+ [manager createDirectoryAtPath:library withIntermediateDirectories:YES+ attributes:nil error:nil];+ [manager createDirectoryAtPath:VZRestoreImagesPath()+ withIntermediateDirectories:YES attributes:nil error:nil];+ [manager createDirectoryAtPath:VZInstallationsPath()+ withIntermediateDirectories:YES attributes:nil error:nil];+ NSString *readme = [library stringByAppendingPathComponent:@"README.md"];+ if (![manager fileExistsAtPath:readme]) {+ NSString *text =+ @"# Virtual Mac\n\n"+ "Use Add in Virtual Mac to install a restore image, or copy a "+ "complete `.bundle` here. A bundle contains `Disk.img`, "+ "`AuxiliaryStorage`, `HardwareModel`, and `MachineIdentifier`.\n";+ [text writeToFile:readme atomically:YES+ encoding:NSUTF8StringEncoding error:nil];+ }++ NSMutableArray *machines = [NSMutableArray array];+ NSMutableSet *seen = [NSMutableSet set];+ void (^append)(NSString *, NSString *) =+ ^(NSString *path, NSString *name) {+ if (!VZIsValidVMBundle(path))+ return;+ NSString *identity = path.stringByResolvingSymlinksInPath;+ if ([seen containsObject:identity])+ return;+ [seen addObject:identity];+ [machines addObject:@{@"name": name, @"path": path}];+ };+ for (NSString *name in [manager contentsOfDirectoryAtPath:library+ error:nil]) {+ if ([name.pathExtension caseInsensitiveCompare:@"bundle"] !=+ NSOrderedSame)+ continue;+ NSString *path = [library stringByAppendingPathComponent:name];+ NSString *display = name.stringByDeletingPathExtension;+ append(path, display);+ }+ [machines sortUsingComparator:^NSComparisonResult(NSDictionary *left,+ NSDictionary *right) {+ return [left[@"name"] localizedStandardCompare:right[@"name"]];+ }];+ return machines;+}++static NSString *VZMarketingNameForRestoreImage(NSURL *url)+{+ NSString *base = url.lastPathComponent.stringByDeletingPathExtension;+ NSString *lower = base.lowercaseString;+ NSDictionary *named = @{+ @"monterey": @"Monterey", @"ventura": @"Ventura",+ @"sonoma": @"Sonoma", @"sequoia": @"Sequoia",+ @"tahoe": @"Tahoe", @"golden gate": @"Golden Gate",+ @"goldengate": @"Golden Gate",+ };+ for (NSString *token in named)+ if ([lower containsString:token])+ return named[token];++ NSRegularExpression *version = [NSRegularExpression+ regularExpressionWithPattern:@"(?:^|[^0-9])([0-9]{2})(?:\\.[0-9]+)(?:[^0-9]|$)"+ options:0 error:nil];+ NSTextCheckingResult *match = [version firstMatchInString:base options:0+ range:NSMakeRange(0, base.length)];+ if (match.numberOfRanges > 1) {+ NSString *major = [base substringWithRange:[match rangeAtIndex:1]];+ NSDictionary *marketing = @{+ @"12": @"Monterey", @"13": @"Ventura",+ @"14": @"Sonoma", @"15": @"Sequoia",+ @"26": @"Tahoe", @"27": @"Golden Gate",+ };+ return marketing[major] ?: [@"macOS " stringByAppendingString:major];+ }+ return base.length ? base : @"macOS";+}++static BOOL VZVMNameIsOccupied(NSString *name)+{+ NSString *bundleName = [name stringByAppendingPathExtension:@"bundle"];+ NSString *installingName = [bundleName+ stringByAppendingPathExtension:@"installing"];+ for (NSString *entry in [NSFileManager.defaultManager+ contentsOfDirectoryAtPath:VZVMLibraryPath() error:nil]) {+ if ([entry caseInsensitiveCompare:bundleName] == NSOrderedSame ||+ [entry caseInsensitiveCompare:installingName] == NSOrderedSame)+ return YES;+ }+ return NO;+}++static NSString *VZUniqueVMName(NSString *requested)+{+ NSString *base = requested.length ? requested : @"macOS";+ if (!VZVMNameIsOccupied(base))+ return base;+ for (NSUInteger suffix = 2; suffix < NSUIntegerMax; suffix++) {+ NSString *candidate = [NSString stringWithFormat:@"%@ %lu", base,+ (unsigned long)suffix];+ if (!VZVMNameIsOccupied(candidate))+ return candidate;+ }+ return [base stringByAppendingFormat:@" %@", NSUUID.UUID.UUIDString];+}++static NSString *VZSanitizedVMName(NSString *requested)+{+ NSCharacterSet *invalid = [NSCharacterSet+ characterSetWithCharactersInString:@"/:\n\r"];+ NSString *name = [[[requested ?: @"" componentsSeparatedByCharactersInSet:+ invalid] componentsJoinedByString:@"-"]+ stringByTrimmingCharactersInSet:+ NSCharacterSet.whitespaceAndNewlineCharacterSet];+ return name.length ? name : @"macOS";+}++static NSString *VZUniqueVMNameExcludingPath(NSString *requested,+ NSString *excludedPath)+{+ NSString *base = VZSanitizedVMName(requested);+ NSString *excluded = excludedPath.stringByStandardizingPath;+ for (NSUInteger suffix = 1; suffix < NSUIntegerMax; suffix++) {+ NSString *candidate = suffix == 1 ? base :+ [NSString stringWithFormat:@"%@ %lu", base,+ (unsigned long)suffix];+ NSString *path = [VZVMLibraryPath() stringByAppendingPathComponent:+ [candidate stringByAppendingPathExtension:@"bundle"]];+ if ([path.stringByStandardizingPath isEqualToString:excluded] ||+ ![NSFileManager.defaultManager fileExistsAtPath:path])+ return candidate;+ }+ return [base stringByAppendingFormat:@" %@", NSUUID.UUID.UUIDString];+}++NSArray<NSString *> *VZInstallationArtifactPaths(void)+{+ NSFileManager *manager = NSFileManager.defaultManager;+ NSMutableArray *paths = [NSMutableArray array];+ for (NSString *name in [manager+ contentsOfDirectoryAtPath:VZInstallationsPath() error:nil])+ [paths addObject:[VZInstallationsPath()+ stringByAppendingPathComponent:name]];++ return paths;+}++NSArray<NSString *> *VZCachedRestoreImagePaths(void)+{+ NSFileManager *manager = NSFileManager.defaultManager;+ NSMutableArray *paths = [NSMutableArray array];+ NSString *directory = VZRestoreImagesPath();+ for (NSString *name in [manager+ contentsOfDirectoryAtPath:directory error:nil])+ [paths addObject:[directory stringByAppendingPathComponent:name]];+ return paths;+}++void VZRemovePaths(NSArray<NSString *> *paths)+{+ NSFileManager *manager = NSFileManager.defaultManager;+ for (NSString *path in paths) {+ NSError *error = nil;+ if ([manager removeItemAtPath:path error:&error])+ continue;+ // Restore helpers run as root and can leave diagnostics or staging+ // files that the UIKit process cannot unlink. The setuid launcher+ // accepts only descendants of the two artifact directories.+ const char *launcher =+ "/var/root/VirtualMac/install/install-launcher";+ char *arguments[] = {(char *)launcher, "--delete-artifact",+ (char *)path.fileSystemRepresentation, NULL};+ pid_t child = 0;+ int spawned = posix_spawn(&child, launcher, NULL, NULL,+ arguments, environ);+ int status = 0;+ if (spawned == 0)+ while (waitpid(child, &status, 0) < 0 && errno == EINTR) {}+ if (spawned != 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)+ NSLog(@"Virtual Mac cleanup could not remove %@: %@", path, error);+ }+}++@interface VZVMConfigurationViewController : UITableViewController+ <UIDocumentPickerDelegate>+@property(nonatomic, copy) NSString *bundlePath;+@property(nonatomic, copy) NSString *vmName;+@property(nonatomic, assign) BOOL running;+@property(nonatomic, retain) NSMutableDictionary *options;+@property(nonatomic, copy) void (^completion)(NSDictionary *options);+@property(nonatomic, copy) void (^deletion)(void);+@end++@implementation VZVMConfigurationViewController++- (instancetype)initWithBundlePath:(NSString *)bundlePath+ options:(NSDictionary *)options+ completion:(void (^)(NSDictionary *))completion+{+ self = [super initWithStyle:UITableViewStyleInsetGrouped];+ if (self) {+ self.bundlePath = bundlePath;+ self.vmName = bundlePath.lastPathComponent.stringByDeletingPathExtension;+ self.options = [NSMutableDictionary dictionaryWithDictionary:options];+ self.completion = completion;+ self.title = bundlePath ? @"Virtual Mac" : @"New Virtual Mac";+ }+ return self;+}++- (void)viewDidLoad+{+ [super viewDidLoad];+ self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]+ initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self+ action:@selector(cancel:)] autorelease];+ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]+ initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self+ action:@selector(done:)] autorelease];+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView+{+ return self.bundlePath ? 6 : 5;+}++- (NSInteger)tableView:(UITableView *)tableView+ numberOfRowsInSection:(NSInteger)section+{+ if (section == 0) {+ NSInteger resourceRows = self.bundlePath ? 2 : 3;+ return 1 + resourceRows + 1 ++ [self.options[VZSharedDirectoriesKey] count];+ }+ if (section == 1)+ return self.bundlePath ? 3 : 2;+ if (section == 2)+ return 2;+ if (section == 3)+ return [self.options[VZDisplayModeKey] isEqualToString:@"Custom"]+ ? 4 : 1;+ if (section == 4)+ return 3;+ return 1;+}++- (NSString *)tableView:(UITableView *)tableView+ titleForHeaderInSection:(NSInteger)section+{+ if (section == 5)+ return nil;+ return @[@"Resources",+ self.bundlePath ? @"Boot and Network" : @"Network",+ @"Input", @"Display", @"Audio and Acceleration"][section];+}++- (NSString *)tableView:(UITableView *)tableView+ titleForFooterInSection:(NSInteger)section+{+ (void)tableView;+ if (self.running && section == 0)+ return @"Configuration changes take effect after the virtual Mac is shut down and started again. Renaming and deletion are unavailable while it is running.";+ return nil;+}++- (UITableViewCell *)tableView:(UITableView *)tableView+ cellForRowAtIndexPath:(NSIndexPath *)indexPath+{+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"v"];+ if (!cell)+ cell = [[[UITableViewCell alloc]+ initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"v"]+ autorelease];+ // Every section shares this reuse identifier. Clear all state that a+ // switch-backed row can leave behind before configuring the new row.+ cell.accessoryView = nil;+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ cell.textLabel.text = nil;+ cell.detailTextLabel.text = nil;+ cell.textLabel.textColor = UIColor.labelColor;+ cell.textLabel.textAlignment = NSTextAlignmentNatural;+ cell.imageView.image = nil;+ cell.userInteractionEnabled = YES;+ if (indexPath.section == 0) {+ NSInteger resourceRows = self.bundlePath ? 2 : 3;+ if (indexPath.row == 0) {+ cell.textLabel.text = @"Name";+ cell.detailTextLabel.text = self.vmName;+ if (self.running) {+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.selectionStyle = UITableViewCellSelectionStyleNone;+ cell.textLabel.textColor = UIColor.secondaryLabelColor;+ }+ return cell;+ }+ NSInteger resourceIndex = indexPath.row - 1;+ if (resourceIndex == resourceRows) {+ cell.textLabel.text = @"Add Shared Folder";+ cell.detailTextLabel.text = nil;+ return cell;+ }+ if (resourceIndex > resourceRows) {+ NSDictionary *share = self.options[VZSharedDirectoriesKey]+ [resourceIndex - resourceRows - 1];+ cell.textLabel.text = [share[@"Path"] lastPathComponent];+ cell.detailTextLabel.text = [share[@"ReadOnly"] boolValue]+ ? @"Read Only" : @"Read & Write";+ return cell;+ }+ NSArray *names = self.bundlePath ? @[@"Processors", @"Memory"]+ : @[@"Processors", @"Memory", @"Storage"];+ NSString *key = @[VZCPUCountKey, VZMemorySizeKey,+ VZStorageSizeKey][resourceIndex];+ cell.textLabel.text = names[resourceIndex];+ uint64_t value = [self.options[key] unsignedLongLongValue];+ cell.detailTextLabel.text = resourceIndex == 0+ ? [NSString stringWithFormat:@"%llu", value]+ : [NSString stringWithFormat:@"%llu GB", value >> 30];+ } else if (indexPath.section == 1 && self.bundlePath &&+ indexPath.row == 0) {+ cell.textLabel.text = @"Start in Recovery";+ UISwitch *toggle = [[[UISwitch alloc] init] autorelease];+ toggle.on = [self.options[VZBootRecoveryKey] boolValue];+ [toggle addTarget:self action:@selector(recoveryChanged:)+ forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = toggle;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.detailTextLabel.text = nil;+ } else if (indexPath.section == 1 &&+ indexPath.row == (self.bundlePath ? 1 : 0)) {+ cell.textLabel.text = @"Network";+ NSString *mode = self.options[VZNetworkModeKey];+ NSString *interface = self.options[VZBridgeInterfaceKey];+ cell.detailTextLabel.text = [mode isEqualToString:@"Bridge"]+ ? [NSString stringWithFormat:@"Bridge via %@",+ VZInterfaceDisplayName(interface)]+ : [mode isEqualToString:@"NAT"]+ ? [NSString stringWithFormat:@"Shared via %@",+ VZActiveInternetDisplayName()] : mode;+ } else if (indexPath.section == 1) {+ cell.textLabel.text = @"MAC Address";+ cell.detailTextLabel.text = self.options[VZMACAddressKey];+ } else if (indexPath.section == 2 && indexPath.row == 0) {+ cell.textLabel.text = @"Keyboard";+ cell.detailTextLabel.text =+ [self.options[VZKeyboardDeviceKey] isEqualToString:@"USBKeyboard"]+ ? @"USB Keyboard" : @"Mac Keyboard";+ } else if (indexPath.section == 2) {+ cell.textLabel.text = @"Pointing Device";+ cell.detailTextLabel.text =+ [self.options[VZPointingDeviceKey] isEqualToString:@"USBMouse"]+ ? @"USB Mouse" : @"Mac Trackpad";+ } else if (indexPath.section == 3 && indexPath.row == 0) {+ cell.textLabel.text = @"Resolution";+ cell.detailTextLabel.text =+ [self.options[VZDisplayModeKey] isEqualToString:@"Custom"]+ ? @"Custom" : @"Native Retina";+ } else if (indexPath.section == 3) {+ NSArray *names = @[@"Width", @"Height", @"Pixels Per Inch"];+ NSArray *keys = @[VZDisplayWidthKey, VZDisplayHeightKey,+ VZDisplayPPIKey];+ cell.textLabel.text = names[indexPath.row - 1];+ cell.detailTextLabel.text = [self.options[keys[indexPath.row - 1]]+ stringValue];+ } else if (indexPath.section == 4) {+ NSArray *names = @[@"Audio Output", @"Microphone Input",+ @"VideoToolbox Acceleration"];+ NSArray *keys = @[VZAudioOutputEnabledKey, VZAudioInputEnabledKey,+ VZVideoToolboxEnabledKey];+ cell.textLabel.text = names[indexPath.row];+ UISwitch *toggle = [[[UISwitch alloc] init] autorelease];+ toggle.on = [self.options[keys[indexPath.row]] boolValue];+ toggle.tag = indexPath.row;+ [toggle addTarget:self action:@selector(deviceToggleChanged:)+ forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = toggle;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.detailTextLabel.text = nil;+ } else {+ cell.textLabel.text = @"Delete Virtual Mac";+ cell.textLabel.textAlignment = NSTextAlignmentCenter;+ cell.textLabel.textColor = self.running+ ? UIColor.secondaryLabelColor : UIColor.systemRedColor;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.selectionStyle = self.running ? UITableViewCellSelectionStyleNone+ : UITableViewCellSelectionStyleDefault;+ }+ return cell;+}++- (void)chooseTitle:(NSString *)title message:(NSString *)message+ choices:(NSArray<NSDictionary *> *)choices key:(NSString *)key+ fromCell:(UITableViewCell *)cell+{+ UIAlertController *sheet = [UIAlertController+ alertControllerWithTitle:title message:message+ preferredStyle:UIAlertControllerStyleActionSheet];+ for (NSDictionary *choice in choices) {+ [sheet addAction:[UIAlertAction actionWithTitle:choice[@"title"]+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ self.options[key] = choice[@"value"];+ [self.tableView reloadData];+ }]];+ }+ [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ sheet.popoverPresentationController.sourceView = cell;+ [self presentViewController:sheet animated:YES completion:nil];+}++- (void)editMACAddress+{+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"MAC Address"+ message:@"Enter six hexadecimal octets separated by colons."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {+ field.text = self.options[VZMACAddressKey];+ field.autocapitalizationType = UITextAutocapitalizationTypeNone;+ field.autocorrectionType = UITextAutocorrectionTypeNo;+ }];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Save"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ NSString *value = alert.textFields.firstObject.text.lowercaseString;+ NSRegularExpression *pattern = [NSRegularExpression+ regularExpressionWithPattern:@"^([0-9a-f]{2}:){5}[0-9a-f]{2}$"+ options:0 error:nil];+ if ([pattern numberOfMatchesInString:value options:0+ range:NSMakeRange(0, value.length)] == 1)+ self.options[VZMACAddressKey] = value;+ [self.tableView reloadData];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)editNumberForKey:(NSString *)key title:(NSString *)title+ min:(uint64_t)minimum max:(uint64_t)maximum+ bytes:(BOOL)bytes+{+ NSString *range = maximum+ ? [NSString stringWithFormat:@"Allowed: %llu–%llu%@",+ bytes ? minimum >> 30 : minimum,+ bytes ? maximum >> 30 : maximum, bytes ? @" GB" : @""]+ : [NSString stringWithFormat:+ @"Minimum: %llu GB. The upper limit is determined by the filesystem.",+ minimum >> 30];+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:title+ message:range+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {+ uint64_t value = [self.options[key] unsignedLongLongValue];+ field.text = [NSString stringWithFormat:@"%llu",+ bytes ? value >> 30 : value];+ field.keyboardType = UIKeyboardTypeNumberPad;+ }];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Save"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ uint64_t entered = strtoull(+ alert.textFields.firstObject.text.UTF8String, NULL, 10);+ uint64_t value = entered;+ if (bytes) {+ uint64_t maximumGiB = (uint64_t)LLONG_MAX >> 30;+ value = entered > maximumGiB ? (uint64_t)LLONG_MAX : GiB(entered);+ }+ value = MAX(minimum, maximum ? MIN(maximum, value) : value);+ self.options[key] = @(value);+ [self.tableView reloadData];+ if ([key isEqualToString:VZStorageSizeKey] &&+ value > VZAvailableStorageSize()) {+ uint64_t available = VZAvailableStorageSize() >> 30;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,+ 250 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{+ UIAlertController *warning = [UIAlertController+ alertControllerWithTitle:@"Disk Exceeds Available Storage"+ message:[NSString stringWithFormat:+ @"Only about %llu GB is currently available. The disk image is sparse, but installation or later use can fail when storage fills up.",+ available]+ preferredStyle:UIAlertControllerStyleAlert];+ [warning addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:warning animated:YES completion:nil];+ });+ }+ }]];+ [self presentViewController:alert animated:YES completion:^{+ UITextField *field = alert.textFields.firstObject;+ [field selectAll:nil];+ [field becomeFirstResponder];+ }];+}++- (void)editVMName+{+ if (self.running)+ return;+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Name"+ message:@"Choose a name for this virtual Mac."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {+ field.text = self.vmName;+ field.clearButtonMode = UITextFieldViewModeWhileEditing;+ field.autocapitalizationType = UITextAutocapitalizationTypeWords;+ }];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Save"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ self.vmName = VZUniqueVMNameExcludingPath(+ alert.textFields.firstObject.text, self.bundlePath);+ [self.tableView reloadData];+ }]];+ [self presentViewController:alert animated:YES completion:^{+ [alert.textFields.firstObject selectAll:nil];+ [alert.textFields.firstObject becomeFirstResponder];+ }];+}++- (void)confirmDeleteVirtualMac+{+ if (!self.bundlePath.length || self.running)+ return;+ NSString *name = self.vmName.length ? self.vmName : @"this virtual Mac";+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Delete Virtual Mac?"+ message:[NSString stringWithFormat:+ @"“%@” and all files stored in it will be permanently deleted.",+ name]+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Delete"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action;+ NSString *path = [[self.bundlePath copy] autorelease];+ VZRemovePaths(@[path]);+ if ([[VZAppSettings.sharedSettings stringForKey:VZAutoBootVMPathKey]+ isEqualToString:path]) {+ [VZAppSettings.sharedSettings setString:nil+ forKey:VZAutoBootVMPathKey];+ [VZAppSettings.sharedSettings setString:nil+ forKey:VZAutoBootVMIdentifierKey];+ }+ void (^deletion)(void) = [[self.deletion copy] autorelease];+ [self dismissViewControllerAnimated:YES completion:^{+ if (deletion) deletion();+ }];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)tableView:(UITableView *)tableView+ didSelectRowAtIndexPath:(NSIndexPath *)indexPath+{+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+ if (indexPath.section == 0) {+ NSInteger resourceRows = self.bundlePath ? 2 : 3;+ if (indexPath.row == 0) {+ [self editVMName];+ return;+ }+ NSInteger resourceIndex = indexPath.row - 1;+ if (resourceIndex == resourceRows) {+ UIDocumentPickerViewController *picker =+ [[[UIDocumentPickerViewController alloc]+ initForOpeningContentTypes:@[UTTypeFolder] asCopy:NO]+ autorelease];+ picker.delegate = self;+ [self presentViewController:picker animated:YES completion:nil];+ } else if (resourceIndex > resourceRows) {+ NSInteger shareIndex = resourceIndex - resourceRows - 1;+ NSDictionary *saved =+ self.options[VZSharedDirectoriesKey][shareIndex];+ NSString *path = saved[@"Path"];+ UIAlertController *sheet = [UIAlertController+ alertControllerWithTitle:path.lastPathComponent message:path+ preferredStyle:UIAlertControllerStyleActionSheet];+ for (NSNumber *readOnly in @[@NO, @YES]) {+ NSString *title = readOnly.boolValue+ ? @"Read Only" : @"Read & Write";+ [sheet addAction:[UIAlertAction actionWithTitle:title+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction *action) {+ (void)action;+ NSMutableArray *shares = [NSMutableArray arrayWithArray:+ self.options[VZSharedDirectoriesKey]];+ shares[shareIndex] =+ @{@"Path": path, @"ReadOnly": readOnly};+ self.options[VZSharedDirectoriesKey] = shares;+ [self.tableView reloadData];+ }]];+ }+ [sheet addAction:[UIAlertAction actionWithTitle:@"Remove"+ style:UIAlertActionStyleDestructive+ handler:^(UIAlertAction *action) {+ (void)action;+ NSMutableArray *shares = [NSMutableArray arrayWithArray:+ self.options[VZSharedDirectoriesKey]];+ [shares removeObjectAtIndex:shareIndex];+ self.options[VZSharedDirectoriesKey] = shares;+ [self.tableView reloadData];+ }]];+ [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ sheet.popoverPresentationController.sourceView =+ [tableView cellForRowAtIndexPath:indexPath];+ [self presentViewController:sheet animated:YES completion:nil];+ } else if (resourceIndex == 0) {+ NSUInteger maxCPU = MAX((NSUInteger)2,+ MIN((NSUInteger)8, NSProcessInfo.processInfo.activeProcessorCount));+ [self editNumberForKey:VZCPUCountKey title:@"Processors"+ min:2 max:maxCPU bytes:NO];+ } else if (resourceIndex == 1) {+ [self editNumberForKey:VZMemorySizeKey title:@"Memory"+ min:GiB(2) max:VZDeviceMemoryLimit() bytes:YES];+ } else if (resourceIndex == 2) {+ [self editNumberForKey:VZStorageSizeKey title:@"Storage"+ min:GiB(32) max:0 bytes:YES];+ }+ } else if (indexPath.section == 1 &&+ indexPath.row == (self.bundlePath ? 1 : 0)) {+ UIAlertController *sheet = [UIAlertController+ alertControllerWithTitle:@"Network Attachment" message:nil+ preferredStyle:UIAlertControllerStyleActionSheet];+ for (NSString *mode in @[@"NAT", @"Disabled"]) {+ NSString *title = [mode isEqualToString:@"NAT"]+ ? [NSString stringWithFormat:@"NAT: Share %@",+ VZActiveInternetDisplayName()] : mode;+ [sheet addAction:[UIAlertAction actionWithTitle:title+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ self.options[VZNetworkModeKey] = mode;+ [self.tableView reloadData];+ }]];+ }+ for (NSString *interface in VZBridgeInterfaceNames()) {+ NSString *title = [NSString stringWithFormat:@"Bridge: %@",+ VZInterfaceDisplayName(interface)];+ [sheet addAction:[UIAlertAction actionWithTitle:title+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ self.options[VZNetworkModeKey] = @"Bridge";+ self.options[VZBridgeInterfaceKey] = interface;+ [self.tableView reloadData];+ }]];+ }+ [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ sheet.popoverPresentationController.sourceView =+ [tableView cellForRowAtIndexPath:indexPath];+ [self presentViewController:sheet animated:YES completion:nil];+ } else if (indexPath.section == 1 &&+ indexPath.row == (self.bundlePath ? 2 : 1)) {+ [self editMACAddress];+ } else if (indexPath.section == 2 && indexPath.row == 0) {+ [self chooseTitle:@"Keyboard" message:+ @"Use USB Keyboard for macOS Monterey. Newer guests support the Mac keyboard device."+ choices:@[+ @{@"title": @"Mac Keyboard", @"value": @"MacKeyboard"},+ @{@"title": @"USB Keyboard", @"value": @"USBKeyboard"},+ ] key:VZKeyboardDeviceKey+ fromCell:[tableView cellForRowAtIndexPath:indexPath]];+ } else if (indexPath.section == 2 && indexPath.row == 1) {+ [self chooseTitle:@"Pointing Device" message:+ @"Use USB Mouse for macOS Monterey. Newer guests support the Mac trackpad device."+ choices:@[+ @{@"title": @"Mac Trackpad", @"value": @"MacTrackpad"},+ @{@"title": @"USB Mouse", @"value": @"USBMouse"},+ ] key:VZPointingDeviceKey+ fromCell:[tableView cellForRowAtIndexPath:indexPath]];+ } else if (indexPath.section == 3 && indexPath.row == 0) {+ [self chooseTitle:@"Display Resolution" message:nil choices:@[+ @{@"title": @"Native Retina", @"value": @"NativeRetina"},+ @{@"title": @"Custom", @"value": @"Custom"},+ ] key:VZDisplayModeKey+ fromCell:[tableView cellForRowAtIndexPath:indexPath]];+ } else if (indexPath.section == 3 && indexPath.row > 0) {+ NSArray *keys = @[VZDisplayWidthKey, VZDisplayHeightKey,+ VZDisplayPPIKey];+ NSArray *titles = @[@"Display Width", @"Display Height",+ @"Pixels Per Inch"];+ uint64_t minimum = indexPath.row == 3 ? 72 : 800;+ uint64_t maximum = indexPath.row == 3 ? 600 : 7680;+ [self editNumberForKey:keys[indexPath.row - 1]+ title:titles[indexPath.row - 1]+ min:minimum max:maximum bytes:NO];+ } else if (indexPath.section == 5) {+ [self confirmDeleteVirtualMac];+ }+}++- (void)documentPicker:(UIDocumentPickerViewController *)controller+ didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls+{+ NSURL *url = urls.firstObject;+ if (!url)+ return;+ [url startAccessingSecurityScopedResource];+ NSMutableArray *shares = [NSMutableArray arrayWithArray:+ self.options[VZSharedDirectoriesKey]];+ [shares addObject:@{@"Path": url.path, @"ReadOnly": @NO}];+ self.options[VZSharedDirectoriesKey] = shares;+ [self.tableView reloadData];+}++- (void)recoveryChanged:(UISwitch *)sender+{+ self.options[VZBootRecoveryKey] = @(sender.on);+}++- (void)deviceToggleChanged:(UISwitch *)sender+{+ NSArray *keys = @[VZAudioOutputEnabledKey, VZAudioInputEnabledKey,+ VZVideoToolboxEnabledKey];+ if (sender.tag < (NSInteger)keys.count)+ self.options[keys[sender.tag]] = @(sender.on);+}++- (void)done:(id)sender+{+ (void)sender;+ if (self.bundlePath) {+ NSError *error = nil;+ NSString *newName = VZUniqueVMNameExcludingPath(+ self.vmName, self.bundlePath);+ NSString *oldName = self.bundlePath.lastPathComponent+ .stringByDeletingPathExtension;+ if (!self.running && ![newName isEqualToString:oldName]) {+ NSString *destination = [VZVMLibraryPath()+ stringByAppendingPathComponent:+ [newName stringByAppendingPathExtension:@"bundle"]];+ if (![NSFileManager.defaultManager moveItemAtPath:self.bundlePath+ toPath:destination error:&error]) {+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Could Not Rename Virtual Mac"+ message:error.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ return;+ }+ NSString *autoBoot = [VZAppSettings.sharedSettings+ stringForKey:VZAutoBootVMPathKey];+ if ([autoBoot isEqualToString:self.bundlePath])+ [VZAppSettings.sharedSettings setString:destination+ forKey:VZAutoBootVMPathKey];+ self.bundlePath = destination;+ self.vmName = newName;+ }+ if (!VZWriteVMOptions(self.options, self.bundlePath, &error)) {+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Could Not Save"+ message:error.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ return;+ }+ }+ void (^completion)(NSDictionary *) = [[self.completion copy] autorelease];+ NSMutableDictionary *result = [NSMutableDictionary+ dictionaryWithDictionary:self.options];+ result[VZVMNameKey] = VZSanitizedVMName(self.vmName);+ NSDictionary *options = [[result copy] autorelease];+ [self dismissViewControllerAnimated:YES completion:^{+ if (completion)+ completion(options);+ }];+}++- (void)cancel:(id)sender+{+ (void)sender;+ [self dismissViewControllerAnimated:YES completion:nil];+}++- (void)dealloc+{+ [_bundlePath release];+ [_vmName release];+ [_options release];+ [_completion release];+ [_deletion release];+ [super dealloc];+}+@end++@interface VZLibraryControlsView : UICollectionReusableView+@property(nonatomic, retain) UISearchBar *searchBar;+@property(nonatomic, retain) UISegmentedControl *layoutControl;+@end++@implementation VZLibraryControlsView+- (instancetype)initWithFrame:(CGRect)frame+{+ if ((self = [super initWithFrame:frame])) {+ self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectZero]+ autorelease];+ self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;+ self.searchBar.placeholder = @"Search Virtual Mac";+ self.searchBar.searchBarStyle = UISearchBarStyleMinimal;+ [self addSubview:self.searchBar];+ self.layoutControl = [[[UISegmentedControl alloc] initWithItems:@[+ [UIImage systemImageNamed:@"square.grid.2x2"],+ [UIImage systemImageNamed:@"list.bullet"]]] autorelease];+ self.layoutControl.translatesAutoresizingMaskIntoConstraints = NO;+ self.layoutControl.accessibilityLabel = @"Library Appearance";+ [self addSubview:self.layoutControl];+ [NSLayoutConstraint activateConstraints:@[+ [self.searchBar.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:24],+ [self.searchBar.topAnchor constraintEqualToAnchor:self.topAnchor constant:4],+ [self.searchBar.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-4],+ [self.layoutControl.leadingAnchor constraintEqualToAnchor:+ self.searchBar.trailingAnchor constant:12],+ [self.layoutControl.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-24],+ [self.layoutControl.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],+ [self.layoutControl.widthAnchor constraintEqualToConstant:112],+ ]];+ }+ return self;+}+- (void)dealloc+{+ [_searchBar release];+ [_layoutControl release];+ [super dealloc];+}+@end++@interface VZVMLibraryViewController () <UICollectionViewDataSource,+ UICollectionViewDelegateFlowLayout, UISearchBarDelegate,+ VZNewVMViewControllerDelegate>+@property(nonatomic, retain) NSArray *machines;+@property(nonatomic, retain) NSArray *filteredMachines;+@property(nonatomic, copy) NSString *searchText;+@property(nonatomic, retain) NSURL *pendingIPSWURL;+@property(nonatomic, retain) UICollectionView *collectionView;+@property(nonatomic, retain) UIView *emptyView;+@property(nonatomic, assign) CGFloat lastCollectionWidth;+@property(nonatomic, retain) NSURLSessionDownloadTask *downloadTask;+@property(nonatomic, retain) NSTimer *downloadTimer;+@property(nonatomic, retain) VZProgressViewController *downloadController;+@property(nonatomic, copy) NSString *downloadDestination;+@property(nonatomic, copy) NSString *downloadMarkerPath;+@property(nonatomic, assign) int64_t downloadLastBytes;+@property(nonatomic, retain) NSDate *downloadLastSample;+@property(nonatomic, assign) BOOL downloadCancelled;+@property(nonatomic, assign) BOOL didCheckInterruptedDownloads;+@end++@implementation VZVMLibraryViewController++- (void)showSettings:(UIBarButtonItem *)sender+{+ (void)sender;+ VZSettingsViewController *settings = [[[VZSettingsViewController alloc]+ initWithMachines:self.machines] autorelease];+ UINavigationController *navigation = [[[UINavigationController alloc]+ initWithRootViewController:settings] autorelease];+ navigation.modalPresentationStyle = UIModalPresentationFormSheet;+ navigation.preferredContentSize = CGSizeMake(620, 720);+ [self presentViewController:navigation animated:YES completion:nil];+}++- (void)presentSettings+{+ [self showSettings:nil];+}++- (void)presentConfiguration:(VZVMConfigurationViewController *)configuration+{+ UINavigationController *navigation = [[[UINavigationController alloc]+ initWithRootViewController:configuration] autorelease];+ navigation.modalPresentationStyle = UIModalPresentationPageSheet;+ navigation.preferredContentSize = CGSizeMake(620, 760);+ [self presentViewController:navigation animated:YES completion:nil];+}++- (instancetype)init+{+ self = [super init];+ if (self) {+ self.title = @"Virtual Mac";+ self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]+ initWithImage:[UIImage systemImageNamed:@"gearshape"]+ style:UIBarButtonItemStylePlain target:self+ action:@selector(showSettings:)] autorelease];+ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]+ initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self+ action:@selector(addVM:)] autorelease];+ }+ return self;+}++- (void)viewDidLoad+{+ [super viewDidLoad];+ self.view.backgroundColor = UIColor.systemBackgroundColor;+ UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];+ layout.sectionInset = UIEdgeInsetsMake(22, 24, 30, 24);+ layout.minimumInteritemSpacing = 18;+ layout.minimumLineSpacing = 18;+ self.collectionView = [[[UICollectionView alloc] initWithFrame:self.view.bounds+ collectionViewLayout:layout] autorelease];+ self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth |+ UIViewAutoresizingFlexibleHeight;+ self.collectionView.backgroundColor = UIColor.systemBackgroundColor;+ self.collectionView.dataSource = self;+ self.collectionView.delegate = self;+ self.collectionView.alwaysBounceVertical = YES;+ [self.collectionView registerClass:UICollectionViewCell.class+ forCellWithReuseIdentifier:@"item"];+ [self.collectionView registerClass:VZLibraryControlsView.class+ forSupplementaryViewOfKind:UICollectionElementKindSectionHeader+ withReuseIdentifier:@"controls"];+ UIRefreshControl *refresh = [[[UIRefreshControl alloc] init] autorelease];+ [refresh addTarget:self action:@selector(reloadLibrary)+ forControlEvents:UIControlEventValueChanged];+ self.collectionView.refreshControl = refresh;+ [self.view addSubview:self.collectionView];++ UIView *empty = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];+ empty.translatesAutoresizingMaskIntoConstraints = NO;+ UIImageView *icon = [[[UIImageView alloc] initWithImage:+ [UIImage systemImageNamed:@"macbook.and.ipad"]] autorelease];+ icon.tintColor = UIColor.secondaryLabelColor;+ icon.contentMode = UIViewContentModeScaleAspectFit;+ icon.translatesAutoresizingMaskIntoConstraints = NO;+ UILabel *title = [[[UILabel alloc] init] autorelease];+ title.text = @"No Virtual Mac";+ title.font = [UIFont preferredFontForTextStyle:UIFontTextStyleTitle2];+ title.textAlignment = NSTextAlignmentCenter;+ title.translatesAutoresizingMaskIntoConstraints = NO;+ UILabel *message = [[[UILabel alloc] init] autorelease];+ message.text = @"Install macOS from an Apple restore image.";+ message.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];+ message.textColor = UIColor.secondaryLabelColor;+ message.textAlignment = NSTextAlignmentCenter;+ message.numberOfLines = 0;+ message.translatesAutoresizingMaskIntoConstraints = NO;+ UIButton *create = [UIButton buttonWithType:UIButtonTypeSystem];+ [create setTitle:@"Create Virtual Mac" forState:UIControlStateNormal];+ create.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];+ create.configuration = [UIButtonConfiguration filledButtonConfiguration];+ [create addTarget:self action:@selector(addVM:) forControlEvents:UIControlEventTouchUpInside];+ create.translatesAutoresizingMaskIntoConstraints = NO;+ for (UIView *view in @[icon, title, message, create]) [empty addSubview:view];+ [self.view addSubview:empty];+ [NSLayoutConstraint activateConstraints:@[+ [empty.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],+ [empty.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor constant:-24],+ [empty.widthAnchor constraintLessThanOrEqualToConstant:430],+ [icon.topAnchor constraintEqualToAnchor:empty.topAnchor],+ [icon.centerXAnchor constraintEqualToAnchor:empty.centerXAnchor],+ [icon.widthAnchor constraintEqualToConstant:76],+ [icon.heightAnchor constraintEqualToConstant:62],+ [title.topAnchor constraintEqualToAnchor:icon.bottomAnchor constant:18],+ [title.leadingAnchor constraintEqualToAnchor:empty.leadingAnchor],+ [title.trailingAnchor constraintEqualToAnchor:empty.trailingAnchor],+ [message.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:8],+ [message.leadingAnchor constraintEqualToAnchor:empty.leadingAnchor],+ [message.trailingAnchor constraintEqualToAnchor:empty.trailingAnchor],+ [create.topAnchor constraintEqualToAnchor:message.bottomAnchor constant:22],+ [create.centerXAnchor constraintEqualToAnchor:empty.centerXAnchor],+ [create.bottomAnchor constraintEqualToAnchor:empty.bottomAnchor],+ ]];+ self.emptyView = empty;+ [NSNotificationCenter.defaultCenter addObserver:self+ selector:@selector(settingsChanged:) name:VZSettingsDidChangeNotification object:nil];+}++- (void)viewDidLayoutSubviews+{+ [super viewDidLayoutSubviews];+ CGFloat width = self.collectionView.bounds.size.width;+ if (ABS(width - self.lastCollectionWidth) > 0.5) {+ self.lastCollectionWidth = width;+ [self.collectionView.collectionViewLayout invalidateLayout];+ }+}++- (void)viewWillAppear:(BOOL)animated+{+ [super viewWillAppear:animated];+ [self reloadLibrary];+ if (!self.didCheckInterruptedDownloads) {+ self.didCheckInterruptedDownloads = YES;+ NSMutableArray *markers = [NSMutableArray array];+ for (NSString *name in [NSFileManager.defaultManager+ contentsOfDirectoryAtPath:VZRestoreImagesPath() error:nil])+ if ([name hasSuffix:@".download.plist"])+ [markers addObject:[VZRestoreImagesPath() stringByAppendingPathComponent:name]];+ if (markers.count) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,+ 350 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:markers.count == 1 ? @"Incomplete Download" : @"Incomplete Downloads"+ message:@"A previous restore-image download did not finish. You can delete its marker and download it again."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Keep"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Delete"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action; VZRemovePaths(markers);+ }]];+ [self presentViewController:alert animated:YES completion:nil];+ });+ }+}++- (void)reloadLibrary+{+ self.machines = VZDiscoverVirtualMachines();+ [self applySearchFilter];+ self.emptyView.hidden = self.machines.count > 0;+ self.collectionView.hidden = self.machines.count == 0;+ [self.collectionView.collectionViewLayout invalidateLayout];+ [self.collectionView reloadData];+ [self.collectionView.refreshControl endRefreshing];+}++- (void)applySearchFilter+{+ if (!self.searchText.length) {+ self.filteredMachines = self.machines;+ return;+ }+ NSString *query = self.searchText;+ self.filteredMachines = [self.machines filteredArrayUsingPredicate:+ [NSPredicate predicateWithBlock:^BOOL(NSDictionary *machine,+ NSDictionary *bindings) {+ (void)bindings;+ return [machine[@"name"] localizedCaseInsensitiveContainsString:query];+ }]];+}++- (void)settingsChanged:(NSNotification *)notification+{+ (void)notification;+ [self.collectionView.collectionViewLayout invalidateLayout];+ [self.collectionView reloadData];+}++- (void)searchBar:(UISearchBar *)searchBar+ textDidChange:(NSString *)searchText+{+ (void)searchBar;+ self.searchText = searchText;+ [self applySearchFilter];+ [self.collectionView reloadData];+}++- (void)libraryLayoutChanged:(UISegmentedControl *)sender+{+ [VZAppSettings.sharedSettings setString:+ sender.selectedSegmentIndex == 1 ? @"list" : @"grid"+ forKey:VZLibraryLayoutKey];+}++- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView+ viewForSupplementaryElementOfKind:(NSString *)kind+ atIndexPath:(NSIndexPath *)indexPath+{+ (void)indexPath;+ VZLibraryControlsView *controls = (id)[collectionView+ dequeueReusableSupplementaryViewOfKind:kind+ withReuseIdentifier:@"controls" forIndexPath:indexPath];+ controls.searchBar.delegate = self;+ controls.searchBar.text = self.searchText;+ controls.layoutControl.selectedSegmentIndex =+ [[VZAppSettings.sharedSettings stringForKey:VZLibraryLayoutKey]+ isEqualToString:@"list"] ? 1 : 0;+ [controls.layoutControl removeTarget:nil action:NULL+ forControlEvents:UIControlEventValueChanged];+ [controls.layoutControl addTarget:self action:@selector(libraryLayoutChanged:)+ forControlEvents:UIControlEventValueChanged];+ return controls;+}++- (CGSize)collectionView:(UICollectionView *)collectionView+ layout:(UICollectionViewLayout *)layout+ referenceSizeForHeaderInSection:(NSInteger)section+{+ (void)layout; (void)section;+ return CGSizeMake(collectionView.bounds.size.width, 58);+}++- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section+{+ (void)collectionView; (void)section;+ return self.filteredMachines.count + 1;+}++- (NSString *)activeVMBundlePath+{+ if ([self.delegate respondsToSelector:+ @selector(activeVMBundlePathForLibrary:)])+ return [self.delegate activeVMBundlePathForLibrary:self];+ return nil;+}++- (BOOL)isMachineActive:(NSDictionary *)machine+{+ return [[[self activeVMBundlePath] stringByStandardizingPath]+ isEqualToString:[machine[@"path"] stringByStandardizingPath]];+}++- (void)startMachine:(NSDictionary *)machine+{+ NSString *activePath = [self activeVMBundlePath];+ if (activePath.length) {+ if ([self isMachineActive:machine]) {+ if ([self.delegate respondsToSelector:+ @selector(vmLibraryResumeActiveVM:)])+ [self.delegate vmLibraryResumeActiveVM:self];+ return;+ }+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Another Virtual Mac Is Running"+ message:@"Switch to the running virtual Mac and shut it down before starting another one."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction+ actionWithTitle:@"Switch to Running Virtual Mac"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ if ([self.delegate respondsToSelector:+ @selector(vmLibraryResumeActiveVM:)])+ [self.delegate vmLibraryResumeActiveVM:self];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+ return;+ }+ [NSUserDefaults.standardUserDefaults setObject:machine[@"path"]+ forKey:@"VZSelectedVMPath"];+ [self.delegate vmLibrary:self bootBundleAtPath:machine[@"path"]+ options:VZVMOptionsForBundle(machine[@"path"])];+}++- (void)confirmDeleteMachine:(NSDictionary *)machine+{+ if ([self isMachineActive:machine])+ return;+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Delete Virtual Mac?"+ message:[NSString stringWithFormat:+ @"“%@” and all files stored in it will be permanently deleted.",+ machine[@"name"]]+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Delete"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action;+ VZRemovePaths(@[machine[@"path"]]);+ if ([[VZAppSettings.sharedSettings stringForKey:VZAutoBootVMPathKey]+ isEqualToString:machine[@"path"]]) {+ [VZAppSettings.sharedSettings setString:nil+ forKey:VZAutoBootVMPathKey];+ [VZAppSettings.sharedSettings setString:nil+ forKey:VZAutoBootVMIdentifierKey];+ }+ [self reloadLibrary];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)configureMachineAtIndex:(NSUInteger)index+{+ if (index >= self.filteredMachines.count)+ return;+ NSDictionary *machine = self.filteredMachines[index];+ BOOL running = [self isMachineActive:machine];+ VZVMConfigurationViewController *configuration =+ [[[VZVMConfigurationViewController alloc]+ initWithBundlePath:machine[@"path"]+ options:VZVMOptionsForBundle(machine[@"path"])+ completion:^(NSDictionary *options) {+ (void)options;+ [self reloadLibrary];+ }] autorelease];+ configuration.title = machine[@"name"];+ configuration.vmName = machine[@"name"];+ configuration.running = running;+ configuration.deletion = ^{ [self reloadLibrary]; };+ [self presentConfiguration:configuration];+}++- (void)forceShutdownMachine:(NSDictionary *)machine+{+ if (![self isMachineActive:machine] ||+ ![self.delegate respondsToSelector:+ @selector(vmLibraryForceShutdownActiveVM:)])+ return;+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Force Shut Down Virtual Mac?"+ message:@"Unsaved changes in macOS may be lost."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Force Shut Down"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action;+ [self.delegate vmLibraryForceShutdownActiveVM:self];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)presentActionsForMachine:(NSDictionary *)machine+ fromView:(UIView *)source+{+ BOOL active = [self isMachineActive:machine];+ UIAlertController *sheet = [UIAlertController+ alertControllerWithTitle:machine[@"name"] message:nil+ preferredStyle:UIAlertControllerStyleActionSheet];+ [sheet addAction:[UIAlertAction actionWithTitle:active ? @"Resume" : @"Start"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action; [self startMachine:machine];+ }]];+ [sheet addAction:[UIAlertAction actionWithTitle:@"Options"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ NSUInteger index = [self.filteredMachines indexOfObject:machine];+ if (index != NSNotFound) [self configureMachineAtIndex:index];+ }]];+ if (active)+ [sheet addAction:[UIAlertAction actionWithTitle:@"Force Shut Down"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action; [self forceShutdownMachine:machine];+ }]];+ else+ [sheet addAction:[UIAlertAction actionWithTitle:@"Delete"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action; [self confirmDeleteMachine:machine];+ }]];+ [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ sheet.popoverPresentationController.sourceView = source ?: self.view;+ sheet.popoverPresentationController.sourceRect = source ? source.bounds :+ CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds), 1, 1);+ [self presentViewController:sheet animated:YES completion:nil];+}++- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView+ cellForItemAtIndexPath:(NSIndexPath *)indexPath+{+ UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item"+ forIndexPath:indexPath];+ for (UIView *view in cell.contentView.subviews) [view removeFromSuperview];+ for (UIGestureRecognizer *gesture in+ [[[cell gestureRecognizers] copy] autorelease])+ if ([gesture isKindOfClass:UISwipeGestureRecognizer.class])+ [cell removeGestureRecognizer:gesture];+ cell.contentView.backgroundColor = UIColor.secondarySystemGroupedBackgroundColor;+ cell.contentView.layer.cornerRadius = 14;+ cell.contentView.layer.borderWidth = 0.5;+ cell.contentView.layer.borderColor = UIColor.separatorColor.CGColor;+ cell.contentView.clipsToBounds = YES;+ BOOL list = [[VZAppSettings.sharedSettings stringForKey:VZLibraryLayoutKey] isEqualToString:@"list"];+ UIView *selected = [[[UIView alloc] initWithFrame:cell.bounds] autorelease];+ selected.backgroundColor = UIColor.tertiarySystemFillColor;+ selected.layer.cornerRadius = 14;+ cell.selectedBackgroundView = selected;+ UIImageView *image = [[[UIImageView alloc] init] autorelease];+ image.translatesAutoresizingMaskIntoConstraints = NO;+ image.contentMode = UIViewContentModeScaleAspectFill;+ image.clipsToBounds = YES;+ // The grid card already clips to its rounded outer edge. A second rounded+ // image mask leaves a visible seam above solid-color artwork such as the+ // Create card; only standalone list thumbnails need their own rounding.+ image.layer.cornerRadius = list ? 10 : 0;+ image.layer.maskedCorners = list ?+ (kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner |+ kCALayerMinXMaxYCorner | kCALayerMaxXMaxYCorner) :+ (kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner);+ image.backgroundColor = UIColor.tertiarySystemFillColor;+ [cell.contentView addSubview:image];+ UILabel *title = [[[UILabel alloc] init] autorelease];+ title.translatesAutoresizingMaskIntoConstraints = NO;+ title.font = [UIFont preferredFontForTextStyle:list ? UIFontTextStyleHeadline : UIFontTextStyleTitle3];+ title.numberOfLines = 1;+ title.lineBreakMode = NSLineBreakByTruncatingTail;+ [cell.contentView addSubview:title];+ UILabel *detail = [[[UILabel alloc] init] autorelease];+ detail.translatesAutoresizingMaskIntoConstraints = NO;+ detail.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];+ detail.textColor = UIColor.secondaryLabelColor;+ [cell.contentView addSubview:detail];+ UIButton *more = [UIButton buttonWithType:UIButtonTypeSystem];+ more.translatesAutoresizingMaskIntoConstraints = NO;+ more.tag = indexPath.item;+ [more addTarget:self action:@selector(moreButton:)+ forControlEvents:UIControlEventTouchUpInside];+ [cell.contentView addSubview:more];+ if (indexPath.item == 0) {+ NSString *art = [[NSBundle mainBundle] pathForResource:@"new"+ ofType:@"png" inDirectory:@"Wallpapers"];+ image.image = [UIImage imageWithContentsOfFile:art];+ title.text = @"Create Virtual Mac";+ detail.text = @"Install macOS";+ more.hidden = YES;+ } else {+ NSDictionary *machine = self.filteredMachines[indexPath.item - 1];+ NSDictionary *options = VZVMOptionsForBundle(machine[@"path"]);+ title.text = machine[@"name"];+ detail.text = [NSString stringWithFormat:@"%@ CPUs · %@ GB · %@%@",+ options[VZCPUCountKey], @([options[VZMemorySizeKey] unsignedLongLongValue] >> 30),+ options[VZNetworkModeKey], [machine[@"legacy"] boolValue] ? @" · Legacy" : @""];+ NSString *wallpaperName = [self wallpaperNameForMachineName:machine[@"name"]];+ NSString *art = [[NSBundle mainBundle] pathForResource:wallpaperName+ ofType:@"jpg" inDirectory:@"Wallpapers"];+ image.image = [UIImage imageWithContentsOfFile:art];+ image.tag = indexPath.item;+ image.userInteractionEnabled = YES;+ UITapGestureRecognizer *start = [[[UITapGestureRecognizer alloc]+ initWithTarget:self action:@selector(machineArtworkTapped:)] autorelease];+ [image addGestureRecognizer:start];+ image.isAccessibilityElement = YES;+ image.accessibilityLabel = [NSString stringWithFormat:@"Start %@", machine[@"name"]];+ image.accessibilityTraits = UIAccessibilityTraitButton;+ [more setImage:[UIImage systemImageNamed:@"ellipsis.circle"] forState:UIControlStateNormal];+ more.accessibilityLabel = [NSString stringWithFormat:@"Configure %@", machine[@"name"]];+ if (!list) {+ UIVisualEffectView *playBackground = [[[UIVisualEffectView alloc]+ initWithEffect:[UIBlurEffect effectWithStyle:+ UIBlurEffectStyleSystemUltraThinMaterialDark]] autorelease];+ playBackground.translatesAutoresizingMaskIntoConstraints = NO;+ playBackground.userInteractionEnabled = YES;+ playBackground.layer.cornerRadius = 36;+ playBackground.clipsToBounds = YES;+ UIButton *play = [UIButton buttonWithType:UIButtonTypeSystem];+ play.translatesAutoresizingMaskIntoConstraints = NO;+ play.tag = indexPath.item;+ play.tintColor = UIColor.whiteColor;+ NSString *symbolName = [self isMachineActive:machine]+ ? @"rectangle.portrait.and.arrow.right" : @"play.fill";+ UIImage *playImage = [[UIImage systemImageNamed:symbolName]+ imageByApplyingSymbolConfiguration:[UIImageSymbolConfiguration+ configurationWithPointSize:24 weight:UIImageSymbolWeightSemibold]];+ [play setImage:playImage forState:UIControlStateNormal];+ [play addTarget:self action:@selector(startButton:)+ forControlEvents:UIControlEventTouchUpInside];+ [playBackground.contentView addSubview:play];+ [cell.contentView addSubview:playBackground];+ [NSLayoutConstraint activateConstraints:@[+ [playBackground.centerXAnchor constraintEqualToAnchor:image.centerXAnchor],+ [playBackground.centerYAnchor constraintEqualToAnchor:image.centerYAnchor],+ [playBackground.widthAnchor constraintEqualToConstant:72],+ [playBackground.heightAnchor constraintEqualToConstant:72],+ [play.centerXAnchor constraintEqualToAnchor:playBackground.contentView.centerXAnchor],+ [play.centerYAnchor constraintEqualToAnchor:playBackground.contentView.centerYAnchor],+ [play.widthAnchor constraintEqualToAnchor:playBackground.widthAnchor],+ [play.heightAnchor constraintEqualToAnchor:playBackground.heightAnchor],+ ]];+ }+ }+ if (list) {+ cell.tag = indexPath.item;+ UISwipeGestureRecognizer *swipe = [[[UISwipeGestureRecognizer alloc]+ initWithTarget:self action:@selector(handleMachineSwipe:)] autorelease];+ swipe.direction = UISwipeGestureRecognizerDirectionRight;+ [cell addGestureRecognizer:swipe];+ [NSLayoutConstraint activateConstraints:@[+ [image.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:10],+ [image.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],+ [image.widthAnchor constraintEqualToConstant:104], [image.heightAnchor constraintEqualToConstant:62],+ [title.leadingAnchor constraintEqualToAnchor:image.trailingAnchor constant:14],+ [title.trailingAnchor constraintLessThanOrEqualToAnchor:more.leadingAnchor constant:-8],+ [title.bottomAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor constant:-2],+ [detail.leadingAnchor constraintEqualToAnchor:title.leadingAnchor],+ [detail.trailingAnchor constraintLessThanOrEqualToAnchor:more.leadingAnchor constant:-8],+ [detail.topAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor constant:3],+ [more.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-14],+ [more.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],+ [more.widthAnchor constraintEqualToConstant:48],+ [more.heightAnchor constraintEqualToConstant:48],+ ]];+ } else {+ [NSLayoutConstraint activateConstraints:@[+ [image.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor],+ [image.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor],+ [image.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],+ [image.heightAnchor constraintEqualToAnchor:cell.contentView.widthAnchor multiplier:0.56],+ [title.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:14],+ [title.trailingAnchor constraintLessThanOrEqualToAnchor:more.leadingAnchor constant:-6],+ [title.topAnchor constraintEqualToAnchor:image.bottomAnchor constant:12],+ [detail.leadingAnchor constraintEqualToAnchor:title.leadingAnchor],+ [detail.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-14],+ [detail.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:3],+ [more.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-12],+ [more.centerYAnchor constraintEqualToAnchor:title.centerYAnchor],+ [more.widthAnchor constraintEqualToConstant:48],+ [more.heightAnchor constraintEqualToConstant:48],+ ]];+ }+ cell.accessibilityLabel = [NSString stringWithFormat:@"%@, %@", title.text, detail.text];+ return cell;+}++- (NSString *)wallpaperNameForMachineName:(NSString *)name+{+ NSString *lower = name.lowercaseString;+ for (NSString *candidate in @[@"monterey", @"ventura", @"sonoma", @"sequoia", @"tahoe", @"golden-gate"])+ if ([lower containsString:[candidate stringByReplacingOccurrencesOfString:@"-" withString:@" "]] ||+ [lower containsString:[candidate stringByReplacingOccurrencesOfString:@"-" withString:@""]]) return candidate;+ NSDictionary *versions = @{@"macos 12":@"monterey", @"macos 13":@"ventura",+ @"macos 14":@"sonoma", @"macos 15":@"sequoia", @"macos 26":@"tahoe",+ @"macos 27":@"golden-gate"};+ for (NSString *token in versions) if ([lower containsString:token]) return versions[token];+ return @"tiger";+}++- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)layout+ sizeForItemAtIndexPath:(NSIndexPath *)indexPath+{+ (void)layout; (void)indexPath;+ CGFloat width = collectionView.bounds.size.width - 48;+ if ([[VZAppSettings.sharedSettings stringForKey:VZLibraryLayoutKey] isEqualToString:@"list"])+ return CGSizeMake(width, 82);+ NSUInteger columns = width >= 900 ? 3 : 2;+ CGFloat itemWidth = floor((width - 18 * (columns - 1)) / columns);+ return CGSizeMake(itemWidth, itemWidth * 0.56 + 76);+}++- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath+{+ [collectionView deselectItemAtIndexPath:indexPath animated:YES];+ if (indexPath.item == 0) { [self presentNewVMFlow]; return; }+ if (indexPath.item > self.filteredMachines.count) return;+ NSDictionary *machine = self.filteredMachines[indexPath.item - 1];+ UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];+ [self presentActionsForMachine:machine fromView:cell];+}++- (void)machineArtworkTapped:(UITapGestureRecognizer *)recognizer+{+ NSInteger item = recognizer.view.tag;+ if (item <= 0 || item > (NSInteger)self.filteredMachines.count) return;+ [self startMachine:self.filteredMachines[item - 1]];+}++- (void)startButton:(UIButton *)sender+{+ if (sender.tag == 0 || sender.tag > self.filteredMachines.count) return;+ [self startMachine:self.filteredMachines[sender.tag - 1]];+}++- (void)moreButton:(UIButton *)sender+{+ if (sender.tag == 0 || sender.tag > self.filteredMachines.count) return;+ [self configureMachineAtIndex:sender.tag - 1];+}++- (void)handleMachineSwipe:(UISwipeGestureRecognizer *)recognizer+{+ UICollectionViewCell *cell = (id)recognizer.view;+ if (cell.tag == 0 || cell.tag > (NSInteger)self.filteredMachines.count)+ return;+ NSDictionary *machine = self.filteredMachines[cell.tag - 1];+ UIAlertController *sheet = [UIAlertController+ alertControllerWithTitle:machine[@"name"] message:nil+ preferredStyle:UIAlertControllerStyleActionSheet];+ [sheet addAction:[UIAlertAction actionWithTitle:@"Options"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action; [self configureMachineAtIndex:cell.tag - 1];+ }]];+ if (![self isMachineActive:machine])+ [sheet addAction:[UIAlertAction actionWithTitle:@"Delete"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action; [self confirmDeleteMachine:machine];+ }]];+ [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ sheet.popoverPresentationController.sourceView = cell;+ sheet.popoverPresentationController.sourceRect = cell.bounds;+ [self presentViewController:sheet animated:YES completion:nil];+}++- (UIContextMenuConfiguration *)collectionView:(UICollectionView *)collectionView+ contextMenuConfigurationForItemAtIndexPath:(NSIndexPath *)indexPath+ point:(CGPoint)point+{+ (void)collectionView; (void)point;+ if (indexPath.item == 0 || indexPath.item > self.filteredMachines.count)+ return nil;+ NSDictionary *machine = self.filteredMachines[indexPath.item - 1];+ BOOL active = [self isMachineActive:machine];+ return [UIContextMenuConfiguration configurationWithIdentifier:nil+ previewProvider:nil actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggested) {+ (void)suggested;+ UIAction *start = [UIAction actionWithTitle:active ? @"Resume" : @"Start"+ image:[UIImage systemImageNamed:active ? @"rectangle.portrait.and.arrow.right" : @"play.fill"]+ identifier:nil handler:^(__kindof UIAction *action) {+ (void)action; [self startMachine:machine];+ }];+ UIAction *options = [UIAction actionWithTitle:@"Options"+ image:[UIImage systemImageNamed:@"gearshape"] identifier:nil+ handler:^(__kindof UIAction *action) {+ (void)action;+ NSUInteger index = [self.filteredMachines indexOfObject:machine];+ if (index != NSNotFound) [self configureMachineAtIndex:index];+ }];+ UIAction *power = [UIAction actionWithTitle:+ active ? @"Force Shut Down" : @"Delete"+ image:[UIImage systemImageNamed:active ? @"power" : @"trash"]+ identifier:nil handler:^(__kindof UIAction *action) {+ (void)action;+ if (active) [self forceShutdownMachine:machine];+ else [self confirmDeleteMachine:machine];+ }];+ power.attributes = UIMenuElementAttributesDestructive;+ return [UIMenu menuWithTitle:@"" children:@[start, options, power]];+ }];+}++- (void)addVM:(id)sender+{+ (void)sender;+ [self presentNewVMFlow];+}++- (void)presentNewVMFlow+{+ VZNewVMViewController *controller = [[[VZNewVMViewController alloc] init] autorelease];+ controller.delegate = self;+ UINavigationController *navigation = [[[UINavigationController alloc]+ initWithRootViewController:controller] autorelease];+ navigation.modalPresentationStyle = UIModalPresentationPageSheet;+ navigation.preferredContentSize = CGSizeMake(650, 700);+ [self presentViewController:navigation animated:YES completion:nil];+}++- (void)presentRestoreImagePicker+{+ UIDocumentPickerViewController *picker = [[[UIDocumentPickerViewController alloc]+ initForOpeningContentTypes:@[UTTypeItem] asCopy:NO] autorelease];+ picker.delegate = self;+ [self presentViewController:picker animated:YES completion:nil];+}++- (void)newVMControllerChooseLocalRestoreImage:(VZNewVMViewController *)controller+{+ [controller dismissViewControllerAnimated:YES completion:^{+ [self presentRestoreImagePicker];+ }];+}++- (void)cancelDownload+{+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Cancel Download?"+ message:@"The partial restore image will be deleted."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Keep Downloading"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel Download"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action;+ self.downloadCancelled = YES;+ [self.downloadTask cancel];+ [self.downloadTimer invalidate];+ self.downloadTimer = nil;+ if (self.downloadDestination.length)+ [NSFileManager.defaultManager removeItemAtPath:self.downloadDestination error:nil];+ if (self.downloadMarkerPath.length)+ [NSFileManager.defaultManager removeItemAtPath:self.downloadMarkerPath error:nil];+ UIApplication.sharedApplication.idleTimerDisabled = NO;+ [self.downloadController.navigationController dismissViewControllerAnimated:YES+ completion:^{+ self.downloadController.cancellationHandler = nil;+ self.downloadController = nil;+ self.downloadTask = nil;+ self.downloadDestination = nil;+ self.downloadMarkerPath = nil;+ }];+ }]];+ [self.downloadController presentViewController:alert animated:YES completion:nil];+}++- (void)newVMController:(VZNewVMViewController *)controller+ downloadRestoreImage:(NSDictionary *)image+{+ NSURL *remoteURL = [NSURL URLWithString:image[@"url"]];+ if (!remoteURL) return;+ [controller dismissViewControllerAnimated:YES completion:^{+ NSString *destination = [VZRestoreImagesPath() stringByAppendingPathComponent:+ remoteURL.lastPathComponent ?: @"Restore.ipsw"];+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:destination error:nil];+ uint64_t expected = [image[@"downloadSize"] unsignedLongLongValue];+ if (attributes && (!expected || [attributes[NSFileSize] unsignedLongLongValue] == expected)) {+ [self documentPicker:(id)self didPickDocumentsAtURLs:@[[NSURL fileURLWithPath:destination]]];+ return;+ }+ [NSFileManager.defaultManager createDirectoryAtPath:VZRestoreImagesPath()+ withIntermediateDirectories:YES attributes:nil error:nil];+ UIApplication.sharedApplication.idleTimerDisabled = YES;+ self.downloadCancelled = NO;+ self.downloadDestination = destination;+ self.downloadMarkerPath = [VZRestoreImagesPath() stringByAppendingPathComponent:+ [NSString stringWithFormat:@".%@.download.plist", destination.lastPathComponent]];+ [@{ @"Name": image[@"name"] ?: destination.lastPathComponent,+ @"URL": remoteURL.absoluteString ?: @"",+ @"Destination": destination,+ @"StartedAt": NSDate.date }+ writeToFile:self.downloadMarkerPath atomically:YES];+ self.downloadController = [[[VZProgressViewController alloc]+ initWithTitle:@"Downloading macOS"] autorelease];+ self.downloadController.statusText = image[@"name"] ?: @"Downloading restore image";+ self.downloadController.detailText = @"Keep Virtual Mac open. The iPad will remain awake until the download finishes.";+ self.downloadController.consoleHidden = YES;+ self.downloadController.indeterminate = expected == 0;+ self.downloadController.cancellationHandler = ^{ [self cancelDownload]; };+ UINavigationController *navigation = [[[UINavigationController alloc]+ initWithRootViewController:self.downloadController] autorelease];+ navigation.modalPresentationStyle = UIModalPresentationPageSheet;+ navigation.modalInPresentation = YES;+ navigation.preferredContentSize = CGSizeMake(620, 300);+ [self presentViewController:navigation animated:YES completion:nil];+ self.downloadTask = [NSURLSession.sharedSession downloadTaskWithURL:remoteURL+ completionHandler:^(NSURL *temporaryURL, NSURLResponse *response, NSError *error) {+ (void)response;+ NSError *moveError = nil;+ if (temporaryURL && !self.downloadCancelled) {+ [NSFileManager.defaultManager removeItemAtPath:destination error:nil];+ [NSFileManager.defaultManager moveItemAtURL:temporaryURL+ toURL:[NSURL fileURLWithPath:destination] error:&moveError];+ }+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.downloadTimer invalidate]; self.downloadTimer = nil;+ self.downloadTask = nil;+ UIApplication.sharedApplication.idleTimerDisabled = NO;+ NSError *failure = error ?: moveError;+ BOOL cancelled = self.downloadCancelled;+ if (!failure)+ [NSFileManager.defaultManager removeItemAtPath:self.downloadMarkerPath error:nil];+ if (!self.downloadController) return;+ [self.downloadController.navigationController dismissViewControllerAnimated:YES completion:^{+ self.downloadController.cancellationHandler = nil;+ self.downloadController = nil;+ self.downloadDestination = nil;+ self.downloadMarkerPath = nil;+ if (failure && !cancelled) {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Download Failed"+ message:failure.localizedDescription preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ } else {+ [self documentPicker:(id)self didPickDocumentsAtURLs:@[[NSURL fileURLWithPath:destination]]];+ }+ }];+ });+ }];+ [self.downloadTask resume];+ self.downloadLastBytes = 0;+ self.downloadLastSample = NSDate.date;+ self.downloadTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer *timer) {+ (void)timer;+ int64_t total = self.downloadTask.countOfBytesExpectedToReceive;+ int64_t received = self.downloadTask.countOfBytesReceived;+ if (total > 0) {+ float progress = (float)received / (float)total;+ self.downloadController.indeterminate = NO;+ self.downloadController.progress = progress;+ NSByteCountFormatter *formatter = [[[NSByteCountFormatter alloc] init] autorelease];+ formatter.countStyle = NSByteCountFormatterCountStyleFile;+ NSTimeInterval elapsed = -[self.downloadLastSample timeIntervalSinceNow];+ int64_t delta = received - self.downloadLastBytes;+ NSString *speed = elapsed > 0.05 && delta >= 0+ ? [NSString stringWithFormat:@"%@/s",+ [formatter stringFromByteCount:(int64_t)(delta / elapsed)]] : @"Calculating speed…";+ self.downloadController.statusText = [NSString stringWithFormat:+ @"%.1f%% complete", progress * 100.0];+ self.downloadController.detailText = [NSString stringWithFormat:+ @"%@ of %@ · %@\nKeep Virtual Mac open. The iPad will remain awake until the download finishes.",+ [formatter stringFromByteCount:received],+ [formatter stringFromByteCount:total], speed];+ self.downloadLastBytes = received;+ self.downloadLastSample = NSDate.date;+ }+ }];+ }];+}++- (void)documentPicker:(UIDocumentPickerViewController *)controller+ didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls+{+ NSURL *url = urls.firstObject;+ if (!url)+ return;+ NSString *extension = url.pathExtension.lowercaseString;+ if (![extension isEqualToString:@"ipsw"]) {+ UIAlertController *invalid = [UIAlertController+ alertControllerWithTitle:@"Unsupported Restore Image"+ message:@"Choose a macOS IPSW restore image."+ preferredStyle:UIAlertControllerStyleAlert];+ [invalid addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:invalid animated:YES completion:nil];+ return;+ }+ [url startAccessingSecurityScopedResource];+ self.pendingIPSWURL = url;+ NSString *suggested = VZUniqueVMName(+ VZMarketingNameForRestoreImage(url));+ NSMutableDictionary *defaults = [NSMutableDictionary+ dictionaryWithDictionary:VZVMDefaultOptions()];+ defaults[VZPointingDeviceKey] =+ VZDefaultPointingDeviceForPath(self.pendingIPSWURL.path);+ defaults[VZKeyboardDeviceKey] =+ VZDefaultKeyboardDeviceForPath(self.pendingIPSWURL.path);+ VZVMConfigurationViewController *configuration =+ [[[VZVMConfigurationViewController alloc]+ initWithBundlePath:nil options:defaults+ completion:^(NSDictionary *result) {+ NSMutableDictionary *options = [NSMutableDictionary+ dictionaryWithDictionary:result];+ NSString *name = VZUniqueVMName(options[VZVMNameKey]);+ [options removeObjectForKey:VZVMNameKey];+ [self.delegate vmLibrary:self+ installRestoreImageAtURL:self.pendingIPSWURL+ name:name options:options];+ }] autorelease];+ configuration.vmName = suggested;+ [self presentConfiguration:configuration];+}++- (void)dealloc+{+ [NSNotificationCenter.defaultCenter removeObserver:self];+ [_machines release];+ [_filteredMachines release];+ [_searchText release];+ [_pendingIPSWURL release];+ [_collectionView release];+ [_emptyView release];+ [_downloadTask cancel];+ [_downloadTask release];+ [_downloadTimer invalidate];+ [_downloadTimer release];+ _downloadController.cancellationHandler = nil;+ [_downloadController release];+ [_downloadDestination release];+ [_downloadMarkerPath release];+ [_downloadLastSample release];+ [super dealloc];+}+@enddiff --git a/VirtualMac/vz/host/VirtualMac-Info.plist b/VirtualMac/vz/host/VirtualMac-Info.plistnew file mode 100644index 0000000..dfd8573--- /dev/null+++ b/VirtualMac/vz/host/VirtualMac-Info.plist@@ -0,0 +1,84 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>Virtual Mac</string>+ <key>CFBundleExecutable</key>+ <string>VirtualMac</string>+ <key>CFBundleIdentifier</key>+ <string>com.mac.virtual</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Virtual Mac</string>+ <key>CFBundleIcons</key>+ <dict>+ <key>CFBundlePrimaryIcon</key>+ <dict>+ <key>CFBundleIconFiles</key>+ <array>+ <string>AppIcon60x60</string>+ </array>+ </dict>+ </dict>+ <key>CFBundleIcons~ipad</key>+ <dict>+ <key>CFBundlePrimaryIcon</key>+ <dict>+ <key>CFBundleIconFiles</key>+ <array>+ <string>AppIcon60x60</string>+ <string>AppIcon76x76</string>+ <string>AppIcon83.5x83.5</string>+ </array>+ </dict>+ </dict>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLName</key>+ <string>Virtual Mac Test Harness</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>virtualmac</string>+ </array>+ </dict>+ </array>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>LSRequiresIPhoneOS</key>+ <true/>+ <key>UILaunchStoryboardName</key>+ <string>VirtualMacLaunchScreen</string>+ <key>LSSupportsOpeningDocumentsInPlace</key>+ <true/>+ <key>MinimumOSVersion</key>+ <string>16.0</string>+ <key>NSMicrophoneUsageDescription</key>+ <string>Pass microphone audio through to the macOS virtual machine.</string>+ <key>UIDeviceFamily</key>+ <array>+ <integer>1</integer>+ <integer>2</integer>+ </array>+ <key>UIApplicationSupportsIndirectInputEvents</key>+ <true/>+ <key>UIFileSharingEnabled</key>+ <true/>+ <key>UISupportedInterfaceOrientations~ipad</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationPortraitUpsideDown</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+</dict>+</plist>diff --git a/VirtualMac/vz/host/VirtualMac.entitlements b/VirtualMac/vz/host/VirtualMac.entitlementsnew file mode 100644index 0000000..b446871--- /dev/null+++ b/VirtualMac/vz/host/VirtualMac.entitlements@@ -0,0 +1,38 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.virtualization</key>+ <true/>+ <key>com.apple.private.virtualization</key>+ <true/>+ <key>com.apple.virtualization.avp.videotoolbox</key>+ <true/>+ <key>com.apple.vm.networking</key>+ <true/>+ <key>com.apple.private.hypervisor</key>+ <true/>+ <key>com.apple.private.memorystatus</key>+ <true/>+ <key>com.apple.private.IOSurface.wiredSendRights</key>+ <true/>+ <key>com.apple.security.exception.iokit-user-client-class</key>+ <array>+ <string>IOSurfaceRootUserClient</string>+ </array>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>platform-application</key>+ <true/>+ <key>com.apple.private.amfi.can-execute-cdhash</key>+ <true/>+ <key>com.apple.private.tcc.allow</key>+ <array>+ <string>kTCCServiceMicrophone</string>+ </array>+ <key>get-task-allow</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/host/VirtualMacApp.m b/VirtualMac/vz/host/VirtualMacApp.mnew file mode 100644index 0000000..596832e--- /dev/null+++ b/VirtualMac/vz/host/VirtualMacApp.m@@ -0,0 +1,3320 @@+#import <Foundation/Foundation.h>+#import <GameController/GameController.h>+#import <UIKit/UIKit.h>+#import <AVFAudio/AVFAudio.h>+#import "NSViewShim.h"+#import "VZVMLibraryViewController.h"+#import "VZAppSettings.h"+#import "VZProgressViewController.h"+#include <dlfcn.h>+#include <objc/runtime.h>+#include <objc/message.h>+#include <mach-o/loader.h>+#include <errno.h>+#include <spawn.h>+#include <sys/wait.h>+#include <unistd.h>++extern char **environ;++static id gVirtualMachine;+static id gVirtualMachineDelegate;+static UIView *gFramebufferView;+static id gFramebuffer;+static id gKeyboard;+static id gPointingDevice;+static UIView *gInputView;+static UIView *gDisplayContainer;+static CALayer *gDisplayLayer;+static UIImageView *gCursorView;+static UILabel *gStatusLabel;+static UIView *gHUDView;+static BOOL gSoftwareKeyboardRequested;+static BOOL gHUDHiddenForBoot;+static BOOL gHUDForcedVisibleForBoot;+static NSLayoutConstraint *gHUDHorizontalConstraint;+static NSLayoutConstraint *gHUDVerticalConstraint;+static IMP gOriginalFrameUpdate;+static IMP gOriginalCursorUpdate;+static uint64_t gFrameUpdateCount;+static uint64_t gCursorUpdateCount;+static uint64_t gPointerEventCount;+static uint64_t gPointerButtonEventCount;+static uint64_t gScrollEventCount;+static uint64_t gKeyEventCount;+static uint64_t gLastHealthFrameCount;+static uint64_t gLastHealthInteractionCount;+static NSUInteger gFrameStallIntervals;+static CGPoint gMouseLocation;+// UIKit's pointer has its own absolute coordinate that cannot be warped when+// a direct touchscreen tap moves the guest cursor. Track raw host motion+// separately and apply its deltas to the guest coordinate so the next click+// remains at the touchscreen-selected location.+static CGPoint gHostPointerLocation;+static BOOL gHostPointerLocationValid;+static BOOL gUIKitHoverActive;+static CGSize gLastInputBoundsSize;+static CGFloat gLastPinchScale = 1.0;+static CGFloat gLastRotation;+// UIKit reports an indirect-pointer click as a touch while GameController+// reports the same physical click independently. Keep both lifetimes and send+// their union so either source releasing first cannot break a drag.+static NSUInteger gHardwareMouseButtons;+static NSUInteger gTouchButtons;+static CGPoint gLastPointerLocation = {NAN, NAN};+static NSUInteger gLastPointerButtons = NSUIntegerMax;+static CGSize gDisplayPixelSize = {1920, 1440};+static CGSize gCursorPixelSize;+static CGPoint gCursorHotspot;+static CFTimeInterval gLastPredictedCursorTime;+static void (*gHostVMStarted)(void);+static SEL S(const char *name);+static void sendKey(UIKeyboardHIDUsage usage, BOOL pressed);+static void sendPointer(CGPoint point, CGRect bounds, NSUInteger pressedButtons);+static void setStatus(NSString *status);+static void updateDisplayGeometry(void);+static void logFramebufferState(id view, id framebuffer, const char *phase);+static void startVirtualMachine(UIView *container, id delegate,+ NSString *bundlePath,+ NSDictionary *options);++static NSUInteger activePointerButtons(void) {+ return gHardwareMouseButtons | gTouchButtons;+}++static BOOL shouldShowStatusLabel(void) {+ NSProcessInfo *processInfo = NSProcessInfo.processInfo;+ if ([processInfo.arguments containsObject:@"--show-status-label"])+ return YES;+ return [VZAppSettings.sharedSettings boolForKey:VZShowStatusLabelKey];+}++static void resetPointerSession(BOOL releaseButtons) {+ gHostPointerLocationValid = NO;+ gUIKitHoverActive = NO;+ if (releaseButtons && (gTouchButtons || gHardwareMouseButtons)) {+ gTouchButtons = 0;+ gHardwareMouseButtons = 0;+ if (gInputView)+ sendPointer(gMouseLocation, gInputView.bounds, 0);+ }+}++static void startHealthMonitor(void) {+ dispatch_queue_t queue = dispatch_get_main_queue();+ dispatch_source_t timer = dispatch_source_create(+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);+ dispatch_source_set_timer(+ timer, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),+ 10 * NSEC_PER_SEC, NSEC_PER_SEC / 2);+ dispatch_source_set_event_handler(timer, ^{+ NSInteger state = gVirtualMachine+ ? ((NSInteger(*)(id, SEL))objc_msgSend)(+ gVirtualMachine, S("state"))+ : -1;+ uint64_t frames = __atomic_load_n(+ &gFrameUpdateCount, __ATOMIC_RELAXED);+ uint64_t interactions = __atomic_load_n(+ &gPointerButtonEventCount, __ATOMIC_RELAXED) ++ __atomic_load_n(&gScrollEventCount, __ATOMIC_RELAXED) ++ __atomic_load_n(&gKeyEventCount, __ATOMIC_RELAXED);+ printf("[VirtualMac] health state=%ld frames=%llu cursors=%llu "+ "pointer=%llu scroll=%llu keys=%llu\n",+ (long)state,+ (unsigned long long)frames,+ (unsigned long long)__atomic_load_n(+ &gCursorUpdateCount, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &gPointerEventCount, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &gScrollEventCount, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &gKeyEventCount, __ATOMIC_RELAXED));+ if (state == 1 && frames != 0 && frames == gLastHealthFrameCount &&+ interactions != gLastHealthInteractionCount) {+ gFrameStallIntervals++;+ if (gFrameStallIntervals == 3 ||+ gFrameStallIntervals % 6 == 0) {+ printf("[VirtualMac] display stall intervals=%lu frames=%llu\n",+ (unsigned long)gFrameStallIntervals,+ (unsigned long long)frames);+ logFramebufferState(+ gFramebufferView, gFramebuffer, "stalled");+ }+ } else {+ gFrameStallIntervals = 0;+ }+ gLastHealthFrameCount = frames;+ gLastHealthInteractionCount = interactions;+ });+ dispatch_resume(timer);+}++typedef struct {+ const void *object;+ const void *control;+} VZFrameUpdateSharedPtr;++static id CLS(const char *name) { return (id)objc_getClass(name); }+static SEL S(const char *name) { return sel_registerName(name); }+static id m0(id object, const char *selector) {+ return ((id(*)(id, SEL))objc_msgSend)(object, S(selector));+}+static id NEW(const char *className) {+ return m0(m0(CLS(className), "alloc"), "init");+}+static void setObj(id object, const char *selector, id value) {+ ((void(*)(id, SEL, id))objc_msgSend)(object, S(selector), value);+}+static NSURL *fileURL(NSString *path) {+ return [NSURL fileURLWithPath:path];+}++static CGPoint clampPointerLocation(CGPoint point, CGRect bounds) {+ return CGPointMake(+ fmin(CGRectGetMaxX(bounds), fmax(CGRectGetMinX(bounds), point.x)),+ fmin(CGRectGetMaxY(bounds), fmax(CGRectGetMinY(bounds), point.y)));+}++static void sendPointer(CGPoint point, CGRect bounds,+ NSUInteger pressedButtons) {+ if (!gPointingDevice || bounds.size.width <= 0 ||+ bounds.size.height <= 0)+ return;+ point = clampPointerLocation(point, bounds);+ gMouseLocation = point;+ CGPoint normalized = CGPointMake(+ fmin(1.0, fmax(0.0, point.x / bounds.size.width)),+ fmin(1.0, fmax(0.0, point.y / bounds.size.height)));+ // Draw the already-decoded guest cursor at the host event location now.+ // Waiting for the pointer round-trip through VMM/PVG adds a very visible+ // frame or two of latency on an iPad trackpad.+ if (gCursorView && !gCursorView.hidden && gCursorView.image) {+ CGFloat scaleX = bounds.size.width / gDisplayPixelSize.width;+ CGFloat scaleY = bounds.size.height / gDisplayPixelSize.height;+ CGSize size = CGSizeMake(gCursorPixelSize.width * scaleX,+ gCursorPixelSize.height * scaleY);+ CGPoint origin = CGPointMake(+ gInputView.frame.origin.x + point.x - gCursorHotspot.x * scaleX,+ gInputView.frame.origin.y + point.y - gCursorHotspot.y * scaleY);+ gCursorView.frame = (CGRect){origin, size};+ gLastPredictedCursorTime = CACurrentMediaTime();+ }+ BOOL buttonsChanged = pressedButtons != gLastPointerButtons;+ if (!buttonsChanged && CGPointEqualToPoint(normalized,+ gLastPointerLocation))+ return;+ gLastPointerLocation = normalized;+ gLastPointerButtons = pressedButtons;+ if (buttonsChanged)+ __sync_add_and_fetch(&gPointerButtonEventCount, 1);+ id event = ((id(*)(id, SEL, CGPoint, NSInteger))objc_msgSend)(+ m0(CLS("_VZScreenCoordinatePointerEvent"), "alloc"),+ S("initWithLocation:pressedButtons:"),+ normalized, (NSInteger)pressedButtons);+ ((void(*)(id, SEL, id))objc_msgSend)(+ gPointingDevice, S("sendPointerEvents:"), @[event]);+ [event release];+ uint64_t count = __sync_add_and_fetch(&gPointerEventCount, 1);+ if (count <= 8 || buttonsChanged)+ printf("[VirtualMac] input pointer=%llu location=%.4f,%.4f buttons=0x%lx\n",+ (unsigned long long)count, normalized.x, normalized.y,+ (unsigned long)pressedButtons);+}++static void sendIndirectPointerLocation(CGPoint hostPoint, CGRect bounds) {+ // Trackpad coordinates are already absolute in the input view. Prefer reliable native absolute tracking;+ // after touching the screen, the next trackpad movement/click simply uses its own location.+ sendPointer(hostPoint, bounds, activePointerButtons());+}++static void sendMagnification(double magnification, NSUInteger phase) {+ if (!gPointingDevice)+ return;+ id event = ((id(*)(id, SEL, double, NSUInteger))objc_msgSend)(+ m0(CLS("_VZMagnifyEvent"), "alloc"),+ S("initWithMagnification:phase:"), magnification, phase);+ if (!event)+ return;+ ((void(*)(id, SEL, id))objc_msgSend)(+ gPointingDevice, S("sendMagnifyEvents:"), @[event]);+ [event release];+ printf("[VirtualMac] input magnify delta=%.4f phase=0x%lx\n",+ magnification, (unsigned long)phase);+}++static void sendRotation(double rotation, NSUInteger phase) {+ if (!gPointingDevice)+ return;+ id event = ((id(*)(id, SEL, double, NSUInteger))objc_msgSend)(+ m0(CLS("_VZRotationEvent"), "alloc"),+ S("initWithRotation:phase:"), rotation, phase);+ if (!event)+ return;+ ((void(*)(id, SEL, id))objc_msgSend)(+ gPointingDevice, S("sendRotationEvents:"), @[event]);+ [event release];+ printf("[VirtualMac] input rotate delta=%.4f phase=0x%lx\n",+ rotation, (unsigned long)phase);+}++static void sendSmartMagnification(void) {+ if (!gPointingDevice)+ return;+ id event = NEW("_VZSmartMagnifyEvent");+ if (!event)+ return;+ ((void(*)(id, SEL, id))objc_msgSend)(+ gPointingDevice, S("sendSmartMagnifyEvents:"), @[event]);+ [event release];+ printf("[VirtualMac] input smart magnify\n");+}++static void sendMouseDelta(float deltaX, float deltaY) {+ dispatch_async(dispatch_get_main_queue(), ^{+ CGRect bounds = gInputView.bounds;+ gMouseLocation.x =+ fmin(CGRectGetMaxX(bounds), fmax(CGRectGetMinX(bounds),+ gMouseLocation.x + deltaX));+ gMouseLocation.y =+ fmin(CGRectGetMaxY(bounds), fmax(CGRectGetMinY(bounds),+ gMouseLocation.y - deltaY));+ sendPointer(gMouseLocation, bounds, activePointerButtons());+ });+}++static void sendMouseButton(NSUInteger mask, BOOL pressed) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (pressed)+ gHardwareMouseButtons |= mask;+ else+ gHardwareMouseButtons &= ~mask;+ sendPointer(gMouseLocation, gInputView.bounds,+ activePointerButtons());+ });+}++static void sendScrollWheel(CGVector rawDelta, CGVector acceleratedDelta,+ BOOL directionInvertedFromDevice,+ NSUInteger deviceCategory,+ NSUInteger phase) {+ if (!gPointingDevice)+ return;+ id event = ((id(*)(id, SEL, double, double, double, double,+ NSUInteger, NSUInteger))objc_msgSend)(+ m0(CLS("_VZScrollWheelEvent"), "alloc"),+ S("initWithScrollingDeltaX:scrollingDeltaY:"+ "acceleratedScrollingDeltaX:acceleratedScrollingDeltaY:"+ "scrollPhase:momentumPhase:"),+ -rawDelta.dy, rawDelta.dx,+ -rawDelta.dy, rawDelta.dx, phase, 0);+ if (!event)+ return;+ ((void(*)(id, SEL, id))objc_msgSend)(+ gPointingDevice, S("sendScrollWheelEvents:"), @[event]);+ [event release];+ uint64_t count = __sync_add_and_fetch(&gScrollEventCount, 1);+ if (count <= 12 || phase != 4)+ printf("[VirtualMac] input scroll=%llu raw=%.3f,%.3f "+ "accelerated=%.3f,%.3f inverted=%d device=%lu "+ "phase=0x%lx\n",+ (unsigned long long)count, rawDelta.dx, rawDelta.dy,+ acceleratedDelta.dx, acceleratedDelta.dy,+ directionInvertedFromDevice, (unsigned long)deviceCategory,+ (unsigned long)phase);+}++static void installGCMouse(void) {+ GCMouse *mouse = GCMouse.current;+ printf("[VirtualMac] GC mouse current=%p input=%p\n",+ mouse, mouse.mouseInput);+ if (!mouse)+ return;+ mouse.mouseInput.mouseMovedHandler =+ ^(GCMouseInput *input, float deltaX, float deltaY) {+ (void)input;+ // UIKit hover is the authoritative absolute path for a trackpad.+ // Some devices also appear as GCMouse; accepting both makes motion+ // jump or hit artificial edges after system UI steals the pointer.+ if (gUIKitHoverActive)+ return;+ sendMouseDelta(deltaX, deltaY);+ };+ mouse.mouseInput.leftButton.pressedChangedHandler =+ ^(GCControllerButtonInput *button, float value, BOOL pressed) {+ (void)button;+ (void)value;+ sendMouseButton(1, pressed);+ };+ mouse.mouseInput.rightButton.pressedChangedHandler =+ ^(GCControllerButtonInput *button, float value, BOOL pressed) {+ (void)button;+ (void)value;+ sendMouseButton(2, pressed);+ };+ mouse.mouseInput.middleButton.pressedChangedHandler =+ ^(GCControllerButtonInput *button, float value, BOOL pressed) {+ (void)button;+ (void)value;+ sendMouseButton(4, pressed);+ };+}++static void scheduleInputSelfTest(void) {+ if (unlink("/tmp/vz-input-self-test") != 0)+ return;+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ CGRect bounds = gInputView.bounds;+ CGPoint point = CGPointMake(+ CGRectGetMinX(bounds) + CGRectGetWidth(bounds) * 0.75,+ CGRectGetMidY(bounds));+ printf("[VirtualMac] input self-test begin\n");+ sendPointer(point, bounds, 0);+ sendKey((UIKeyboardHIDUsage)0x39, YES); // Caps Lock+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{+ sendKey((UIKeyboardHIDUsage)0x39, NO);+ printf("[VirtualMac] input self-test sent pointer and Caps Lock\n");+ });+ });+}++static void pollInputCommand(void) {+ NSString *path = @"/tmp/vz-input-command";+ NSString *command = [NSString stringWithContentsOfFile:path+ encoding:NSUTF8StringEncoding+ error:nil];+ if (command.length && unlink(path.fileSystemRepresentation) == 0) {+ NSArray<NSString *> *fields = [command+ componentsSeparatedByCharactersInSet:+ NSCharacterSet.whitespaceAndNewlineCharacterSet];+ NSMutableArray<NSString *> *tokens = [NSMutableArray array];+ for (NSString *field in fields) {+ if (field.length)+ [tokens addObject:field];+ }+ if (tokens.count == 2 && [tokens[0] isEqualToString:@"tapkey"]) {+ UIKeyboardHIDUsage usage = (UIKeyboardHIDUsage)tokens[1].intValue;+ printf("[VirtualMac] input command tapkey HID=0x%x\n",+ (unsigned int)usage);+ sendKey(usage, YES);+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{ sendKey(usage, NO); });+ } else if (tokens.count == 3 &&+ [tokens[0] isEqualToString:@"key"]) {+ UIKeyboardHIDUsage usage = (UIKeyboardHIDUsage)tokens[1].intValue;+ BOOL pressed = tokens[2].boolValue;+ printf("[VirtualMac] input command key HID=0x%x pressed=%d\n",+ (unsigned int)usage, pressed);+ sendKey(usage, pressed);+ } else if (tokens.count == 4 &&+ [tokens[0] isEqualToString:@"click"]) {+ CGFloat x = MAX(0, MIN(1, tokens[1].doubleValue));+ CGFloat y = MAX(0, MIN(1, tokens[2].doubleValue));+ NSUInteger button = MAX(1, MIN(4, tokens[3].integerValue));+ CGRect bounds = gInputView.bounds;+ CGPoint point = CGPointMake(CGRectGetWidth(bounds) * x,+ CGRectGetHeight(bounds) * y);+ printf("[VirtualMac] input command click %.3f,%.3f button=0x%lx\n",+ x, y, (unsigned long)button);+ sendPointer(point, bounds, button);+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{ sendPointer(point, bounds, 0); });+ } else if (tokens.count == 4 &&+ [tokens[0] isEqualToString:@"scroll"]) {+ double x = tokens[1].doubleValue;+ double y = tokens[2].doubleValue;+ NSUInteger phase = tokens[3].integerValue;+ printf("[VirtualMac] input command scroll %.3f,%.3f phase=0x%lx\n",+ x, y, (unsigned long)phase);+ sendScrollWheel(CGVectorMake(x, y), CGVectorMake(x, y),+ NO, 0, phase);+ } else if (tokens.count == 3 &&+ [tokens[0] isEqualToString:@"magnify"]) {+ double delta = tokens[1].doubleValue;+ NSUInteger phase = tokens[2].integerValue;+ printf("[VirtualMac] input command magnify %.4f phase=0x%lx\n",+ delta, (unsigned long)phase);+ sendMagnification(delta, phase);+ } else if (tokens.count == 3 &&+ [tokens[0] isEqualToString:@"rotate"]) {+ double delta = tokens[1].doubleValue;+ NSUInteger phase = tokens[2].integerValue;+ printf("[VirtualMac] input command rotate %.4f phase=0x%lx\n",+ delta, (unsigned long)phase);+ sendRotation(delta, phase);+ } else if (tokens.count == 1 &&+ [tokens[0] isEqualToString:@"smartmagnify"]) {+ printf("[VirtualMac] input command smart magnify\n");+ sendSmartMagnification();+ } else {+ printf("[VirtualMac] invalid input command: %s\n",+ command.UTF8String);+ }+ }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{ pollInputCommand(); });+}++static void scheduleRecoveryDialogDismissal(void) {+ if (unlink("/tmp/vz-dismiss-restart-alert") != 0)+ return;+ printf("[VirtualMac] recovery dialog auto-dismiss armed\n");+ for (int attempt = 0; attempt < 10; attempt++) {+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW,+ (4 + attempt) * NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ printf("[VirtualMac] recovery dialog Return attempt=%d\n",+ attempt + 1);+ sendKey((UIKeyboardHIDUsage)0x28, YES);+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{+ sendKey((UIKeyboardHIDUsage)0x28, NO);+ });+ });+ }+}++static BOOL gForceStopPending;+static dispatch_source_t gControlTimer;++static void writeStopMarker(const char *path, const char *message) {+ FILE *marker = fopen(path, "w");+ if (!marker)+ return;+ fputs(message, marker);+ fputc('\n', marker);+ fclose(marker);+}++static void forceStopVirtualMachine(void) {+ if (!gVirtualMachine || gForceStopPending)+ return;++ NSInteger state = ((NSInteger(*)(id, SEL))objc_msgSend)(+ gVirtualMachine, S("state"));+ if (state == 0) {+ writeStopMarker("/tmp/vz-guest-stopped", "already stopped");+ return;+ }+ if (![gVirtualMachine respondsToSelector:S("stopWithCompletionHandler:")]) {+ writeStopMarker("/tmp/vz-force-stop-failed",+ "stopWithCompletionHandler: unavailable");+ return;+ }++ gForceStopPending = YES;+ printf("[VirtualMac] direct virtual machine stop requested state=%ld\n",+ (long)state);+ void (^completion)(NSError *) = ^(NSError *error) {+ gForceStopPending = NO;+ if (error) {+ const char *description = [[error description] UTF8String];+ writeStopMarker("/tmp/vz-force-stop-failed",+ description ?: "unknown direct stop error");+ printf("[VirtualMac] direct virtual machine stop failed: %s\n",+ description ?: "unknown error");+ return;+ }+ writeStopMarker("/tmp/vz-guest-stopped", "direct stop complete");+ printf("[VirtualMac] direct virtual machine stop complete\n");+ dispatch_async(dispatch_get_main_queue(), ^{+ if ([gVirtualMachineDelegate respondsToSelector:+ S("finishVMAndShowLibraryWithError:")])+ ((void(*)(id, SEL, id))objc_msgSend)(+ gVirtualMachineDelegate,+ S("finishVMAndShowLibraryWithError:"), nil);+ });+ };+ ((void(*)(id, SEL, id))objc_msgSend)(+ gVirtualMachine, S("stopWithCompletionHandler:"), completion);+}++static void startControlMonitor(void) {+ gControlTimer = dispatch_source_create(+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());+ dispatch_source_set_timer(+ gControlTimer,+ dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC),+ NSEC_PER_SEC, NSEC_PER_SEC / 10);+ dispatch_source_set_event_handler(gControlTimer, ^{+ if (unlink("/tmp/vz-request-guest-stop") == 0)+ forceStopVirtualMachine();+ if (unlink("/tmp/vz-request-force-stop") == 0)+ forceStopVirtualMachine();+ });+ dispatch_resume(gControlTimer);+}++// Translate USB HID usages reported by UIKit to the macOS virtual key codes+// consumed by _VZKeyEvent. Cover the standard alphanumeric, navigation,+// function, and modifier keys used by the built-in iPad keyboard.+static NSInteger macVirtualKeyCode(UIKeyboardHIDUsage usage) {+ static const int16_t alphaAndNumberRow[] = {+ 0, 11, 8, 2, 14, 3, 5, 4, 34, 38, 40, 37, 46,+ 45, 31, 35, 12, 15, 1, 17, 32, 9, 13, 7, 16, 6,+ 18, 19, 20, 21, 23, 22, 26, 28, 25, 29,+ };+ NSInteger raw = (NSInteger)usage;+ if (raw >= 0x04 && raw <= 0x27)+ return alphaAndNumberRow[raw - 0x04];+ switch (raw) {+ case 0x28: return 36; // Return+ case 0x29: return 53; // Escape+ case 0x2a: return 51; // Delete / Backspace+ case 0x2b: return 48; // Tab+ case 0x2c: return 49; // Space+ case 0x2d: return 27; // -+ case 0x2e: return 24; // =+ case 0x2f: return 33; // [+ case 0x30: return 30; // ]+ case 0x31: return 42; // Backslash+ case 0x33: return 41; // ;+ case 0x34: return 39; // Quote+ case 0x35: return 50; // Grave+ case 0x36: return 43; // Comma+ case 0x37: return 47; // Period+ case 0x38: return 44; // Slash+ case 0x39: return 57; // Caps Lock+ case 0x3a: return 122; // F1+ case 0x3b: return 120; // F2+ case 0x3c: return 99; // F3+ case 0x3d: return 118; // F4+ case 0x3e: return 96; // F5+ case 0x3f: return 97; // F6+ case 0x40: return 98; // F7+ case 0x41: return 100; // F8+ case 0x42: return 101; // F9+ case 0x43: return 109; // F10+ case 0x44: return 103; // F11+ case 0x45: return 111; // F12+ case 0x46: return 105; // Print Screen / F13+ case 0x47: return 107; // Scroll Lock / F14+ case 0x48: return 113; // Pause / F15+ case 0x49: return 114; // Insert / Help+ case 0x4a: return 115; // Home+ case 0x4b: return 116; // Page Up+ case 0x4c: return 117; // Forward Delete+ case 0x4d: return 119; // End+ case 0x4e: return 121; // Page Down+ case 0x4f: return 124; // Right Arrow+ case 0x50: return 123; // Left Arrow+ case 0x51: return 125; // Down Arrow+ case 0x52: return 126; // Up Arrow+ case 0x53: return 71; // Keypad Clear / Num Lock+ case 0x54: return 75; // Keypad /+ case 0x55: return 67; // Keypad *+ case 0x56: return 78; // Keypad -+ case 0x57: return 69; // Keypad ++ case 0x58: return 76; // Keypad Enter+ case 0x59: return 83; // Keypad 1+ case 0x5a: return 84; // Keypad 2+ case 0x5b: return 85; // Keypad 3+ case 0x5c: return 86; // Keypad 4+ case 0x5d: return 87; // Keypad 5+ case 0x5e: return 88; // Keypad 6+ case 0x5f: return 89; // Keypad 7+ case 0x60: return 91; // Keypad 8+ case 0x61: return 92; // Keypad 9+ case 0x62: return 82; // Keypad 0+ case 0x63: return 65; // Keypad decimal+ case 0x64: return 10; // ISO non-US backslash+ case 0x67: return 81; // Keypad =+ case 0x87: return 94; // JIS underscore / Ro+ case 0x89: return 93; // JIS Yen+ case 0x8a: return 104; // JIS Kana / conversion+ case 0x8b: return 102; // JIS Eisu / non-conversion+ case 0x8c: return 95; // JIS keypad comma+ case 0x90: return 104; // LANG1 / Kana+ case 0x91: return 102; // LANG2 / Eisu+ case 0xe0: return 59; // Left Control+ case 0xe1: return 56; // Left Shift+ case 0xe2: return 58; // Left Option+ case 0xe3: return 55; // Left Command+ case 0xe4: return 62; // Right Control+ case 0xe5: return 60; // Right Shift+ case 0xe6: return 61; // Right Option+ case 0xe7: return 54; // Right Command+ default: return -1;+ }+}++static void sendKey(UIKeyboardHIDUsage usage, BOOL pressed) {+ if (!gKeyboard)+ return;+ NSInteger keyCode = macVirtualKeyCode(usage);+ if (keyCode < 0) {+ printf("[VirtualMac] input unmapped HID usage=0x%lx\n",+ (unsigned long)usage);+ return;+ }+ id event = ((id(*)(id, SEL, NSInteger, unsigned short))objc_msgSend)(+ m0(CLS("_VZKeyEvent"), "alloc"), S("initWithType:keyCode:"),+ pressed ? 0 : 1, (unsigned short)keyCode);+ ((void(*)(id, SEL, id))objc_msgSend)(+ gKeyboard, S("sendKeyEvents:"), @[event]);+ [event release];+ uint64_t count = __sync_add_and_fetch(&gKeyEventCount, 1);+ if (count <= 12)+ printf("[VirtualMac] input key=%llu HID=0x%lx mac=%ld pressed=%d\n",+ (unsigned long long)count, (unsigned long)usage,+ (long)keyCode, pressed);+}++static BOOL sendPresses(NSSet<UIPress *> *presses, BOOL pressed) {+ // When no guest keyboard is active, UIKit owns hardware key events (for+ // example numeric input in the VM configuration alert). Treating a press+ // as handled merely because it has a HID key swallowed those keystrokes.+ if (!gKeyboard || !gInputView || gInputView.hidden || !gInputView.window)+ return NO;+ BOOL handled = NO;+ for (UIPress *press in presses) {+ if (press.key) {+ sendKey(press.key.keyCode, pressed);+ handled = YES;+ }+ }+ return handled;+}++static void shellShortcutNotification(CFNotificationCenterRef center,+ void *observer, CFStringRef name,+ const void *object,+ CFDictionaryRef userInfo) {+ (void)center;+ (void)observer;+ (void)object;+ (void)userInfo;+ NSString *notification = (NSString *)name;+ BOOL pressed = [notification hasSuffix:@".down"];+ UIKeyboardHIDUsage usage = 0;+ if ([notification containsString:@"command-space"])+ usage = (UIKeyboardHIDUsage)0x2c;+ else if ([notification containsString:@"command-tab"])+ usage = (UIKeyboardHIDUsage)0x2b;+ else if ([notification containsString:@"command-grave"])+ usage = (UIKeyboardHIDUsage)0x35;+ if (usage) {+ printf("[VirtualMac] SpringBoard shortcut relay usage=0x%lx pressed=%d\n",+ (unsigned long)usage, pressed);+ sendKey(usage, pressed);+ }+}++static void installShellShortcutRelay(void) {+ CFNotificationCenterRef center =+ CFNotificationCenterGetDarwinNotifyCenter();+ for (NSString *shortcut in @[@"command-space", @"command-tab",+ @"command-grave"]) {+ for (NSString *state in @[@"down", @"up"]) {+ NSString *name = [NSString stringWithFormat:+ @"com.mac.virtual.%@.%@", shortcut, state];+ CFNotificationCenterAddObserver(+ center, NULL, shellShortcutNotification,+ (CFStringRef)name, NULL,+ CFNotificationSuspensionBehaviorDeliverImmediately);+ }+ }+}++@interface NSObject (VZScrollEventSPI)+- (CGVector)nonAcceleratedDelta;+- (CGVector)acceleratedDelta;+- (BOOL)directionInvertedFromDevice;+@end++@interface UIPanGestureRecognizer (VZScrollEventSPI)+- (void)_scrollingChangedWithEvent:(id)event;+@end++@interface VZRawScrollRecognizer : UIPanGestureRecognizer {+ CGVector _vzRawDelta;+ CGVector _vzAcceleratedDelta;+ BOOL _vzDirectionInverted;+}+- (CGVector)vzRawDelta;+- (CGVector)vzAcceleratedDelta;+- (BOOL)vzDirectionInverted;+@end++@implementation VZRawScrollRecognizer++- (void)_scrollingChangedWithEvent:(id)event+{+ _vzRawDelta = [event nonAcceleratedDelta];+ _vzAcceleratedDelta = [event acceleratedDelta];+ _vzDirectionInverted = [event directionInvertedFromDevice];+ [super _scrollingChangedWithEvent:event];+}++- (CGVector)vzRawDelta { return _vzRawDelta; }+- (CGVector)vzAcceleratedDelta { return _vzAcceleratedDelta; }+- (BOOL)vzDirectionInverted { return _vzDirectionInverted; }++@end++static void sendSoftwareKey(UIKeyboardHIDUsage usage, BOOL shifted);++@interface VZInputView : UIView <UIPointerInteractionDelegate, UIKeyInput> {+ UIInputView *_vzAccessoryView;+ UIStackView *_vzAccessoryStack;+ NSMutableSet<NSNumber *> *_vzHeldSoftwareModifiers;+}+@end++@implementation VZInputView++- (BOOL)canBecomeFirstResponder+{+ return YES;+}++- (BOOL)hasText { return YES; }++- (UIView *)inputAccessoryView+{+ if (GCKeyboard.coalescedKeyboard)+ return nil;+ if (_vzAccessoryView)+ return _vzAccessoryView;+ _vzHeldSoftwareModifiers = [[NSMutableSet alloc] init];+ _vzAccessoryView = [[UIInputView alloc]+ initWithFrame:CGRectMake(0, 0, 0, 52)+ inputViewStyle:UIInputViewStyleKeyboard];+ UIScrollView *scroll = [[[UIScrollView alloc] init] autorelease];+ scroll.translatesAutoresizingMaskIntoConstraints = NO;+ scroll.alwaysBounceHorizontal = YES;+ scroll.showsHorizontalScrollIndicator = YES;+ scroll.directionalLockEnabled = YES;+ UIStackView *stack = [[[UIStackView alloc] init] autorelease];+ _vzAccessoryStack = [stack retain];+ stack.translatesAutoresizingMaskIntoConstraints = NO;+ stack.axis = UILayoutConstraintAxisHorizontal;+ stack.distribution = UIStackViewDistributionFill;+ stack.spacing = 6;+ NSArray *keys = @[+ @[@"esc", @0x29, @NO],+ @[@"⇧", @0xe1, @YES], @[@"⌃", @0xe0, @YES],+ @[@"⌥", @0xe2, @YES], @[@"⌘", @0xe3, @YES],+ @[@"←", @0x50, @NO], @[@"↓", @0x51, @NO],+ @[@"↑", @0x52, @NO], @[@"→", @0x4f, @NO],+ @[@"home", @0x4a, @NO], @[@"end", @0x4d, @NO],+ @[@"pg up", @0x4b, @NO], @[@"pg dn", @0x4e, @NO],+ @[@"F1", @0x3a, @NO], @[@"F2", @0x3b, @NO],+ @[@"F3", @0x3c, @NO], @[@"F4", @0x3d, @NO],+ @[@"F5", @0x3e, @NO], @[@"F6", @0x3f, @NO],+ @[@"F7", @0x40, @NO], @[@"F8", @0x41, @NO],+ @[@"F9", @0x42, @NO], @[@"F10", @0x43, @NO],+ @[@"F11", @0x44, @NO], @[@"F12", @0x45, @NO],+ ];+ for (NSArray *key in keys) {+ UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];+ [button setTitle:key[0] forState:UIControlStateNormal];+ [button setTitleColor:UIColor.labelColor forState:UIControlStateNormal];+ button.titleLabel.font = [UIFont systemFontOfSize:17+ weight:UIFontWeightSemibold];+ button.tag = [key[1] integerValue];+ button.accessibilityHint = [key[2] boolValue]+ ? @"Double-tap to hold or release this modifier" : nil;+ [button addTarget:self action:@selector(accessoryKeyPressed:)+ forControlEvents:UIControlEventTouchUpInside];+ button.layer.cornerRadius = 7;+ button.layer.borderWidth = 0.5;+ button.layer.borderColor = UIColor.separatorColor.CGColor;+ button.backgroundColor = UIColor.secondarySystemBackgroundColor;+ CGFloat width = [key[0] length] > 3 ? 62 : 48;+ [button.widthAnchor constraintEqualToConstant:width].active = YES;+ [stack addArrangedSubview:button];+ }+ [scroll addSubview:stack];+ [_vzAccessoryView addSubview:scroll];+ [NSLayoutConstraint activateConstraints:@[+ [scroll.leadingAnchor constraintEqualToAnchor:_vzAccessoryView.leadingAnchor],+ [scroll.trailingAnchor constraintEqualToAnchor:_vzAccessoryView.trailingAnchor],+ [scroll.topAnchor constraintEqualToAnchor:_vzAccessoryView.topAnchor],+ [scroll.bottomAnchor constraintEqualToAnchor:_vzAccessoryView.bottomAnchor],+ [stack.leadingAnchor constraintEqualToAnchor:scroll.contentLayoutGuide.leadingAnchor constant:8],+ [stack.trailingAnchor constraintEqualToAnchor:scroll.contentLayoutGuide.trailingAnchor constant:-8],+ [stack.topAnchor constraintEqualToAnchor:scroll.frameLayoutGuide.topAnchor constant:5],+ [stack.bottomAnchor constraintEqualToAnchor:scroll.frameLayoutGuide.bottomAnchor constant:-5],+ ]];+ return _vzAccessoryView;+}++- (void)accessoryKeyPressed:(UIButton *)sender+{+ UIKeyboardHIDUsage usage = (UIKeyboardHIDUsage)sender.tag;+ BOOL modifier = usage >= 0xe0 && usage <= 0xe7;+ if (modifier) {+ NSNumber *key = @(usage);+ BOOL hold = ![_vzHeldSoftwareModifiers containsObject:key];+ if (hold) [_vzHeldSoftwareModifiers addObject:key];+ else [_vzHeldSoftwareModifiers removeObject:key];+ sender.backgroundColor = hold ? UIColor.systemGray3Color+ : UIColor.secondarySystemBackgroundColor;+ [sender setTitleColor:UIColor.labelColor+ forState:UIControlStateNormal];+ sender.accessibilityTraits = hold+ ? (sender.accessibilityTraits | UIAccessibilityTraitSelected)+ : (sender.accessibilityTraits & ~UIAccessibilityTraitSelected);+ sendKey(usage, hold);+ } else {+ sendSoftwareKey(usage, NO);+ }+}++- (void)releaseSoftwareModifiers+{+ for (NSNumber *usage in _vzHeldSoftwareModifiers)+ sendKey((UIKeyboardHIDUsage)usage.unsignedIntegerValue, NO);+ [_vzHeldSoftwareModifiers removeAllObjects];+ for (UIView *view in _vzAccessoryStack.arrangedSubviews) {+ if ([view isKindOfClass:UIButton.class]) {+ UIButton *button = (id)view;+ button.backgroundColor = UIColor.secondarySystemBackgroundColor;+ [button setTitleColor:UIColor.labelColor forState:UIControlStateNormal];+ button.accessibilityTraits &= ~UIAccessibilityTraitSelected;+ }+ }+}++- (BOOL)resignFirstResponder+{+ [self releaseSoftwareModifiers];+ return [super resignFirstResponder];+}++static void sendSoftwareKey(UIKeyboardHIDUsage usage, BOOL shifted)+{+ if (shifted) sendKey((UIKeyboardHIDUsage)0xE1, YES);+ sendKey(usage, YES);+ sendKey(usage, NO);+ if (shifted) sendKey((UIKeyboardHIDUsage)0xE1, NO);+}++static void sendSoftwareChord(UIKeyboardHIDUsage usage, BOOL shifted,+ BOOL option)+{+ if (option) sendKey((UIKeyboardHIDUsage)0xE2, YES);+ if (shifted) sendKey((UIKeyboardHIDUsage)0xE1, YES);+ sendKey(usage, YES);+ sendKey(usage, NO);+ if (shifted) sendKey((UIKeyboardHIDUsage)0xE1, NO);+ if (option) sendKey((UIKeyboardHIDUsage)0xE2, NO);+}++- (void)insertText:(NSString *)text+{+ for (NSUInteger index = 0; index < text.length; index++) {+ unichar character = [text characterAtIndex:index];+ if (character >= 'a' && character <= 'z')+ sendSoftwareKey((UIKeyboardHIDUsage)(0x04 + character - 'a'), NO);+ else if (character >= 'A' && character <= 'Z')+ sendSoftwareKey((UIKeyboardHIDUsage)(0x04 + character - 'A'), YES);+ else if (character >= '1' && character <= '9')+ sendSoftwareKey((UIKeyboardHIDUsage)(0x1e + character - '1'), NO);+ else if (character == '0') sendSoftwareKey((UIKeyboardHIDUsage)0x27, NO);+ else if (character == ' ') sendSoftwareKey((UIKeyboardHIDUsage)0x2c, NO);+ else if (character == '\t') sendSoftwareKey((UIKeyboardHIDUsage)0x2b, NO);+ else if (character == '\n' || character == '\r') sendSoftwareKey((UIKeyboardHIDUsage)0x28, NO);+ else {+ NSString *shiftedNumbers = @"!@#$%^&*()";+ NSString *oneCharacter = [NSString stringWithCharacters:&character length:1];+ NSUInteger numberPosition = [shiftedNumbers rangeOfString:oneCharacter].location;+ if (numberPosition != NSNotFound) {+ UIKeyboardHIDUsage usage = numberPosition == 9+ ? (UIKeyboardHIDUsage)0x27+ : (UIKeyboardHIDUsage)(0x1e + numberPosition);+ sendSoftwareKey(usage, YES);+ continue;+ }+ switch (character) {+ case 0x00a3: // £: Option-3 on the macOS U.S. layout.+ sendSoftwareChord((UIKeyboardHIDUsage)0x20, NO, YES); continue;+ case 0x20ac: // €: Option-Shift-2.+ sendSoftwareChord((UIKeyboardHIDUsage)0x1f, YES, YES); continue;+ case 0x00a5: case 0xffe5: // ¥ / full-width yen: Option-Y.+ sendSoftwareChord((UIKeyboardHIDUsage)0x1c, NO, YES); continue;+ case 0x2026: // …: Option-semicolon.+ sendSoftwareChord((UIKeyboardHIDUsage)0x33, NO, YES); continue;+ case 0x2018: // ‘: Option-right bracket.+ sendSoftwareChord((UIKeyboardHIDUsage)0x30, NO, YES); continue;+ case 0x2019: // ’: Option-Shift-right bracket.+ sendSoftwareChord((UIKeyboardHIDUsage)0x30, YES, YES); continue;+ case 0x201c: // “: Option-left bracket.+ sendSoftwareChord((UIKeyboardHIDUsage)0x2f, NO, YES); continue;+ case 0x201d: // ”: Option-Shift-left bracket.+ sendSoftwareChord((UIKeyboardHIDUsage)0x2f, YES, YES); continue;+ default: break;+ }+ NSString *plain = @"-=[]\\;',./`";+ NSString *shift = @"_+{}|:\"<>?~";+ NSUInteger position = [plain rangeOfString:oneCharacter].location;+ BOOL shifted = NO;+ if (position == NSNotFound) {+ position = [shift rangeOfString:oneCharacter].location;+ shifted = position != NSNotFound;+ }+ static const UIKeyboardHIDUsage usages[] = {0x2d,0x2e,0x2f,0x30,0x31,0x33,0x34,0x36,0x37,0x38,0x35};+ if (position != NSNotFound)+ sendSoftwareKey(usages[position], shifted);+ }+ }+}++- (void)deleteBackward { sendSoftwareKey((UIKeyboardHIDUsage)0x2a, NO); }++- (void)dealloc+{+ [self releaseSoftwareModifiers];+ [_vzAccessoryView release];+ [_vzAccessoryStack release];+ [_vzHeldSoftwareModifiers release];+ [super dealloc];+}++- (void)handleHover:(UIHoverGestureRecognizer *)recognizer+{+ CGPoint location = [recognizer locationInView:self];+ switch (recognizer.state) {+ case UIGestureRecognizerStateBegan:+ gUIKitHoverActive = YES;+ sendIndirectPointerLocation(location, self.bounds);+ break;+ case UIGestureRecognizerStateChanged:+ gUIKitHoverActive = YES;+ sendIndirectPointerLocation(location, self.bounds);+ break;+ case UIGestureRecognizerStateEnded:+ case UIGestureRecognizerStateCancelled:+ case UIGestureRecognizerStateFailed:+ // A UIKit hover session can end while an indirect-pointer touch still+ // owns the physical button. Releasing buttons here truncated every+ // trackpad click-drag. Lifecycle and touch cancellation paths own+ // stuck-button cleanup instead.+ gUIKitHoverActive = NO;+ gHostPointerLocationValid = NO;+ break;+ default:+ break;+ }+}++- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer+{+ NSUInteger phase = 0;+ double delta = 0;+ switch (recognizer.state) {+ case UIGestureRecognizerStateBegan:+ phase = 1;+ gLastPinchScale = recognizer.scale;+ break;+ case UIGestureRecognizerStateChanged:+ phase = 4;+ // Indirect trackpad pinch scale is cumulative and, unlike direct+ // touch pinch, does not honor assigning scale=1 as a delta reset.+ // VZ/NSEvent magnification is incremental, so derive the frame delta.+ delta = recognizer.scale - gLastPinchScale;+ gLastPinchScale = recognizer.scale;+ break;+ case UIGestureRecognizerStateEnded: phase = 8; break;+ case UIGestureRecognizerStateCancelled:+ case UIGestureRecognizerStateFailed: phase = 16; break;+ default: return;+ }+ sendMagnification(delta, phase);+}++- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer+{+ NSUInteger phase = 0;+ double delta = 0;+ switch (recognizer.state) {+ case UIGestureRecognizerStateBegan:+ phase = 1;+ gLastRotation = recognizer.rotation;+ break;+ case UIGestureRecognizerStateChanged:+ phase = 4;+ delta = recognizer.rotation - gLastRotation;+ gLastRotation = recognizer.rotation;+ break;+ case UIGestureRecognizerStateEnded: phase = 8; break;+ case UIGestureRecognizerStateCancelled:+ case UIGestureRecognizerStateFailed: phase = 16; break;+ default: return;+ }+ sendRotation(delta, phase);+}++- (void)handleSmartMagnify:(UITapGestureRecognizer *)recognizer+{+ if (recognizer.state == UIGestureRecognizerStateRecognized)+ sendSmartMagnification();+}++- (void)handleScroll:(VZRawScrollRecognizer *)recognizer+{+ // NSEventPhase and the private VZ event use the same bit values:+ // began=1, changed=4, ended=8, cancelled=16. The recognizer captures the+ // incremental hardware deltas before UIKit builds cumulative translation.+ NSUInteger phase = 0;+ switch (recognizer.state) {+ case UIGestureRecognizerStateBegan:+ phase = 1;+ break;+ case UIGestureRecognizerStateChanged:+ phase = 4;+ break;+ case UIGestureRecognizerStateEnded:+ phase = 8;+ break;+ case UIGestureRecognizerStateCancelled:+ case UIGestureRecognizerStateFailed:+ phase = 16;+ break;+ default:+ return;+ }+ sendScrollWheel(recognizer.vzRawDelta,+ recognizer.vzAcceleratedDelta,+ recognizer.vzDirectionInverted,+ 0,+ phase);+}++- (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction+ regionForRequest:(UIPointerRegionRequest *)request+ defaultRegion:(UIPointerRegion *)defaultRegion+{+ (void)interaction;+ (void)request;+ (void)defaultRegion;+ // Do not mutate guest input from this delegate. UIKit calls it during+ // region invalidation and system-UI transitions, not only real motion.+ return [UIPointerRegion regionWithRect:self.bounds identifier:@"VirtualMacDisplay"];+}++- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction+ styleForRegion:(UIPointerRegion *)region+{+ (void)interaction;+ (void)region;+ return [UIPointerStyle hiddenPointerStyle];+}++- (void)touchesBegan:(NSSet<UITouch *> *)touches+ withEvent:(UIEvent *)event+{+ UITouch *touch = [touches anyObject];+ if (touch) {+ // Hardware trackpad clicks reach a UIKit view as indirect-pointer+ // touches even when GameController exposes no GCMouse. Preserve+ // UIKit's native primary/secondary/middle button bits instead of+ // turning every such click into a primary click. A direct finger+ // touch has no button mask and remains a primary click.+ NSUInteger eventButtons = (NSUInteger)event.buttonMask & 0x7U;+ gTouchButtons = eventButtons ?: 1U;+ // UIKit suspends hover updates while a trackpad button is held, but+ // the indirect UITouch continues to report every live drag position.+ // Treat it as authoritative or the guest only sees the final point.+ CGPoint point = [touch locationInView:self];+ sendPointer(point, self.bounds,+ activePointerButtons());+ printf("[VirtualMac] touch began type=%ld buttons=0x%lx\n",+ (long)touch.type, (unsigned long)gTouchButtons);+ }+}++- (void)touchesMoved:(NSSet<UITouch *> *)touches+ withEvent:(UIEvent *)event+{+ UITouch *touch = [touches anyObject];+ if (touch) {+ NSUInteger eventButtons = (NSUInteger)event.buttonMask & 0x7U;+ if (eventButtons)+ gTouchButtons = eventButtons;+ CGPoint point = [touch locationInView:self];+ sendPointer(point, self.bounds,+ activePointerButtons());+ }+}++- (void)touchesEnded:(NSSet<UITouch *> *)touches+ withEvent:(UIEvent *)event+{+ UITouch *touch = [touches anyObject];+ if (touch) {+ (void)event;+ gTouchButtons = 0;+ CGPoint point = [touch locationInView:self];+ sendPointer(point, self.bounds,+ activePointerButtons());+ }+}++- (void)touchesCancelled:(NSSet<UITouch *> *)touches+ withEvent:(UIEvent *)event+{+ [self touchesEnded:touches withEvent:event];+}++- (void)pressesBegan:(NSSet<UIPress *> *)presses+ withEvent:(UIPressesEvent *)event+{+ if (!sendPresses(presses, YES))+ [super pressesBegan:presses withEvent:event];+}++- (void)pressesEnded:(NSSet<UIPress *> *)presses+ withEvent:(UIPressesEvent *)event+{+ if (!sendPresses(presses, NO))+ [super pressesEnded:presses withEvent:event];+}++- (void)pressesCancelled:(NSSet<UIPress *> *)presses+ withEvent:(UIPressesEvent *)event+{+ sendPresses(presses, NO);+}++@end++@interface VZHUDView : UIVisualEffectView+- (instancetype)initWithTarget:(id)target;+@end++@implementation VZHUDView+- (instancetype)initWithTarget:(id)target+{+ if ((self = [super initWithEffect:[UIBlurEffect effectWithStyle:+ UIBlurEffectStyleSystemUltraThinMaterialDark]])) {+ self.layer.cornerRadius = 18;+ self.clipsToBounds = YES;+ self.translatesAutoresizingMaskIntoConstraints = NO;+ UIStackView *stack = [[[UIStackView alloc] init] autorelease];+ stack.translatesAutoresizingMaskIntoConstraints = NO;+ stack.axis = UILayoutConstraintAxisHorizontal;+ stack.spacing = 2;+ for (NSDictionary *item in @[+ @{@"icon": @"keyboard", @"selector": @"hudKeyboard:"},+ @{@"icon": @"ellipsis", @"menu": @YES},+ ]) {+ UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];+ [button setImage:[UIImage systemImageNamed:item[@"icon"]]+ forState:UIControlStateNormal];+ button.tintColor = UIColor.whiteColor;+ if ([item[@"menu"] boolValue]) {+ button.menu = ((id(*)(id, SEL))objc_msgSend)(+ target, NSSelectorFromString(@"hudMenu"));+ button.showsMenuAsPrimaryAction = YES;+ button.accessibilityLabel = @"Virtual Mac Controls";+ } else {+ [button addTarget:target action:NSSelectorFromString(item[@"selector"])+ forControlEvents:UIControlEventTouchUpInside];+ }+ [button.widthAnchor constraintEqualToConstant:46].active = YES;+ [button.heightAnchor constraintEqualToConstant:46].active = YES;+ [stack addArrangedSubview:button];+ }+ [self.contentView addSubview:stack];+ [NSLayoutConstraint activateConstraints:@[+ [stack.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:4],+ [stack.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-4],+ [stack.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:4],+ [stack.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-4],+ ]];+ }+ return self;+}+@end++@interface VZViewController : UIViewController+ <VZVMLibraryViewControllerDelegate>+@property(nonatomic, retain) UINavigationController *libraryNavigationController;+@property(nonatomic, retain) VZProgressViewController *installationController;+@property(nonatomic, retain) NSTimer *installationTimer;+@property(nonatomic, copy) NSString *installationLogPath;+@property(nonatomic, copy) NSString *installationBundlePath;+@property(nonatomic, copy) NSString *installationStagingPath;+@property(nonatomic, copy) NSString *installationAttemptPath;+@property(nonatomic, copy) NSString *installationRestoreImagePath;+@property(nonatomic, retain) NSDictionary *installationOptions;+@property(nonatomic, assign) pid_t installationProcess;+@property(nonatomic, copy) NSString *activeVMBundlePath;+@property(nonatomic, assign, getter=isVMDisplayActive) BOOL vmDisplayActive;+@property(nonatomic, assign) BOOL didCheckInstallationAttempts;+- (void)presentVMLibrary;+- (void)finishVMAndShowLibraryWithError:(NSError *)error;+- (void)activateVMDisplay:(BOOL)active;+- (void)updateHUDVisibility;+- (void)updateHUDPosition;+- (UIMenu *)hudMenu;+- (void)confirmForceShutdown;+@end++@implementation VZViewController++- (void)viewDidLoad+{+ [super viewDidLoad];+ [NSNotificationCenter.defaultCenter addObserver:self+ selector:@selector(appSettingsChanged:)+ name:VZSettingsDidChangeNotification object:nil];+ [NSNotificationCenter.defaultCenter addObserver:self+ selector:@selector(peripheralChanged:)+ name:GCKeyboardDidConnectNotification object:nil];+ [NSNotificationCenter.defaultCenter addObserver:self+ selector:@selector(peripheralChanged:)+ name:GCKeyboardDidDisconnectNotification object:nil];+ [NSNotificationCenter.defaultCenter addObserver:self+ selector:@selector(peripheralChanged:)+ name:GCMouseDidConnectNotification object:nil];+ [NSNotificationCenter.defaultCenter addObserver:self+ selector:@selector(peripheralChanged:)+ name:GCMouseDidDisconnectNotification object:nil];+}++- (void)peripheralChanged:(NSNotification *)notification+{+ (void)notification;+ if (GCKeyboard.coalescedKeyboard && self.isVMDisplayActive &&+ !gInputView.hidden) {+ [gInputView becomeFirstResponder];+ [gInputView reloadInputViews];+ } else if (!gSoftwareKeyboardRequested) {+ [gInputView resignFirstResponder];+ }+ [self updateHUDVisibility];+}++- (void)appSettingsChanged:(NSNotification *)notification+{+ (void)notification;+ if (gStatusLabel)+ gStatusLabel.hidden = !shouldShowStatusLabel();+ [self updateImmersivePresentation];+ [self updateHUDPosition];+ [self updateHUDVisibility];+ updateDisplayGeometry();+}++- (void)updateHUDPosition+{+ if (!gHUDView)+ return;+ if (gHUDHorizontalConstraint)+ [gHUDHorizontalConstraint setActive:NO];+ if (gHUDVerticalConstraint)+ [gHUDVerticalConstraint setActive:NO];+ NSString *corner = [VZAppSettings.sharedSettings stringForKey:VZHUDCornerKey]+ ?: @"top-right";+ BOOL left = [corner hasSuffix:@"left"];+ BOOL bottom = [corner hasPrefix:@"bottom"];+ UILayoutGuide *guide = self.view.safeAreaLayoutGuide;+ gHUDHorizontalConstraint = left+ ? [gHUDView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor constant:16]+ : [gHUDView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor constant:-16];+ gHUDVerticalConstraint = bottom+ ? [gHUDView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor constant:-16]+ : [gHUDView.topAnchor constraintEqualToAnchor:guide.topAnchor constant:16];+ [NSLayoutConstraint activateConstraints:@[+ gHUDHorizontalConstraint, gHUDVerticalConstraint]];+}++- (void)updateHUDVisibility+{+ NSString *choice = [VZAppSettings.sharedSettings stringForKey:VZHUDVisibilityKey]+ ?: @"automatic";+ BOOL hidden = !self.isVMDisplayActive || (!gHUDForcedVisibleForBoot &&+ (gHUDHiddenForBoot || [choice isEqualToString:@"hidden"]));+ if (!gHUDForcedVisibleForBoot && [choice isEqualToString:@"automatic"])+ hidden = hidden || (GCKeyboard.coalescedKeyboard != nil && GCMouse.current != nil);+ gHUDView.hidden = hidden;+}++- (void)hudKeyboard:(UIButton *)sender+{+ (void)sender;+ if (gSoftwareKeyboardRequested && gInputView.isFirstResponder) {+ gSoftwareKeyboardRequested = NO;+ [gInputView resignFirstResponder];+ } else {+ gSoftwareKeyboardRequested = YES;+ [gInputView becomeFirstResponder];+ [gInputView reloadInputViews];+ }+}++- (UIMenu *)hudMenu+{+ UIAction *library = [UIAction actionWithTitle:@"Show Library"+ image:[UIImage systemImageNamed:@"square.grid.2x2"] identifier:nil+ handler:^(UIAction *action) { (void)action; [self presentVMLibrary]; }];+ UIAction *shutdown = [UIAction actionWithTitle:@"Force Shut Down"+ image:[UIImage systemImageNamed:@"power"] identifier:nil+ handler:^(UIAction *action) { (void)action; [self confirmForceShutdown]; }];+ shutdown.attributes = UIMenuElementAttributesDestructive;+ UIAction *hide = [UIAction actionWithTitle:@"Hide for This Boot"+ image:[UIImage systemImageNamed:@"eye.slash"] identifier:nil+ handler:^(UIAction *action) { (void)action;+ gHUDHiddenForBoot = YES;+ [self updateHUDVisibility];+ }];+ NSMutableArray *placements = [NSMutableArray array];+ NSString *current = [VZAppSettings.sharedSettings stringForKey:VZHUDCornerKey]+ ?: @"top-right";+ for (NSArray *placement in @[+ @[@"Top Left", @"top-left"], @[@"Top Right", @"top-right"],+ @[@"Bottom Left", @"bottom-left"], @[@"Bottom Right", @"bottom-right"],+ ]) {+ UIAction *move = [UIAction actionWithTitle:placement[0] image:nil+ identifier:nil handler:^(UIAction *action) {+ (void)action;+ [VZAppSettings.sharedSettings setString:placement[1]+ forKey:VZHUDCornerKey];+ [self updateHUDPosition];+ }];+ move.state = [current isEqualToString:placement[1]]+ ? UIMenuElementStateOn : UIMenuElementStateOff;+ [placements addObject:move];+ }+ UIMenu *moveMenu = [UIMenu menuWithTitle:@"Move Controls" children:placements];+ return [UIMenu menuWithTitle:@""+ children:@[library, shutdown, hide, moveMenu]];+}++- (void)confirmForceShutdown+{+ if (!gVirtualMachine)+ return;+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Force Shut Down Virtual Mac?"+ message:@"Unsaved changes in macOS may be lost."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Force Shut Down"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action;+ forceStopVirtualMachine();+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++static NSURL *persistentRestoreImageURL(NSURL *sourceURL, NSError **error)+{+ NSString *directory = VZRestoreImagesPath();+ if (![NSFileManager.defaultManager+ createDirectoryAtPath:directory+ withIntermediateDirectories:YES attributes:nil error:error])+ return nil;+ NSString *sourcePath = sourceURL.path.stringByStandardizingPath;+ NSString *directoryPrefix = [directory.stringByStandardizingPath+ stringByAppendingString:@"/"];+ if ([sourcePath hasPrefix:directoryPrefix])+ return sourceURL;++ NSString *filename = sourceURL.lastPathComponent.length+ ? sourceURL.lastPathComponent : @"Restore.ipsw";+ NSString *destinationPath = [directory+ stringByAppendingPathComponent:filename];+ NSURL *destinationURL = [NSURL fileURLWithPath:destinationPath];+ if ([NSFileManager.defaultManager fileExistsAtPath:destinationPath]) {+ NSDictionary *sourceAttributes = [NSFileManager.defaultManager+ attributesOfItemAtPath:sourcePath error:nil];+ NSDictionary *destinationAttributes = [NSFileManager.defaultManager+ attributesOfItemAtPath:destinationPath error:nil];+ // Reuse only the exact existing hard link. A different IPSW can have+ // the same filename (and even size), so size is not a safe identity.+ if ([sourceAttributes[NSFileSystemFileNumber] isEqual:+ destinationAttributes[NSFileSystemFileNumber]])+ return destinationURL;+ NSString *stem = filename.stringByDeletingPathExtension;+ NSString *extension = filename.pathExtension;+ filename = [NSString stringWithFormat:@"%@-%@%@%@", stem,+ NSUUID.UUID.UUIDString,+ extension.length ? @"." : @"", extension];+ destinationPath = [directory stringByAppendingPathComponent:filename];+ destinationURL = [NSURL fileURLWithPath:destinationPath];+ }+ // Downloads and the VM library are on the same APFS volume. A hard link+ // makes the security-scoped File Provider item permanently reachable by+ // the root installer without copying a multi-gigabyte IPSW.+ if (![NSFileManager.defaultManager linkItemAtURL:sourceURL+ toURL:destinationURL+ error:error])+ return nil;+ return destinationURL;+}++static NSString *VZInstallationLogTail(NSString *path, NSUInteger limit,+ BOOL omitProgress)+{+ NSString *contents = [NSString stringWithContentsOfFile:path+ encoding:NSUTF8StringEncoding error:nil];+ if (!contents.length)+ return @"";+ if (omitProgress) {+ NSMutableArray *filtered = [NSMutableArray array];+ for (NSString *line in [contents componentsSeparatedByString:@"\n"]) {+ if (![line hasPrefix:@"INSTALL_PROGRESS\t"])+ [filtered addObject:line];+ }+ contents = [filtered componentsJoinedByString:@"\n"];+ }+ if (contents.length > limit)+ contents = [@"… earlier output omitted …\n"+ stringByAppendingString:+ [contents substringFromIndex:contents.length - limit]];+ return contents;+}++static NSString *VZInstallationConsoleText(NSString *installLogPath)+{+ NSArray *sources = @[+ @[@"INSTALLER", installLogPath ?: @"", @YES],+ @[@"INSTALLER LAUNCHER", @"/tmp/installation.stderr.log", @NO],+ @[@"INSTALLATION HOOK", @"/tmp/installationhook.log", @NO],+ @[@"VIRTUALIZATION FRAMEWORK", @"/tmp/vzxpchook.log", @NO],+ @[@"MOBILEDEVICE / RESTORE USB", @"/tmp/installation-usb.log", @NO],+ @[@"USBMUXD", @"/tmp/vz-usbmuxd.log", @NO],+ @[@"USBMUXD LAUNCHER", @"/tmp/vz-usbmuxd-launch.log", @NO],+ @[@"RESTORE VMM STDERR", @"/tmp/restore-vmm.stderr.log", @NO],+ @[@"RESTORE VMM", @"/tmp/vmmhook.log", @NO],+ ];+ NSMutableString *console = [NSMutableString string];+ for (NSArray *source in sources) {+ NSString *tail = VZInstallationLogTail(+ source[1], 16 * 1024, [source[2] boolValue]);+ if (!tail.length)+ continue;+ if (console.length)+ [console appendString:@"\n\n"];+ [console appendFormat:@"── %@ ──\n%@", source[0], tail];+ }+ return console.length ? console : @"Waiting for restore output…";+}++static void VZWriteInstallationAttempt(NSString *attemptPath, NSString *state,+ NSDictionary *details)+{+ if (!attemptPath.length) return;+ NSMutableDictionary *record = [NSMutableDictionary dictionaryWithDictionary:+ [NSDictionary dictionaryWithContentsOfFile:[attemptPath stringByAppendingPathComponent:@"Attempt.plist"]] ?: @{}];+ [record addEntriesFromDictionary:details ?: @{}];+ record[@"State"] = state;+ record[@"UpdatedAt"] = NSDate.date;+ [record writeToFile:[attemptPath stringByAppendingPathComponent:@"Attempt.plist"] atomically:YES];+}+- (BOOL)prefersStatusBarHidden+{+ return self.isVMDisplayActive;+}++- (BOOL)prefersHomeIndicatorAutoHidden+{+ return self.isVMDisplayActive && [VZAppSettings.sharedSettings+ boolForKey:VZHomeIndicatorSuppressionKey];+}++- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures+{+ return self.isVMDisplayActive && [VZAppSettings.sharedSettings+ boolForKey:VZSystemGestureSuppressionKey] ? UIRectEdgeAll : UIRectEdgeNone;+}++- (void)updateImmersivePresentation+{+ BOOL active = self.isVMDisplayActive;+ printf("[VirtualMac] presentation activeVM=%d statusBarHidden=%d "+ "homeIndicatorHidden=%d deferredEdges=0x%lx\n",+ active, active, active,+ (unsigned long)(active ? UIRectEdgeAll : UIRectEdgeNone));+ [self setNeedsStatusBarAppearanceUpdate];+ [self setNeedsUpdateOfHomeIndicatorAutoHidden];+ [self setNeedsUpdateOfScreenEdgesDeferringSystemGestures];+}++- (void)activateVMDisplay:(BOOL)active+{+ self.vmDisplayActive = active;+ self.view.backgroundColor = active ? UIColor.blackColor+ : UIColor.systemBackgroundColor;+ if (active) {+ FILE *marker = fopen("/tmp/virtual-mac-vm-active", "w");+ if (marker) {+ fputs("active\n", marker);+ fclose(marker);+ }+ resetPointerSession(YES);+ } else {+ unlink("/tmp/virtual-mac-vm-active");+ }+ [self updateImmersivePresentation];+ [self updateHUDVisibility];+}++- (void)presentVMLibrary+{+ printf("[VirtualMac] presenting VM library\n");+ BOOL crossfade = self.isVMDisplayActive;+ gHUDHiddenForBoot = NO;+ gHUDForcedVisibleForBoot = NO;+ if (!self.libraryNavigationController) {+ VZVMLibraryViewController *library =+ [[[VZVMLibraryViewController alloc] init] autorelease];+ library.delegate = self;+ self.libraryNavigationController = [[[UINavigationController alloc]+ initWithRootViewController:library] autorelease];+ [self addChildViewController:self.libraryNavigationController];+ self.libraryNavigationController.view.frame = self.view.bounds;+ self.libraryNavigationController.view.autoresizingMask =+ UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ self.libraryNavigationController.view.hidden = crossfade;+ [self.view addSubview:self.libraryNavigationController.view];+ [self.libraryNavigationController didMoveToParentViewController:self];+ } else {+ VZVMLibraryViewController *library =+ (id)self.libraryNavigationController.viewControllers.firstObject;+ [library reloadLibrary];+ }+ void (^showLibrary)(void) = ^{+ self.libraryNavigationController.view.hidden = NO;+ [self.view bringSubviewToFront:self.libraryNavigationController.view];+ gInputView.hidden = YES;+ gSoftwareKeyboardRequested = NO;+ [gInputView resignFirstResponder];+ gCursorView.hidden = YES;+ [self activateVMDisplay:NO];+ };+ if (crossfade) {+ [UIView transitionWithView:self.view duration:0.24+ options:UIViewAnimationOptionTransitionCrossDissolve |+ UIViewAnimationOptionAllowAnimatedContent+ animations:showLibrary completion:nil];+ } else {+ showLibrary();+ }+ if (!self.didCheckInstallationAttempts) {+ self.didCheckInstallationAttempts = YES;+ NSMutableArray *interrupted = [NSMutableArray array];+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:+ VZInstallationsPath() error:nil]) {+ if (![name hasSuffix:@".installation"]) continue;+ NSString *path = [VZInstallationsPath() stringByAppendingPathComponent:name];+ NSDictionary *attempt = [NSDictionary dictionaryWithContentsOfFile:+ [path stringByAppendingPathComponent:@"Attempt.plist"]];+ NSString *state = attempt[@"State"];+ if ([state isEqualToString:@"installing"] || [state isEqualToString:@"failed"])+ [interrupted addObject:@{ @"path": path, @"record": attempt ?: @{} }];+ }+ if (interrupted.count) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,+ 400 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:+ interrupted.count == 1 ? @"Incomplete Installation" : @"Incomplete Installations"+ message:@"A previous macOS installation did not finish. You can review its details, keep it for debugging, or delete it."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Keep" style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"View Details" style:UIAlertActionStyleDefault+ handler:^(UIAlertAction *action) {+ (void)action;+ NSMutableString *details = [NSMutableString string];+ for (NSDictionary *item in interrupted) {+ NSDictionary *record = item[@"record"];+ [details appendFormat:@"%@\nState: %@\n%@\n\n",+ record[@"Name"] ?: [item[@"path"] lastPathComponent],+ record[@"State"] ?: @"Unknown", item[@"path"]];+ }+ UIAlertController *info = [UIAlertController alertControllerWithTitle:@"Installation Details"+ message:details preferredStyle:UIAlertControllerStyleAlert];+ [info addAction:[UIAlertAction actionWithTitle:@"Keep Files" style:UIAlertActionStyleCancel handler:nil]];+ [info addAction:[UIAlertAction actionWithTitle:@"Delete All"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *innerAction) {+ (void)innerAction;+ NSMutableArray *paths = [NSMutableArray array];+ for (NSDictionary *item in interrupted) [paths addObject:item[@"path"]];+ VZRemovePaths(paths);+ }]];+ [self presentViewController:info animated:YES completion:nil];+ }]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Delete All" style:UIAlertActionStyleDestructive+ handler:^(UIAlertAction *action) {+ (void)action;+ NSMutableArray *paths = [NSMutableArray array];+ for (NSDictionary *item in interrupted) [paths addObject:item[@"path"]];+ VZRemovePaths(paths);+ }]];+ [self presentViewController:alert animated:YES completion:nil];+ });+ }+}++- (void)vmLibrary:(VZVMLibraryViewController *)library+ bootBundleAtPath:(NSString *)path options:(NSDictionary *)options+{+ (void)library;+ printf("[VirtualMac] selected VM path=%s options=%s\n", path.UTF8String,+ options.description.UTF8String);+ gHUDHiddenForBoot = NO;+ gHUDForcedVisibleForBoot = NO;+ self.activeVMBundlePath = path;+ if (self.libraryNavigationController.view.window &&+ !self.libraryNavigationController.view.hidden) {+ [UIView transitionWithView:self.view duration:0.32+ options:UIViewAnimationOptionTransitionCrossDissolve |+ UIViewAnimationOptionAllowAnimatedContent+ animations:^{+ self.libraryNavigationController.view.hidden = YES;+ gInputView.hidden = NO;+ } completion:nil];+ } else {+ self.libraryNavigationController.view.hidden = YES;+ gInputView.hidden = NO;+ }+ [self activateVMDisplay:YES];+ startVirtualMachine(self.view, self, path, options);+}++- (NSString *)activeVMBundlePathForLibrary:+ (VZVMLibraryViewController *)library+{+ (void)library;+ return gVirtualMachine ? self.activeVMBundlePath : nil;+}++- (void)vmLibraryResumeActiveVM:(VZVMLibraryViewController *)library+{+ (void)library;+ if (!gVirtualMachine)+ return;+ [UIView transitionWithView:self.view duration:0.24+ options:UIViewAnimationOptionTransitionCrossDissolve+ animations:^{+ self.libraryNavigationController.view.hidden = YES;+ gInputView.hidden = NO;+ if (gCursorView.image) gCursorView.hidden = NO;+ } completion:nil];+ [self activateVMDisplay:YES];+ if (GCKeyboard.coalescedKeyboard)+ [gInputView becomeFirstResponder];+}++- (void)vmLibraryForceShutdownActiveVM:+ (VZVMLibraryViewController *)library+{+ (void)library;+ forceStopVirtualMachine();+}++- (void)vmLibrary:(VZVMLibraryViewController *)library+ installRestoreImageAtURL:(NSURL *)url name:(NSString *)name+ options:(NSDictionary *)options+{+ (void)library;+ if (self.installationController || self.installationTimer) {+ printf("[VirtualMac] ignored duplicate installation request\n");+ return;+ }+ NSError *imageError = nil;+ NSURL *persistentURL = persistentRestoreImageURL(url, &imageError);+ [url stopAccessingSecurityScopedResource];+ if (!persistentURL) {+ UIAlertController *failure = [UIAlertController+ alertControllerWithTitle:@"Could Not Prepare Restore Image"+ message:imageError.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [failure addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:failure animated:YES completion:nil];+ return;+ }+ url = persistentURL;+ NSString *bundlePath = [VZVMLibraryPath() stringByAppendingPathComponent:+ [name stringByAppendingPathExtension:@"bundle"]];+ NSString *attempt = [NSString stringWithFormat:@"%@-%@", name,+ NSUUID.UUID.UUIDString];+ NSString *attemptPath = [VZInstallationsPath() stringByAppendingPathComponent:+ [attempt stringByAppendingPathExtension:@"installation"]];+ NSString *stagingPath = [attemptPath stringByAppendingPathComponent:@"Staging.bundle.installing"];+ // Keep the launcher's allowlisted suffix while retaining all files inside+ // the durable attempt directory.+ NSString *logPath = [attemptPath stringByAppendingPathComponent:@"Installer.install.log"];+ [NSFileManager.defaultManager createDirectoryAtPath:attemptPath+ withIntermediateDirectories:YES attributes:nil error:nil];+ if ([NSFileManager.defaultManager fileExistsAtPath:bundlePath]) {+ UIAlertController *exists = [UIAlertController+ alertControllerWithTitle:@"Name Already Used"+ message:@"Delete or rename the existing virtual Mac first."+ preferredStyle:UIAlertControllerStyleAlert];+ [exists addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:exists animated:YES completion:nil];+ return;+ }+ NSString *cpu = [options[@"CPUCount"] stringValue];+ uint64_t runtimeMemory = [options[@"MemorySize"] unsignedLongLongValue];+ uint64_t restoreMemory = VZRestoreImageUsesMontereyProfile(url.path)+ ? MIN(runtimeMemory, 4ULL << 30) : runtimeMemory;+ NSString *memory = [@(restoreMemory) stringValue];+ NSString *storage = [options[@"StorageSize"] stringValue];+ const char *launcher =+ "/var/root/VirtualMac/install/install-launcher";+ char *arguments[] = {+ (char *)launcher,+ (char *)url.path.fileSystemRepresentation,+ (char *)stagingPath.fileSystemRepresentation,+ (char *)bundlePath.fileSystemRepresentation,+ (char *)logPath.fileSystemRepresentation,+ (char *)cpu.UTF8String,+ (char *)memory.UTF8String,+ (char *)storage.UTF8String,+ NULL,+ };+ [@"" writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];+ VZWriteInstallationAttempt(attemptPath, @"installing", @{+ @"Name": name, @"RestoreImage": url.path, @"Destination": bundlePath,+ @"StartedAt": NSDate.date,+ });+ pid_t process = 0;+ posix_spawnattr_t attributes;+ posix_spawnattr_init(&attributes);+ posix_spawnattr_setflags(&attributes, POSIX_SPAWN_SETPGROUP);+ posix_spawnattr_setpgroup(&attributes, 0);+ int result = posix_spawn(&process, launcher, NULL, &attributes,+ arguments, environ);+ posix_spawnattr_destroy(&attributes);+ if (result != 0) {+ VZWriteInstallationAttempt(attemptPath, @"failed", @{+ @"Failure": [NSString stringWithFormat:@"Could not start installer: %s", strerror(result)]+ });+ UIAlertController *failure = [UIAlertController+ alertControllerWithTitle:@"Could Not Start Installer"+ message:[NSString stringWithFormat:+ @"install-launcher failed: %s", strerror(result)]+ preferredStyle:UIAlertControllerStyleAlert];+ [failure addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:failure animated:YES completion:nil];+ return;+ }+ printf("[VirtualMac] installation launcher pid=%d ipsw=%s bundle=%s\n",+ process, url.path.UTF8String, bundlePath.UTF8String);+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{+ int status = 0;+ pid_t changed;+ do {+ changed = waitpid(process, &status, 0);+ } while (changed < 0 && errno == EINTR);+ int exitCode = changed == process && WIFEXITED(status)+ ? WEXITSTATUS(status) : -1;+ int signalCode = changed == process && WIFSIGNALED(status)+ ? WTERMSIG(status) : 0;+ printf("[VirtualMac] installation launcher exited pid=%d status=%d "+ "signal=%d wait=%d\n", process,+ exitCode, signalCode, changed);+ if (exitCode != 0 || signalCode != 0 || changed != process) {+ NSString *existing = [NSString stringWithContentsOfFile:logPath+ encoding:NSUTF8StringEncoding error:nil] ?: @"";+ NSString *failure = [NSString stringWithFormat:+ @"INSTALL_FAILED\tlauncher exited status=%d signal=%d wait=%d\n",+ exitCode, signalCode, changed];+ if (![existing containsString:@"INSTALL_FAILED"]) {+ FILE *file = fopen(logPath.fileSystemRepresentation, "a");+ if (file) { fputs(failure.UTF8String, file); fclose(file); }+ }+ VZWriteInstallationAttempt(attemptPath, @"failed", @{@"Failure": failure});+ }+ });+ if (restoreMemory != runtimeMemory)+ printf("[VirtualMac] Monterey restore memory=%lluMiB runtime-memory=%lluMiB\n",+ restoreMemory >> 20, runtimeMemory >> 20);+ UIApplication.sharedApplication.idleTimerDisabled = YES;+ self.installationAttemptPath = attemptPath;+ self.installationRestoreImagePath = url.path;+ self.installationProcess = process;+ self.installationLogPath = logPath;+ self.installationBundlePath = bundlePath;+ self.installationStagingPath = stagingPath;+ self.installationOptions = options;+ self.installationController = [[[VZProgressViewController alloc]+ initWithTitle:@"Installing macOS"] autorelease];+ self.installationController.statusText = @"Preparing restore…";+ self.installationController.detailText =+ @"Progress may pause for several minutes while the virtual Mac starts the Restore Environment. The iPad will remain awake.";+ self.installationController.consoleText = @"Waiting for restore output…";+ self.installationController.indeterminate = YES;+ self.installationController.cancellationHandler = ^{+ UIAlertController *confirmation = [UIAlertController+ alertControllerWithTitle:@"Cancel Installation?"+ message:@"The incomplete virtual Mac and its installation files will be deleted."+ preferredStyle:UIAlertControllerStyleAlert];+ [confirmation addAction:[UIAlertAction actionWithTitle:@"Keep Installing"+ style:UIAlertActionStyleCancel handler:nil]];+ [confirmation addAction:[UIAlertAction actionWithTitle:@"Cancel Installation"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action;+ [self.installationTimer invalidate];+ self.installationTimer = nil;+ NSString *pid = [NSString stringWithFormat:@"%d", self.installationProcess];+ const char *cancelLauncher = "/var/root/VirtualMac/install/install-launcher";+ char *cancelArguments[] = {(char *)cancelLauncher, "--cancel-install",+ (char *)pid.UTF8String,+ (char *)self.installationAttemptPath.fileSystemRepresentation, NULL};+ pid_t cancellation = 0;+ posix_spawn(&cancellation, cancelLauncher, NULL, NULL,+ cancelArguments, environ);+ UIApplication.sharedApplication.idleTimerDisabled = NO;+ self.installationController.cancellationHandler = nil;+ [self.installationController.navigationController+ dismissViewControllerAnimated:YES completion:^{+ self.installationController = nil;+ self.installationProcess = 0;+ [self presentVMLibrary];+ }];+ }]];+ [self.installationController presentViewController:confirmation+ animated:YES completion:nil];+ };+ UINavigationController *installationNavigation = [[[UINavigationController alloc]+ initWithRootViewController:self.installationController] autorelease];+ installationNavigation.modalPresentationStyle = UIModalPresentationPageSheet;+ installationNavigation.modalInPresentation = YES;+ installationNavigation.preferredContentSize = CGSizeMake(640, 620);+ [self presentViewController:installationNavigation animated:YES completion:nil];+ self.installationTimer = [NSTimer scheduledTimerWithTimeInterval:1.0+ repeats:YES block:^(NSTimer *timer) {+ NSString *log = [NSString stringWithContentsOfFile:self.installationLogPath+ encoding:NSUTF8StringEncoding error:nil] ?: @"";+ self.installationController.consoleText = VZInstallationConsoleText(+ self.installationLogPath);+ if ([log containsString:@"INSTALL_SUCCEEDED"]) {+ [timer invalidate];+ UIApplication.sharedApplication.idleTimerDisabled = NO;+ self.installationController.indeterminate = NO;+ self.installationController.progress = 1.0;+ NSError *writeError = nil;+ VZWriteVMOptions(self.installationOptions,+ self.installationBundlePath, &writeError);+ VZWriteInstallationAttempt(self.installationAttemptPath, @"complete",+ @{@"CompletedAt": NSDate.date});+ if ([VZAppSettings.sharedSettings boolForKey:VZAutoDeleteRestoreImageKey])+ VZRemovePaths(@[self.installationRestoreImagePath]);+ NSString *installedPath = [[self.installationBundlePath copy] autorelease];+ NSDictionary *installedOptions = [[self.installationOptions copy] autorelease];+ self.installationController.cancellationHandler = nil;+ [self.installationController.navigationController dismissViewControllerAnimated:YES completion:^{+ self.installationController = nil;+ self.installationTimer = nil;+ self.installationProcess = 0;+ [self presentVMLibrary];+ if (writeError)+ setStatus([NSString stringWithFormat:+ @"Installed, but settings save failed: %@", writeError]);+ UIAlertController *success = [UIAlertController+ alertControllerWithTitle:@"macOS Installed"+ message:@"The new virtual Mac is ready to use."+ preferredStyle:UIAlertControllerStyleAlert];+ [success addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleCancel handler:nil]];+ [success addAction:[UIAlertAction actionWithTitle:@"Start"+ style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ (void)action;+ VZVMLibraryViewController *library = (id)+ self.libraryNavigationController.viewControllers.firstObject;+ [self vmLibrary:library bootBundleAtPath:installedPath+ options:installedOptions];+ }]];+ [self presentViewController:success animated:YES completion:nil];+ }];+ return;+ }+ NSRange failure = [log rangeOfString:@"INSTALL_FAILED"+ options:NSBackwardsSearch];+ if (failure.location != NSNotFound) {+ [timer invalidate];+ UIApplication.sharedApplication.idleTimerDisabled = NO;+ NSString *tail = [log substringFromIndex:failure.location];+ VZWriteInstallationAttempt(self.installationAttemptPath, @"failed",+ @{@"Failure": tail});+ NSString *archivePath = nil;+ if ([NSFileManager.defaultManager+ fileExistsAtPath:self.installationStagingPath]) {+ NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]+ autorelease];+ formatter.dateFormat = @"yyyyMMdd-HHmmss";+ archivePath = [[self.installationStagingPath+ stringByDeletingPathExtension]+ stringByAppendingFormat:@".failed-%@",+ [formatter stringFromDate:NSDate.date]];+ NSError *archiveError = nil;+ if (![NSFileManager.defaultManager+ moveItemAtPath:self.installationStagingPath+ toPath:archivePath error:&archiveError]) {+ printf("[VirtualMac] failed to archive installer staging path: %s\n",+ archiveError.description.UTF8String);+ archivePath = nil;+ }+ }+ NSString *message = archivePath+ ? [NSString stringWithFormat:+ @"%@\n\nThe incomplete bundle was retained in Installation Artifacts as %@. It can be deleted from Settings.",+ tail, archivePath.lastPathComponent]+ : tail;+ NSString *failedAttempt = [[self.installationAttemptPath copy] autorelease];+ self.installationController.cancellationHandler = nil;+ [self.installationController.navigationController dismissViewControllerAnimated:YES completion:^{+ self.installationController = nil;+ self.installationTimer = nil;+ self.installationProcess = 0;+ UIAlertController *failureAlert = [UIAlertController+ alertControllerWithTitle:@"Installation Failed" message:message+ preferredStyle:UIAlertControllerStyleAlert];+ [failureAlert addAction:[UIAlertAction actionWithTitle:@"Keep Files"+ style:UIAlertActionStyleCancel handler:nil]];+ [failureAlert addAction:[UIAlertAction actionWithTitle:@"Delete Incomplete Installation"+ style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ (void)action; VZRemovePaths(@[failedAttempt]);+ }]];+ [self presentViewController:failureAlert animated:YES completion:nil];+ }];+ return;+ }+ NSRange progress = [log rangeOfString:@"INSTALL_PROGRESS\t"+ options:NSBackwardsSearch];+ if (progress.location != NSNotFound) {+ NSString *tail = [log substringFromIndex:NSMaxRange(progress)];+ double fraction = tail.doubleValue;+ if (fraction <= 0.0) {+ self.installationController.indeterminate = YES;+ self.installationController.statusText = @"Booting Restore Environment…";+ self.installationController.detailText = @"The first progress value can take several minutes while the virtual Mac changes from DFU to RestoreOS. The iPad will remain awake.";+ return;+ }+ self.installationController.indeterminate = NO;+ self.installationController.progress = MAX(0, MIN(1, fraction));+ self.installationController.statusText = [NSString stringWithFormat:+ @"%.1f%% complete", fraction * 100.0];+ self.installationController.detailText = @"Installation can pause at some stages while macOS prepares the next restore phase. The iPad will remain awake.";+ } else if ([log containsString:@"INSTALL_BEGIN"]) {+ self.installationController.statusText = @"Starting restore…";+ } else if ([log containsString:@"RESTORE_LOAD_OK"]) {+ self.installationController.statusText = @"Preparing virtual hardware…";+ } else if ([log containsString:@"RESTORE_LOAD_BEGIN"]) {+ self.installationController.statusText = @"Reading restore image…";+ } else if ([log containsString:@"INSTALL_PREPARE_BEGIN"]) {+ self.installationController.statusText = @"Starting restoration services…";+ }+ }];+}++- (void)viewDidLayoutSubviews+{+ [super viewDidLayoutSubviews];+ if (!CGSizeEqualToSize(gLastInputBoundsSize, gInputView.bounds.size)) {+ gLastInputBoundsSize = gInputView.bounds.size;+ resetPointerSession(YES);+ for (id interaction in gInputView.interactions)+ if ([interaction respondsToSelector:@selector(invalidate)])+ [interaction invalidate];+ }+ updateDisplayGeometry();+}++- (void)pressesBegan:(NSSet<UIPress *> *)presses+ withEvent:(UIPressesEvent *)event+{+ if (!sendPresses(presses, YES))+ [super pressesBegan:presses withEvent:event];+}++- (void)pressesEnded:(NSSet<UIPress *> *)presses+ withEvent:(UIPressesEvent *)event+{+ if (!sendPresses(presses, NO))+ [super pressesEnded:presses withEvent:event];+}++- (void)pressesCancelled:(NSSet<UIPress *> *)presses+ withEvent:(UIPressesEvent *)event+{+ sendPresses(presses, NO);+}++- (void)virtualMachine:(id)virtualMachine didStopWithError:(NSError *)error+{+ (void)virtualMachine;+ printf("[VirtualMac] VM delegate didStopWithError=%s\n",+ error ? [[error description] UTF8String] : "(none)");+ setStatus([NSString stringWithFormat:@"Virtual Mac stopped: %@",+ error.localizedDescription]);+ [self finishVMAndShowLibraryWithError:error];+}++- (void)guestDidStopVirtualMachine:(id)virtualMachine+{+ (void)virtualMachine;+ printf("[VirtualMac] VM delegate guestDidStopVirtualMachine\n");+ [self finishVMAndShowLibraryWithError:nil];+}++- (void)finishVMAndShowLibraryWithError:(NSError *)error+{+ [gDisplayLayer removeFromSuperlayer];+ gDisplayLayer = nil;+ gDisplayContainer = nil;+ gFramebuffer = nil;+ [gFramebufferView release];+ gFramebufferView = nil;+ [gVirtualMachine release];+ gVirtualMachine = nil;+ gVirtualMachineDelegate = nil;+ gKeyboard = nil;+ gPointingDevice = nil;+ gTouchButtons = 0;+ gHardwareMouseButtons = 0;+ gLastPointerButtons = NSUIntegerMax;+ gCursorView.image = nil;+ gCursorView.hidden = YES;+ gInputView.hidden = YES;+ self.activeVMBundlePath = nil;+ [self presentVMLibrary];+ if (error) {+ UIAlertController *alert = [UIAlertController+ alertControllerWithTitle:@"Virtual Mac Stopped"+ message:error.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ }+}++- (void)dealloc+{+ [NSNotificationCenter.defaultCenter removeObserver:self];+ [_libraryNavigationController release];+ _installationController.cancellationHandler = nil;+ [_installationController release];+ [_installationTimer invalidate];+ [_installationTimer release];+ [_installationLogPath release];+ [_installationBundlePath release];+ [_installationStagingPath release];+ [_installationAttemptPath release];+ [_installationRestoreImagePath release];+ [_installationOptions release];+ [_activeVMBundlePath release];+ [super dealloc];+}+@end++static CGRect aspectFitRect(CGSize contentSize, CGRect bounds) {+ if (contentSize.width <= 0 || contentSize.height <= 0 ||+ bounds.size.width <= 0 || bounds.size.height <= 0)+ return bounds;+ CGFloat scale = fmin(bounds.size.width / contentSize.width,+ bounds.size.height / contentSize.height);+ CGSize size = CGSizeMake(contentSize.width * scale,+ contentSize.height * scale);+ return CGRectIntegral(CGRectMake(+ CGRectGetMidX(bounds) - size.width / 2.0,+ CGRectGetMidY(bounds) - size.height / 2.0,+ size.width, size.height));+}++static CGRect aspectFillRect(CGSize contentSize, CGRect bounds) {+ if (contentSize.width <= 0 || contentSize.height <= 0 ||+ bounds.size.width <= 0 || bounds.size.height <= 0)+ return bounds;+ CGFloat scale = fmax(bounds.size.width / contentSize.width,+ bounds.size.height / contentSize.height);+ CGSize size = CGSizeMake(contentSize.width * scale,+ contentSize.height * scale);+ return CGRectIntegral(CGRectMake(+ CGRectGetMidX(bounds) - size.width / 2.0,+ CGRectGetMidY(bounds) - size.height / 2.0,+ size.width, size.height));+}++static CGRect displayViewportRect(CGSize contentSize, CGRect bounds) {+ BOOL fill = [[VZAppSettings.sharedSettings stringForKey:+ VZDisplayScalingKey] isEqualToString:@"fill"];+ return fill ? aspectFillRect(contentSize, bounds)+ : aspectFitRect(contentSize, bounds);+}++static void updateDisplayGeometry(void) {+ static CGRect lastViewport = {{NAN, NAN}, {NAN, NAN}};+ static CGSize lastContainer = {NAN, NAN};+ if (!gDisplayContainer)+ return;+ CGRect viewport = displayViewportRect(gDisplayPixelSize,+ gDisplayContainer.bounds);+ if (gDisplayLayer)+ gDisplayLayer.frame = viewport;+ if (gInputView)+ gInputView.frame = viewport;+ if (!CGRectEqualToRect(viewport, lastViewport) ||+ !CGSizeEqualToSize(gDisplayContainer.bounds.size, lastContainer)) {+ printf("[VirtualMac] display viewport %.0fx%.0f at %.0f,%.0f "+ "guest=%.0fx%.0f container=%.0fx%.0f\n",+ viewport.size.width, viewport.size.height,+ viewport.origin.x, viewport.origin.y,+ gDisplayPixelSize.width, gDisplayPixelSize.height,+ gDisplayContainer.bounds.size.width,+ gDisplayContainer.bounds.size.height);+ lastViewport = viewport;+ lastContainer = gDisplayContainer.bounds.size;+ }+}++static void setStatus(NSString *status) {+ printf("[VirtualMac] %s\n", [status UTF8String]);+ if (gStatusLabel)+ gStatusLabel.text = status;+}++static void traceFrameUpdate(id self, SEL selector, id framebuffer,+ VZFrameUpdateSharedPtr update) {+ uint64_t count = __sync_add_and_fetch(&gFrameUpdateCount, 1);+ const VZFrameUpdateSharedPtr *shared = update.object;+ if (count <= 3 || count % 300 == 0)+ printf("[VirtualMac] PVG frame=%llu framebuffer=%p update=%p control=%p\n",+ (unsigned long long)count, framebuffer,+ shared ? shared->object : NULL,+ shared ? shared->control : NULL);+ ((void(*)(id, SEL, id, VZFrameUpdateSharedPtr))gOriginalFrameUpdate)(+ self, selector, framebuffer, update);+}++static UIImage *copyCursorImage(const uint8_t *cursor) {+ const void *pixels = *(const void *const *)(cursor + 0);+ uint32_t width = *(const uint32_t *)(cursor + 8);+ uint32_t height = *(const uint32_t *)(cursor + 12);+ uint32_t bytesPerPixel = *(const uint32_t *)(cursor + 16);+ if (!pixels || width == 0 || height == 0 || bytesPerPixel != 4 ||+ width > 4096 || height > 4096)+ return nil;+ size_t bytesPerRow = (size_t)width * bytesPerPixel;+ if (bytesPerRow > SIZE_MAX / height)+ return nil;+ CFDataRef data = CFDataCreate(+ kCFAllocatorDefault, pixels, (CFIndex)(bytesPerRow * height));+ CGDataProviderRef provider = data+ ? CGDataProviderCreateWithCFData(data) : NULL;+ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();+ CGImageRef image = provider && colorSpace+ ? CGImageCreate(width, height, 8, 32, bytesPerRow, colorSpace,+ (CGBitmapInfo)0x2004, provider, NULL, false,+ kCGRenderingIntentDefault)+ : NULL;+ UIImage *result = image ? [[UIImage alloc] initWithCGImage:image] : nil;+ if (image)+ CGImageRelease(image);+ if (colorSpace)+ CGColorSpaceRelease(colorSpace);+ if (provider)+ CGDataProviderRelease(provider);+ if (data)+ CFRelease(data);+ return result;+}++static void updateCursorOverlay(VZFrameUpdateSharedPtr update) {+ // Clang passes this non-trivial C++ shared_ptr parameter indirectly even+ // though the Objective-C type encoding describes its two pointer fields.+ const VZFrameUpdateSharedPtr *shared = update.object;+ const uint8_t *cursor = shared ? shared->object : NULL;+ if (!cursor || !gCursorView)+ return;+ BOOL imageChanged = *(const uint8_t *)(cursor + 40) != 0;+ BOOL imagePresent = *(const uint8_t *)(cursor + 32) != 0;+ uint32_t width = *(const uint32_t *)(cursor + 8);+ uint32_t height = *(const uint32_t *)(cursor + 12);+ uint32_t hotspotX = *(const uint32_t *)(cursor + 24);+ uint32_t hotspotY = *(const uint32_t *)(cursor + 28);+ uint32_t guestX = *(const uint32_t *)(cursor + 48);+ uint32_t guestY = *(const uint32_t *)(cursor + 52);+ UIImage *image = imageChanged && imagePresent+ ? copyCursorImage(cursor) : nil;++ dispatch_async(dispatch_get_main_queue(), ^{+ if (imageChanged) {+ gCursorView.image = image;+ gCursorView.hidden = image == nil;+ gCursorPixelSize = image+ ? CGSizeMake(width, height) : CGSizeZero;+ gCursorHotspot = image+ ? CGPointMake(hotspotX, hotspotY) : CGPointZero;+ }+ CGFloat scaleX = gInputView.bounds.size.width /+ gDisplayPixelSize.width;+ CGFloat scaleY = gInputView.bounds.size.height /+ gDisplayPixelSize.height;+ CGSize size = CGSizeMake(gCursorPixelSize.width * scaleX,+ gCursorPixelSize.height * scaleY);+ CGPoint origin = CGPointMake(+ gInputView.frame.origin.x ++ ((CGFloat)guestX - gCursorHotspot.x) * scaleX,+ gInputView.frame.origin.y ++ ((CGFloat)guestY - gCursorHotspot.y) * scaleY);+ // A just-sent host pointer event is newer than this asynchronous PVG+ // callback. Keep the predicted position briefly; a subsequent guest+ // update reconciles it without the cursor jumping one frame backward.+ if (CACurrentMediaTime() - gLastPredictedCursorTime >= 0.05)+ gCursorView.frame = (CGRect){origin, size};+ [image release];+ });+}++static void traceCursorUpdate(id self, SEL selector, id framebuffer,+ VZFrameUpdateSharedPtr update) {+ uint64_t count = __sync_add_and_fetch(&gCursorUpdateCount, 1);+ if (count <= 8 || count % 300 == 0) {+ const VZFrameUpdateSharedPtr *shared = update.object;+ const uint8_t *cursor = shared ? shared->object : NULL;+ printf("[VirtualMac] PVG cursor=%llu pos=%u,%u image-change=%d "+ "image=%d size=%ux%u\n",+ (unsigned long long)count,+ cursor ? *(const uint32_t *)(cursor + 48) : 0,+ cursor ? *(const uint32_t *)(cursor + 52) : 0,+ cursor ? *(const uint8_t *)(cursor + 40) != 0 : 0,+ cursor ? *(const uint8_t *)(cursor + 32) != 0 : 0,+ cursor ? *(const uint32_t *)(cursor + 8) : 0,+ cursor ? *(const uint32_t *)(cursor + 12) : 0);+ }+ updateCursorOverlay(update);+ ((void(*)(id, SEL, id, VZFrameUpdateSharedPtr))gOriginalCursorUpdate)(+ self, selector, framebuffer, update);+}++static BOOL installFramebufferTrace(void) {+ Class framebufferViewClass = objc_getClass("_VZFramebufferView");+ Method method = class_getInstanceMethod(+ framebufferViewClass, S("framebuffer:didUpdateFrame:"));+ if (!method)+ return NO;+ IMP frameImplementation = method_getImplementation(method);+ if (frameImplementation != (IMP)&traceFrameUpdate) {+ gOriginalFrameUpdate = method_setImplementation(+ method, (IMP)&traceFrameUpdate);+ } else if (!gOriginalFrameUpdate) {+ printf("[VirtualMac] frame callback already traced without original\n");+ return NO;+ }+ Method cursorMethod = class_getInstanceMethod(+ framebufferViewClass, S("framebuffer:didUpdateCursor:"));+ if (cursorMethod) {+ IMP cursorImplementation = method_getImplementation(cursorMethod);+ if (cursorImplementation != (IMP)&traceCursorUpdate) {+ gOriginalCursorUpdate = method_setImplementation(+ cursorMethod, (IMP)&traceCursorUpdate);+ } else if (!gOriginalCursorUpdate) {+ printf("[VirtualMac] cursor callback already traced without original\n");+ return NO;+ }+ printf("[VirtualMac] cursor callback type=%s original=%p trace=%p\n",+ method_getTypeEncoding(cursorMethod), gOriginalCursorUpdate,+ (void *)&traceCursorUpdate);+ }+ printf("[VirtualMac] frame callback type=%s original=%p trace=%p\n",+ method_getTypeEncoding(method), gOriginalFrameUpdate,+ (void *)&traceFrameUpdate);+ return gOriginalFrameUpdate != NULL && gOriginalCursorUpdate != NULL;+}++static void logFramebufferState(id view, id framebuffer, const char *phase) {+ Ivar rateIvar = class_getInstanceVariable(+ object_getClass(framebuffer), "_currentFrameRate");+ Ivar observersIvar = class_getInstanceVariable(+ object_getClass(framebuffer), "_observers");+ Ivar lastFrameIvar = class_getInstanceVariable(+ object_getClass(framebuffer), "_lastFrameUpdate");+ const uint8_t *bytes = (const uint8_t *)(__bridge const void *)framebuffer;+ uint64_t rate = *(const uint64_t *)(bytes + ivar_getOffset(rateIvar));+ const void *const *observers =+ (const void *const *)(bytes + ivar_getOffset(observersIvar));+ const void *const *lastFrame =+ (const void *const *)(bytes + ivar_getOffset(lastFrameIvar));+ NSUInteger observerCount = observers[0] && observers[1]+ ? ((const uint8_t *)observers[1] - (const uint8_t *)observers[0]) / 16+ : 0;+ printf("[VirtualMac] framebuffer state %s window=%p rate=%llu "+ "observers=%lu [%p,%p) lastFrame=%p/%p\n",+ phase, m0(view, "window"), (unsigned long long)rate,+ (unsigned long)observerCount, observers[0], observers[1],+ lastFrame[0], lastFrame[1]);+}++// VZVirtualMachine owns a libc++ unordered_map of host RPC callbacks at+// ivar offset 0x98 in the extracted 22D68 framework. Keep this diagnostic+// alongside the port so a device run can prove that the stock+// process_frame_update callback survived construction and start.+static void dumpRPCHandlers(id virtualMachine, const char *phase) {+ const uint8_t *vm = (const uint8_t *)(__bridge const void *)virtualMachine;+ const uint8_t *table = *(const uint8_t *const *)(vm + 0x98);+ if (!table) {+ printf("[VirtualMac] RPC handlers %s table=NULL\n", phase);+ return;+ }++ const void *buckets = *(const void *const *)(table + 0x0);+ uint64_t bucketCount = *(const uint64_t *)(table + 0x8);+ const uint8_t *node = *(const uint8_t *const *)(table + 0x10);+ uint64_t declaredCount = *(const uint64_t *)(table + 0x18);+ printf("[VirtualMac] RPC handlers %s table=%p buckets=%p "+ "bucketCount=%llu declaredCount=%llu head=%p\n",+ phase, table, buckets,+ (unsigned long long)bucketCount,+ (unsigned long long)declaredCount, node);++ for (uint64_t i = 0; node && i < declaredCount && i < 64; i++) {+ int8_t discriminator = *(const int8_t *)(node + 0x27);+ const char *name;+ uint64_t length;+ if (discriminator < 0) {+ name = *(const char *const *)(node + 0x10);+ length = *(const uint64_t *)(node + 0x18);+ } else {+ name = (const char *)(node + 0x10);+ length = (uint8_t)discriminator;+ }+ printf("[VirtualMac] RPC handler[%llu] node=%p hash=0x%llx "+ "name=%.*s callback=%p\n",+ (unsigned long long)i, node,+ (unsigned long long)*(const uint64_t *)(node + 0x8),+ (int)length, name,+ *(const void *const *)(node + 0x40));+ node = *(const uint8_t *const *)node;+ }+}++static BOOL loadExtractedFrameworks(void) {+ NSString *hookPath =+ [NSBundle.mainBundle pathForResource:@"VZHostCompat"+ ofType:@"dylib"];+ void *hook = hookPath+ ? dlopen([hookPath fileSystemRepresentation], RTLD_NOW | RTLD_GLOBAL)+ : NULL;+ if (!hook) {+ printf("[VirtualMac] dlopen host hook FAILED: %s\n", dlerror());+ return NO;+ }+ printf("[VirtualMac] loaded host hook: %s\n",+ [hookPath fileSystemRepresentation]);++ const char *images[] = {+ "/var/root/VirtualMac/payload/Frameworks/vmnet.framework/vmnet",+ "/var/root/VirtualMac/payload/Frameworks/Hypervisor.framework/Hypervisor",+ "/var/root/VirtualMac/payload/Frameworks/ParavirtualizedGraphics.framework/ParavirtualizedGraphics",+ "/var/root/VirtualMac/payload/Frameworks/Virtualization.framework/Virtualization",+ };+ for (NSUInteger i = 0; i < sizeof(images) / sizeof(images[0]); i++) {+ if (!dlopen(images[i], RTLD_NOW | RTLD_GLOBAL)) {+ printf("[VirtualMac] dlopen %s FAILED: %s\n", images[i], dlerror());+ return NO;+ }+ }++ Method start = class_getInstanceMethod(+ objc_getClass("VZVirtualMachine"),+ sel_registerName("startWithCompletionHandler:"));+ Dl_info virtualizationInfo = {0};+ dladdr((const void *)method_getImplementation(start), &virtualizationInfo);+ printf("[VirtualMac] VZ image=%p (%s)\n",+ virtualizationInfo.dli_fbase,+ virtualizationInfo.dli_fname ?: "?");+ if (!virtualizationInfo.dli_fbase)+ return NO;+ int (*rebindVirtualization)(void *) =+ (int(*)(void *))dlsym(hook, "vz_rebind_virtualization");+ gHostVMStarted = (void(*)(void))dlsym(hook, "vz_host_vm_started");+ int rebindResult = rebindVirtualization+ ? rebindVirtualization(virtualizationInfo.dli_fbase)+ : -1;+ printf("[VirtualMac] authenticated VZ rebind=%p result=%d\n",+ rebindVirtualization, rebindResult);+ if (rebindResult != 0 || !gHostVMStarted)+ return NO;+ return installFramebufferTrace();+}++static void configureAudio(id configuration, NSDictionary *options) {+ if ([NSUserDefaults.standardUserDefaults boolForKey:@"VZDisableAudio"]) {+ printf("[VirtualMac] audio disabled by VZDisableAudio\n");+ return;+ }++ // Ventura's native macOS VM configuration uses virtio-sound with host+ // stream attachments. Use the same path for playback and microphone input.+ BOOL outputEnabled = [options[@"AudioOutputEnabled"] boolValue];+ BOOL inputEnabled = [options[@"AudioInputEnabled"] boolValue];+ if (!outputEnabled && !inputEnabled) {+ printf("[VirtualMac] audio disabled by VM configuration\n");+ return;+ }+ id sink = outputEnabled ? NEW("VZHostAudioOutputStreamSink") : nil;+ id output = outputEnabled+ ? NEW("VZVirtioSoundDeviceOutputStreamConfiguration") : nil;+ id source = inputEnabled ? NEW("VZHostAudioInputStreamSource") : nil;+ id input = inputEnabled+ ? NEW("VZVirtioSoundDeviceInputStreamConfiguration") : nil;+ id sound = NEW("VZVirtioSoundDeviceConfiguration");+ if ((outputEnabled && (!sink || !output)) ||+ (inputEnabled && (!source || !input)) || !sound) {+ printf("[VirtualMac] virtio audio classes unavailable sink=%p output=%p "+ "source=%p input=%p device=%p\n",+ sink, output, source, input, sound);+ return;+ }+ NSMutableArray *streams = [NSMutableArray array];+ if (inputEnabled) {+ setObj(input, "setSource:", source);+ [streams addObject:input];+ }+ if (outputEnabled) {+ setObj(output, "setSink:", sink);+ [streams addObject:output];+ }+ setObj(sound, "setStreams:", streams);+ setObj(configuration, "setAudioDevices:", @[sound]);+ printf("[VirtualMac] configured virtio audio output=%d/%p input=%d/%p\n",+ outputEnabled, sink, inputEnabled, source);+}++static BOOL videoToolboxAcceleratorSupported(id self, SEL selector) {+ (void)self;+ (void)selector;+ return YES;+}++static void configureVideoToolbox(id configuration, NSDictionary *options) {+ if (![options[@"VideoToolboxEnabled"] boolValue]) {+ printf("[VirtualMac] VideoToolbox accelerator disabled by VM configuration\n");+ return;+ }+ Class deviceClass = CLS("_VZMacVideoToolboxDeviceConfiguration");+ SEL supportedSelector = S("_isSupported");+ BOOL nativePredicate = deviceClass &&+ [deviceClass respondsToSelector:supportedSelector] &&+ ((BOOL(*)(id, SEL))objc_msgSend)(deviceClass, supportedSelector);+ if (!deviceClass) {+ printf("[VirtualMac] VideoToolbox accelerator class unavailable\n");+ return;+ }+ // The extracted framework's predicate resolves its weak VideoToolbox+ // imports in this UIKit host process, where iPadOS's system VideoToolbox+ // lacks the three Mac host-session exports. The VMM has our matching+ // extracted implementation, so make the configuration predicate describe+ // the actual child runtime before both init and validation consult it.+ Method supportedMethod = class_getClassMethod(deviceClass,+ supportedSelector);+ if (supportedMethod)+ method_setImplementation(supportedMethod,+ (IMP)videoToolboxAcceleratorSupported);+ id device = NEW("_VZMacVideoToolboxDeviceConfiguration");+ if (!device ||+ ![configuration respondsToSelector:S("_setAcceleratorDevices:")]) {+ printf("[VirtualMac] VideoToolbox accelerator construction failed device=%p\n",+ device);+ [device release];+ return;+ }+ setObj(configuration, "_setAcceleratorDevices:", @[device]);+ printf("[VirtualMac] configured native VideoToolbox accelerator=%p "+ "original-supported=%d\n", device, nativePredicate);+ [device release];+}++static void requestMicrophoneAccess(dispatch_block_t continuation) {+ AVAudioSession *session = AVAudioSession.sharedInstance;+ AVAudioSessionRecordPermission permission = session.recordPermission;+ printf("[VirtualMac] microphone permission before request=%lu\n",+ (unsigned long)permission);+ NSError *sessionError = nil;+ AVAudioSessionCategoryOptions sessionOptions =+ AVAudioSessionCategoryOptionMixWithOthers |+ AVAudioSessionCategoryOptionDefaultToSpeaker |+ AVAudioSessionCategoryOptionAllowBluetoothHFP;+ BOOL categoryOK = [session+ setCategory:AVAudioSessionCategoryPlayAndRecord+ mode:AVAudioSessionModeDefault+ options:sessionOptions error:&sessionError];+ BOOL activeOK = [session setActive:YES error:&sessionError];+ printf("[VirtualMac] audio session category=%d active=%d error=%s\n",+ categoryOK, activeOK,+ sessionError ? sessionError.localizedDescription.UTF8String+ : "none");+ if (permission != AVAudioSessionRecordPermissionUndetermined) {+ continuation();+ return;+ }++ // The host audio source is created by Virtualization only after VM setup.+ // Ask under the visible application bundle first so TCC attributes capture+ // to Virtual Mac instead of silently giving its private VMM child zeros.+ __block BOOL continued = NO;+ void (^finish)(BOOL, const char *) = ^(BOOL granted, const char *reason) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (continued)+ return;+ continued = YES;+ printf("[VirtualMac] microphone permission granted=%d via=%s\n",+ granted, reason);+ continuation();+ });+ };+ [session requestRecordPermission:^(BOOL granted) {+ finish(granted, "TCC callback");+ }];+ // A platform-installed app on iPadOS can fail to receive a+ // TCC callback. Never make the VM library depend indefinitely on it.+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ finish(NO, "timeout");+ });+}++static void configureNetwork(id configuration, NSDictionary *options) {+ NSString *mode = options[@"NetworkMode"] ?: @"NAT";+ if ([mode isEqualToString:@"Disabled"] ||+ [NSUserDefaults.standardUserDefaults boolForKey:@"VZDisableNetwork"]) {+ printf("[VirtualMac] network disabled\n");+ return;+ }++ id attachment = nil;+ if ([mode isEqualToString:@"Bridge"]) {+ NSString *identifier = options[@"BridgeInterface"] ?: @"en0";+ NSArray *interfaces = ((id(*)(id, SEL))objc_msgSend)(+ CLS("VZBridgedNetworkInterface"), S("networkInterfaces"));+ id selected = nil;+ for (id candidate in interfaces) {+ NSString *candidateIdentifier = [candidate valueForKey:@"identifier"];+ if ([candidateIdentifier isEqualToString:identifier]) {+ selected = candidate;+ break;+ }+ }+ if (selected) {+ attachment = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZBridgedNetworkDeviceAttachment"), "alloc"),+ S("initWithInterface:"), selected);+ }+ printf("[VirtualMac] bridge request interface=%s available=%s selected=%p\n",+ identifier.UTF8String, interfaces.description.UTF8String,+ selected);+ } else {+ attachment = NEW("VZNATNetworkDeviceAttachment");+ }+ id network = NEW("VZVirtioNetworkDeviceConfiguration");+ if (!attachment || !network) {+ printf("[VirtualMac] virtio NAT classes unavailable attachment=%p "+ "device=%p\n", attachment, network);+ return;+ }+ // Keep the guest NIC identity stable across app launches. The framework's+ // default is valid but randomly generated for every new configuration.+ NSString *macString = options[@"MACAddress"];+ id macAddress = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZMACAddress"), "alloc"), S("initWithString:"),+ macString);+ if (!macAddress) {+ macAddress = [m0(CLS("VZMACAddress"),+ "randomLocallyAdministeredAddress") retain];+ macString = [[macAddress valueForKey:@"string"] description];+ }+ setObj(network, "setMACAddress:", macAddress);+ setObj(network, "setAttachment:", attachment);+ setObj(configuration, "setNetworkDevices:", @[network]);+ printf("[VirtualMac] configured virtio %s network attachment=%p mac=%s\n",+ mode.UTF8String, attachment,+ [[[macAddress valueForKey:@"string"] description]+ UTF8String]);+}++static void configureDirectorySharing(id configuration,+ NSDictionary *options) {+ NSArray *shares = options[@"SharedDirectories"];+ if (![shares isKindOfClass:NSArray.class] || shares.count == 0)+ return;+ NSMutableDictionary *directories = [NSMutableDictionary dictionary];+ for (NSDictionary *saved in shares) {+ NSString *path = saved[@"Path"];+ if (![path isKindOfClass:NSString.class] || !path.length)+ continue;+ id directory = ((id(*)(id, SEL, id, BOOL))objc_msgSend)(+ m0(CLS("VZSharedDirectory"), "alloc"),+ S("initWithURL:readOnly:"), fileURL(path),+ [saved[@"ReadOnly"] boolValue]);+ if (!directory)+ continue;+ NSString *baseName = path.lastPathComponent.length+ ? path.lastPathComponent : @"Shared Folder";+ NSString *name = baseName;+ for (NSUInteger suffix = 2; directories[name]; suffix++)+ name = [NSString stringWithFormat:@"%@ %lu", baseName,+ (unsigned long)suffix];+ directories[name] = directory;+ }+ if (!directories.count)+ return;+ id share = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZMultipleDirectoryShare"), "alloc"),+ S("initWithDirectories:"), directories);+ id fileSystemClass = CLS("VZVirtioFileSystemDeviceConfiguration");+ NSString *tag = m0(fileSystemClass, "macOSGuestAutomountTag");+ id device = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(fileSystemClass, "alloc"), S("initWithTag:"), tag);+ if (!share || !device)+ return;+ setObj(device, "setShare:", share);+ setObj(configuration, "setDirectorySharingDevices:", @[device]);+ printf("[VirtualMac] configured directory shares count=%lu tag=%s names=%s\n",+ (unsigned long)directories.count, tag.UTF8String,+ directories.allKeys.description.UTF8String);+}++static id makeConfiguration(NSString *bundlePath, NSDictionary *options,+ NSError **error) {+ id platform = NEW("VZMacPlatformConfiguration");+ id auxiliaryStorage = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZMacAuxiliaryStorage"), "alloc"),+ S("initWithContentsOfURL:"),+ fileURL([bundlePath stringByAppendingPathComponent:@"AuxiliaryStorage"]));+ setObj(platform, "setAuxiliaryStorage:", auxiliaryStorage);++ NSData *hardwareModelData = [NSData dataWithContentsOfFile:+ [bundlePath stringByAppendingPathComponent:@"HardwareModel"]];+ id hardwareModel = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZMacHardwareModel"), "alloc"),+ S("initWithDataRepresentation:"), hardwareModelData);+ if (!hardwareModel ||+ !((BOOL(*)(id, SEL))objc_msgSend)(hardwareModel, S("isSupported"))) {+ printf("[VirtualMac] unsupported hardware model\n");+ return nil;+ }+ setObj(platform, "setHardwareModel:", hardwareModel);++ NSData *machineIdentifierData = [NSData dataWithContentsOfFile:+ [bundlePath stringByAppendingPathComponent:@"MachineIdentifier"]];+ id machineIdentifier = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZMacMachineIdentifier"), "alloc"),+ S("initWithDataRepresentation:"), machineIdentifierData);+ setObj(platform, "setMachineIdentifier:", machineIdentifier);++ id configuration = NEW("VZVirtualMachineConfiguration");+ setObj(configuration, "setPlatform:", platform);+ NSUInteger hostCPUCount = NSProcessInfo.processInfo.activeProcessorCount;+ NSUInteger cpuCount = [options[@"CPUCount"] unsignedIntegerValue];+ cpuCount = MAX((NSUInteger)2, MIN(cpuCount, hostCPUCount));+ uint64_t memoryLimit = NSProcessInfo.processInfo.physicalMemory >=+ (12ULL << 30) ? (8ULL << 30) : (4ULL << 30);+ uint64_t memorySize = [options[@"MemorySize"] unsignedLongLongValue];+ memorySize = MAX((2ULL << 30), MIN(memorySize, memoryLimit));+ ((void(*)(id, SEL, NSUInteger))objc_msgSend)(+ configuration, S("setCPUCount:"), cpuCount);+ ((void(*)(id, SEL, unsigned long long))objc_msgSend)(+ configuration, S("setMemorySize:"), memorySize);+ printf("[VirtualMac] configured guest cpus=%lu host-active-cpus=%lu "+ "memory=%lluMiB\n",+ (unsigned long)cpuCount, (unsigned long)hostCPUCount,+ memorySize >> 20);+ setObj(configuration, "setBootLoader:", NEW("VZMacOSBootLoader"));++ UIScreen *screen = UIScreen.mainScreen;+ CGSize hostSize = screen.bounds.size;+ CGFloat nativeScale = screen.nativeScale > 0+ ? screen.nativeScale : screen.scale;+ // The app is landscape-only, so multiplying the oriented UIKit bounds by+ // nativeScale produces the panel's exact native landscape pixel size+ // (2388x1668 on the connected 11-inch iPad Pro). A Retina-density PPI+ // makes macOS expose this as a 2x logical desktop instead of a scaled+ // low-density monitor.+ BOOL customDisplay = [options[@"DisplayMode"] isEqualToString:@"Custom"];+ NSInteger displayWidth = customDisplay+ ? [options[@"DisplayWidth"] integerValue]+ : (NSInteger)llround(hostSize.width * nativeScale);+ NSInteger displayHeight = customDisplay+ ? [options[@"DisplayHeight"] integerValue]+ : (NSInteger)llround(hostSize.height * nativeScale);+ NSInteger pixelsPerInch = customDisplay+ ? [options[@"DisplayPixelsPerInch"] integerValue] : 264;+ displayWidth = MAX(800, MIN(7680, displayWidth));+ displayHeight = MAX(800, MIN(7680, displayHeight));+ pixelsPerInch = MAX(72, MIN(600, pixelsPerInch));+ gDisplayPixelSize = CGSizeMake(displayWidth, displayHeight);+ printf("[VirtualMac] configured guest display %ldx%ld at %ld ppi "+ "for host %.0fx%.0f scale=%.3f\n",+ (long)displayWidth, (long)displayHeight,+ (long)pixelsPerInch, hostSize.width, hostSize.height,+ nativeScale);+ id graphics = NEW("VZMacGraphicsDeviceConfiguration");+ id display = ((id(*)(id, SEL, NSInteger, NSInteger, NSInteger))objc_msgSend)(+ m0(CLS("VZMacGraphicsDisplayConfiguration"), "alloc"),+ S("initWithWidthInPixels:heightInPixels:pixelsPerInch:"),+ displayWidth, displayHeight, pixelsPerInch);+ setObj(graphics, "setDisplays:", @[display]);+ setObj(configuration, "setGraphicsDevices:", @[graphics]);++ id attachment = ((id(*)(id, SEL, id, BOOL, NSError **))objc_msgSend)(+ m0(CLS("VZDiskImageStorageDeviceAttachment"), "alloc"),+ S("initWithURL:readOnly:error:"),+ fileURL([bundlePath stringByAppendingPathComponent:@"Disk.img"]),+ NO, error);+ if (!attachment)+ return nil;+ id blockDevice = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZVirtioBlockDeviceConfiguration"), "alloc"),+ S("initWithAttachment:"), attachment);+ setObj(configuration, "setStorageDevices:", @[blockDevice]);++ // Monterey requires the older USB keyboard and absolute USB mouse guest devices.+ NSString *keyboardChoice = options[@"KeyboardDevice"];+ BOOL useUSBKeyboard = [keyboardChoice isEqualToString:@"USBKeyboard"];+ id keyboard = useUSBKeyboard+ ? NEW("VZUSBKeyboardConfiguration")+ : NEW("_VZMacKeyboardConfiguration");+ NSString *pointingChoice = options[@"PointingDevice"];+ BOOL useUSBMouse = [pointingChoice isEqualToString:@"USBMouse"];+ id pointing = useUSBMouse+ ? NEW("VZUSBScreenCoordinatePointingDeviceConfiguration")+ : NEW("VZMacTrackpadConfiguration");+ if (keyboard)+ setObj(configuration, "setKeyboards:", @[keyboard]);+ if (pointing)+ setObj(configuration, "setPointingDevices:", @[pointing]);+ printf("[VirtualMac] configured keyboard device=%s class=%s\n",+ useUSBKeyboard ? "USB Keyboard" : "Mac Keyboard",+ keyboard ? object_getClassName(keyboard) : "(unavailable)");+ printf("[VirtualMac] configured pointing device=%s class=%s\n",+ useUSBMouse ? "USB Mouse" : "Mac Trackpad",+ pointing ? object_getClassName(pointing) : "(unavailable)");+ configureAudio(configuration, options);+ configureVideoToolbox(configuration, options);+ configureNetwork(configuration, options);+ configureDirectorySharing(configuration, options);+ return configuration;+}++static BOOL prepareFramebuffer(UIView *container) {+ NSArray *graphicsDevices = m0(gVirtualMachine, "_graphicsDevices");+ id graphicsDevice = [graphicsDevices firstObject];+ NSArray *framebuffers = graphicsDevice ? m0(graphicsDevice, "framebuffers") : nil;+ id framebuffer = [framebuffers firstObject];+ printf("[VirtualMac] graphicsDevices=%s framebuffers=%s\n",+ [[graphicsDevices description] UTF8String],+ [[framebuffers description] UTF8String]);+ if (!framebuffer) {+ setStatus(@"Virtual Mac has no published framebuffer");+ return NO;+ }++ Class framebufferViewClass = objc_getClass("_VZFramebufferView");+ if (!framebufferViewClass) {+ setStatus(@"_VZFramebufferView is unavailable");+ return NO;+ }+ VZSetNSViewFrameRequestsSuppressed(NO);+ gDisplayContainer = container;+ container.clipsToBounds = YES;+ CGRect viewport = displayViewportRect(gDisplayPixelSize, container.bounds);+ id view = ((id(*)(id, SEL, CGRect))objc_msgSend)(+ [framebufferViewClass alloc], S("initWithFrame:"), viewport);+ gFramebufferView = view;+ gFramebuffer = framebuffer;+ gFramebufferView.backgroundColor = [UIColor blackColor];+ gFramebufferView.autoresizingMask =+ UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ // Do not insert the AppKit-ABI subclass into UIKit's UIView tree: UIKit's+ // private hierarchy traversal and AppKit's compiled NSView layout are not+ // ABI-compatible. Its custom display layer is portable, so host that layer+ // inside an ordinary UIView while NSViewShim supplies the key window.+ CALayer *displayLayer =+ ((CALayer *(*)(id, SEL))objc_msgSend)(view, S("layer"));+ gDisplayLayer = displayLayer;+ displayLayer.frame = viewport;+ [container.layer insertSublayer:displayLayer atIndex:0];+ ((void(*)(id, SEL, BOOL))objc_msgSend)(+ view, S("setShowsCursor:"), NO);+ setObj(view, "setFramebuffer:", framebuffer);+ if ([view respondsToSelector:S("layout")])+ ((void(*)(id, SEL))objc_msgSend)(view, S("layout"));+ updateDisplayGeometry();+ logFramebufferState(view, framebuffer, "pre-registered");+ return YES;+}++static void activateFramebuffer(void) {+ id view = gFramebufferView;+ id framebuffer = gFramebuffer;+ if (!view || !framebuffer)+ return;+ VZSetNSViewFrameRequestsSuppressed(NO);+ if ([view respondsToSelector:S("viewDidMoveToWindow")])+ ((void(*)(id, SEL))objc_msgSend)(view, S("viewDidMoveToWindow"));+ if ([view respondsToSelector:S("layout")])+ ((void(*)(id, SEL))objc_msgSend)(view, S("layout"));+ BOOL inputFocused = GCKeyboard.coalescedKeyboard+ ? [gInputView becomeFirstResponder] : gInputView.isFirstResponder;+ printf("[VirtualMac] input focus after-start requested=%d active=%d window=%p\n",+ inputFocused, [gInputView isFirstResponder], gInputView.window);+ scheduleInputSelfTest();+ pollInputCommand();+ scheduleRecoveryDialogDismissal();+ logFramebufferState(view, framebuffer, "activated");+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ logFramebufferState(view, framebuffer, "after-2s");+ });+ setStatus(@"Virtual Mac running — native PVG framebuffer attached");+}++static void startVirtualMachine(UIView *container, id delegate,+ NSString *bundlePath,+ NSDictionary *options) {+ unlink("/tmp/vzxpchook.log");+ unlink("/tmp/vmmhook.log");+ unlink("/tmp/vmm.stderr.log");+ setenv("VZ_VMM_BIN",+ "/var/root/VirtualMac/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine",+ 1);+ setenv("VZ_AVP_BOOTER",+ "/var/root/VirtualMac/payload/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin",+ 1);+ setenv("VMMHOOK_TRACE_VCPU_LIMIT", "8", 1);+ setenv("VMMHOOK_TRACE_XPC_LIMIT", "8", 1);+ setenv("VMM_FACTORY_SETTLE_USEC", "100000", 1);+ // Timestamp correlation places PGIOSurfaceHostDevice finalization just+ // before serialized factory boundary 6. Pause only that boundary long+ // enough for its asynchronous Metal/IOSurface capability exchange.+ setenv("VMM_FACTORY_LONG_STOP", "6", 1);+ setenv("VMM_FACTORY_LONG_SETTLE_USEC", "5000000", 1);+ setenv("PVG_TRACE", "1", 1);+ setenv("PVG_TRACE_METHODS", "1", 1);+ // WindowServer's long-lived PVG task reached 1.07 GiB while Launchpad was+ // populating its icon textures. Keep ordinary app clients at 1 GiB so 20++ // simultaneous clients fit in the iPad VA, but give the first three+ // long-lived system clients 2 GiB. Their slots are recycled on deletion.+ setenv("PVG_TASK_RESERVATION_GB", "1", 1);+ setenv("PVG_LARGE_TASK_RESERVATION_GB", "2", 1);+ setenv("PVG_LARGE_TASK_COUNT", "3", 1);+ setenv("PVG_METALLIB_FALLBACK", "1", 1);++ setStatus(@"Loading extracted Apple virtualization frameworks…");+ if (!loadExtractedFrameworks()) {+ setStatus(@"Failed to load extracted frameworks");+ NSError *loadError = [NSError errorWithDomain:@"VirtualMac" code:1+ userInfo:@{NSLocalizedDescriptionKey:+ @"Failed to load the extracted Apple virtualization frameworks."}];+ [delegate finishVMAndShowLibraryWithError:loadError];+ return;+ }++ printf("[VirtualMac] starting selected VM path=%s\n", bundlePath.UTF8String);+ NSError *error = nil;+ id configuration = makeConfiguration(bundlePath, options, &error);+ if (!configuration) {+ setStatus([NSString stringWithFormat:@"Configuration failed: %@",+ error.localizedDescription]);+ if (!error)+ error = [NSError errorWithDomain:@"VirtualMac" code:2+ userInfo:@{NSLocalizedDescriptionKey:+ @"The virtual Mac configuration could not be created."}];+ [delegate finishVMAndShowLibraryWithError:error];+ return;+ }+ BOOL valid = ((BOOL(*)(id, SEL, NSError **))objc_msgSend)(+ configuration, S("validateWithError:"), &error);+ if (!valid) {+ setStatus([NSString stringWithFormat:@"Validation failed: %@",+ error.localizedDescription]);+ [delegate finishVMAndShowLibraryWithError:error];+ return;+ }++ gVirtualMachine = ((id(*)(id, SEL, id))objc_msgSend)(+ m0(CLS("VZVirtualMachine"), "alloc"),+ S("initWithConfiguration:"), configuration);+ gVirtualMachineDelegate = delegate;+ if ([gVirtualMachine respondsToSelector:S("setDelegate:")])+ setObj(gVirtualMachine, "setDelegate:", delegate);+ id keyboards = [gVirtualMachine respondsToSelector:S("_keyboards")]+ ? m0(gVirtualMachine, "_keyboards") : nil;+ id pointingDevices =+ [gVirtualMachine respondsToSelector:S("_pointingDevices")]+ ? m0(gVirtualMachine, "_pointingDevices") : nil;+ printf("[VirtualMac] runtime input keyboards=%s pointingDevices=%s\n",+ [[keyboards description] UTF8String],+ [[pointingDevices description] UTF8String]);+ gKeyboard = [keyboards firstObject];+ gPointingDevice = [pointingDevices firstObject];+ dumpRPCHandlers(gVirtualMachine, "after-init");+ // setFramebuffer: installs the process_frame_update handler needed by the+ // VMM. The host hook holds its set_frame_rate message until start succeeds.+ if (!prepareFramebuffer(container)) {+ NSError *framebufferError = [NSError errorWithDomain:@"VirtualMac"+ code:3 userInfo:@{NSLocalizedDescriptionKey:+ @"The virtual Mac did not publish a display framebuffer."}];+ [delegate finishVMAndShowLibraryWithError:framebufferError];+ return;+ }+ setStatus(@"Starting virtual Mac…");+ void (^completion)(NSError *) = ^(NSError *startError) {+ if (startError) {+ setStatus([NSString stringWithFormat:@"Virtual Mac start failed: %@",+ startError.localizedDescription]);+ [delegate finishVMAndShowLibraryWithError:startError];+ return;+ }+ printf("[VirtualMac] VM STARTED state=%ld\n",+ (long)((NSInteger(*)(id, SEL))objc_msgSend)(+ gVirtualMachine, S("state")));+ dumpRPCHandlers(gVirtualMachine, "after-start");+ setStatus(@"Virtual Mac running — preparing native PVG display");+ gHostVMStarted();+ // Let the start reply return before exposing the registered display.+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC),+ dispatch_get_main_queue(), ^{+ activateFramebuffer();+ });+ };+ if ([options[@"BootRecovery"] boolValue] &&+ [gVirtualMachine respondsToSelector:+ S("startWithOptions:completionHandler:")]) {+ id startOptions = NEW("VZMacOSVirtualMachineStartOptions");+ ((void(*)(id, SEL, BOOL))objc_msgSend)(+ startOptions, S("setStartUpFromMacOSRecovery:"), YES);+ printf("[VirtualMac] configured recovery start\n");+ ((void(*)(id, SEL, id, id))objc_msgSend)(+ gVirtualMachine, S("startWithOptions:completionHandler:"),+ startOptions, completion);+ [startOptions release];+ } else {+ ((void(*)(id, SEL, id))objc_msgSend)(+ gVirtualMachine, S("startWithCompletionHandler:"), completion);+ }+}++@interface VirtualMacAppDelegate : UIResponder <UIApplicationDelegate>+@property(nonatomic, retain) UIWindow *window;+@end++@implementation VirtualMacAppDelegate+@synthesize window = _window;++- (VZVMLibraryViewController *)libraryController+{+ VZViewController *root = (id)self.window.rootViewController;+ [root presentVMLibrary];+ return (id)root.libraryNavigationController.viewControllers.firstObject;+}++- (BOOL)application:(UIApplication *)application+ didFinishLaunchingWithOptions:(NSDictionary *)launchOptions+{+ UIApplicationShortcutItem *shortcut = launchOptions[+ UIApplicationLaunchOptionsShortcutItemKey];+ BOOL bypassAutoBoot = [shortcut.type isEqualToString:@"com.mac.virtual.show-library"];+ freopen("/tmp/VirtualMac.log", "a", stdout);+ freopen("/tmp/VirtualMac.log", "a", stderr);+ setvbuf(stdout, NULL, _IONBF, 0);+ installShellShortcutRelay();++ self.window = [[[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds]+ autorelease];+ VZViewController *controller =+ [[[VZViewController alloc] init] autorelease];+ controller.view.backgroundColor = UIColor.systemBackgroundColor;+ self.window.rootViewController = controller;++ {+ gStatusLabel = [[UILabel alloc] initWithFrame:CGRectZero];+ gStatusLabel.hidden = !shouldShowStatusLabel();+ gStatusLabel.translatesAutoresizingMaskIntoConstraints = NO;+ gStatusLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.72];+ gStatusLabel.textColor = [UIColor whiteColor];+ gStatusLabel.font =+ [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];+ gStatusLabel.textAlignment = NSTextAlignmentCenter;+ gStatusLabel.numberOfLines = 2;+ gStatusLabel.userInteractionEnabled = NO;+ gStatusLabel.layer.cornerRadius = 10;+ gStatusLabel.clipsToBounds = YES;+ [controller.view addSubview:gStatusLabel];+ [NSLayoutConstraint activateConstraints:@[+ [gStatusLabel.centerXAnchor constraintEqualToAnchor:+ controller.view.centerXAnchor],+ [gStatusLabel.bottomAnchor constraintEqualToAnchor:+ controller.view.safeAreaLayoutGuide.bottomAnchor constant:-12],+ [gStatusLabel.widthAnchor constraintEqualToConstant:560],+ [gStatusLabel.heightAnchor constraintEqualToConstant:48],+ ]];+ }++ VZInputView *inputView =+ [[[VZInputView alloc] initWithFrame:controller.view.bounds]+ autorelease];+ gInputView = inputView;+ inputView.backgroundColor = [UIColor clearColor];+ inputView.multipleTouchEnabled = YES;+ inputView.autoresizingMask =+ UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ [inputView addGestureRecognizer:+ [[[UIHoverGestureRecognizer alloc]+ initWithTarget:inputView action:@selector(handleHover:)]+ autorelease]];+ [inputView addInteraction:+ [[[UIPointerInteraction alloc] initWithDelegate:inputView]+ autorelease]];+ VZRawScrollRecognizer *scrollRecognizer =+ [[[VZRawScrollRecognizer alloc]+ initWithTarget:inputView action:@selector(handleScroll:)]+ autorelease];+ scrollRecognizer.allowedScrollTypesMask = UIScrollTypeMaskAll;+ // Scroll-wheel input is not represented by UITouch. Rejecting all touch+ // types keeps direct touchscreen click-drag on the existing touch path.+ scrollRecognizer.allowedTouchTypes = @[];+ scrollRecognizer.cancelsTouchesInView = NO;+ [inputView addGestureRecognizer:scrollRecognizer];+ UIPinchGestureRecognizer *pinch = [[[UIPinchGestureRecognizer alloc]+ initWithTarget:inputView action:@selector(handlePinch:)] autorelease];+ pinch.cancelsTouchesInView = NO;+ [inputView addGestureRecognizer:pinch];+ UIRotationGestureRecognizer *rotation = [[[UIRotationGestureRecognizer alloc]+ initWithTarget:inputView action:@selector(handleRotation:)] autorelease];+ rotation.cancelsTouchesInView = NO;+ [inputView addGestureRecognizer:rotation];+ UITapGestureRecognizer *smartMagnify = [[[UITapGestureRecognizer alloc]+ initWithTarget:inputView action:@selector(handleSmartMagnify:)]+ autorelease];+ smartMagnify.numberOfTouchesRequired = 2;+ smartMagnify.numberOfTapsRequired = 2;+ smartMagnify.cancelsTouchesInView = NO;+ [inputView addGestureRecognizer:smartMagnify];+ [controller.view addSubview:inputView];++ gCursorView = [[UIImageView alloc] initWithFrame:CGRectZero];+ gCursorView.backgroundColor = [UIColor clearColor];+ gCursorView.contentMode = UIViewContentModeScaleToFill;+ gCursorView.userInteractionEnabled = NO;+ gCursorView.hidden = YES;+ [controller.view addSubview:gCursorView];+ VZHUDView *hud = [[[VZHUDView alloc] initWithTarget:controller] autorelease];+ gHUDView = hud;+ hud.hidden = YES;+ [controller.view addSubview:hud];+ [controller updateHUDPosition];+ if (gStatusLabel)+ [controller.view bringSubviewToFront:gStatusLabel];++ [self.window makeKeyAndVisible];+ UIApplicationShortcutIcon *libraryIcon = [UIApplicationShortcutIcon+ iconWithSystemImageName:@"square.grid.2x2"];+ UIApplicationShortcutIcon *controlsIcon = [UIApplicationShortcutIcon+ iconWithSystemImageName:@"slider.horizontal.3"];+ application.shortcutItems = @[[[[UIApplicationShortcutItem alloc]+ initWithType:@"com.mac.virtual.show-library"+ localizedTitle:@"Show Library" localizedSubtitle:nil+ icon:libraryIcon userInfo:nil] autorelease],+ [[[UIApplicationShortcutItem alloc]+ initWithType:@"com.mac.virtual.show-controls"+ localizedTitle:@"Show Virtual Mac Controls" localizedSubtitle:nil+ icon:controlsIcon userInfo:nil] autorelease]];+ unlink("/tmp/virtual-mac-vm-active");+ gMouseLocation = CGPointMake(CGRectGetMidX(inputView.bounds),+ CGRectGetMidY(inputView.bounds));+ installGCMouse();+ startHealthMonitor();+ startControlMonitor();+ printf("[VirtualMac] VM picker ready inputWindow=%p\n", inputView.window);+ requestMicrophoneAccess(^{+ NSString *controlPath = @"/tmp/vz-autoboot-path";+ NSString *autoBootPath = [NSString+ stringWithContentsOfFile:controlPath+ encoding:NSUTF8StringEncoding error:nil];+ autoBootPath = [autoBootPath+ stringByTrimmingCharactersInSet:+ NSCharacterSet.whitespaceAndNewlineCharacterSet];+ NSString *persistentAutoBoot = [VZAppSettings.sharedSettings+ stringForKey:VZAutoBootVMPathKey];+ if (persistentAutoBoot.length && !VZIsValidVMBundle(persistentAutoBoot)) {+ NSString *identifier = [VZAppSettings.sharedSettings+ stringForKey:VZAutoBootVMIdentifierKey];+ persistentAutoBoot = nil;+ for (NSDictionary *machine in VZDiscoverVirtualMachines()) {+ if (identifier.length && [VZVMStableIdentifier(machine[@"path"])+ isEqualToString:identifier]) {+ persistentAutoBoot = machine[@"path"];+ [VZAppSettings.sharedSettings setString:persistentAutoBoot+ forKey:VZAutoBootVMPathKey];+ break;+ }+ }+ if (!persistentAutoBoot) {+ printf("[VirtualMac] clearing missing auto boot VM\n");+ [VZAppSettings.sharedSettings setString:nil forKey:VZAutoBootVMPathKey];+ [VZAppSettings.sharedSettings setString:nil forKey:VZAutoBootVMIdentifierKey];+ }+ }+ if (!autoBootPath.length && !bypassAutoBoot)+ autoBootPath = persistentAutoBoot;+ if (autoBootPath.length && VZIsValidVMBundle(autoBootPath)) {+ unlink(controlPath.fileSystemRepresentation);+ [NSUserDefaults.standardUserDefaults setObject:autoBootPath+ forKey:@"VZSelectedVMPath"];+ printf("[VirtualMac] one-shot auto boot path=%s\n",+ autoBootPath.UTF8String);+ controller.activeVMBundlePath = autoBootPath;+ [controller activateVMDisplay:YES];+ startVirtualMachine(controller.view, controller, autoBootPath,+ VZVMOptionsForBundle(autoBootPath));+ } else {+ if ([[NSFileManager defaultManager]+ fileExistsAtPath:controlPath]) {+ printf("[VirtualMac] rejected one-shot auto boot path=%s\n",+ autoBootPath.UTF8String ?: "(unreadable)");+ unlink(controlPath.fileSystemRepresentation);+ }+ [controller presentVMLibrary];+ // Reproducible on-device integration path: a root-side test script+ // can request one real UIKit installation after launching the app.+ // The normal library, visible progress alert, polling timer, and+ // completion handling are all used; this is not a headless helper.+ NSString *requestPath = [VZVMSupportPath()+ stringByAppendingPathComponent:@".visible-install-request"];+ NSString *request = [NSString+ stringWithContentsOfFile:requestPath+ encoding:NSUTF8StringEncoding error:nil];+ NSArray *lines = [request componentsSeparatedByCharactersInSet:+ NSCharacterSet.newlineCharacterSet];+ NSString *installName = lines.count > 0 ? lines[0] : @"";+ NSString *installPath = lines.count > 1 ? lines[1] : @"";+ BOOL validRequest = installName.length && installPath.length &&+ [installName rangeOfString:@"/"].location == NSNotFound &&+ [installPath hasPrefix:[VZRestoreImagesPath()+ stringByAppendingString:@"/"]] &&+ [NSFileManager.defaultManager fileExistsAtPath:installPath];+ if (request.length) {+ unlink(requestPath.fileSystemRepresentation);+ if (validRequest) {+ printf("[VirtualMac] visible installation request name=%s ipsw=%s\n",+ installName.UTF8String, installPath.UTF8String);+ NSMutableDictionary *options = [NSMutableDictionary+ dictionaryWithDictionary:VZVMDefaultOptions()];+ if (VZRestoreImageUsesMontereyProfile(installPath)) {+ options[@"KeyboardDevice"] = @"USBKeyboard";+ options[@"PointingDevice"] = @"USBMouse";+ }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,+ (int64_t)(0.75 * NSEC_PER_SEC)),+ dispatch_get_main_queue(), ^{+ VZVMLibraryViewController *library = (id)+ controller.libraryNavigationController+ .viewControllers.firstObject;+ [controller vmLibrary:library+ installRestoreImageAtURL:+ [NSURL fileURLWithPath:installPath]+ name:installName options:options];+ });+ } else {+ printf("[VirtualMac] rejected visible installation request=%s\n",+ request.UTF8String);+ }+ }+ }+ });+ return YES;+}++- (void)applicationWillResignActive:(UIApplication *)application+{+ (void)application;+ resetPointerSession(YES);+}++- (void)applicationDidBecomeActive:(UIApplication *)application+{+ (void)application;+ resetPointerSession(YES);+ if (gInputView) {+ for (id interaction in gInputView.interactions)+ if ([interaction respondsToSelector:@selector(invalidate)])+ [interaction invalidate];+ VZViewController *controller = (id)self.window.rootViewController;+ if (controller.isVMDisplayActive && GCKeyboard.coalescedKeyboard)+ [gInputView becomeFirstResponder];+ }+}++- (void)application:(UIApplication *)application+ performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem+ completionHandler:(void (^)(BOOL succeeded))completionHandler+{+ (void)application;+ VZViewController *controller = (id)self.window.rootViewController;+ BOOL handled = [shortcutItem.type isEqualToString:@"com.mac.virtual.show-library"] ||+ [shortcutItem.type isEqualToString:@"com.mac.virtual.show-controls"];+ if ([shortcutItem.type isEqualToString:@"com.mac.virtual.show-library"]) {+ [controller presentVMLibrary];+ } else if ([shortcutItem.type isEqualToString:@"com.mac.virtual.show-controls"]) {+ gHUDHiddenForBoot = NO;+ gHUDForcedVisibleForBoot = YES;+ [controller updateHUDVisibility];+ }+ if (completionHandler) completionHandler(handled);+}++- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url+ options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options+{+ (void)application; (void)options;+ if (![url.scheme isEqualToString:@"virtualmac"]) return NO;+ NSString *action = url.host.lowercaseString;+ // Developer-only visible UI checks for the touch keyboard. Keep these+ // outside libraryController so exercising them does not hide the running+ // virtual Mac first.+ if ([action isEqualToString:@"keyboard-show"]) {+ gSoftwareKeyboardRequested = YES;+ return gInputView && [gInputView becomeFirstResponder];+ }+ if ([action isEqualToString:@"keyboard-hide"]) {+ gSoftwareKeyboardRequested = NO;+ return gInputView && [gInputView resignFirstResponder];+ }+ VZVMLibraryViewController *library = [self libraryController];+ if ([action isEqualToString:@"new"])+ [library presentNewVMFlow];+ else if ([action isEqualToString:@"settings"])+ [library presentSettings];+ else if ([action isEqualToString:@"library"])+ ;+ else+ return NO;+ return YES;+}++- (void)dealloc+{+ [_window release];+ [super dealloc];+}+@end++int main(int argc, char **argv) {+ @autoreleasepool {+ return UIApplicationMain(argc, argv,+ nil,+ NSStringFromClass([VirtualMacAppDelegate class]));+ }+}diff --git a/VirtualMac/vz/host/VirtualMacControl-Info.plist b/VirtualMac/vz/host/VirtualMacControl-Info.plistnew file mode 100644index 0000000..620ca69--- /dev/null+++ b/VirtualMac/vz/host/VirtualMacControl-Info.plist@@ -0,0 +1,38 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>Virtual Mac Control</string>+ <key>CFBundleExecutable</key>+ <string>VirtualMacControl</string>+ <key>CFBundleIdentifier</key>+ <string>com.mac.virtual.control</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Virtual Mac Control</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>LSMinimumSystemVersion</key>+ <string>13.0</string>+ <key>NSHighResolutionCapable</key>+ <true/>+ <key>LSEnvironment</key>+ <dict>+ <key>VZ_GUI</key>+ <string>1</string>+ <key>VZ_LOG_PATH</key>+ <string>/tmp/VirtualMac-control.log</string>+ <key>VZ_RUN_SECONDS</key>+ <string>1800</string>+ </dict>+</dict>+</plist>diff --git a/VirtualMac/vz/host/VirtualMacLaunchScreen.storyboard b/VirtualMac/vz/host/VirtualMacLaunchScreen.storyboardnew file mode 100644index 0000000..4a991a3--- /dev/null+++ b/VirtualMac/vz/host/VirtualMacLaunchScreen.storyboard@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="UTF-8"?>+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="23094" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="launch-controller">+ <device id="ipad12_9" orientation="landscape" layout="fullscreen" appearance="light"/>+ <dependencies>+ <deployment identifier="iOS"/>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="23084"/>+ <capability name="Named colors" minToolsVersion="9.0"/>+ <capability name="Safe area layout guides" minToolsVersion="9.0"/>+ <capability name="System colors in document resources" minToolsVersion="11.0"/>+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>+ </dependencies>+ <scenes>+ <scene sceneID="launch-scene">+ <objects>+ <viewController id="launch-controller" sceneMemberID="viewController">+ <view key="view" contentMode="scaleToFill" id="launch-view">+ <rect key="frame" x="0.0" y="0.0" width="1366" height="1024"/>+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>+ <viewLayoutGuide key="safeArea" id="launch-safe-area"/>+ <color key="backgroundColor" red="0.94901960784313721" green="0.94901960784313721" blue="0.96862745098039216" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>+ </view>+ </viewController>+ <placeholder placeholderIdentifier="IBFirstResponder" id="launch-first-responder" userLabel="First Responder" sceneMemberID="firstResponder"/>+ </objects>+ </scene>+ </scenes>+</document>diff --git a/VirtualMac/vz/host/authorization_compat.c b/VirtualMac/vz/host/authorization_compat.cnew file mode 100644index 0000000..14b4b2f--- /dev/null+++ b/VirtualMac/vz/host/authorization_compat.c@@ -0,0 +1,139 @@+#include <stdint.h>+#include <stdio.h>+#include <string.h>+#include <unistd.h>+#include <dlfcn.h>+#include <CoreFoundation/CoreFoundation.h>++typedef int32_t OSStatus;+typedef void *AuthorizationRef;+typedef uint32_t AuthorizationFlags;+typedef unsigned char Boolean;++typedef Boolean (*SMJobSetEnabledFn)(CFStringRef domain,+ AuthorizationRef authorization,+ CFStringRef jobLabel,+ Boolean enabled,+ CFErrorRef *error);++extern Boolean SMJobSetEnabled(CFStringRef domain,+ AuthorizationRef authorization,+ CFStringRef jobLabel,+ Boolean enabled,+ CFErrorRef *error);++extern int memorystatus_control(uint32_t command, int32_t pid,+ uint32_t flags, void *buffer,+ size_t buffer_size);++__attribute__((constructor)) static void raiseInternetSharingMemoryLimit(void) {+ // iPadOS rootless launch daemons have a 6 MiB default jetsam limit.+ // Ventura's InternetSharing loads its desktop framework graph before main+ // and cannot even allocate its first dispatch queue within that budget.+ // XNU command 5 sets both active and inactive soft limits; flags are MiB.+ const uint32_t memoryStatusSetHighWaterMark = 5;+ int result = memorystatus_control(memoryStatusSetHighWaterMark,+ getpid(), 128, NULL, 0);+ dprintf(STDERR_FILENO,+ "AuthorizationCompat: set 128 MiB jetsam limit result=%d\n",+ result);++ typedef CFTypeRef (*SecTaskCreateFromSelfFn)(CFAllocatorRef);+ typedef CFTypeRef (*SecTaskCopyValueForEntitlementFn)(+ CFTypeRef, CFStringRef, CFErrorRef *);+ SecTaskCreateFromSelfFn createTask =+ (SecTaskCreateFromSelfFn)dlsym(RTLD_DEFAULT,+ "SecTaskCreateFromSelf");+ SecTaskCopyValueForEntitlementFn copyEntitlement =+ (SecTaskCopyValueForEntitlementFn)dlsym(+ RTLD_DEFAULT, "SecTaskCopyValueForEntitlement");+ if (createTask && copyEntitlement) {+ CFTypeRef task = createTask(kCFAllocatorDefault);+ CFTypeRef value = task ? copyEntitlement(+ task, CFSTR("com.apple.networking.ethernet.user-access"),+ NULL) : NULL;+ int granted = value && CFGetTypeID(value) == CFBooleanGetTypeID() &&+ CFBooleanGetValue((CFBooleanRef)value);+ dprintf(STDERR_FILENO,+ "AuthorizationCompat: ethernet entitlement=%d value=%p\n",+ granted, value);+ if (value)+ CFRelease(value);+ if (task)+ CFRelease(task);+ }+}++// InternetSharing runs as a root platform daemon on iPadOS. Desktop Security's+// Authorization Services entry points are absent there, while the daemon only+// uses them to establish and release its privileged launchd-operation context.+OSStatus AuthorizationCreate(const void *rights, const void *environment,+ AuthorizationFlags flags,+ AuthorizationRef *authorization) {+ (void)rights;+ (void)environment;+ (void)flags;+ if (authorization)+ *authorization = 0;+ return 0;+}++OSStatus AuthorizationFree(AuthorizationRef authorization,+ AuthorizationFlags flags) {+ (void)authorization;+ (void)flags;+ return 0;+}++// iPadOS redirects rootless launch daemons without an explicit System session+// into the foreground-user domain. InternetSharing must live there to reach+// MobileInternetSharing, but Ventura hard-codes kSMDomainSystemLaunchd when it+// enables bootpd. Remap only our private matching-helper label to the user+// domain; every other ServiceManagement operation is forwarded unchanged.+static Boolean compatSMJobSetEnabled(CFStringRef domain,+ AuthorizationRef authorization,+ CFStringRef jobLabel,+ Boolean enabled,+ CFErrorRef *error) {+ static SMJobSetEnabledFn realFunction;+ static const CFStringRef *userDomain;+ if (!realFunction || !userDomain) {+ void *serviceManagement = dlopen(+ "/System/Library/PrivateFrameworks/ServiceManagement.framework/ServiceManagement",+ RTLD_LAZY | RTLD_LOCAL);+ realFunction = serviceManagement ? (SMJobSetEnabledFn)dlsym(+ serviceManagement, "SMJobSetEnabled") : NULL;+ userDomain = serviceManagement ? (const CFStringRef *)dlsym(+ serviceManagement, "kSMDomainUserLaunchd") : NULL;+ // An interposed dlsym result must never recurse back into this shim.+ if ((void *)realFunction == (void *)&compatSMJobSetEnabled)+ realFunction = (SMJobSetEnabledFn)dlsym(+ RTLD_NEXT, "SMJobSetEnabled");+ dprintf(STDERR_FILENO,+ "AuthorizationCompat: resolved ServiceManagement "+ "function=%p user-domain=%p\n",+ realFunction, userDomain);+ }+ bool isMatchingBootpd = jobLabel &&+ CFEqual(jobLabel, CFSTR("vzi.apple.bootpd"));+ if (isMatchingBootpd && userDomain && *userDomain) {+ domain = *userDomain;+ dprintf(STDERR_FILENO,+ "AuthorizationCompat: bootpd launch domain -> user (%d)\n",+ enabled);+ }+ if (!realFunction) {+ dprintf(STDERR_FILENO,+ "AuthorizationCompat: SMJobSetEnabled unavailable\n");+ return 0;+ }+ return realFunction(domain, authorization, jobLabel, enabled, error);+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} interposeSMJobSetEnabled __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&compatSMJobSetEnabled,+ (const void *)&SMJobSetEnabled,+};diff --git a/VirtualMac/vz/host/coreservices_compat.c b/VirtualMac/vz/host/coreservices_compat.cnew file mode 100644index 0000000..a335c16--- /dev/null+++ b/VirtualMac/vz/host/coreservices_compat.c@@ -0,0 +1,23 @@+#include <math.h>++/* Legacy Carbon assertion hook; MobileDevice uses it only on failed checks. */+void DebugAssert(void *componentSignature, unsigned long options,+ const char *assertionString, const char *exceptionLabelString,+ const char *errorString, const char *fileName,+ long lineNumber, void *value)+{+ (void)componentSignature;+ (void)options;+ (void)assertionString;+ (void)exceptionLabelString;+ (void)errorString;+ (void)fileName;+ (void)lineNumber;+ (void)value;+}++/* macOS CoreServices re-exports this libSystem math entry point; iPadOS does not. */+double log2(double value)+{+ return log(value) / 0.69314718055994530942;+}diff --git a/VirtualMac/vz/host/coreutils_compat.c b/VirtualMac/vz/host/coreutils_compat.cnew file mode 100644index 0000000..fe491da--- /dev/null+++ b/VirtualMac/vz/host/coreutils_compat.c@@ -0,0 +1,23 @@+#include <stddef.h>+#include <stdlib.h>+#include <string.h>++/*+ * Ventura's MobileDevice binds strndup to CoreUtils rather than libSystem.+ * iPadOS provides strndup in libSystem but does not re-export it from its+ * CoreUtils image. This compatibility image occupies MobileDevice's+ * CoreUtils dependency ordinal, re-exports native CoreUtils, and supplies the+ * one missing entry point.+ */+char *strndup(const char *source, size_t maximumLength)+{+ const char *end = memchr(source, '\0', maximumLength);+ size_t length = end ? (size_t)(end - source) : maximumLength;+ char *copy = malloc(length + 1);+ if (copy == NULL) {+ return NULL;+ }+ memcpy(copy, source, length);+ copy[length] = '\0';+ return copy;+}diff --git a/VirtualMac/vz/host/crashreporter_compat.c b/VirtualMac/vz/host/crashreporter_compat.cnew file mode 100644index 0000000..6d8e64f--- /dev/null+++ b/VirtualMac/vz/host/crashreporter_compat.c@@ -0,0 +1,7 @@+#include <stdbool.h>++/* MobileDevice only consults this policy bit while preparing diagnostics. */+bool CRIsAutoSubmitEnabled(void)+{+ return false;+}diff --git a/VirtualMac/vz/host/diskimages_compat.c b/VirtualMac/vz/host/diskimages_compat.cnew file mode 100644index 0000000..f35a93e--- /dev/null+++ b/VirtualMac/vz/host/diskimages_compat.c@@ -0,0 +1,11 @@+#include <stdbool.h>++/*+ * iPadOS 16 has DIInitialize and the attach APIs used by MobileDevice, but it+ * lacks macOS's DIIsInitialized query. Returning false asks MobileDevice to+ * run the native idempotent initializer before use.+ */+bool DIIsInitialized(void)+{+ return false;+}diff --git a/VirtualMac/vz/host/installation_usb_shim.m b/VirtualMac/vz/host/installation_usb_shim.mnew file mode 100644index 0000000..1131e31--- /dev/null+++ b/VirtualMac/vz/host/installation_usb_shim.m@@ -0,0 +1,1846 @@+// Publish VMM's real AVP-backed restore USB device to MobileDevice without+// requiring macOS's AppleUSBUserHCIResources kernel service. MobileDevice+// continues to use iPadOS's native IOUSBLib; only IOKit registry/user-client+// calls for our synthetic handles are redirected to the VMM socket bridge.++#include <CoreFoundation/CoreFoundation.h>+#include <CoreFoundation/CFPlugInCOM.h>+#include <IOKit/IOKitLib.h>+#include <dispatch/dispatch.h>+#include <dlfcn.h>+#include <errno.h>+#include <pthread.h>+#include <stdarg.h>+#include <stdbool.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/socket.h>+#include <sys/un.h>+#include <unistd.h>++#include "usb_restore_bridge.h"++#define FAKE_USB_DEVICE_SERVICE_BASE ((io_service_t)0x766d2000)+#define FAKE_USB_DEVICE_SERVICE_LIMIT ((io_service_t)0x766d2100)+#define FAKE_USB_INTERFACE_SERVICE ((io_service_t)0x766d0002)+#define FAKE_USB_ITERATOR_BASE ((io_iterator_t)0x766d0100)+#define FAKE_USB_INTERFACE_ITERATOR ((io_iterator_t)0x766d0200)+#define FAKE_USB_CONNECTION_BASE ((io_connect_t)0x766d1000)+#define FAKE_USB_CONNECTION_LIMIT ((io_connect_t)0x766d1100)+#define FAKE_USB_INTERFACE_CONNECTION ((io_connect_t)0x766d1200)+#define FAKE_USB_POWER_CONNECTION ((io_connect_t)0x766d1300)+#define FAKE_USB_POWER_NOTIFIER ((io_object_t)0x766d1301)+#define FAKE_USB_MAX_NOTIFICATIONS 64+#define FAKE_USB_MAX_PORTS 8++typedef struct IOCFPlugInInterfaceStruct {+ IUNKNOWN_C_GUTS;+ UInt16 version;+ UInt16 revision;+ IOReturn (*Probe)(void *, CFDictionaryRef, io_service_t, SInt32 *);+ IOReturn (*Start)(void *, CFDictionaryRef, io_service_t);+ IOReturn (*Stop)(void *);+} IOCFPlugInInterface;++extern kern_return_t IOCreatePlugInInterfaceForService(+ io_service_t service, CFUUIDRef plugin_type, CFUUIDRef interface_type,+ IOCFPlugInInterface ***interface, SInt32 *score);+extern io_connect_t IORegisterForSystemPower(+ void *refcon, IONotificationPortRef *notify_port,+ IOServiceInterestCallback callback, io_object_t *notifier);+extern IOReturn IOAllowPowerChange(io_connect_t connection,+ intptr_t notification_id);++typedef struct {+ bool used;+ bool delivered;+ bool termination;+ bool interface;+ uint16_t product_id;+ uint32_t observed_generation;+ io_service_t delivered_service;+ IOServiceMatchingCallback callback;+ void *refcon;+ dispatch_queue_t callback_queue;+} fake_usb_notification_t;++typedef struct {+ IONotificationPortRef port;+ dispatch_queue_t queue;+} fake_usb_port_queue_t;++static fake_usb_notification_t fake_usb_notifications[+ FAKE_USB_MAX_NOTIFICATIONS];+static fake_usb_port_queue_t fake_usb_port_queues[FAKE_USB_MAX_PORTS];+static dispatch_queue_t fake_usb_notification_queue;+static dispatch_queue_t fake_usb_bulk_input_queue;+static dispatch_queue_t fake_usb_bulk_output_queue;+static bool fake_usb_notification_poller_started;+static bool fake_usb_interface_iterator_ready;+static uint32_t fake_usb_logged_configuration_generation;+static uint8_t fake_usb_selected_interface_number;+static uint8_t fake_usb_selected_interface_alternate;+static pthread_mutex_t fake_usb_configuration_lock =+ PTHREAD_MUTEX_INITIALIZER;+static uint32_t fake_usb_configured_generation;+static uint8_t fake_usb_recovery_dfu_recipient_mode;+static uint8_t fake_usb_pipe_endpoints[256];++static void usb_shim_log(const char *format, ...) {+ FILE *file = fopen("/tmp/installation-usb.log", "a");+ if (!file)+ return;+ va_list arguments;+ va_start(arguments, format);+ fprintf(file, "[installation-usb] pid=%d ", getpid());+ vfprintf(file, format, arguments);+ fputc('\n', file);+ va_end(arguments);+ fclose(file);+}++static bool usb_shim_trace_transfers(void) {+ const char *value = getenv("INSTALL_USB_TRACE_TRANSFERS");+ return value && value[0] != '\0' && strcmp(value, "0") != 0;+}++static void usb_shim_log_cf(const char *label, CFTypeRef object) {+ if (!object)+ return;+ CFStringRef description = CFCopyDescription(object);+ if (!description)+ return;+ char text[4096] = {0};+ if (CFStringGetCString(description, text, sizeof(text),+ kCFStringEncodingUTF8))+ usb_shim_log("%s %s", label, text);+ CFRelease(description);+}++static void usb_shim_log_descriptor(uint16_t value, const void *data,+ uint32_t length) {+ if ((value >> 8) != 3 || !data || length < 2)+ return;+ const uint8_t *bytes = data;+ char text[512];+ size_t used = 0;+ for (uint32_t index = 2; index + 1 < length && used + 2 < sizeof(text);+ index += 2) {+ uint16_t character = (uint16_t)bytes[index] |+ ((uint16_t)bytes[index + 1] << 8);+ text[used++] = character >= 0x20 && character <= 0x7e+ ? (char)character : '?';+ }+ text[used] = '\0';+ usb_shim_log("real USB string descriptor index=%u length=%u text=%s",+ value & 0xff, length, text);+}++static bool usb_read_full(int fd, void *buffer, size_t length) {+ uint8_t *bytes = buffer;+ while (length) {+ ssize_t count = read(fd, bytes, length);+ if (count == 0)+ return false;+ if (count < 0) {+ if (errno == EINTR)+ continue;+ return false;+ }+ bytes += count;+ length -= (size_t)count;+ }+ return true;+}++static bool usb_write_full(int fd, const void *buffer, size_t length) {+ const uint8_t *bytes = buffer;+ while (length) {+ ssize_t count = write(fd, bytes, length);+ if (count < 0) {+ if (errno == EINTR)+ continue;+ return false;+ }+ bytes += count;+ length -= (size_t)count;+ }+ return true;+}++static int usb_bridge_request(+ struct vz_usb_bridge_request *request, const void *output_payload,+ void *input_payload, uint32_t input_capacity,+ struct vz_usb_bridge_response *response) {+ struct sockaddr_un address = { .sun_family = AF_UNIX };+ strlcpy(address.sun_path, VZ_USB_BRIDGE_SOCKET,+ sizeof(address.sun_path));+ int socket_fd = -1;+ int error = 0;+ uint32_t retry_ms = request->timeout_ms;+ if (!retry_ms || retry_ms > 5000)+ retry_ms = 5000;+ for (uint32_t elapsed_ms = 0;; elapsed_ms++) {+ socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);+ if (socket_fd < 0)+ return errno;+ if (connect(socket_fd, (struct sockaddr *)&address,+ sizeof(address)) == 0)+ break;+ error = errno;+ close(socket_fd);+ socket_fd = -1;+ bool transient = error == ECONNREFUSED || error == EAGAIN ||+ error == ENOENT;+ if (!transient || elapsed_ms >= retry_ms)+ return error;+ usleep(1000);+ }+ request->magic = VZ_USB_BRIDGE_MAGIC;+ request->version = VZ_USB_BRIDGE_VERSION;+ if (!usb_write_full(socket_fd, request, sizeof(*request)) ||+ (request->payload_length &&+ !usb_write_full(socket_fd, output_payload,+ request->payload_length)) ||+ !usb_read_full(socket_fd, response, sizeof(*response)) ||+ response->magic != VZ_USB_BRIDGE_MAGIC) {+ close(socket_fd);+ return EIO;+ }+ if (response->payload_length) {+ if (response->payload_length > input_capacity ||+ !usb_read_full(socket_fd, input_payload,+ response->payload_length)) {+ close(socket_fd);+ return EMSGSIZE;+ }+ }+ close(socket_fd);+ return response->status;+}++static bool usb_bridge_get_state(struct vz_usb_bridge_response *response) {+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_GET_STATE,+ .timeout_ms = 1000,+ };+ memset(response, 0, sizeof(*response));+ int result = usb_bridge_request(&request, NULL, NULL, 0, response);+ return response->magic == VZ_USB_BRIDGE_MAGIC &&+ (result == 0 || result == ENODEV);+}++static bool usb_bridge_ready(void) {+ struct vz_usb_bridge_response response = {0};+ return usb_bridge_get_state(&response) && response.ready &&+ response.vendor_id == 0x05ac;+}++static uint32_t usb_bridge_read_descriptor(uint16_t value, uint16_t index,+ void *buffer,+ uint32_t capacity) {+ if (capacity > UINT16_MAX)+ capacity = UINT16_MAX;+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_CONTROL,+ .timeout_ms = 30000,+ .request_type = 0x80,+ .request = 6,+ .value = value,+ .index = index,+ .length = (uint16_t)capacity,+ };+ struct vz_usb_bridge_response response = {0};+ int result = usb_bridge_request(&request, NULL, buffer, capacity,+ &response);+ return result ? 0 : response.payload_length;+}++static uint32_t usb_bridge_read_interface_configuration(void *buffer,+ uint32_t capacity) {+ uint8_t raw[4096] = {0};+ uint32_t raw_length = usb_bridge_read_descriptor(+ 0x0200, 0, raw, sizeof(raw));+ if (!raw_length)+ return 0;++ struct vz_usb_bridge_response state = {0};+ usb_bridge_get_state(&state);+ uint32_t insertion = 0;+ bool selected = false;+ bool has_functional_descriptor = false;+ for (uint32_t offset = 0; offset + 2 <= raw_length;) {+ uint8_t descriptor_length = raw[offset];+ if (descriptor_length < 2 || offset + descriptor_length > raw_length)+ break;+ uint8_t descriptor_type = raw[offset + 1];+ if (descriptor_type == 4 && descriptor_length >= 9) {+ if (selected)+ break;+ selected = raw[offset + 2] == fake_usb_selected_interface_number &&+ raw[offset + 3] == fake_usb_selected_interface_alternate;+ if (selected)+ insertion = offset + descriptor_length;+ } else if (selected && descriptor_type == 0x21) {+ has_functional_descriptor = true;+ }+ offset += descriptor_length;+ }++ // The recovery personality's wire descriptor identifies its transfer+ // interface as DFU class but omits the DFU functional descriptor.+ // IOUSBHost publishes that host-side metadata to IOUSBLib on macOS;+ // MobileRestore uses it to obtain the transfer size before opening the+ // real bulk endpoint. Recreate only that registry-side view, leaving all+ // control transfers and the physical descriptor stream untouched.+ static const uint8_t functional[] = { 7, 0x21, 1, 10, 0, 0, 8 };+ uint8_t hosted[sizeof(raw) + sizeof(functional)] = {0};+ const uint8_t *source = raw;+ uint32_t source_length = raw_length;+ bool should_insert = state.product_id == 0x1281 && selected &&+ !has_functional_descriptor && insertion &&+ raw_length + sizeof(functional) <= sizeof(hosted);+ if (should_insert) {+ memcpy(hosted, raw, insertion);+ memcpy(hosted + insertion, functional, sizeof(functional));+ memcpy(hosted + insertion + sizeof(functional), raw + insertion,+ raw_length - insertion);+ source = hosted;+ source_length = raw_length + sizeof(functional);+ hosted[2] = (uint8_t)source_length;+ hosted[3] = (uint8_t)(source_length >> 8);+ }+ uint32_t copied = source_length < capacity ? source_length : capacity;+ memcpy(buffer, source, copied);+ usb_shim_log("interface host configuration raw=%u hosted=%u "+ "inserted-dfu=%d selected=%u/%u", raw_length,+ source_length, should_insert,+ fake_usb_selected_interface_number,+ fake_usb_selected_interface_alternate);+ return copied;+}++static int usb_bridge_create_active_endpoints(void);++static int usb_bridge_set_configuration(uint8_t configuration) {+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_CONTROL,+ .timeout_ms = 30000,+ .request_type = 0x00,+ .request = 9,+ .value = configuration,+ };+ struct vz_usb_bridge_response response = {0};+ return usb_bridge_request(&request, NULL, NULL, 0, &response);+}++static int usb_bridge_create_endpoint(const uint8_t *descriptor) {+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_CREATE_ENDPOINT,+ .payload_length = 7,+ .timeout_ms = 30000,+ .endpoint = descriptor[2],+ };+ struct vz_usb_bridge_response response = {0};+ return usb_bridge_request(&request, descriptor, NULL, 0, &response);+}++static int usb_bridge_create_active_endpoints(void) {+ uint8_t configuration[4096] = {0};+ uint32_t length = usb_bridge_read_descriptor(+ 0x0200, 0, configuration, sizeof(configuration));+ bool active = false;+ int result = 0;+ for (uint32_t offset = 0; offset + 2 <= length;) {+ uint8_t descriptor_length = configuration[offset];+ if (descriptor_length < 2 || offset + descriptor_length > length)+ break;+ uint8_t descriptor_type = configuration[offset + 1];+ if (descriptor_type == 4 && descriptor_length >= 9) {+ uint8_t number = configuration[offset + 2];+ uint8_t alternate = configuration[offset + 3];+ active = alternate == 0 ||+ (number == fake_usb_selected_interface_number &&+ alternate == fake_usb_selected_interface_alternate);+ } else if (active && descriptor_type == 5 &&+ descriptor_length >= 7) {+ result = usb_bridge_create_endpoint(configuration + offset);+ usb_shim_log("created real USB endpoint=0x%02x -> %d",+ configuration[offset + 2], result);+ if (result)+ return result;+ }+ offset += descriptor_length;+ }+ return result;+}++static bool usb_bridge_endpoint_for_pipe(uint8_t wanted_pipe,+ uint8_t *endpoint) {+ if (fake_usb_pipe_endpoints[wanted_pipe]) {+ *endpoint = fake_usb_pipe_endpoints[wanted_pipe];+ return true;+ }+ uint8_t configuration[4096] = {0};+ uint32_t configuration_length = usb_bridge_read_descriptor(+ 0x0200, 0, configuration, sizeof(configuration));+ uint8_t pipe = 0;+ bool selected = false;+ for (uint32_t offset = 0; offset + 2 <= configuration_length;) {+ uint8_t descriptor_length = configuration[offset];+ if (descriptor_length < 2 ||+ offset + descriptor_length > configuration_length)+ break;+ uint8_t descriptor_type = configuration[offset + 1];+ if (descriptor_type == 4 && descriptor_length >= 9) {+ selected = configuration[offset + 2] ==+ fake_usb_selected_interface_number &&+ configuration[offset + 3] ==+ fake_usb_selected_interface_alternate;+ pipe = 0;+ } else if (selected && descriptor_type == 5 &&+ descriptor_length >= 7) {+ pipe++;+ if (pipe == wanted_pipe) {+ *endpoint = configuration[offset + 2];+ fake_usb_pipe_endpoints[wanted_pipe] = *endpoint;+ return true;+ }+ }+ offset += descriptor_length;+ }+ return false;+}++static int usb_bridge_bulk_transfer(uint8_t endpoint, void *buffer,+ uint32_t length, uint32_t timeout_ms,+ uint32_t *actual_length) {+ bool input = (endpoint & 0x80U) != 0;+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_BULK,+ .payload_length = input ? 0 : length,+ .timeout_ms = timeout_ms ?: 30000,+ .endpoint = endpoint,+ .transfer_length = length,+ };+ struct vz_usb_bridge_response response = {0};+ int result = usb_bridge_request(+ &request, input ? NULL : buffer, input ? buffer : NULL,+ input ? length : 0, &response);+ if (!result && actual_length)+ *actual_length = input ? response.payload_length : length;+ if (result || usb_shim_trace_transfers())+ usb_shim_log("bulk endpoint=0x%02x direction=%s length=%u -> %d "+ "actual=%u", endpoint, input ? "in" : "out", length,+ result, response.payload_length);+ return result;+}++static bool usb_bridge_configure_generation(uint32_t generation) {+ pthread_mutex_lock(&fake_usb_configuration_lock);+ if (fake_usb_configured_generation == generation) {+ pthread_mutex_unlock(&fake_usb_configuration_lock);+ return true;+ }+ uint8_t descriptor[9] = {0};+ uint32_t actual = usb_bridge_read_descriptor(+ 0x0200, 0, descriptor, sizeof(descriptor));+ uint8_t configuration = actual >= sizeof(descriptor) &&+ descriptor[1] == 2+ ? descriptor[5] : 1;+ int result = usb_bridge_set_configuration(configuration);+ if (!result)+ result = usb_bridge_create_active_endpoints();+ if (!result)+ fake_usb_configured_generation = generation;+ pthread_mutex_unlock(&fake_usb_configuration_lock);+ usb_shim_log("configured real USB generation=%u value=%u -> %d",+ generation, configuration, result);+ return result == 0;+}++static CFStringRef usb_bridge_copy_string_descriptor(uint8_t index) {+ uint8_t descriptor[255] = {0};+ uint32_t actual = usb_bridge_read_descriptor(+ (uint16_t)(0x0300U | index), 0x0409, descriptor,+ sizeof(descriptor));+ if (actual < 2 || descriptor[1] != 3)+ return NULL;+ uint32_t length = descriptor[0];+ if (length > actual)+ length = actual;+ if (length < 2)+ return NULL;+ CFStringRef string = CFStringCreateWithBytes(+ kCFAllocatorDefault, descriptor + 2, (CFIndex)(length - 2),+ kCFStringEncodingUTF16LE, false);+ usb_shim_log_descriptor((uint16_t)(0x0300U | index), descriptor,+ length);+ return string;+}++static bool is_fake_usb_service(io_object_t object) {+ return (object >= FAKE_USB_DEVICE_SERVICE_BASE &&+ object < FAKE_USB_DEVICE_SERVICE_LIMIT) ||+ object == FAKE_USB_INTERFACE_SERVICE;+}++static io_service_t fake_usb_device_service(uint32_t generation) {+ return FAKE_USB_DEVICE_SERVICE_BASE + (generation & 0xffU);+}++static uint32_t fake_usb_service_generation(io_object_t object) {+ return object >= FAKE_USB_DEVICE_SERVICE_BASE &&+ object < FAKE_USB_DEVICE_SERVICE_LIMIT+ ? object - FAKE_USB_DEVICE_SERVICE_BASE : 0;+}++static bool is_fake_usb_device_connection(io_connect_t connection) {+ return connection > FAKE_USB_CONNECTION_BASE &&+ connection < FAKE_USB_CONNECTION_LIMIT;+}++static uint32_t fake_usb_connection_generation(io_connect_t connection) {+ return is_fake_usb_device_connection(connection)+ ? connection - FAKE_USB_CONNECTION_BASE : 0;+}++static bool fake_usb_connection_is_current(io_connect_t connection) {+ struct vz_usb_bridge_response state = {0};+ uint32_t generation = fake_usb_connection_generation(connection);+ bool current = generation && usb_bridge_get_state(&state) && state.ready &&+ state.device_generation == generation;+ if (!current)+ usb_shim_log("rejected stale USB device connection=0x%x "+ "generation=%u current=%u ready=%u", connection,+ generation, state.device_generation, state.ready);+ return current;+}++static int notification_index(io_iterator_t iterator) {+ uint32_t value = (uint32_t)iterator;+ if (value < FAKE_USB_ITERATOR_BASE ||+ value >= FAKE_USB_ITERATOR_BASE + FAKE_USB_MAX_NOTIFICATIONS)+ return -1;+ return (int)(value - FAKE_USB_ITERATOR_BASE);+}++static bool matching_wants_usb(CFDictionaryRef matching,+ uint16_t *wanted_product,+ bool *wanted_interface) {+ if (!matching)+ return false;+ CFTypeRef value = CFDictionaryGetValue(+ matching, CFSTR("IOProviderClass"));+ if (!value || CFGetTypeID(value) != CFStringGetTypeID())+ return false;+ bool usb_device_class =+ CFStringCompare(value, CFSTR("IOUSBDevice"), 0) ==+ kCFCompareEqualTo ||+ CFStringCompare(value, CFSTR("IOUSBHostDevice"), 0) ==+ kCFCompareEqualTo;+ bool usb_interface_class =+ CFStringCompare(value, CFSTR("IOUSBInterface"), 0) ==+ kCFCompareEqualTo ||+ CFStringCompare(value, CFSTR("IOUSBHostInterface"), 0) ==+ kCFCompareEqualTo;+ if (!usb_device_class && !usb_interface_class)+ return false;+ CFTypeRef product = CFDictionaryGetValue(matching, CFSTR("idProduct"));+ if (!product) {+ CFTypeRef property_match = CFDictionaryGetValue(+ matching, CFSTR("IOPropertyMatch"));+ if (property_match &&+ CFGetTypeID(property_match) == CFDictionaryGetTypeID())+ product = CFDictionaryGetValue(+ (CFDictionaryRef)property_match, CFSTR("idProduct"));+ }+ int32_t product_id = 0x12ac;+ bool product_matches = usb_interface_class;+ if (product && CFGetTypeID(product) == CFNumberGetTypeID() &&+ CFNumberGetValue((CFNumberRef)product, kCFNumberSInt32Type,+ &product_id) && product_id >= 0 &&+ product_id <= UINT16_MAX) {+ product_matches = true;+ } else if (usb_device_class) {+ CFTypeRef products = CFDictionaryGetValue(+ matching, CFSTR("idProductArray"));+ if (products && CFGetTypeID(products) == CFArrayGetTypeID()) {+ CFIndex count = CFArrayGetCount((CFArrayRef)products);+ for (CFIndex index = 0; index < count; index++) {+ CFTypeRef item = CFArrayGetValueAtIndex(+ (CFArrayRef)products, index);+ int32_t candidate = 0;+ if (item && CFGetTypeID(item) == CFNumberGetTypeID() &&+ CFNumberGetValue((CFNumberRef)item,+ kCFNumberSInt32Type, &candidate) &&+ candidate == 0x12ac) {+ product_matches = true;+ break;+ }+ }+ }+ }+ if (!product_matches)+ return false;+ CFTypeRef vendor = CFDictionaryGetValue(matching, CFSTR("idVendor"));+ if (!vendor) {+ CFTypeRef property_match = CFDictionaryGetValue(+ matching, CFSTR("IOPropertyMatch"));+ if (property_match &&+ CFGetTypeID(property_match) == CFDictionaryGetTypeID())+ vendor = CFDictionaryGetValue(+ (CFDictionaryRef)property_match, CFSTR("idVendor"));+ }+ int32_t vendor_id = 0x05ac;+ if (vendor && (CFGetTypeID(vendor) != CFNumberGetTypeID() ||+ !CFNumberGetValue((CFNumberRef)vendor,+ kCFNumberSInt32Type, &vendor_id)))+ return false;+ if (vendor_id != 0x05ac)+ return false;+ if (usb_interface_class) {+ int32_t interface_class = 0;+ int32_t interface_subclass = 0;+ int32_t interface_protocol = 0;+ CFTypeRef class_value = CFDictionaryGetValue(+ matching, CFSTR("bInterfaceClass"));+ CFTypeRef subclass_value = CFDictionaryGetValue(+ matching, CFSTR("bInterfaceSubClass"));+ CFTypeRef protocol_value = CFDictionaryGetValue(+ matching, CFSTR("bInterfaceProtocol"));+ if (!class_value || !subclass_value || !protocol_value ||+ CFGetTypeID(class_value) != CFNumberGetTypeID() ||+ CFGetTypeID(subclass_value) != CFNumberGetTypeID() ||+ CFGetTypeID(protocol_value) != CFNumberGetTypeID() ||+ !CFNumberGetValue((CFNumberRef)class_value,+ kCFNumberSInt32Type, &interface_class) ||+ !CFNumberGetValue((CFNumberRef)subclass_value,+ kCFNumberSInt32Type, &interface_subclass) ||+ !CFNumberGetValue((CFNumberRef)protocol_value,+ kCFNumberSInt32Type, &interface_protocol) ||+ interface_class != 0xff || interface_subclass != 0xfe ||+ interface_protocol != 2)+ return false;+ }+ *wanted_product = usb_interface_class ? 0x12ac+ : (uint16_t)product_id;+ *wanted_interface = usb_interface_class;+ return true;+}++static CFMutableDictionaryRef fake_usb_properties(bool interface) {+ CFMutableDictionaryRef properties = CFDictionaryCreateMutable(+ kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks,+ &kCFTypeDictionaryValueCallBacks);+ struct vz_usb_bridge_response state = {0};+ usb_bridge_get_state(&state);+ uint8_t device[18] = {0};+ uint8_t configuration[4096] = {0};+ uint32_t device_length = usb_bridge_read_descriptor(+ 0x0100, 0, device, sizeof(device));+ uint32_t configuration_length = usb_bridge_read_descriptor(+ 0x0200, 0, configuration, sizeof(configuration));+ if (configuration_length &&+ fake_usb_logged_configuration_generation != state.device_generation) {+ char bytes[3 * 128 + 1] = {0};+ size_t cursor = 0;+ uint32_t shown = configuration_length < 128+ ? configuration_length : 128;+ for (uint32_t index = 0; index < shown; index++) {+ int count = snprintf(bytes + cursor, sizeof(bytes) - cursor,+ "%02x%s", configuration[index],+ index + 1 == shown ? "" : " ");+ if (count < 0 || (size_t)count >= sizeof(bytes) - cursor)+ break;+ cursor += (size_t)count;+ }+ usb_shim_log("real USB configuration generation=%u length=%u: %s",+ state.device_generation, configuration_length, bytes);+ fake_usb_logged_configuration_generation = state.device_generation;+ }+ uint16_t vendor_id = state.vendor_id ?: 0x05ac;+ uint16_t product_id = state.product_id;+ uint16_t bcd_usb = 0x0200;+ uint16_t bcd_device = 0;+ uint8_t device_class = 0;+ uint8_t device_subclass = 0;+ uint8_t device_protocol = 0;+ uint8_t max_packet_size = 64;+ uint8_t manufacturer_index = 2;+ uint8_t product_index = 3;+ uint8_t serial_index = 4;+ uint8_t configuration_count = 1;+ if (device_length >= sizeof(device) && device[1] == 1) {+ bcd_usb = (uint16_t)device[2] | ((uint16_t)device[3] << 8);+ device_class = device[4];+ device_subclass = device[5];+ device_protocol = device[6];+ max_packet_size = device[7];+ vendor_id = (uint16_t)device[8] | ((uint16_t)device[9] << 8);+ product_id = (uint16_t)device[10] | ((uint16_t)device[11] << 8);+ bcd_device = (uint16_t)device[12] | ((uint16_t)device[13] << 8);+ manufacturer_index = device[14];+ product_index = device[15];+ serial_index = device[16];+ configuration_count = device[17];+ }+ uint8_t interface_class = 0;+ uint8_t interface_subclass = 0;+ uint8_t interface_protocol = 0;+ uint8_t interface_number = 0;+ uint8_t alternate_setting = 0;+ uint8_t endpoint_count = 0;+ uint8_t interface_index = 0;+ for (uint32_t offset = 0; offset + 2 <= configuration_length;) {+ uint8_t descriptor_length = configuration[offset];+ if (descriptor_length < 2 || offset + descriptor_length >+ configuration_length)+ break;+ if (configuration[offset + 1] == 4 && descriptor_length >= 9 &&+ (!interface ||+ (configuration[offset + 2] ==+ fake_usb_selected_interface_number &&+ configuration[offset + 3] ==+ fake_usb_selected_interface_alternate))) {+ interface_number = configuration[offset + 2];+ alternate_setting = configuration[offset + 3];+ endpoint_count = configuration[offset + 4];+ interface_class = configuration[offset + 5];+ interface_subclass = configuration[offset + 6];+ interface_protocol = configuration[offset + 7];+ interface_index = configuration[offset + 8];+ break;+ }+ offset += descriptor_length;+ }+ struct { const char *key; int32_t value; } numbers[] = {+ { "locationID", (int32_t)0x80100000U },+ { "idVendor", vendor_id }, { "idProduct", product_id },+ { "bDeviceClass", device_class },+ { "bDeviceSubClass", device_subclass },+ { "bDeviceProtocol", device_protocol },+ { "bMaxPacketSize0", max_packet_size },+ { "bcdUSB", bcd_usb }, { "bcdDevice", bcd_device },+ { "iManufacturer", manufacturer_index },+ { "iProduct", product_index },+ { "iSerialNumber", serial_index },+ { "bNumConfigurations", configuration_count },+ { "kUSBAddress", state.device_address },+ { "USB Address", state.device_address },+ { "Device Speed", 3 }, { "kUSBCurrentConfiguration", 0 },+ };+ for (size_t index = 0; index < sizeof(numbers) / sizeof(numbers[0]);+ index++) {+ CFStringRef key = CFStringCreateWithCString(+ kCFAllocatorDefault, numbers[index].key,+ kCFStringEncodingUTF8);+ CFNumberRef number = CFNumberCreate(+ kCFAllocatorDefault, kCFNumberSInt32Type,+ &numbers[index].value);+ CFDictionarySetValue(properties, key, number);+ CFRelease(number);+ CFRelease(key);+ }+ CFStringRef vendor = usb_bridge_copy_string_descriptor(+ manufacturer_index);+ CFStringRef product = usb_bridge_copy_string_descriptor(product_index);+ CFStringRef serial = usb_bridge_copy_string_descriptor(serial_index);+ CFDictionarySetValue(properties, CFSTR("USB Product Name"),+ product ?: CFSTR("Apple Virtual Restore Device"));+ CFDictionarySetValue(properties, CFSTR("USB Vendor Name"),+ vendor ?: CFSTR("Apple Inc."));+ if (serial)+ CFDictionarySetValue(properties, CFSTR("USB Serial Number"), serial);+ if (vendor)+ CFRelease(vendor);+ if (product)+ CFRelease(product);+ if (serial)+ CFRelease(serial);+ CFDictionarySetValue(properties, CFSTR("IOClass"),+ interface ? CFSTR("IOUSBHostInterface")+ : CFSTR("IOUSBHostDevice"));+ if (interface) {+ struct { const char *key; int32_t value; } interface_numbers[] = {+ { "bInterfaceClass", interface_class },+ { "bInterfaceSubClass", interface_subclass },+ { "bInterfaceProtocol", interface_protocol },+ { "bInterfaceNumber", interface_number },+ { "bAlternateSetting", alternate_setting },+ { "bNumEndpoints", endpoint_count },+ { "iInterface", interface_index },+ };+ for (size_t index = 0;+ index < sizeof(interface_numbers) / sizeof(interface_numbers[0]);+ index++) {+ CFStringRef key = CFStringCreateWithCString(+ kCFAllocatorDefault, interface_numbers[index].key,+ kCFStringEncodingUTF8);+ CFNumberRef number = CFNumberCreate(+ kCFAllocatorDefault, kCFNumberSInt32Type,+ &interface_numbers[index].value);+ CFDictionarySetValue(properties, key, number);+ CFRelease(number);+ CFRelease(key);+ }+ }+ return properties;+}++static void fake_usb_deliver_notification(unsigned index) {+ if (index >= FAKE_USB_MAX_NOTIFICATIONS)+ return;+ fake_usb_notification_t *notification = &fake_usb_notifications[index];+ if (!notification->used || notification->delivered ||+ !notification->callback)+ return;+ notification->delivered = true;+ usb_shim_log("delivering %s notification %u product=0x%04x on "+ "queue=%s",+ notification->termination ? "termination" : "matched",+ index, notification->product_id,+ notification->callback_queue+ ? dispatch_queue_get_label(notification->callback_queue)+ : "(none)");+ notification->callback(notification->refcon,+ FAKE_USB_ITERATOR_BASE + index);+}++static void fake_usb_deliver_on_registered_queue(unsigned index) {+ dispatch_queue_t callback_queue =+ fake_usb_notifications[index].callback_queue;+ if (callback_queue) {+ dispatch_sync(callback_queue, ^{+ fake_usb_deliver_notification(index);+ });+ } else {+ dispatch_sync(dispatch_get_main_queue(), ^{+ fake_usb_deliver_notification(index);+ });+ }+}++static void fake_usb_deliver_prior_terminations(+ const struct vz_usb_bridge_response *state) {+ // IOKit publishes removal of the old personality before matching the+ // newly enumerated one. MobileRestore uses that ordering to retire its+ // DFU state machine before accepting iBoot recovery. Independent polling+ // workers used to race and deliver recovery first, which made the DFU+ // worker try to send iBEC with DFU requests to the recovery interface.+ for (unsigned index = 0; index < FAKE_USB_MAX_NOTIFICATIONS; index++) {+ fake_usb_notification_t *notification =+ &fake_usb_notifications[index];+ if (!notification->used || !notification->termination ||+ !notification->observed_generation)+ continue;+ bool still_matches = state->ready && state->vendor_id == 0x05ac &&+ state->product_id == notification->product_id &&+ state->device_generation ==+ notification->observed_generation;+ if (still_matches)+ continue;+ notification->delivered_service = fake_usb_device_service(+ notification->observed_generation);+ notification->observed_generation = 0;+ usb_shim_log("ordering termination %u product=0x%04x before "+ "generation=%u product=0x%04x", index,+ notification->product_id, state->device_generation,+ state->product_id);+ fake_usb_deliver_on_registered_queue(index);+ }+}++static void fake_usb_start_notification_poller(void) {+ if (__atomic_exchange_n(&fake_usb_notification_poller_started, true,+ __ATOMIC_ACQ_REL))+ return;+ dispatch_async(fake_usb_notification_queue, ^{+ const char *poll_text = getenv("INSTALL_USB_POLL_US");+ useconds_t poll_interval = poll_text+ ? (useconds_t)strtoul(poll_text, NULL, 0) : 250000;+ if (poll_interval < 1000)+ poll_interval = 1000;+ const char *enable_file = getenv("INSTALL_USB_ENABLE_FILE");+ while (enable_file && access(enable_file, F_OK) != 0)+ usleep(1000);+ for (;;) {+ struct vz_usb_bridge_response state = {0};+ bool have_state = usb_bridge_get_state(&state);+ for (unsigned index = 0; index < FAKE_USB_MAX_NOTIFICATIONS;+ index++) {+ fake_usb_notification_t *notification =+ &fake_usb_notifications[index];+ if (!notification->used)+ continue;+ bool matches = have_state && state.ready &&+ state.vendor_id == 0x05ac &&+ state.product_id == notification->product_id;+ bool should_deliver = false;+ if (!notification->termination && matches &&+ state.device_generation !=+ notification->observed_generation) {+ notification->observed_generation =+ state.device_generation;+ notification->delivered_service =+ fake_usb_device_service(state.device_generation);+ should_deliver = true;+ } else if (notification->termination) {+ if (!notification->observed_generation && matches) {+ notification->observed_generation =+ state.device_generation;+ } else if (notification->observed_generation &&+ have_state &&+ (!matches || state.device_generation !=+ notification->observed_generation)) {+ notification->delivered_service =+ fake_usb_device_service(+ notification->observed_generation);+ notification->observed_generation = 0;+ should_deliver = true;+ }+ }+ if (should_deliver && !notification->termination &&+ notification->product_id != 0x12ac &&+ !usb_bridge_configure_generation(+ state.device_generation)) {+ notification->observed_generation = 0;+ should_deliver = false;+ }+ if (should_deliver) {+ if (!notification->termination)+ fake_usb_deliver_prior_terminations(&state);+ const char *debug_delay = getenv(+ "INSTALL_USB_DEBUG_DELAY_MS");+ if (debug_delay && !notification->termination) {+ unsigned milliseconds = (unsigned)strtoul(+ debug_delay, NULL, 0);+ usb_shim_log("delaying DFU notification %u ms for "+ "debugger", milliseconds);+ usleep((useconds_t)milliseconds * 1000U);+ }+ dispatch_queue_t callback_queue =+ fake_usb_notifications[index].callback_queue;+ if (callback_queue) {+ dispatch_async(callback_queue, ^{+ fake_usb_deliver_notification(index);+ });+ } else {+ dispatch_async(dispatch_get_main_queue(), ^{+ fake_usb_deliver_notification(index);+ });+ }+ }+ }+ usleep(poll_interval);+ }+ });+}++static kern_return_t shim_IOServiceAddMatchingNotification(+ IONotificationPortRef notify_port, const io_name_t notification_type,+ CFDictionaryRef matching, IOServiceMatchingCallback callback,+ void *refcon, io_iterator_t *iterator) {+ usb_shim_log_cf("IOServiceAddMatchingNotification", matching);+ uint16_t wanted_product = 0;+ bool wanted_interface = false;+ if (!matching_wants_usb(matching, &wanted_product,+ &wanted_interface))+ return IOServiceAddMatchingNotification(+ notify_port, notification_type, matching, callback, refcon,+ iterator);+ usb_shim_log("matching notification type=%s product=0x%04x "+ "interface=%d dictionary=%p", notification_type,+ wanted_product, wanted_interface, matching);+ CFRelease(matching);+ for (unsigned index = 0; index < FAKE_USB_MAX_NOTIFICATIONS; index++) {+ if (!fake_usb_notifications[index].used) {+ bool termination = strstr(notification_type, "Terminate") != NULL;+ dispatch_queue_t callback_queue = NULL;+ for (unsigned port_index = 0; port_index < FAKE_USB_MAX_PORTS;+ port_index++) {+ if (fake_usb_port_queues[port_index].port == notify_port) {+ callback_queue = fake_usb_port_queues[port_index].queue;+ break;+ }+ }+ fake_usb_notifications[index] = (fake_usb_notification_t){+ .used = true, .termination = termination,+ .interface = wanted_interface,+ .product_id = wanted_product,+ .callback = callback, .refcon = refcon,+ .callback_queue = callback_queue,+ };+ *iterator = FAKE_USB_ITERATOR_BASE + index;+ fake_usb_start_notification_poller();+ return KERN_SUCCESS;+ }+ }+ return kIOReturnNoResources;+}++static kern_return_t shim_IOServiceGetMatchingServices(+ mach_port_t main_port, CFDictionaryRef matching,+ io_iterator_t *iterator) {+ usb_shim_log_cf("IOServiceGetMatchingServices", matching);+ return IOServiceGetMatchingServices(main_port, matching, iterator);+}++static void shim_IONotificationPortSetDispatchQueue(+ IONotificationPortRef notify_port, dispatch_queue_t queue) {+ for (unsigned index = 0; index < FAKE_USB_MAX_PORTS; index++) {+ if (!fake_usb_port_queues[index].port ||+ fake_usb_port_queues[index].port == notify_port) {+ fake_usb_port_queues[index] = (fake_usb_port_queue_t){+ .port = notify_port, .queue = queue,+ };+ break;+ }+ }+ usb_shim_log("notification port=%p queue=%s", notify_port,+ queue ? dispatch_queue_get_label(queue) : "(none)");+ IONotificationPortSetDispatchQueue(notify_port, queue);+}++static io_object_t shim_IOIteratorNext(io_iterator_t iterator) {+ if (iterator == FAKE_USB_INTERFACE_ITERATOR) {+ if (!fake_usb_interface_iterator_ready)+ return IO_OBJECT_NULL;+ fake_usb_interface_iterator_ready = false;+ usb_shim_log("interface iterator returned real DFU interface facade");+ return FAKE_USB_INTERFACE_SERVICE;+ }+ int index = notification_index(iterator);+ if (index < 0)+ return IOIteratorNext(iterator);+ fake_usb_notification_t *notification = &fake_usb_notifications[index];+ if (notification->delivered) {+ notification->delivered = false;+ if (notification->interface) {+ usb_shim_log("iterator %d returned RestoreOS USBMux "+ "interface facade", index);+ return FAKE_USB_INTERFACE_SERVICE;+ }+ usb_shim_log("iterator %d returned restore service=0x%x "+ "generation=%u", index,+ notification->delivered_service,+ fake_usb_service_generation(+ notification->delivered_service));+ return notification->delivered_service;+ }+ return IO_OBJECT_NULL;+}++static kern_return_t shim_IORegistryEntryGetParentEntry(+ io_registry_entry_t entry, const io_name_t plane,+ io_registry_entry_t *parent) {+ (void)plane;+ if (entry != FAKE_USB_INTERFACE_SERVICE)+ return IORegistryEntryGetParentEntry(entry, plane, parent);+ struct vz_usb_bridge_response state = {0};+ if (!parent || !usb_bridge_get_state(&state) || !state.ready)+ return kIOReturnNotFound;+ *parent = fake_usb_device_service(state.device_generation);+ usb_shim_log("returned real RestoreOS device parent for interface");+ return KERN_SUCCESS;+}++static kern_return_t shim_IOServiceAddInterestNotification(+ IONotificationPortRef notify_port, io_service_t service,+ const io_name_t interest_type, IOServiceInterestCallback callback,+ void *refcon, io_object_t *notification) {+ (void)notify_port;+ (void)interest_type;+ (void)callback;+ (void)refcon;+ if (!is_fake_usb_service(service))+ return IOServiceAddInterestNotification(+ notify_port, service, interest_type, callback, refcon,+ notification);+ if (notification)+ *notification = FAKE_USB_POWER_NOTIFIER;+ usb_shim_log("registered RestoreOS interface interest notification");+ return KERN_SUCCESS;+}++static kern_return_t shim_IOObjectRetain(io_object_t object) {+ if (is_fake_usb_service(object) || notification_index(object) >= 0 ||+ object == FAKE_USB_INTERFACE_ITERATOR ||+ is_fake_usb_device_connection(object) ||+ object == FAKE_USB_INTERFACE_CONNECTION ||+ object == FAKE_USB_POWER_CONNECTION ||+ object == FAKE_USB_POWER_NOTIFIER)+ return KERN_SUCCESS;+ return IOObjectRetain(object);+}++static kern_return_t shim_IOObjectRelease(io_object_t object) {+ if (is_fake_usb_service(object) || notification_index(object) >= 0 ||+ object == FAKE_USB_INTERFACE_ITERATOR ||+ is_fake_usb_device_connection(object) ||+ object == FAKE_USB_INTERFACE_CONNECTION ||+ object == FAKE_USB_POWER_CONNECTION ||+ object == FAKE_USB_POWER_NOTIFIER)+ return KERN_SUCCESS;+ return IOObjectRelease(object);+}++static boolean_t shim_IOObjectConformsTo(io_object_t object,+ const io_name_t class_name) {+ if (!is_fake_usb_service(object))+ return IOObjectConformsTo(object, class_name);+ if (object == FAKE_USB_INTERFACE_SERVICE)+ return strcmp(class_name, "IOUSBInterface") == 0 ||+ strcmp(class_name, "IOUSBHostInterface") == 0 ||+ strcmp(class_name, "IOService") == 0;+ return strcmp(class_name, "IOUSBDevice") == 0 ||+ strcmp(class_name, "IOUSBHostDevice") == 0 ||+ strcmp(class_name, "IOService") == 0;+}++static kern_return_t shim_IORegistryEntryCreateCFProperties(+ io_registry_entry_t entry, CFMutableDictionaryRef *properties,+ CFAllocatorRef allocator, IOOptionBits options) {+ (void)allocator; (void)options;+ if (!is_fake_usb_service(entry))+ return IORegistryEntryCreateCFProperties(+ entry, properties, allocator, options);+ *properties = fake_usb_properties(entry == FAKE_USB_INTERFACE_SERVICE);+ usb_shim_log("returned real DFU %s registry properties",+ entry == FAKE_USB_INTERFACE_SERVICE ? "interface" : "device");+ return KERN_SUCCESS;+}++static CFTypeRef shim_IORegistryEntryCreateCFProperty(+ io_registry_entry_t entry, CFStringRef key, CFAllocatorRef allocator,+ IOOptionBits options) {+ if (!is_fake_usb_service(entry))+ return IORegistryEntryCreateCFProperty(entry, key, allocator,+ options);+ CFMutableDictionaryRef properties = fake_usb_properties(+ entry == FAKE_USB_INTERFACE_SERVICE);+ CFTypeRef value = CFDictionaryGetValue(properties, key);+ if (value)+ CFRetain(value);+ CFRelease(properties);+ return value;+}++static kern_return_t shim_IORegistryEntryGetName(+ io_registry_entry_t entry, io_name_t name) {+ if (!is_fake_usb_service(entry))+ return IORegistryEntryGetName(entry, name);+ strlcpy(name, entry == FAKE_USB_INTERFACE_SERVICE+ ? "Apple Virtual DFU Interface"+ : "Apple Virtual DFU Device",+ sizeof(io_name_t));+ return KERN_SUCCESS;+}++static kern_return_t shim_IORegistryEntryGetNameInPlane(+ io_registry_entry_t entry, const io_name_t plane, io_name_t name) {+ (void)plane;+ return shim_IORegistryEntryGetName(entry, name);+}++static kern_return_t shim_IORegistryEntryGetRegistryEntryID(+ io_registry_entry_t entry, uint64_t *entry_id) {+ if (!is_fake_usb_service(entry))+ return IORegistryEntryGetRegistryEntryID(entry, entry_id);+ *entry_id = entry == FAKE_USB_INTERFACE_SERVICE+ ? 0x766d00020000ULL+ : 0x766d20000000ULL |+ fake_usb_service_generation(entry);+ return KERN_SUCCESS;+}++static kern_return_t shim_IOServiceOpen(+ io_service_t service, task_port_t owning_task, uint32_t type,+ io_connect_t *connection) {+ (void)owning_task;+ if (!is_fake_usb_service(service))+ return IOServiceOpen(service, owning_task, type, connection);+ *connection = service == FAKE_USB_INTERFACE_SERVICE+ ? FAKE_USB_INTERFACE_CONNECTION+ : FAKE_USB_CONNECTION_BASE ++ fake_usb_service_generation(service);+ usb_shim_log("opened real DFU %s facade type=%u",+ service == FAKE_USB_INTERFACE_SERVICE+ ? "interface" : "device", type);+ return KERN_SUCCESS;+}++static kern_return_t shim_IOServiceClose(io_connect_t connection) {+ if (is_fake_usb_device_connection(connection) ||+ connection == FAKE_USB_INTERFACE_CONNECTION ||+ connection == FAKE_USB_POWER_CONNECTION)+ return KERN_SUCCESS;+ return IOServiceClose(connection);+}++static io_connect_t shim_IORegisterForSystemPower(+ void *refcon, IONotificationPortRef *notify_port,+ IOServiceInterestCallback callback, io_object_t *notifier) {+ (void)refcon;+ (void)callback;+ if (!notify_port || !notifier)+ return MACH_PORT_NULL;+ *notify_port = IONotificationPortCreate(kIOMainPortDefault);+ if (!*notify_port)+ return MACH_PORT_NULL;+ *notifier = FAKE_USB_POWER_NOTIFIER;+ usb_shim_log("supplied userspace system-power notification facade");+ return FAKE_USB_POWER_CONNECTION;+}++static IOReturn shim_IOAllowPowerChange(io_connect_t connection,+ intptr_t notification_id) {+ if (connection == FAKE_USB_POWER_CONNECTION)+ return KERN_SUCCESS;+ return IOAllowPowerChange(connection, notification_id);+}++static kern_return_t shim_IOServiceWaitQuiet(+ io_service_t service, mach_timespec_t *wait_time) {+ if (!is_fake_usb_service(service))+ return IOServiceWaitQuiet(service, wait_time);+ // The AVP device has completed enumeration before the bridge publishes+ // it. MobileDevice's classic restore path waits for the registry service+ // to quiesce before reading properties; there is no kernel registry node+ // behind our userspace handle, so report that already-achieved state.+ usb_shim_log("virtual DFU service is quiet");+ return KERN_SUCCESS;+}++static kern_return_t usb_device_request(+ uint32_t selector, const uint64_t *input, uint32_t input_count,+ uint64_t *output, uint32_t *output_count, void *output_struct,+ size_t *output_struct_count) {+ if (!input || input_count < 8)+ return kIOReturnBadArgument;+ uint16_t length = (uint16_t)input[5];+ bool input_direction = selector == 7;+ void *data = (void *)(uintptr_t)input[6];+ // Ventura IOUSBLib's scalar user-client ABI reports the recovery command+ // buffer's allocation length here on iPadOS, while libusbrestore expects+ // the NUL-terminated command length. Recover that protocol length from+ // the real caller buffer for iBoot's vendor command request only.+ if (!input_direction && input[1] == 0x40 && input[2] == 0 && data) {+ size_t command_length = strnlen((const char *)data, UINT16_MAX - 1);+ if (command_length < UINT16_MAX && command_length + 1 != length) {+ usb_shim_log("corrected recovery command length %u -> %zu",+ length, command_length + 1);+ length = (uint16_t)(command_length + 1);+ }+ }+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_CONTROL,+ .payload_length = input_direction ? 0 : length,+ .timeout_ms = (uint32_t)(input[7] ? input[7] : 30000),+ .request_type = (uint8_t)input[1],+ .request = (uint8_t)input[2],+ .value = (uint16_t)input[3],+ .index = (uint16_t)input[4],+ .length = length,+ };+ struct vz_usb_bridge_response state = {0};+ usb_bridge_get_state(&state);+ bool restoreos_endpoint_feature =+ state.product_id == 0x12ac &&+ (request.request_type & 0x7fU) == 0x02 &&+ (request.request == 1 || request.request == 3) &&+ request.value == 0;+ if (restoreos_endpoint_feature) {+ // IOUSBLib's ResetPipe sequence toggles ENDPOINT_HALT before asking+ // the interface user client to clear its pipe. The VMM HCI already+ // owns and resets these endpoint rings; forwarding the standard USB+ // request makes RestoreOS wait for a kernel-host completion that does+ // not exist and eventually reset the whole virtual device.+ usb_shim_log("handled RestoreOS endpoint feature request=0x%02x "+ "endpoint=0x%02x in userspace", request.request,+ request.index);+ if (output && output_count && *output_count) {+ output[0] = 0;+ *output_count = 1;+ }+ if (output_struct_count)+ *output_struct_count = 0;+ return KERN_SUCCESS;+ }+ bool recovery_dfu_request = state.product_id == 0x1281 &&+ (request.request_type & 0x60U) == 0x20U;+ if (recovery_dfu_request && fake_usb_recovery_dfu_recipient_mode == 1)+ request.index = 1;+ else if (recovery_dfu_request &&+ fake_usb_recovery_dfu_recipient_mode == 2) {+ request.request_type &= ~0x1fU;+ request.index = 0;+ }+ usb_shim_log("DeviceRequest raw selector=%u scalars="+ "%llx,%llx,%llx,%llx,%llx,%llx,%llx,%llx",+ selector, input[0], input[1], input[2], input[3],+ input[4], input[5], input[6], input[7]);+ if (!input_direction && data && length && length <= 64)+ usb_shim_log("DeviceRequest OUT bytes=%.*s", (int)length,+ (const char *)data);+ if (input_direction && output_struct)+ data = output_struct;+ uint32_t capacity = length;+ if (input_direction && output_struct_count &&+ *output_struct_count < capacity)+ capacity = (uint32_t)*output_struct_count;+ struct vz_usb_bridge_response response = {0};+ int result = usb_bridge_request(+ &request, input_direction ? NULL : data,+ input_direction ? data : NULL, capacity, &response);+ if (result && recovery_dfu_request && request.request == 5 &&+ fake_usb_recovery_dfu_recipient_mode == 0) {+ request.index = 1;+ result = usb_bridge_request(+ &request, NULL, data, capacity, &response);+ usb_shim_log("recovery GETSTATE interface-index=1 probe -> %d",+ result);+ if (!result) {+ fake_usb_recovery_dfu_recipient_mode = 1;+ } else {+ request.request_type &= ~0x1fU;+ request.index = 0;+ result = usb_bridge_request(+ &request, NULL, data, capacity, &response);+ usb_shim_log("recovery GETSTATE device-recipient probe -> %d",+ result);+ if (!result)+ fake_usb_recovery_dfu_recipient_mode = 2;+ }+ }+ usb_shim_log("DeviceRequest selector=%u type=0x%02llx request=0x%02llx "+ "value=0x%04llx index=0x%04llx length=%u -> %d actual=%u",+ selector, input[1], input[2], input[3], input[4], length,+ result, response.payload_length);+ if (result)+ return kIOReturnNotResponding;+ if (input_direction)+ usb_shim_log_descriptor((uint16_t)input[3], data,+ response.payload_length);+ if (output && output_count && *output_count) {+ // IOUSBLib treats this scalar as a transport error flag and obtains+ // wLenDone from outputStructCnt. A byte count here makes it add+ // kIOUSBTransactionTimeout to an otherwise successful IOReturn.+ output[0] = 0;+ *output_count = 1;+ }+ if (output_struct_count)+ *output_struct_count = response.payload_length;+ return KERN_SUCCESS;+}++static kern_return_t shim_IOConnectCallMethod(+ mach_port_t connection, uint32_t selector, const uint64_t *input,+ uint32_t input_count, const void *input_struct,+ size_t input_struct_count, uint64_t *output, uint32_t *output_count,+ void *output_struct, size_t *output_struct_count) {+ if (!is_fake_usb_device_connection(connection) &&+ connection != FAKE_USB_INTERFACE_CONNECTION)+ return IOConnectCallMethod(+ connection, selector, input, input_count, input_struct,+ input_struct_count, output, output_count, output_struct,+ output_struct_count);+ if (is_fake_usb_device_connection(connection) &&+ !fake_usb_connection_is_current(connection))+ return kIOReturnNoDevice;+ if (is_fake_usb_device_connection(connection) &&+ (selector == 6 || selector == 7))+ return usb_device_request(selector, input, input_count, output,+ output_count, output_struct,+ output_struct_count);+ if (connection == FAKE_USB_INTERFACE_CONNECTION &&+ (selector == 0xb || selector == 0xc))+ return usb_device_request(selector == 0xc ? 7 : 6,+ input, input_count, output, output_count,+ output_struct, output_struct_count);+ if (connection == FAKE_USB_INTERFACE_CONNECTION &&+ (selector == 6 || selector == 7) && input && input_count >= 7) {+ uint8_t endpoint = 0;+ if (!usb_bridge_endpoint_for_pipe((uint8_t)input[0], &endpoint)) {+ usb_shim_log("pipe %llu has no endpoint", input[0]);+ return kIOReturnBadArgument;+ }+ bool input_direction = selector == 6;+ if (input_direction != ((endpoint & 0x80U) != 0)) {+ usb_shim_log("pipe %llu endpoint=0x%02x has wrong direction for "+ "selector=%u", input[0], endpoint, selector);+ return kIOReturnBadArgument;+ }+ void *buffer = NULL;+ uint32_t length = 0;+ if (input_direction) {+ if (!output_struct || !output_struct_count ||+ *output_struct_count > UINT32_MAX)+ return kIOReturnBadArgument;+ buffer = output_struct;+ length = (uint32_t)*output_struct_count;+ } else {+ uint64_t requested = input[5];+ if (requested > UINT32_MAX || input_struct_count < requested)+ return kIOReturnBadArgument;+ buffer = (void *)(input_struct ?: (const void *)(uintptr_t)input[4]);+ length = (uint32_t)requested;+ }+ uint64_t timeout = input[2] > input[3] ? input[2] : input[3];+ if (timeout > UINT32_MAX)+ timeout = UINT32_MAX;+ uint32_t actual = 0;+ int result = usb_bridge_bulk_transfer(+ endpoint, buffer, length, (uint32_t)timeout, &actual);+ if (result)+ return kIOReturnNotResponding;+ if (input_direction)+ *output_struct_count = actual;+ return KERN_SUCCESS;+ }+ bool interface_configuration_descriptor =+ connection == FAKE_USB_INTERFACE_CONNECTION && selector == 24;+ bool wants_configuration_descriptor =+ (is_fake_usb_device_connection(connection) && selector == 4) ||+ interface_configuration_descriptor;+ if (wants_configuration_descriptor && input && input_count >= 1 &&+ output_struct && output_struct_count) {+ size_t requested = *output_struct_count;+ if (requested > UINT16_MAX)+ requested = UINT16_MAX;+ uint32_t actual = interface_configuration_descriptor+ ? usb_bridge_read_interface_configuration(+ output_struct, (uint32_t)requested)+ : usb_bridge_read_descriptor(+ 0x0200, 0, output_struct, (uint32_t)requested);+ int result = actual ? 0 : EIO;+ if (!result)+ *output_struct_count = actual;+ usb_shim_log("%s configuration descriptor index=%llu length=%zu -> "+ "%d actual=%u",+ connection == FAKE_USB_INTERFACE_CONNECTION+ ? "interface" : "device",+ input[0], requested, result, actual);+ return result ? kIOReturnNotResponding : KERN_SUCCESS;+ }+ usb_shim_log("unimplemented IOConnectCallMethod selector=%u inputs=%u",+ selector, input_count);+ return kIOReturnUnsupported;+}++static kern_return_t shim_IOConnectCallScalarMethod(+ mach_port_t connection, uint32_t selector, const uint64_t *input,+ uint32_t input_count, uint64_t *output, uint32_t *output_count) {+ if (!is_fake_usb_device_connection(connection) &&+ connection != FAKE_USB_INTERFACE_CONNECTION)+ return IOConnectCallScalarMethod(connection, selector, input,+ input_count, output, output_count);+ usb_shim_log("IOConnectCallScalarMethod connection=0x%x selector=%u "+ "inputs=%u", connection, selector, input_count);+ if (input && input_count) {+ usb_shim_log("scalar inputs=%llx,%llx,%llx,%llx",+ input_count > 0 ? input[0] : 0,+ input_count > 1 ? input[1] : 0,+ input_count > 2 ? input[2] : 0,+ input_count > 3 ? input[3] : 0);+ }+ if (is_fake_usb_device_connection(connection) &&+ !fake_usb_connection_is_current(connection))+ return kIOReturnNoDevice;+ if (is_fake_usb_device_connection(connection) && selector == 12) {+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_RESET,+ .timeout_ms = 30000,+ };+ struct vz_usb_bridge_response response = {0};+ int result = usb_bridge_request(&request, NULL, NULL, 0, &response);+ usb_shim_log("re-enumerated real VM restore device flags=0x%llx "+ "-> %d generation=%u", input_count ? input[0] : 0,+ result, response.device_generation);+ return result ? kIOReturnNotResponding : KERN_SUCCESS;+ }+ if (is_fake_usb_device_connection(connection) && selector == 2 && input &&+ input_count >= 1) {+ int result = usb_bridge_set_configuration((uint8_t)input[0]);+ usb_shim_log("set real USB configuration=%llu options=0x%llx "+ "-> %d", input[0], input_count > 1 ? input[1] : 0,+ result);+ return result ? kIOReturnNotResponding : KERN_SUCCESS;+ }+ if (is_fake_usb_device_connection(connection) && selector == 8 && output &&+ output_count && *output_count) {+ uint8_t configuration[4096] = {0};+ uint32_t configuration_length = usb_bridge_read_descriptor(+ 0x0200, 0, configuration, sizeof(configuration));+ struct vz_usb_bridge_response state = {0};+ usb_bridge_get_state(&state);+ bool found = false;+ uint8_t selected_number = 0;+ uint8_t selected_alternate = 0;+ for (uint32_t offset = 0; offset + 2 <= configuration_length;) {+ uint8_t descriptor_length = configuration[offset];+ if (descriptor_length < 2 ||+ offset + descriptor_length > configuration_length)+ break;+ if (configuration[offset + 1] == 4 &&+ descriptor_length >= 9) {+ uint8_t number = configuration[offset + 2];+ uint8_t alternate = configuration[offset + 3];+ uint8_t interface_class = configuration[offset + 5];+ uint8_t subclass = configuration[offset + 6];+ uint8_t protocol = configuration[offset + 7];+ bool matches = input && input_count >= 4 &&+ (input[0] == UINT16_MAX || input[0] == interface_class) &&+ (input[1] == UINT16_MAX || input[1] == subclass) &&+ (input[2] == UINT16_MAX || input[2] == protocol) &&+ (input[3] == UINT16_MAX || input[3] == alternate);+ if (matches && !found) {+ found = true;+ selected_number = number;+ selected_alternate = alternate;+ break;+ }+ }+ offset += descriptor_length;+ }+ fake_usb_interface_iterator_ready = found;+ if (found) {+ fake_usb_selected_interface_number = selected_number;+ fake_usb_selected_interface_alternate = selected_alternate;+ }+ usb_shim_log("interface match product=0x%04x found=%d number=%u "+ "alternate=%u", state.product_id, found,+ selected_number, selected_alternate);+ output[0] = FAKE_USB_INTERFACE_ITERATOR;+ *output_count = 1;+ return KERN_SUCCESS;+ }+ if (connection == FAKE_USB_INTERFACE_CONNECTION && selector == 2 &&+ output && output_count && *output_count) {+ struct vz_usb_bridge_response state = {0};+ if (!usb_bridge_get_state(&state) || !state.ready)+ return kIOReturnNotResponding;+ output[0] = fake_usb_device_service(state.device_generation);+ *output_count = 1;+ return KERN_SUCCESS;+ }+ if (connection == FAKE_USB_INTERFACE_CONNECTION && selector == 3 &&+ input && input_count >= 1) {+ struct vz_usb_bridge_request request = {+ .operation = VZ_USB_BRIDGE_CONTROL,+ .timeout_ms = 30000,+ .request_type = 0x01,+ .request = 0x0b,+ .value = (uint16_t)input[0],+ .index = fake_usb_selected_interface_number,+ };+ struct vz_usb_bridge_response response = {0};+ int result = usb_bridge_request(+ &request, NULL, NULL, 0, &response);+ if (!result)+ fake_usb_selected_interface_alternate = (uint8_t)input[0];+ if (!result)+ result = usb_bridge_create_active_endpoints();+ usb_shim_log("set real interface=%u alternate=%llu -> %d",+ fake_usb_selected_interface_number, input[0], result);+ return result ? kIOReturnNotResponding : KERN_SUCCESS;+ }+ if (connection == FAKE_USB_INTERFACE_CONNECTION && selector == 5 &&+ input && input_count >= 1 && output && output_count &&+ *output_count >= 5) {+ uint8_t configuration[4096] = {0};+ uint32_t configuration_length = usb_bridge_read_descriptor(+ 0x0200, 0, configuration, sizeof(configuration));+ uint8_t wanted_pipe = (uint8_t)input[0];+ uint8_t pipe = 0;+ bool selected = false;+ for (uint32_t offset = 0; offset + 2 <= configuration_length;) {+ uint8_t descriptor_length = configuration[offset];+ if (descriptor_length < 2 ||+ offset + descriptor_length > configuration_length)+ break;+ if (configuration[offset + 1] == 4 &&+ descriptor_length >= 9) {+ selected = configuration[offset + 2] ==+ fake_usb_selected_interface_number &&+ configuration[offset + 3] ==+ fake_usb_selected_interface_alternate;+ pipe = 0;+ } else if (selected && configuration[offset + 1] == 5 &&+ descriptor_length >= 7) {+ pipe++;+ if (pipe == wanted_pipe) {+ uint8_t endpoint = configuration[offset + 2];+ fake_usb_pipe_endpoints[wanted_pipe] = endpoint;+ output[0] = (endpoint & 0x80U) ? 1 : 0;+ output[1] = endpoint & 0x0fU;+ output[2] = configuration[offset + 3] & 0x03U;+ output[3] = (uint16_t)configuration[offset + 4] |+ ((uint16_t)configuration[offset + 5] << 8);+ output[4] = configuration[offset + 6];+ *output_count = 5;+ usb_shim_log("pipe %u endpoint=0x%02x type=%llu "+ "max-packet=%llu", wanted_pipe, endpoint,+ output[2], output[3]);+ return KERN_SUCCESS;+ }+ }+ offset += descriptor_length;+ }+ return kIOReturnNotFound;+ }+ if (connection == FAKE_USB_INTERFACE_CONNECTION && selector == 14 &&+ input && input_count >= 3 && output && output_count &&+ *output_count >= 3) {+ uint8_t configuration[4096] = {0};+ uint32_t configuration_length = usb_bridge_read_descriptor(+ 0x0200, 0, configuration, sizeof(configuration));+ uint8_t wanted_alternate = (uint8_t)input[0];+ uint8_t wanted_number = (uint8_t)input[1] & 0x0fU;+ bool wanted_input = input[2] != 0;+ bool selected = false;+ for (uint32_t offset = 0; offset + 2 <= configuration_length;) {+ uint8_t descriptor_length = configuration[offset];+ if (descriptor_length < 2 ||+ offset + descriptor_length > configuration_length)+ break;+ if (configuration[offset + 1] == 4 &&+ descriptor_length >= 9) {+ selected = configuration[offset + 2] ==+ fake_usb_selected_interface_number &&+ configuration[offset + 3] ==+ wanted_alternate;+ } else if (selected && configuration[offset + 1] == 5 &&+ descriptor_length >= 7) {+ uint8_t endpoint = configuration[offset + 2];+ if ((endpoint & 0x0fU) == wanted_number &&+ ((endpoint & 0x80U) != 0) == wanted_input) {+ output[0] = configuration[offset + 3] & 0x03U;+ output[1] = (uint16_t)configuration[offset + 4] |+ ((uint16_t)configuration[offset + 5] << 8);+ output[2] = configuration[offset + 6];+ *output_count = 3;+ usb_shim_log("endpoint properties alternate=%u "+ "number=%u direction=%s type=%llu "+ "max-packet=%llu interval=%llu",+ wanted_alternate, wanted_number,+ wanted_input ? "in" : "out", output[0],+ output[1], output[2]);+ return KERN_SUCCESS;+ }+ }+ offset += descriptor_length;+ }+ return kIOReturnNotFound;+ }+ if (connection == FAKE_USB_INTERFACE_CONNECTION &&+ (selector == 8 || selector == 9 || selector == 10 ||+ selector == 13)) {+ // GetPipeStatus, AbortPipe, ClearPipeStall, and SetPipePolicy are+ // bookkeeping operations for the kernel user client. The bridge+ // performs transfers synchronously and VMM owns endpoint-ring state,+ // so there is no additional kernel-side operation to perform here.+ return KERN_SUCCESS;+ }+ if (selector <= 5)+ return KERN_SUCCESS;+ return kIOReturnUnsupported;+}++static kern_return_t shim_IOConnectCallAsyncScalarMethod(+ mach_port_t connection, uint32_t selector, mach_port_t wake_port,+ uint64_t *reference, uint32_t reference_count, const uint64_t *input,+ uint32_t input_count, uint64_t *output, uint32_t *output_count) {+ if (connection != FAKE_USB_INTERFACE_CONNECTION)+ return IOConnectCallAsyncScalarMethod(+ connection, selector, wake_port, reference, reference_count,+ input, input_count, output, output_count);+ usb_shim_log("IOConnectCallAsyncScalarMethod selector=%u wake=0x%x "+ "references=%u inputs=%u", selector, wake_port,+ reference_count, input_count);+ // IOUSBLib selector 19 registers the notification port used for its+ // kernel-delivered completions. Completions for the userspace bridge are+ // dispatched directly below, but IOUSBLib still requires this setup call+ // to succeed before it will submit asynchronous pipe transfers.+ return selector == 19 ? KERN_SUCCESS : kIOReturnUnsupported;+}++static kern_return_t shim_IOConnectCallAsyncMethod(+ mach_port_t connection, uint32_t selector, mach_port_t wake_port,+ uint64_t *reference, uint32_t reference_count, const uint64_t *input,+ uint32_t input_count, const void *input_struct, size_t input_struct_count,+ uint64_t *output, uint32_t *output_count, void *output_struct,+ size_t *output_struct_count) {+ if (connection != FAKE_USB_INTERFACE_CONNECTION)+ return IOConnectCallAsyncMethod(+ connection, selector, wake_port, reference, reference_count,+ input, input_count, input_struct, input_struct_count, output,+ output_count, output_struct, output_struct_count);+ if (usb_shim_trace_transfers())+ usb_shim_log("IOConnectCallAsyncMethod selector=%u wake=0x%x "+ "references=%u inputs=%u", selector, wake_port,+ reference_count, input_count);+ if ((selector != 6 && selector != 7) || !reference ||+ reference_count < 3 || !input || input_count < 7)+ return kIOReturnUnsupported;+ uint8_t endpoint = 0;+ if (!usb_bridge_endpoint_for_pipe((uint8_t)input[0], &endpoint))+ return kIOReturnBadArgument;+ bool input_direction = selector == 6;+ if (input_direction != ((endpoint & 0x80U) != 0))+ return kIOReturnBadArgument;+ if (input[5] > UINT32_MAX)+ return kIOReturnBadArgument;+ void *buffer = (void *)(uintptr_t)input[4];+ uint32_t length = (uint32_t)input[5];+ uint64_t timeout_value = input[2] > input[3] ? input[2] : input[3];+ uint32_t timeout = timeout_value > UINT32_MAX+ ? UINT32_MAX+ : (uint32_t)timeout_value;+ if (input_direction && timeout == 0)+ timeout = UINT32_MAX;+ IOAsyncCallback1 callback = (IOAsyncCallback1)(uintptr_t)reference[1];+ void *refcon = (void *)(uintptr_t)reference[2];+ if (!callback || (!buffer && length))+ return kIOReturnBadArgument;+ if (usb_shim_trace_transfers())+ usb_shim_log("queued async bulk pipe=%llu endpoint=0x%02x length=%u "+ "timeout=%u callback=%p refcon=%p", input[0], endpoint,+ length, timeout, callback, refcon);+ dispatch_queue_t transfer_queue = input_direction+ ? fake_usb_bulk_input_queue : fake_usb_bulk_output_queue;+ dispatch_async(transfer_queue, ^{+ uint32_t actual = 0;+ int result = usb_bridge_bulk_transfer(endpoint, buffer, length,+ timeout, &actual);+ IOReturn completion_result =+ result ? kIOReturnNotResponding : KERN_SUCCESS;+ if (result || usb_shim_trace_transfers())+ usb_shim_log("completing async bulk endpoint=0x%02x result=0x%x "+ "actual=%u", endpoint, completion_result, actual);+ // Native IOUSBLib posts this completion to the notification port+ // whose run-loop source usbmuxd installed on its main run loop.+ // Preserve that threading contract; its mux-interface state is not+ // designed to be mutated from bridge worker queues.+ dispatch_async(dispatch_get_main_queue(), ^{+ callback(refcon, completion_result,+ (void *)(uintptr_t)actual);+ });+ });+ return KERN_SUCCESS;+}++static kern_return_t shim_IOCreatePlugInInterfaceForService(+ io_service_t service, CFUUIDRef plugin_type, CFUUIDRef interface_type,+ IOCFPlugInInterface ***interface, SInt32 *score) {+ if (!is_fake_usb_service(service)) {+ static kern_return_t (*original)(io_service_t, CFUUIDRef, CFUUIDRef,+ IOCFPlugInInterface ***, SInt32 *);+ if (!original)+ original = dlsym(RTLD_NEXT,+ "IOCreatePlugInInterfaceForService");+ return original ? original(service, plugin_type, interface_type,+ interface, score)+ : kIOReturnUnsupported;+ }+ static void *library;+ static void *(*factory)(CFAllocatorRef, CFUUIDRef);+ if (!library) {+ library = dlopen(+ "/System/Library/Extensions/IOUSBHostFamily.kext/PlugIns/"+ "IOUSBLib.bundle/IOUSBLib", RTLD_NOW | RTLD_GLOBAL);+ if (library)+ factory = dlsym(library, "IOUSBLibFactory");+ usb_shim_log("loaded native IOUSBLib=%p factory=%p error=%s",+ library, factory, library ? "none" : dlerror());+ }+ if (!factory)+ return kIOReturnUnsupported;+ IOCFPlugInInterface **plugin = factory(kCFAllocatorDefault, plugin_type);+ if (!plugin || !*plugin)+ return kIOReturnNoMemory;+ SInt32 local_score = 0;+ IOReturn result = (*plugin)->Probe(+ plugin, NULL, service, score ? score : &local_score);+ if (result == KERN_SUCCESS)+ result = (*plugin)->Start(plugin, NULL, service);+ usb_shim_log("native IOUSBLib plugin=%p probe/start -> 0x%x",+ plugin, result);+ if (result != KERN_SUCCESS) {+ (*plugin)->Release(plugin);+ return result;+ }+ *interface = plugin;+ return KERN_SUCCESS;+}++#define INTERPOSE(name, replacement, original) \+ __attribute__((used)) static struct { \+ const void *replacement; const void *original; \+ } name __attribute__((section("__DATA,__interpose"))) = { \+ (const void *)&replacement, (const void *)&original \+ }++INTERPOSE(ip_usb_add_matching, shim_IOServiceAddMatchingNotification,+ IOServiceAddMatchingNotification);+INTERPOSE(ip_usb_get_matching, shim_IOServiceGetMatchingServices,+ IOServiceGetMatchingServices);+INTERPOSE(ip_usb_notification_queue,+ shim_IONotificationPortSetDispatchQueue,+ IONotificationPortSetDispatchQueue);+INTERPOSE(ip_usb_iterator_next, shim_IOIteratorNext, IOIteratorNext);+INTERPOSE(ip_usb_object_retain, shim_IOObjectRetain, IOObjectRetain);+INTERPOSE(ip_usb_object_release, shim_IOObjectRelease, IOObjectRelease);+INTERPOSE(ip_usb_object_conforms, shim_IOObjectConformsTo,+ IOObjectConformsTo);+INTERPOSE(ip_usb_properties, shim_IORegistryEntryCreateCFProperties,+ IORegistryEntryCreateCFProperties);+INTERPOSE(ip_usb_property, shim_IORegistryEntryCreateCFProperty,+ IORegistryEntryCreateCFProperty);+INTERPOSE(ip_usb_name, shim_IORegistryEntryGetName,+ IORegistryEntryGetName);+INTERPOSE(ip_usb_name_plane, shim_IORegistryEntryGetNameInPlane,+ IORegistryEntryGetNameInPlane);+INTERPOSE(ip_usb_entry_id, shim_IORegistryEntryGetRegistryEntryID,+ IORegistryEntryGetRegistryEntryID);+INTERPOSE(ip_usb_parent, shim_IORegistryEntryGetParentEntry,+ IORegistryEntryGetParentEntry);+INTERPOSE(ip_usb_interest, shim_IOServiceAddInterestNotification,+ IOServiceAddInterestNotification);+INTERPOSE(ip_usb_service_open, shim_IOServiceOpen, IOServiceOpen);+INTERPOSE(ip_usb_service_close, shim_IOServiceClose, IOServiceClose);+INTERPOSE(ip_usb_service_wait_quiet, shim_IOServiceWaitQuiet,+ IOServiceWaitQuiet);+INTERPOSE(ip_usb_connect_method, shim_IOConnectCallMethod,+ IOConnectCallMethod);+INTERPOSE(ip_usb_connect_scalar, shim_IOConnectCallScalarMethod,+ IOConnectCallScalarMethod);+INTERPOSE(ip_usb_connect_async_scalar,+ shim_IOConnectCallAsyncScalarMethod,+ IOConnectCallAsyncScalarMethod);+INTERPOSE(ip_usb_connect_async, shim_IOConnectCallAsyncMethod,+ IOConnectCallAsyncMethod);+INTERPOSE(ip_usb_create_plugin, shim_IOCreatePlugInInterfaceForService,+ IOCreatePlugInInterfaceForService);+INTERPOSE(ip_usb_system_power, shim_IORegisterForSystemPower,+ IORegisterForSystemPower);+INTERPOSE(ip_usb_allow_power, shim_IOAllowPowerChange,+ IOAllowPowerChange);++__attribute__((constructor)) static void installation_usb_shim_init(void) {+ fake_usb_notification_queue = dispatch_queue_create(+ "org.jb.virtualization.installation-usb", DISPATCH_QUEUE_CONCURRENT);+ // IOUSBLib submits multiple reads and writes ahead of time, but each USB+ // endpoint is an ordered stream. Preserve submission order before the+ // requests cross the userspace bridge; a concurrent worker queue can+ // otherwise associate later USBMux sequence packets with earlier read+ // callbacks and make usbmuxd report duplicate/skipped packets.+ fake_usb_bulk_input_queue = dispatch_queue_create(+ "org.jb.virtualization.installation-usb.bulk-in",+ DISPATCH_QUEUE_SERIAL);+ fake_usb_bulk_output_queue = dispatch_queue_create(+ "org.jb.virtualization.installation-usb.bulk-out",+ DISPATCH_QUEUE_SERIAL);+ usb_shim_log("loaded; native IOUSBLib bridge enabled");+}diff --git a/VirtualMac/vz/host/installationhook.m b/VirtualMac/vz/host/installationhook.mnew file mode 100644index 0000000..f1190b4--- /dev/null+++ b/VirtualMac/vz/host/installationhook.m@@ -0,0 +1,225 @@+// Compatibility hook loaded into Ventura's iOS-stamped+// com.apple.Virtualization.Installation helper.+//+// A macOS XPC service normally receives its listener from launchd through+// xpc_main(). The iPad host starts this helper directly, so publish an+// anonymous listener endpoint which VZHostCompat can recover through the+// child's task port. This is the same rendezvous already proven for the VMM.+#include <dispatch/dispatch.h>+#include <dlfcn.h>+#include <ptrauth.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include <sys/stat.h>++#define DEFAULT_INSTALLATION_EP_FILE "/tmp/installation_ep.txt"+#define XPC_ENDPOINT_PORT_OFF 0x18++typedef void *xpc_object_t;+typedef void *xpc_connection_t;+typedef void *xpc_endpoint_t;++extern void xpc_main(void (*handler)(xpc_object_t));+extern xpc_connection_t xpc_connection_create(+ const char *name, dispatch_queue_t targetQueue);+extern void xpc_connection_set_event_handler(+ xpc_connection_t connection, void (^handler)(xpc_object_t));+extern void xpc_connection_resume(xpc_connection_t connection);+extern xpc_endpoint_t xpc_endpoint_create(xpc_connection_t connection);+extern const void *xpc_get_type(xpc_object_t object);+extern char *xpc_copy_description(xpc_object_t object);+extern int sandbox_init_with_parameters(+ const char *profile, uint64_t flags,+ const char *const parameters[], char **errorbuf);+extern char _xpc_type_connection[];+extern size_t confstr(int name, char *buffer, size_t length);++static void installation_log(const char *message)+{+ FILE *file = fopen("/tmp/installationhook.log", "a");+ if (!file)+ return;+ fchmod(fileno(file), 0666);+ fprintf(file, "[installationhook] pid=%d %s\n", getpid(), message);+ fclose(file);+}++static uintptr_t installation_decode_adrp(uint32_t instruction, uintptr_t pc)+{+ int64_t immediate =+ ((instruction >> 29) & 0x3) |+ (((instruction >> 5) & 0x7ffff) << 2);+ if (immediate & (1 << 20))+ immediate -= 1 << 21;+ return (pc & ~(uintptr_t)0xfff) + immediate * 4096;+}++static void *installation_repair_crypto_error_implementation(+ void *(*getter)(void))+{+ void *implementation = getter();+ if (implementation)+ return implementation;++ // Ventura 13.2.1's ERR_get_implementation is a tiny wrapper around an+ // internal initializer. Decode its own global-slot load and the default+ // implementation reference in that initializer instead of baking in an+ // ASLR address. Refuse to patch if this exact instruction shape changes.+ uint32_t *code = (uint32_t *)ptrauth_strip(+ (void *)getter, ptrauth_key_function_pointer);+ uint32_t slotADRP = code[4]; // getter + 0x10+ uint32_t slotLDR = code[5]; // getter + 0x14+ uint32_t defaultADRP = code[26]; // getter + 0x68+ uint32_t defaultADD = code[27]; // getter + 0x6c+ if ((slotADRP & 0x9f000000) != 0x90000000 ||+ (slotLDR & 0xffc00000) != 0xf9400000 ||+ (defaultADRP & 0x9f000000) != 0x90000000 ||+ (defaultADD & 0xffc00000) != 0x91000000)+ return NULL;++ uintptr_t slotPage = installation_decode_adrp(+ slotADRP, (uintptr_t)&code[4]);+ uintptr_t defaultPage = installation_decode_adrp(+ defaultADRP, (uintptr_t)&code[26]);+ void **slot = (void **)(slotPage + (((slotLDR >> 10) & 0xfff) << 3));+ void *defaultImplementation =+ (void *)(defaultPage + ((defaultADD >> 10) & 0xfff));+ *slot = defaultImplementation;+ return getter();+}++__attribute__((constructor)) static void installation_hook_init(void)+{+ installation_log("loaded");+}++static void installation_xpc_main(void (*handler)(xpc_object_t))+{+ // MobileDevice's constructor starts its booted-device registration worker+ // while the restore-image request can concurrently enter+ // AMRestorableBuildCreate. On macOS libcrypto is already process-global;+ // here it is private to this freshly launched helper, and the two threads+ // can both reach ERR_get_state before its implementation table exists.+ // Initialize that table before MobileDevice is allowed to load and create+ // its worker threads.+ void *crypto = dlopen("@loader_path/crypto.dylib",+ RTLD_NOW | RTLD_GLOBAL);+ if (!crypto) {+ installation_log(dlerror() ?: "failed to preload crypto.dylib");+ } else {+ void *(*get_error_implementation)(void) =+ dlsym(crypto, "ERR_get_implementation");+ if (get_error_implementation) {+ void *implementation =+ installation_repair_crypto_error_implementation(+ get_error_implementation);+ char message[128];+ snprintf(message, sizeof(message),+ "preinitialized libcrypto error state: %p",+ implementation);+ installation_log(message);+ } else {+ installation_log("ERR_get_implementation is unavailable");+ }+ }++ installation_log("creating anonymous XPC listener");+ xpc_connection_t listener =+ xpc_connection_create(NULL, dispatch_get_main_queue());+ xpc_connection_set_event_handler(listener, ^(xpc_object_t event) {+ if (xpc_get_type(event) == (const void *)_xpc_type_connection) {+ installation_log("accepted host peer");+ handler(event);+ } else {+ char *description = xpc_copy_description(event);+ FILE *file = fopen("/tmp/installationhook.log", "a");+ if (file) {+ fprintf(file, "[installationhook] listener event: %s\n",+ description ?: "(unknown)");+ fclose(file);+ }+ free(description);+ }+ });+ xpc_connection_resume(listener);++ xpc_endpoint_t endpoint = xpc_endpoint_create(listener);+ uint32_t port = *(uint32_t *)((char *)endpoint + XPC_ENDPOINT_PORT_OFF);+ const char *endpointFile = getenv("VZ_INSTALLATION_ENDPOINT_FILE");+ if (!endpointFile || !endpointFile[0])+ endpointFile = DEFAULT_INSTALLATION_EP_FILE;+ FILE *file = fopen(endpointFile, "w");+ if (!file) {+ installation_log("failed to publish endpoint");+ _exit(70);+ }+ fprintf(file, "0x%x\n", port);+ fclose(file);+ installation_log("published endpoint");+ dispatch_main();+}++static int installation_sandbox_init_with_parameters(+ const char *profile, uint64_t flags,+ const char *const parameters[], char **errorbuf)+{+ (void)profile;+ (void)flags;+ (void)parameters;+ if (errorbuf)+ *errorbuf = NULL;+ installation_log("bypassed macOS runtime sandbox profile");+ return 0;+}++static size_t installation_confstr(int name, char *buffer, size_t length)+{+ // iPadOS returns EIO for Darwin's non-containerized per-user cache and+ // temp selectors. The Ventura helper treats that as fatal before it can+ // accept its XPC peer.+ if (name == 65537 || name == 65538) {+ static const char path[] = "/tmp/";+ size_t required = sizeof(path);+ if (buffer && length) {+ size_t copied = required < length ? required : length;+ memcpy(buffer, path, copied);+ buffer[length - 1] = '\0';+ }+ installation_log("supplied Darwin user cache/temp directory");+ return required;+ }+ static size_t (*realConfstr)(int, char *, size_t);+ if (!realConfstr)+ realConfstr = dlsym(RTLD_NEXT, "confstr");+ return realConfstr ? realConfstr(name, buffer, length) : 0;+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} installation_xpc_main_interpose+ __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&installation_xpc_main,+ (const void *)&xpc_main,+ };++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} installation_sandbox_interpose+ __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&installation_sandbox_init_with_parameters,+ (const void *)&sandbox_init_with_parameters,+ };++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} installation_confstr_interpose+ __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&installation_confstr,+ (const void *)&confstr,+ };diff --git a/VirtualMac/vz/host/lsshim.m b/VirtualMac/vz/host/lsshim.mnew file mode 100644index 0000000..bc36606--- /dev/null+++ b/VirtualMac/vz/host/lsshim.m@@ -0,0 +1,16 @@+// CoreServices/LaunchServices shim for the iOS-ported VZ VMM service.+// macOS CoreServices re-exports LaunchServices, which exports _LSApplicationCheckIn+// (the app's check-in with the LS database during launch). iOS CoreServices has no+// such export. The extracted VMM binds it (it's an Application-type XPCService), so+// dyld fails the load. We re-export the device's real CoreServices (so every other+// symbol resolves) and define _LSApplicationCheckIn as a benign success stub — on the+// headless direct-spawn path there is no LS launch context to check into.+// Wire-up: change the VMM binary's CoreServices LC_LOAD_DYLIB to /var/root/lsshim.ios.+#import <CoreFoundation/CoreFoundation.h>++// Real macOS signature is private/variadic; as a noErr stub the args are irrelevant+// (callee ignores them; returns 0 in x0). Four pointer params cover the common ABI.+int _LSApplicationCheckIn(void *a, void *b, void *c, void *d) {+ (void)a; (void)b; (void)c; (void)d;+ return 0; // noErr+}diff --git a/VirtualMac/vz/host/metalshim.m b/VirtualMac/vz/host/metalshim.mnew file mode 100644index 0000000..6c14ced--- /dev/null+++ b/VirtualMac/vz/host/metalshim.m@@ -0,0 +1,384 @@+// Metal shim for the iOS-ported VZ VMM service. macOS Metal exports MTLCopyAllDevices+// (multi-GPU enumeration); iOS Metal does not (single GPU). The extracted VMM binds it,+// so dyld fails the load. We build a tiny arm64e dylib that re-exports the device's real+// Metal (so every other Metal symbol the VMM needs resolves through us) and defines the+// few macOS-only entry points the VMM imports, backed by the iOS single-device API.+// Wire-up: change the VMM binary's Metal LC_LOAD_DYLIB to /var/root/metalshim.ios.+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#import <objc/message.h>+#import <objc/runtime.h>++static id (*gNewBufferWithLength)(id, SEL, NSUInteger, MTLResourceOptions);+static id (*gNewBufferWithBytes)(+ id, SEL, const void *, NSUInteger, MTLResourceOptions);+static id (*gNewBufferWithBytesNoCopy)(+ id, SEL, void *, NSUInteger, MTLResourceOptions,+ void (^)(void *, NSUInteger));+static id (*gNewTextureWithDescriptor)(+ id, SEL, MTLTextureDescriptor *);+static id (*gNewTextureWithDescriptorIOSurface)(+ id, SEL, MTLTextureDescriptor *, void *, NSUInteger);+static void (*gSetTextureStorageMode)(id, SEL, MTLStorageMode);+static void (*gSetTexturePixelFormat)(id, SEL, MTLPixelFormat);+static void (*gSetHeapStorageMode)(id, SEL, MTLStorageMode);+static BOOL gInstalledSharedBufferCompatibility;+static unsigned long gMacCompressedTextureCount;++// macOS: NSArray<id<MTLDevice>> *MTLCopyAllDevices(void) — +1 (the "Copy" rule).+// iOS has exactly one GPU, so return the system default in a one-element array.+NSArray *MTLCopyAllDevices(void) {+ id dev = MTLCreateSystemDefaultDevice();+ NSArray *a = dev ? @[dev] : @[];+ return [a retain]; // built without ARC; "Copy" rule => return +1+}++// macOS-only; iOS logs "Ignoring call MTLSetShaderCachePath(...)" — so a no-op matches iOS behavior.+void MTLSetShaderCachePath(const char *path) { (void)path; }++// The macOS 13 VMM selects a Metal device by querying this macOS MTLDevice+// property. iOS has one integrated GPU and its concrete AGX device class does+// not implement the selector. Report the iPad GPU as integrated/non-low-power+// so the unmodified VMM can complete device selection.+static BOOL iPadMetalDeviceIsLowPower(id self, SEL selector) {+ (void)self;+ (void)selector;+ return NO;+}++static BOOL iPadMetalDeviceIsRemovable(id self, SEL selector) {+ (void)self;+ (void)selector;+ return NO;+}++static BOOL iPadMetalDeviceIsHeadless(id self, SEL selector) {+ (void)self;+ (void)selector;+ return NO;+}++static BOOL iPadMetalDeviceIsDepth24Stencil8PixelFormatSupported(+ id self, SEL selector) {+ (void)self;+ (void)selector;+ // Apple-family GPUs use 32-bit depth formats. This macOS compatibility+ // query is absent from iOS's MTLDevice surface, and reporting NO makes+ // PVG advertise the formats the iPad GPU actually supports.+ return NO;+}++static BOOL iPadMetalDeviceIsFramebufferReadSupported(id self, SEL selector) {+ (void)self;+ (void)selector;+ // Apple GPUs support framebuffer fetch. macOS exposes this private+ // capability query, while the iOS MTLDevice protocol omits the selector.+ return YES;+}++static BOOL iPadMetalDeviceReturnsYes(id self, SEL selector) {+ (void)self;+ (void)selector;+ return YES;+}++static NSUInteger iPadMetalDeviceMaxTextureDimension(id self, SEL selector) {+ (void)self;+ (void)selector;+ return 16384;+}++static NSUInteger iPadMetalDeviceMaxTotalThreads(id self, SEL selector) {+ (void)self;+ (void)selector;+ return 1024;+}++static void iPadSamplerSetReductionMode(id self, SEL selector,+ NSUInteger reductionMode) {+ (void)self;+ (void)selector;+ (void)reductionMode;+ // Sampler reduction mode is a macOS-only descriptor property.+ // The default weighted-average mode is value zero.+}++static NSUInteger iPadSamplerReductionMode(id self, SEL selector) {+ (void)self;+ (void)selector;+ return 0;+}++static void AddMetalMethodIfMissing(id device, NSString *name,+ IMP implementation,+ const char *types) {+ SEL selector = NSSelectorFromString(name);+ if (![device respondsToSelector:selector]) {+ class_addMethod([device class], selector, implementation, types);+ }+}++static MTLResourceOptions iPadMetalResourceOptions(+ MTLResourceOptions options) {+ // MTLStorageModeManaged is macOS-only. Apple Silicon has unified memory,+ // and current Metal headers explicitly direct Apple Silicon clients to+ // Shared instead.+ const MTLResourceOptions managed = 1UL << MTLResourceStorageModeShift;+ if ((options & MTLResourceStorageModeMask) == managed) {+ options &= ~MTLResourceStorageModeMask;+ options |= MTLResourceStorageModeShared;+ }+ return options;+}++static MTLStorageMode iPadMetalStorageMode(MTLStorageMode storageMode) {+ // Raw value 1 is MTLStorageModeManaged on macOS.+ return storageMode == (MTLStorageMode)1+ ? MTLStorageModeShared+ : storageMode;+}++static void iPadSetTextureStorageMode(id self, SEL selector,+ MTLStorageMode storageMode) {+ gSetTextureStorageMode(+ self, selector, iPadMetalStorageMode(storageMode));+}++static BOOL IsMacBCPixelFormat(MTLPixelFormat pixelFormat) {+ // BC1 through BC7 occupy the Mac-only Metal values 130...153.+ // iPadOS's descriptor validator rejects the enum.+ return (NSUInteger)pixelFormat >= 130 && (NSUInteger)pixelFormat <= 153;+}++static MTLPixelFormat iPadCompressedFallback(MTLPixelFormat pixelFormat) {+ // Keep each format's 4x4 block dimensions and byte count so guest upload+ // pitches, mip offsets, and buffer sizes remain valid. iPadOS 16.3 rejects+ // BC formats before the GPU driver; its native ETC/EAC/ASTC formats are a+ // safe crash-prevention fallback for effects and transient image textures.+ switch ((NSUInteger)pixelFormat) {+ case 130: return (MTLPixelFormat)180; // BC1 -> ETC2 RGB8+ case 131: return (MTLPixelFormat)181; // BC1 sRGB -> ETC2 RGB8 sRGB+ case 140: return (MTLPixelFormat)170; // BC4 unorm -> EAC R11 unorm+ case 141: return (MTLPixelFormat)172; // BC4 snorm -> EAC R11 snorm+ case 142: return (MTLPixelFormat)174; // BC5 unorm -> EAC RG11 unorm+ case 143: return (MTLPixelFormat)176; // BC5 snorm -> EAC RG11 snorm+ case 133: case 135: case 153:+ return (MTLPixelFormat)186; // 16-byte sRGB -> ASTC 4x4 sRGB+ case 150: case 151:+ return (MTLPixelFormat)222; // BC6H -> ASTC 4x4 HDR+ default:+ return (MTLPixelFormat)204; // 16-byte linear -> ASTC 4x4 LDR+ }+}++static void iPadSetTexturePixelFormat(id self, SEL selector,+ MTLPixelFormat pixelFormat) {+ if (!IsMacBCPixelFormat(pixelFormat)) {+ gSetTexturePixelFormat(self, selector, pixelFormat);+ return;+ }+ MTLPixelFormat fallback = iPadCompressedFallback(pixelFormat);+ unsigned long count = __sync_add_and_fetch(&gMacCompressedTextureCount, 1);+ if (count <= 20 || count % 100 == 0)+ fprintf(stderr, "[metalshim] mapped Mac BC format=%lu to iPad format=%lu count=%lu\n",+ (unsigned long)pixelFormat, (unsigned long)fallback, count);+ gSetTexturePixelFormat(self, selector, fallback);+}++static void iPadSetHeapStorageMode(id self, SEL selector,+ MTLStorageMode storageMode) {+ gSetHeapStorageMode(+ self, selector, iPadMetalStorageMode(storageMode));+}++static void NormalizeTextureDescriptor(MTLTextureDescriptor *descriptor) {+ if ((NSUInteger)descriptor.storageMode == 1) {+ descriptor.storageMode = MTLStorageModeShared;+ }+}++static id iPadNewTextureWithDescriptor(+ id self, SEL selector, MTLTextureDescriptor *descriptor) {+ NormalizeTextureDescriptor(descriptor);+ id texture = gNewTextureWithDescriptor(self, selector, descriptor);+ if (IsMacBCPixelFormat(descriptor.pixelFormat))+ fprintf(stderr, "[metalshim] BC texture format=%lu %lux%lu -> %p\n",+ (unsigned long)descriptor.pixelFormat,+ (unsigned long)descriptor.width,+ (unsigned long)descriptor.height, texture);+ return texture;+}++static id iPadNewTextureWithDescriptorIOSurface(+ id self, SEL selector, MTLTextureDescriptor *descriptor,+ void *surface, NSUInteger plane) {+ NormalizeTextureDescriptor(descriptor);+ return gNewTextureWithDescriptorIOSurface(+ self, selector, descriptor, surface, plane);+}++static void iPadSharedBufferDidModifyRange(id self, SEL selector,+ NSRange range) {+ (void)self;+ (void)selector;+ (void)range;+ // Shared memory is coherent on Apple Silicon; this macOS managed-memory+ // flush has no work to perform on iOS.+}++static id InstallSharedBufferCompatibility(id buffer) {+ if (buffer != nil &&+ __sync_bool_compare_and_swap(+ &gInstalledSharedBufferCompatibility, NO, YES)) {+ Method method = class_getInstanceMethod(+ [buffer class], NSSelectorFromString(@"didModifyRange:"));+ if (method != NULL) {+ method_setImplementation(+ method, (IMP)iPadSharedBufferDidModifyRange);+ }+ }+ return buffer;+}++static id iPadNewBufferWithLength(id self, SEL selector, NSUInteger length,+ MTLResourceOptions options) {+ return InstallSharedBufferCompatibility(gNewBufferWithLength(+ self, selector, length, iPadMetalResourceOptions(options)));+}++static id iPadNewBufferWithBytes(id self, SEL selector, const void *bytes,+ NSUInteger length,+ MTLResourceOptions options) {+ return InstallSharedBufferCompatibility(gNewBufferWithBytes(+ self, selector, bytes, length, iPadMetalResourceOptions(options)));+}++static id iPadNewBufferWithBytesNoCopy(+ id self, SEL selector, void *bytes, NSUInteger length,+ MTLResourceOptions options, void (^deallocator)(void *, NSUInteger)) {+ return InstallSharedBufferCompatibility(gNewBufferWithBytesNoCopy(+ self, selector, bytes, length, iPadMetalResourceOptions(options),+ deallocator));+}++static IMP ReplaceMetalMethod(Class cls, NSString *name, IMP replacement) {+ SEL selector = NSSelectorFromString(name);+ Method method = class_getInstanceMethod(cls, selector);+ if (method == NULL) {+ return NULL;+ }+ return method_setImplementation(method, replacement);+}++__attribute__((constructor))+static void InstallMacMetalDeviceCompatibility(void) {+ @autoreleasepool {+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();+ if (device == nil) {+ return;+ }+ class_addMethod([device class],+ NSSelectorFromString(@"isLowPower"),+ (IMP)iPadMetalDeviceIsLowPower,+ "B@:");+ class_addMethod([device class],+ NSSelectorFromString(@"isRemovable"),+ (IMP)iPadMetalDeviceIsRemovable,+ "B@:");+ class_addMethod([device class],+ NSSelectorFromString(@"isHeadless"),+ (IMP)iPadMetalDeviceIsHeadless,+ "B@:");+ class_addMethod(+ [device class],+ NSSelectorFromString(+ @"isDepth24Stencil8PixelFormatSupported"),+ (IMP)iPadMetalDeviceIsDepth24Stencil8PixelFormatSupported,+ "B@:");+ class_addMethod(+ [device class],+ NSSelectorFromString(@"isFramebufferReadSupported"),+ (IMP)iPadMetalDeviceIsFramebufferReadSupported,+ "B@:");+ AddMetalMethodIfMissing(+ device, @"isRGB10A2GammaSupported",+ (IMP)iPadMetalDeviceReturnsYes, "B@:");+ AddMetalMethodIfMissing(+ device, @"supportsExtendedXR10Formats",+ (IMP)iPadMetalDeviceReturnsYes, "B@:");+ AddMetalMethodIfMissing(+ device, @"supportsNativeHardwareFP16",+ (IMP)iPadMetalDeviceReturnsYes, "B@:");+ AddMetalMethodIfMissing(+ device, @"maxTextureWidth2D",+ (IMP)iPadMetalDeviceMaxTextureDimension, "Q@:");+ AddMetalMethodIfMissing(+ device, @"maxTextureHeight2D",+ (IMP)iPadMetalDeviceMaxTextureDimension, "Q@:");+ AddMetalMethodIfMissing(+ device, @"maxTotalThreadsPerThreadgroup",+ (IMP)iPadMetalDeviceMaxTotalThreads, "Q@:");+ gNewBufferWithLength =+ (id (*)(id, SEL, NSUInteger, MTLResourceOptions))+ ReplaceMetalMethod(+ [device class],+ @"newBufferWithLength:options:",+ (IMP)iPadNewBufferWithLength);+ gNewBufferWithBytes =+ (id (*)(id, SEL, const void *, NSUInteger, MTLResourceOptions))+ ReplaceMetalMethod(+ [device class],+ @"newBufferWithBytes:length:options:",+ (IMP)iPadNewBufferWithBytes);+ gNewBufferWithBytesNoCopy =+ (id (*)(id, SEL, void *, NSUInteger, MTLResourceOptions,+ void (^)(void *, NSUInteger)))+ ReplaceMetalMethod(+ [device class],+ @"newBufferWithBytesNoCopy:length:options:deallocator:",+ (IMP)iPadNewBufferWithBytesNoCopy);+ gNewTextureWithDescriptor =+ (id (*)(id, SEL, MTLTextureDescriptor *))ReplaceMetalMethod(+ [device class],+ @"newTextureWithDescriptor:",+ (IMP)iPadNewTextureWithDescriptor);+ gNewTextureWithDescriptorIOSurface =+ (id (*)(id, SEL, MTLTextureDescriptor *, void *, NSUInteger))+ ReplaceMetalMethod(+ [device class],+ @"newTextureWithDescriptor:iosurface:plane:",+ (IMP)iPadNewTextureWithDescriptorIOSurface);++ MTLTextureDescriptor *textureDescriptor =+ [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:+ MTLPixelFormatBGRA8Unorm+ width:1+ height:1+ mipmapped:NO];+ gSetTextureStorageMode =+ (void (*)(id, SEL, MTLStorageMode))ReplaceMetalMethod(+ [textureDescriptor class],+ @"setStorageMode:",+ (IMP)iPadSetTextureStorageMode);+ gSetTexturePixelFormat =+ (void (*)(id, SEL, MTLPixelFormat))ReplaceMetalMethod(+ [textureDescriptor class], @"setPixelFormat:",+ (IMP)iPadSetTexturePixelFormat);++ MTLHeapDescriptor *heapDescriptor = [[MTLHeapDescriptor alloc] init];+ gSetHeapStorageMode =+ (void (*)(id, SEL, MTLStorageMode))ReplaceMetalMethod(+ [heapDescriptor class],+ @"setStorageMode:",+ (IMP)iPadSetHeapStorageMode);++ MTLSamplerDescriptor *samplerDescriptor =+ [[MTLSamplerDescriptor alloc] init];+ AddMetalMethodIfMissing(+ samplerDescriptor, @"setReductionMode:",+ (IMP)iPadSamplerSetReductionMode, "v@:Q");+ AddMetalMethodIfMissing(+ samplerDescriptor, @"reductionMode",+ (IMP)iPadSamplerReductionMode, "Q@:");+ }+}diff --git a/VirtualMac/vz/host/open_directory_compat.c b/VirtualMac/vz/host/open_directory_compat.cnew file mode 100644index 0000000..cb5b74c--- /dev/null+++ b/VirtualMac/vz/host/open_directory_compat.c@@ -0,0 +1,116 @@+#include <CoreFoundation/CoreFoundation.h>++/*+ * Ventura's bootpd still links OpenDirectory for optional NetBoot and+ * directory-backed account management. iPadOS 16 ships the framework but+ * not these desktop-only exports. Basic DHCP never enters these routines;+ * keep the imports resolvable and report the optional service as unavailable+ * if a future configuration does request it.+ */++const void *kODAttributeTypeStandardOnly = NULL;+const void *kODRecordTypeGroups = NULL;+const void *kODSessionDefault = NULL;++static void clear_error(void **error)+{+ if (error != NULL) {+ *error = NULL;+ }+}++void *ODNodeCopyRecord(void *node, void *record_type, void *record_name,+ void *attributes, void **error)+{+ (void)node;+ (void)record_type;+ (void)record_name;+ (void)attributes;+ clear_error(error);+ return NULL;+}++void *ODNodeCreateRecord(void *node, void *record_type, void *record_name,+ void *attributes, void **error)+{+ (void)node;+ (void)record_type;+ (void)record_name;+ (void)attributes;+ clear_error(error);+ return NULL;+}++void *ODNodeCreateWithNodeType(void *allocator, void *session,+ unsigned int node_type, void **error)+{+ (void)allocator;+ (void)session;+ (void)node_type;+ clear_error(error);+ return NULL;+}++void *ODQueryCreateWithNode(void *allocator, void *node, void *record_types,+ void *attribute, unsigned int match_type,+ void *query_values, void *return_attributes,+ long maximum_results, void **error)+{+ (void)allocator;+ (void)node;+ (void)record_types;+ (void)attribute;+ (void)match_type;+ (void)query_values;+ (void)return_attributes;+ (void)maximum_results;+ clear_error(error);+ return NULL;+}++void *ODQueryCopyResults(void *query, Boolean allow_partial, void **error)+{+ (void)query;+ (void)allow_partial;+ clear_error(error);+ return NULL;+}++Boolean ODRecordAddMember(void *group, void *member, void **error)+{+ (void)group;+ (void)member;+ clear_error(error);+ return false;+}++Boolean ODRecordChangePassword(void *record, void *old_password,+ void *new_password, void **error)+{+ (void)record;+ (void)old_password;+ (void)new_password;+ clear_error(error);+ return false;+}++void *ODRecordCopyValues(void *record, void *attribute, void **error)+{+ (void)record;+ (void)attribute;+ clear_error(error);+ return NULL;+}++void *ODRecordGetRecordName(void *record)+{+ (void)record;+ return NULL;+}++Boolean ODRecordSynchronize(void *record, void **error)+{+ (void)record;+ clear_error(error);+ return false;+}diff --git a/VirtualMac/vz/host/pvg_trace.m b/VirtualMac/vz/host/pvg_trace.mnew file mode 100644index 0000000..7f271e8--- /dev/null+++ b/VirtualMac/vz/host/pvg_trace.m@@ -0,0 +1,966 @@+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#import <objc/message.h>+#import <objc/runtime.h>+#import <dlfcn.h>+#import <errno.h>+#import <fcntl.h>+#import <ptrauth.h>+#import <pthread.h>+#import <stdint.h>+#import <stdlib.h>+#import <string.h>+#import <sys/mman.h>+#import <time.h>+#import <unistd.h>++static BOOL (*gOriginalSetupBlitPipelines)(id, SEL);+static BOOL (*gOriginalSetupReporting)(id, SEL);+static id (*gOriginalInitWithDescriptor)(id, SEL, id);+static id (*gOriginalIOSurfaceInitWithDescriptor)(id, SEL, id);+static id (*gOriginalNewDisplay)(id, SEL, id, NSUInteger, uint32_t);+static id (*gOriginalDisplayInit)(+ id, SEL, id, id, NSUInteger, uint32_t);+static id (*gOriginalPipelineCacheInit)(id, SEL, id);+static id (*gOriginalNewDefaultLibraryWithBundle)(id, SEL, NSBundle *, NSError **);+static void (*gOriginalCommandBufferCommit)(id, SEL);+static BOOL (*gOriginalTextureValidate)(id, SEL, id);+static SEL gOriginalNewDefaultLibrarySelector;+static dispatch_data_t gSerializedMetallib;+static dispatch_source_t gMetalHealthTimer;+static uint64_t gMetalCommandBufferCommits;+static uint64_t gMetalCommandBufferCompletions;+static uint64_t gMetalCommandBufferErrors;+static uint64_t gPVGCaughtExceptions;+static id (*gOriginalGetTaskID)(id, SEL, uint32_t);+static void (*gOriginalCreateTaskID)(+ id, SEL, uint32_t, uint32_t, uint64_t, BOOL);+static BOOL (*gOriginalDeleteTaskID)(id, SEL, uint32_t);+static uint64_t gTaskLookupCount;+static uint64_t gTaskLookupMissCount;+static uint64_t gTaskMapCount;+static uint64_t gTaskMapHighWater;+static uint64_t gManagedTextureTranslations;+static pthread_mutex_t gLargeTaskLock = PTHREAD_MUTEX_INITIALIZER;+static pthread_mutex_t gTaskCreateLock = PTHREAD_MUTEX_INITIALIZER;+static uint32_t gLargeTaskIDs[8];+static uint32_t gLargeTaskLimit;+static uint64_t gLargeTaskReservationGB;+static uint64_t gCreatingTaskReservationGB;+static id (*gOriginalGetBufferForReferenceNonNull)(id, SEL, uint32_t);++extern id PGNewDeviceWithDescriptor(id descriptor);++typedef void *(^PVGCreateTaskBlock)(uint64_t length, void **baseAddress);+typedef BOOL (^PVGMapMemoryBlock)(void *task, uint32_t segmentCount,+ uint64_t offset, BOOL readonly,+ const uint64_t *ranges);++static const char *TracePath(void) {+ const char *configured = getenv("PVG_TRACE_PATH");+ return configured && configured[0] ? configured : "/tmp/pvg-trace.log";+}++static void Trace(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2);++static void Trace(NSString *format, ...) {+ va_list args;+ va_start(args, format);+ NSString *line = [[NSString alloc] initWithFormat:format arguments:args];+ va_end(args);++ int fd = open(TracePath(), O_WRONLY | O_CREAT | O_APPEND, 0644);+ if (fd >= 0) {+ struct timespec now = {0};+ clock_gettime(CLOCK_MONOTONIC, &now);+ dprintf(fd, "[%lld.%06ld]\t%s\n",+ (long long)now.tv_sec, now.tv_nsec / 1000,+ line.UTF8String);+ close(fd);+ }+}++extern void *objc_begin_catch(void *exceptionStorage);++static void *TraceObjCBeginCatch(void *exceptionStorage) {+ void *result = objc_begin_catch(exceptionStorage);+ Dl_info caller = {0};+ void *returnAddress = __builtin_return_address(0);+ if (result != NULL &&+ dladdr(returnAddress, &caller) != 0 &&+ caller.dli_fname != NULL &&+ strstr(caller.dli_fname, "ParavirtualizedGraphics") != NULL) {+ uint64_t count = __atomic_add_fetch(+ &gPVGCaughtExceptions, 1, __ATOMIC_RELAXED);+ id exception = (id)result;+ NSString *name = [exception isKindOfClass:[NSException class]]+ ? [(NSException *)exception name] : nil;+ NSString *reason = [exception isKindOfClass:[NSException class]]+ ? [(NSException *)exception reason] : nil;+ Trace(@"PVG_EXCEPTION\tcount=%llu\tclass=%s\tname=%@\treason=%@"+ "\tcaller=%p\toffset=0x%llx",+ (unsigned long long)count,+ object_getClassName(exception), name, reason,+ returnAddress,+ (unsigned long long)((uintptr_t)returnAddress -+ (uintptr_t)caller.dli_fbase));+ }+ return result;+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} gInterposeObjCBeginCatch+ __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&TraceObjCBeginCatch,+ (const void *)&objc_begin_catch,+ };++static void TraceMethod(Class cls, SEL selector) {+ Method method = class_getInstanceMethod(cls, selector);+ if (method == NULL) {+ Trace(@"METHOD\t%@\tmissing", NSStringFromSelector(selector));+ return;+ }++ Dl_info info = {0};+ IMP implementation = method_getImplementation(method);+ dladdr((const void *)implementation, &info);+ Trace(@"METHOD\t%@\t%p\t%s",+ NSStringFromSelector(selector),+ implementation,+ info.dli_fname != NULL ? info.dli_fname : "(unknown)");+}++static id TraceGetBufferForReferenceNonNull(id self, SEL selector,+ uint32_t reference) {+ if (reference == 0) {+ void *returnAddress = __builtin_return_address(0);+ Dl_info caller = {0};+ dladdr(returnAddress, &caller);+ Trace(@"METAL_BUFFER_REFERENCE\tinvalid-zero\tdecoder=%s"+ "\tcaller=%p\toffset=0x%llx\timage=%s",+ object_getClassName(self), returnAddress,+ (unsigned long long)((uintptr_t)returnAddress -+ (uintptr_t)caller.dli_fbase),+ caller.dli_fname ?: "(unknown)");+ }+ return gOriginalGetBufferForReferenceNonNull(+ self, selector, reference);+}++static void InstallMetalSerializerReferenceTrace(void) {+ Class cls = NSClassFromString(@"MTLDeserializerBlitDecoder");+ SEL selector = NSSelectorFromString(@"getBufferForReferenceNonNull:");+ Method method = class_getInstanceMethod(cls, selector);+ if (method == NULL) {+ Trace(@"METAL_BUFFER_REFERENCE\thook-missing\tclass=%@", cls);+ return;+ }+ gOriginalGetBufferForReferenceNonNull =+ (id (*)(id, SEL, uint32_t))method_setImplementation(+ method, (IMP)TraceGetBufferForReferenceNonNull);+ Trace(@"METAL_BUFFER_REFERENCE\thook-installed\tclass=%@\toriginal=%p",+ cls, gOriginalGetBufferForReferenceNonNull);+}++static id TraceGetTaskID(id self, SEL selector, uint32_t taskID) {+ uint64_t count = __atomic_add_fetch(+ &gTaskLookupCount, 1, __ATOMIC_RELAXED);+ @try {+ id task = gOriginalGetTaskID(self, selector, taskID);+ if (count <= 12) {+ Trace(@"TASK_LOOKUP\tcount=%llu\tid=%u\tresult=%p",+ (unsigned long long)count, taskID, task);+ }+ return task;+ } @catch (NSException *exception) {+ uint64_t misses = __atomic_add_fetch(+ &gTaskLookupMissCount, 1, __ATOMIC_RELAXED);+ Ivar tasksIvar = class_getInstanceVariable([self class], "_tasks");+ id tasks = tasksIvar != NULL ? object_getIvar(self, tasksIvar) : nil;+ Trace(@"TASK_LOOKUP_MISS\tmiss=%llu\tcount=%llu\tid=%u"+ "\ttasks=%@\texception=%@",+ (unsigned long long)misses,+ (unsigned long long)count,+ taskID,+ tasks,+ exception);+ @throw;+ }+}++static id TaskDictionary(id device) {+ Ivar tasksIvar = class_getInstanceVariable([device class], "_tasks");+ return tasksIvar != NULL ? object_getIvar(device, tasksIvar) : nil;+}++static BOOL ReserveLargeTaskSlot(uint32_t taskID, uint64_t length) {+ if (length != (16ULL << 30) || gLargeTaskReservationGB == 0 ||+ gLargeTaskLimit == 0)+ return NO;+ BOOL reserved = NO;+ pthread_mutex_lock(&gLargeTaskLock);+ for (uint32_t index = 0; index < gLargeTaskLimit; index++) {+ if (gLargeTaskIDs[index] == taskID) {+ reserved = YES;+ break;+ }+ if (gLargeTaskIDs[index] == 0) {+ gLargeTaskIDs[index] = taskID;+ reserved = YES;+ break;+ }+ }+ pthread_mutex_unlock(&gLargeTaskLock);+ return reserved;+}++static void ReleaseLargeTaskSlot(uint32_t taskID) {+ pthread_mutex_lock(&gLargeTaskLock);+ for (uint32_t index = 0; index < gLargeTaskLimit; index++) {+ if (gLargeTaskIDs[index] == taskID) {+ gLargeTaskIDs[index] = 0;+ break;+ }+ }+ pthread_mutex_unlock(&gLargeTaskLock);+}++static void TraceCreateTaskID(id self, SEL selector, uint32_t taskID,+ uint32_t taskRoot, uint64_t length,+ BOOL restoring) {+ BOOL largeTask = ReserveLargeTaskSlot(taskID, length);+ Trace(@"TASK_CREATE\tbegin\tid=%u\troot=%u\tlength=%llu"+ "\trestoring=%d\tlarge=%d\ttasks=%@",+ taskID, taskRoot, (unsigned long long)length, restoring,+ largeTask,+ TaskDictionary(self));+ // The extracted framework invokes createTask on another thread while the+ // createTaskWithID: call is in flight. Serialize creations and publish the+ // selected tier process-wide so that callback sees it.+ pthread_mutex_lock(&gTaskCreateLock);+ __atomic_store_n(&gCreatingTaskReservationGB,+ largeTask ? gLargeTaskReservationGB : 0,+ __ATOMIC_RELEASE);+ @try {+ gOriginalCreateTaskID(+ self, selector, taskID, taskRoot, length, restoring);+ } @finally {+ __atomic_store_n(&gCreatingTaskReservationGB, 0, __ATOMIC_RELEASE);+ pthread_mutex_unlock(&gTaskCreateLock);+ }+ id createdTask = [TaskDictionary(self) objectForKey:@(taskID)];+ if (largeTask && createdTask == nil)+ ReleaseLargeTaskSlot(taskID);+ Trace(@"TASK_CREATE\tend\tid=%u\ttasks=%@",+ taskID, TaskDictionary(self));+}++static BOOL TraceDeleteTaskID(id self, SEL selector, uint32_t taskID) {+ Trace(@"TASK_DELETE\tbegin\tid=%u\ttasks=%@",+ taskID, TaskDictionary(self));+ BOOL result = gOriginalDeleteTaskID(self, selector, taskID);+ if (result || [TaskDictionary(self) objectForKey:@(taskID)] == nil)+ ReleaseLargeTaskSlot(taskID);+ Trace(@"TASK_DELETE\tend\tid=%u\tresult=%d\ttasks=%@",+ taskID, result, TaskDictionary(self));+ return result;+}++static void TraceCommandBufferCommit(id self, SEL selector) {+ uint64_t commit = __atomic_add_fetch(+ &gMetalCommandBufferCommits, 1, __ATOMIC_RELAXED);+ [self addCompletedHandler:^(id<MTLCommandBuffer> commandBuffer) {+ uint64_t completion = __atomic_add_fetch(+ &gMetalCommandBufferCompletions, 1, __ATOMIC_RELAXED);+ MTLCommandBufferStatus status = commandBuffer.status;+ NSError *error = commandBuffer.error;+ if (status == MTLCommandBufferStatusError || error != nil) {+ uint64_t errors = __atomic_add_fetch(+ &gMetalCommandBufferErrors, 1, __ATOMIC_RELAXED);+ Trace(@"METAL_COMMAND_BUFFER\terror=%llu\tcommit=%llu"+ "\tcompletion=%llu\tstatus=%lu\tdescription=%@",+ (unsigned long long)errors,+ (unsigned long long)commit,+ (unsigned long long)completion,+ (unsigned long)status,+ error);+ }+ }];+ gOriginalCommandBufferCommit(self, selector);+}++static void InstallCommandBufferTrace(id<MTLDevice> device) {+ id<MTLCommandQueue> queue = [device newCommandQueue];+ id<MTLCommandBuffer> commandBuffer = [queue commandBuffer];+ Method commitMethod = class_getInstanceMethod(+ [commandBuffer class], @selector(commit));+ if (commitMethod == NULL) {+ Trace(@"METAL_COMMAND_BUFFER\tcommit-method-missing\tclass=%@",+ [commandBuffer class]);+ [queue release];+ return;+ }+ gOriginalCommandBufferCommit =+ (void (*)(id, SEL))method_setImplementation(+ commitMethod, (IMP)TraceCommandBufferCommit);+ Trace(@"METAL_COMMAND_BUFFER\ttrace-installed\tclass=%@\toriginal=%p",+ [commandBuffer class], gOriginalCommandBufferCommit);++ dispatch_queue_t healthQueue = dispatch_get_global_queue(+ QOS_CLASS_UTILITY, 0);+ gMetalHealthTimer = dispatch_source_create(+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0, healthQueue);+ dispatch_source_set_timer(+ gMetalHealthTimer,+ dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),+ 10 * NSEC_PER_SEC,+ NSEC_PER_SEC / 2);+ dispatch_source_set_event_handler(gMetalHealthTimer, ^{+ Trace(@"METAL_HEALTH\tcommits=%llu\tcompletions=%llu\terrors=%llu",+ (unsigned long long)__atomic_load_n(+ &gMetalCommandBufferCommits, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &gMetalCommandBufferCompletions, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &gMetalCommandBufferErrors, __ATOMIC_RELAXED));+ });+ dispatch_resume(gMetalHealthTimer);+ [queue release];+}++static BOOL ValidateTextureDescriptorForIOS(id self, SEL selector,+ id device) {+ MTLStorageMode storageMode = ((MTLStorageMode (*)(id, SEL))objc_msgSend)(+ self, @selector(storageMode));+ // MTLStorageModeManaged is numerically 1 but unavailable in the iOS SDK.+ if (storageMode == (MTLStorageMode)1) {+ ((void (*)(id, SEL, MTLStorageMode))objc_msgSend)(+ self, @selector(setStorageMode:), MTLStorageModeShared);+ uint64_t count = __atomic_add_fetch(+ &gManagedTextureTranslations, 1, __ATOMIC_RELAXED);+ if (count <= 12 || count % 100 == 0) {+ Trace(@"METAL_TEXTURE\tmanaged-to-shared=%llu\tdescriptor=%@",+ (unsigned long long)count, self);+ }+ }+ return gOriginalTextureValidate(self, selector, device);+}++static void InstallTextureDescriptorCompatibility(void) {+ MTLTextureDescriptor *descriptor = [[MTLTextureDescriptor alloc] init];+ Class cls = [descriptor class];+ SEL selector = NSSelectorFromString(@"validateWithDevice:");+ Method method = class_getInstanceMethod(cls, selector);+ if (method == NULL) {+ Trace(@"METAL_TEXTURE\tvalidate-hook-missing\tclass=%@", cls);+ [descriptor release];+ return;+ }+ gOriginalTextureValidate =+ (BOOL (*)(id, SEL, id))method_setImplementation(+ method, (IMP)ValidateTextureDescriptorForIOS);+ Trace(@"METAL_TEXTURE\tvalidate-hook-installed\tclass=%@"+ "\ttype=%s\toriginal=%p",+ cls, method_getTypeEncoding(method), gOriginalTextureValidate);+ [descriptor release];+}++static BOOL TraceSetupBlitPipelines(id self, SEL selector) {+ Trace(@"CALL\tsetupBlitPipelines\tbegin");+ BOOL result = gOriginalSetupBlitPipelines(self, selector);+ Trace(@"CALL\tsetupBlitPipelines\tresult=%d", result);+ return result;+}++static BOOL TraceSetupReporting(id self, SEL selector) {+ Trace(@"CALL\tsetupReporting\tbegin");+ BOOL result = gOriginalSetupReporting(self, selector);+ Trace(@"CALL\tsetupReporting\tresult=%d", result);+ return result;+}++static id TraceInitWithDescriptor(id self, SEL selector, id descriptor) {+ Trace(@"CALL\tinitWithDescriptor:\tbegin\tdescriptor=%@", descriptor);+ id result = gOriginalInitWithDescriptor(self, selector, descriptor);+ Trace(@"CALL\tinitWithDescriptor:\tresult=%@", result);+ return result;+}++static id TraceIOSurfaceInitWithDescriptor(id self, SEL selector, id descriptor) {+ Trace(@"CALL\tPGIOSurfaceHostDevice initWithDescriptor:\tbegin"+ "\tdescriptor=%@\tmmioLength=%@",+ descriptor,+ [descriptor valueForKey:@"mmioLength"]);+ id result =+ gOriginalIOSurfaceInitWithDescriptor(self, selector, descriptor);+ Trace(@"CALL\tPGIOSurfaceHostDevice initWithDescriptor:\tresult=%@",+ result);+ if (result != nil) {+ // This is the last component of the PVG device stack constructed by+ // VMM. Give its asynchronously started FIFO workers a bounded window+ // to finish the initial Metal capability exchange before VMM+ // finalizes all host devices.+ const char *configured = getenv("PVG_SETTLE_USEC");+ useconds_t delay = configured && configured[0]+ ? (useconds_t)strtoul(configured, NULL, 10)+ : 1000000;+ if (delay > 1000000) {+ delay = 1000000;+ }+ Trace(@"CALL\tPGIOSurfaceHostDevice initWithDescriptor:"+ "\tsettle-usec=%u",+ delay);+ usleep(delay);+ }+ return result;+}++static id TraceNewDisplay(id self, SEL selector, id descriptor,+ NSUInteger port, uint32_t serialNumber) {+ Trace(@"CALL\tnewDisplayWithDescriptor:port:serialNum:\tbegin"+ "\tdescriptor=%@\tport=%lu\tserial=%u",+ descriptor, (unsigned long)port, serialNumber);+ id result =+ gOriginalNewDisplay(self, selector, descriptor, port, serialNumber);+ Trace(@"CALL\tnewDisplayWithDescriptor:port:serialNum:\tresult=%@",+ result);+ return result;+}++static id TraceDisplayInit(id self, SEL selector, id device, id descriptor,+ NSUInteger port, uint32_t serialNumber) {+ Trace(@"CALL\t_PGDisplay init\tbegin\tdevice=%@\tdescriptor=%@"+ "\tport=%lu\tserial=%u",+ device, descriptor, (unsigned long)port, serialNumber);+ id result = gOriginalDisplayInit(+ self, selector, device, descriptor, port, serialNumber);+ Trace(@"CALL\t_PGDisplay init\tresult=%@", result);+ return result;+}++static id TracePipelineCacheInit(id self, SEL selector, id device) {+ Trace(@"CALL\tPGDisplayPipelineCache initWithDevice:\tbegin"+ "\tdevice=%@",+ device);+ id result = gOriginalPipelineCacheInit(self, selector, device);+ Trace(@"CALL\tPGDisplayPipelineCache initWithDevice:\tresult=%@",+ result);+ return result;+}++static id TracePGNewDeviceWithDescriptor(id descriptor) {+ id device = nil;+ id mapper = nil;+ id mmioLength = nil;+ id displayPortCount = nil;+ id createTask = nil;+ id destroyTask = nil;+ id mapMemory = nil;+ id unmapMemory = nil;+ id readMemory = nil;+ @try {+ device = [descriptor valueForKey:@"device"];+ mapper = [descriptor valueForKey:@"usingIOSurfaceMapper"];+ mmioLength = [descriptor valueForKey:@"mmioLength"];+ displayPortCount = [descriptor valueForKey:@"displayPortCount"];+ createTask = [descriptor valueForKey:@"createTask"];+ destroyTask = [descriptor valueForKey:@"destroyTask"];+ mapMemory = [descriptor valueForKey:@"mapMemory"];+ unmapMemory = [descriptor valueForKey:@"unmapMemory"];+ readMemory = [descriptor valueForKey:@"readMemory"];+ } @catch (NSException *exception) {+ Trace(@"CALL\tPGNewDeviceWithDescriptor\tdescriptor-read-exception=%@",+ exception);+ }+ Trace(@"CALL\tPGNewDeviceWithDescriptor\tbegin\tdescriptor=%@"+ "\tdevice=%@\tusingIOSurfaceMapper=%@\tmmioLength=%@"+ "\tdisplayPortCount=%@",+ descriptor, device, mapper, mmioLength, displayPortCount);+ NSDictionary *blocks = @{+ @"createTask": createTask ?: [NSNull null],+ @"destroyTask": destroyTask ?: [NSNull null],+ @"mapMemory": mapMemory ?: [NSNull null],+ @"unmapMemory": unmapMemory ?: [NSNull null],+ @"readMemory": readMemory ?: [NSNull null],+ };+ for (NSString *name in blocks) {+ id block = blocks[name];+ if (block == (id)[NSNull null])+ continue;+ const uintptr_t *words = (const uintptr_t *)(const void *)block;+ void *invoke = (void *)ptrauth_strip(+ (void *)words[2], ptrauth_key_function_pointer);+ Dl_info info = {0};+ dladdr(invoke, &info);+ Trace(@"CALLBACK\t%@\tblock=%p\tinvoke=%p\tbase=%p"+ "\toffset=0x%llx\timage=%s",+ name, block, invoke, info.dli_fbase,+ (unsigned long long)((uintptr_t)invoke -+ (uintptr_t)info.dli_fbase),+ info.dli_fname ?: "(unknown)");+ }++ // iPadOS extended-VA processes have only enough address space for three+ // 16 GiB reservations. macOS PVG asks the VMM to reserve 16 GiB for every+ // graphics client, so the third ordinary client otherwise fails to exist.+ // Keep PVG's logical 16 GiB task size but reduce the VMM's sparse host+ // reservation. The map wrapper verifies whether the guest ever crosses+ // the physical reservation before forwarding each fixed remap.+ const char *reservationText = getenv("PVG_TASK_RESERVATION_GB");+ uint64_t reservationGB = reservationText && reservationText[0]+ ? strtoull(reservationText, NULL, 10) : 0;+ const char *largeReservationText = getenv(+ "PVG_LARGE_TASK_RESERVATION_GB");+ gLargeTaskReservationGB = largeReservationText &&+ largeReservationText[0]+ ? strtoull(largeReservationText, NULL, 10) : 0;+ const char *largeTaskCountText = getenv("PVG_LARGE_TASK_COUNT");+ uint64_t largeTaskCount = largeTaskCountText && largeTaskCountText[0]+ ? strtoull(largeTaskCountText, NULL, 10) : 0;+ gLargeTaskLimit = (uint32_t)MIN(+ largeTaskCount, sizeof(gLargeTaskIDs) / sizeof(gLargeTaskIDs[0]));+ if (createTask != nil) {+ PVGCreateTaskBlock originalCreate = (PVGCreateTaskBlock)createTask;+ PVGCreateTaskBlock wrappedCreate = ^void *(uint64_t length,+ void **baseAddress) {+ uint64_t effectiveLength = length;+ uint64_t creatingReservationGB = __atomic_load_n(+ &gCreatingTaskReservationGB, __ATOMIC_ACQUIRE);+ uint64_t selectedReservationGB = creatingReservationGB+ ? creatingReservationGB : reservationGB;+ if (selectedReservationGB != 0 && length == (16ULL << 30))+ effectiveLength = selectedReservationGB << 30;+ void *task = originalCreate(effectiveLength, baseAddress);+ Trace(@"TASK_RESERVE\trequested=%llu\teffective=%llu"+ "\tresult=%p\tbase=%p",+ (unsigned long long)length,+ (unsigned long long)effectiveLength,+ task,+ baseAddress ? *baseAddress : NULL);+ return task;+ };+ [descriptor setValue:wrappedCreate forKey:@"createTask"];+ }+ if (mapMemory != nil) {+ PVGMapMemoryBlock originalMap = (PVGMapMemoryBlock)mapMemory;+ PVGMapMemoryBlock wrappedMap = ^BOOL(+ void *task, uint32_t segmentCount, uint64_t offset,+ BOOL readonly, const uint64_t *ranges) {+ uint64_t mappedLength = 0;+ for (uint32_t index = 0; index < segmentCount; index++) {+ uint64_t length = ranges[index * 2 + 1];+ if (UINT64_MAX - mappedLength < length) {+ mappedLength = UINT64_MAX;+ break;+ }+ mappedLength += length;+ }+ uint64_t base = task ? ((const uint64_t *)task)[0] : 0;+ uint64_t reserved = task ? ((const uint64_t *)task)[1] : 0;+ uint64_t end = UINT64_MAX - offset < mappedLength+ ? UINT64_MAX : offset + mappedLength;+ uint64_t count = __atomic_add_fetch(+ &gTaskMapCount, 1, __ATOMIC_RELAXED);+ // Never let a fixed remap escape the sparse reservation. The VM+ // allocator may happen to leave a gap after it, which made the+ // old 1 GiB limit appear to work until a graphics-heavy UI such+ // as Launchpad crossed into unowned address space and killed the+ // VMM. Report a clean map failure instead of corrupting adjacent+ // virtual allocations.+ BOOL withinReservation = task && end <= reserved;+ BOOL result = withinReservation && originalMap(+ task, segmentCount, offset, readonly, ranges);+ uint64_t previousHighWater = __atomic_load_n(+ &gTaskMapHighWater, __ATOMIC_RELAXED);+ BOOL raisedHighWater = NO;+ while (end > previousHighWater) {+ if (__atomic_compare_exchange_n(+ &gTaskMapHighWater, &previousHighWater, end, NO,+ __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {+ raisedHighWater = YES;+ break;+ }+ }+ BOOL crossedHighWaterBucket = raisedHighWater &&+ ((end >> 24) != (previousHighWater >> 24));+ if (count <= 16 || !result || !withinReservation ||+ crossedHighWaterBucket) {+ Trace(@"TASK_MAP\tcount=%llu\ttask=%p\tbase=0x%llx"+ "\treserved=%llu\toffset=%llu\tlength=%llu"+ "\tend=%llu\twithin=%d\thighwater=%d\tsegments=%u"+ "\treadonly=%d\tresult=%d",+ (unsigned long long)count, task,+ (unsigned long long)base,+ (unsigned long long)reserved,+ (unsigned long long)offset,+ (unsigned long long)mappedLength,+ (unsigned long long)end,+ withinReservation,+ crossedHighWaterBucket,+ segmentCount, readonly, result);+ }+ return result;+ };+ [descriptor setValue:wrappedMap forKey:@"mapMemory"];+ }+ id result = PGNewDeviceWithDescriptor(descriptor);+ Trace(@"CALL\tPGNewDeviceWithDescriptor\tresult=%@", result);+ return result;+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} gInterposePGNewDeviceWithDescriptor+ __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&TracePGNewDeviceWithDescriptor,+ (const void *)&PGNewDeviceWithDescriptor,+ };++static id TraceNewDefaultLibraryWithBundle(id self,+ SEL selector,+ NSBundle *bundle,+ NSError **error)+ __attribute__((ns_returns_retained));++static id TraceNewDefaultLibraryWithBundle(id self,+ SEL selector,+ NSBundle *bundle,+ NSError **error) {+ Trace(@"METAL_HOOK\tenter\tselector=%@\tdevice=%p\tbundle=%@",+ NSStringFromSelector(selector),+ self,+ bundle.bundlePath);+ NSError *fallbackError = nil;+ id library = nil;+ if (gSerializedMetallib != nil) {+ library = [self newLibraryWithData:gSerializedMetallib+ error:&fallbackError];+ }++ NSURL *url = [[NSBundle mainBundle]+ URLForResource:@"default"+ withExtension:@"metallib"];+ if (url == nil) {+ url = [bundle URLForResource:@"default" withExtension:@"metallib"];+ }+ if (library == nil && url != nil) {+ fallbackError = nil;+ library = [self newLibraryWithURL:url error:&fallbackError];+ }+ Trace(@"METAL_HOOK\tfallback\turl=%@\tresult=%@\terror=%@",+ url.path,+ library,+ fallbackError);+ if (library != nil && error != NULL) {+ *error = nil;+ } else if (error != NULL) {+ *error = fallbackError;+ }+ return library;+}++static void InstallMetalLibraryFallback(id<MTLDevice> device) {+ SEL selector = @selector(newDefaultLibraryWithBundle:error:);+ Class cls = object_getClass(device);+ Method method = class_getInstanceMethod(cls, selector);+ if (method == NULL) {+ Trace(@"METAL_HOOK\tmissing\tclass=%@", cls);+ return;+ }++ gOriginalNewDefaultLibrarySelector = selector;+ gOriginalNewDefaultLibraryWithBundle =+ (id (*)(id, SEL, NSBundle *, NSError **))method_getImplementation(method);++ Class pvgClass = NSClassFromString(@"_PGDevice");+ Method setupMethod =+ class_getInstanceMethod(pvgClass, NSSelectorFromString(@"setupBlitPipelines"));+ Dl_info pvgInfo = {0};+ if (setupMethod == NULL ||+ dladdr((const void *)method_getImplementation(setupMethod), &pvgInfo) == 0) {+ Trace(@"METAL_HOOK\tfailed-to-find-pvg-image");+ return;+ }++ uintptr_t targetAddress = (uintptr_t)ptrauth_strip(+ (void *)TraceNewDefaultLibraryWithBundle,+ ptrauth_key_function_pointer);+ // Exact macOS 13.2.1 (22D68) calls to+ // -[MTLDevice newDefaultLibraryWithBundle:error:] in+ // PGDisplayPipelineCache and _PGDevice.+ const uintptr_t callOffsets[] = {0xe6d8, 0xed24};+ for (size_t index = 0;+ index < sizeof(callOffsets) / sizeof(callOffsets[0]);+ index++) {+ uint32_t *callInstruction =+ (uint32_t *)((uintptr_t)pvgInfo.dli_fbase + callOffsets[index]);+ uintptr_t callAddress = (uintptr_t)callInstruction;+ intptr_t delta = (intptr_t)targetAddress - (intptr_t)callAddress;+ if ((delta & 3) != 0 ||+ delta < -(1LL << 27) ||+ delta >= (1LL << 27)) {+ Trace(@"METAL_HOOK\tbranch-out-of-range\tcall=%p\ttarget=%p",+ callInstruction,+ (void *)targetAddress);+ return;+ }++ uintptr_t page =+ callAddress & ~((uintptr_t)getpagesize() - 1);+ if (mprotect((void *)page,+ (size_t)getpagesize(),+ PROT_READ | PROT_WRITE) != 0) {+ Trace(@"METAL_HOOK\ttext-mprotect-write-failed\terrno=%d", errno);+ return;+ }+ uint32_t originalInstruction = *callInstruction;+ uint32_t replacementInstruction =+ 0x94000000U | ((uint32_t)(delta >> 2) & 0x03ffffffU);+ *callInstruction = replacementInstruction;+ __builtin___clear_cache(+ (char *)callInstruction,+ (char *)callInstruction + sizeof(*callInstruction));+ if (mprotect((void *)page,+ (size_t)getpagesize(),+ PROT_READ | PROT_EXEC) != 0) {+ Trace(@"METAL_HOOK\ttext-mprotect-read-failed\terrno=%d", errno);+ return;+ }++ Trace(@"METAL_HOOK\tpatched\tcall=%p\ttarget=%p"+ "\tinstruction=%08x->%08x",+ callInstruction,+ (void *)targetAddress,+ originalInstruction,+ replacementInstruction);+ }++ Trace(@"METAL_HOOK\tinstalled\tclass=%@\toriginal=%p\treplacement=%p",+ cls,+ gOriginalNewDefaultLibraryWithBundle,+ TraceNewDefaultLibraryWithBundle);+}++static void InstallBoolHook(Class cls,+ SEL selector,+ BOOL (**original)(id, SEL),+ IMP replacement) {+ Method method = class_getInstanceMethod(cls, selector);+ if (method == NULL) {+ Trace(@"HOOK\t%@\tmissing", NSStringFromSelector(selector));+ return;+ }+ *original = (BOOL (*)(id, SEL))method_setImplementation(method, replacement);+ Trace(@"HOOK\t%@\tinstalled", NSStringFromSelector(selector));+}++static void ProbeMetalLibrary(Class pvgDeviceClass) {+ NSBundle *bundle = [NSBundle bundleForClass:pvgDeviceClass];+ NSURL *url = [bundle URLForResource:@"default" withExtension:@"metallib"];+ Trace(@"BUNDLE\tpath=%@\tmetallib=%@", bundle.bundlePath, url.path);++ NSData *serializedMetallib = [NSData dataWithContentsOfURL:url];+ if (serializedMetallib != nil) {+ void *bytes = malloc(serializedMetallib.length);+ if (bytes != NULL) {+ memcpy(bytes, serializedMetallib.bytes, serializedMetallib.length);+ gSerializedMetallib =+ dispatch_data_create(bytes,+ serializedMetallib.length,+ NULL,+ DISPATCH_DATA_DESTRUCTOR_FREE);+ }+ }+ Trace(@"METAL\tserialized-metallib-bytes=%lu",+ (unsigned long)serializedMetallib.length);++ id<MTLDevice> device = MTLCreateSystemDefaultDevice();+ Trace(@"METAL\tdevice=%@", device);+ if (device == nil) {+ return;+ }+ InstallCommandBufferTrace(device);+ if (getenv("PVG_METALLIB_FALLBACK") != NULL) {+ InstallMetalLibraryFallback(device);+ }++ NSError *error = nil;+ id<MTLLibrary> library = [device newDefaultLibraryWithBundle:bundle error:&error];+ Trace(@"METAL\tnewDefaultLibraryWithBundle\tresult=%@\terror=%@", library, error);+ if (library == nil && url != nil) {+ error = nil;+ library = [device newLibraryWithURL:url error:&error];+ Trace(@"METAL\tnewLibraryWithURL\tresult=%@\terror=%@", library, error);+ }+ if (library == nil) {+ return;+ }++ NSArray<NSString *> *names =+ [library.functionNames sortedArrayUsingSelector:@selector(compare:)];+ Trace(@"METAL\tfunctions=%@", names);+ for (NSString *name in names) {+ if (![name hasPrefix:@"Blit"]) {+ continue;+ }+ id<MTLFunction> function = [library newFunctionWithName:name];+ error = nil;+ id<MTLComputePipelineState> pipeline =+ [device newComputePipelineStateWithFunction:function error:&error];+ Trace(@"METAL\tcompute-pipeline=%d\tfunction=%@\terror=%@",+ pipeline != nil,+ name,+ error);+ }+}++__attribute__((constructor))+static void InstallPVGTrace(void) {+ @autoreleasepool {+ if (getenv("PVG_TRACE") == NULL) {+ return;+ }+ unlink(TracePath());+ Trace(@"TRACE\tloaded\tpid=%d", getpid());++ void *factory = dlsym(RTLD_DEFAULT, "PGNewDeviceWithDescriptor");+ Dl_info factoryInfo = {0};+ dladdr(factory, &factoryInfo);+ Trace(@"SYMBOL\tPGNewDeviceWithDescriptor=%p\tbase=%p\toffset=0x%llx"+ "\timage=%s",+ factory,+ factoryInfo.dli_fbase,+ (unsigned long long)((uintptr_t)factory -+ (uintptr_t)factoryInfo.dli_fbase),+ factoryInfo.dli_fname ?: "(unknown)");++ Class cls = NSClassFromString(@"_PGDevice");+ Trace(@"CLASS\t_PGDevice=%@", cls);+ if (cls == Nil) {+ return;+ }++ SEL initSelector = NSSelectorFromString(@"initWithDescriptor:");+ SEL blitSelector = NSSelectorFromString(@"setupBlitPipelines");+ SEL reportingSelector = NSSelectorFromString(@"setupReporting");+ SEL getTaskSelector = NSSelectorFromString(@"getTaskID:");+ SEL createTaskSelector = NSSelectorFromString(+ @"createTaskID:taskRoot:length:restoring:");+ SEL deleteTaskSelector = NSSelectorFromString(@"deleteTaskID:");+ TraceMethod(cls, initSelector);+ TraceMethod(cls, blitSelector);+ TraceMethod(cls, reportingSelector);+ TraceMethod(cls, getTaskSelector);+ TraceMethod(cls, createTaskSelector);+ TraceMethod(cls, deleteTaskSelector);+ const char *pause = getenv("PVG_TRACE_PAUSE_SECONDS");+ if (pause != NULL) {+ unsigned int seconds = (unsigned int)strtoul(pause, NULL, 10);+ Trace(@"TRACE\tpausing=%u", seconds);+ sleep(seconds);+ Trace(@"TRACE\tresumed");+ }+ ProbeMetalLibrary(cls);+ InstallTextureDescriptorCompatibility();+ InstallMetalSerializerReferenceTrace();++ if (getenv("PVG_TRACE_METHODS") != NULL) {+ Method createTaskMethod = class_getInstanceMethod(+ cls, createTaskSelector);+ if (createTaskMethod != NULL) {+ gOriginalCreateTaskID =+ (void (*)(id, SEL, uint32_t, uint32_t, uint64_t, BOOL))+ method_setImplementation(+ createTaskMethod, (IMP)TraceCreateTaskID);+ Trace(@"HOOK\tcreateTaskID:\tinstalled");+ }+ Method deleteTaskMethod = class_getInstanceMethod(+ cls, deleteTaskSelector);+ if (deleteTaskMethod != NULL) {+ gOriginalDeleteTaskID =+ (BOOL (*)(id, SEL, uint32_t))method_setImplementation(+ deleteTaskMethod, (IMP)TraceDeleteTaskID);+ Trace(@"HOOK\tdeleteTaskID:\tinstalled");+ }+ Method getTaskMethod = class_getInstanceMethod(+ cls, getTaskSelector);+ if (getTaskMethod != NULL) {+ gOriginalGetTaskID =+ (id (*)(id, SEL, uint32_t))method_setImplementation(+ getTaskMethod, (IMP)TraceGetTaskID);+ Trace(@"HOOK\tgetTaskID:\tinstalled");+ } else {+ Trace(@"HOOK\tgetTaskID:\tmissing");+ }+ Method initMethod = class_getInstanceMethod(cls, initSelector);+ if (initMethod != NULL) {+ gOriginalInitWithDescriptor =+ (id (*)(id, SEL, id))method_setImplementation(+ initMethod, (IMP)TraceInitWithDescriptor);+ Trace(@"HOOK\tinitWithDescriptor:\tinstalled");+ }+ Class surfaceClass =+ NSClassFromString(@"PGIOSurfaceHostDevice");+ Method surfaceInitMethod =+ class_getInstanceMethod(surfaceClass, initSelector);+ if (surfaceInitMethod != NULL) {+ gOriginalIOSurfaceInitWithDescriptor =+ (id (*)(id, SEL, id))method_setImplementation(+ surfaceInitMethod,+ (IMP)TraceIOSurfaceInitWithDescriptor);+ Trace(@"HOOK\tPGIOSurfaceHostDevice initWithDescriptor:"+ "\tinstalled");+ } else {+ Trace(@"HOOK\tPGIOSurfaceHostDevice initWithDescriptor:"+ "\tmissing");+ }+ Method newDisplayMethod = class_getInstanceMethod(+ cls,+ NSSelectorFromString(+ @"newDisplayWithDescriptor:port:serialNum:"));+ if (newDisplayMethod != NULL) {+ gOriginalNewDisplay =+ (id (*)(id, SEL, id, NSUInteger, uint32_t))+ method_setImplementation(+ newDisplayMethod, (IMP)TraceNewDisplay);+ Trace(@"HOOK\tnewDisplayWithDescriptor:port:serialNum:"+ "\tinstalled");+ }+ Class displayClass = NSClassFromString(@"_PGDisplay");+ Method displayInitMethod = class_getInstanceMethod(+ displayClass,+ NSSelectorFromString(+ @"initWithDevice:descriptor:port:serialNum:"));+ if (displayInitMethod != NULL) {+ gOriginalDisplayInit =+ (id (*)(id, SEL, id, id, NSUInteger, uint32_t))+ method_setImplementation(+ displayInitMethod, (IMP)TraceDisplayInit);+ Trace(@"HOOK\t_PGDisplay init\tinstalled");+ }+ Class cacheClass =+ NSClassFromString(@"PGDisplayPipelineCache");+ Method cacheInitMethod = class_getInstanceMethod(+ cacheClass, NSSelectorFromString(@"initWithDevice:"));+ if (cacheInitMethod != NULL) {+ gOriginalPipelineCacheInit =+ (id (*)(id, SEL, id))method_setImplementation(+ cacheInitMethod, (IMP)TracePipelineCacheInit);+ Trace(@"HOOK\tPGDisplayPipelineCache initWithDevice:"+ "\tinstalled");+ }+ InstallBoolHook(cls,+ blitSelector,+ &gOriginalSetupBlitPipelines,+ (IMP)TraceSetupBlitPipelines);+ InstallBoolHook(cls,+ reportingSelector,+ &gOriginalSetupReporting,+ (IMP)TraceSetupReporting);+ }+ }+}diff --git a/VirtualMac/vz/host/security_compat.c b/VirtualMac/vz/host/security_compat.cnew file mode 100644index 0000000..d087921--- /dev/null+++ b/VirtualMac/vz/host/security_compat.c@@ -0,0 +1,61 @@+#include <stdint.h>+#include <stdlib.h>++typedef int32_t OSStatus;+enum { errSecUnimplemented = -4, errSecSuccess = 0 };++/*+ * These six APIs are the legacy macOS keychain surface imported by+ * MobileDevice 1857. iPadOS's Security framework has the underlying SecItem+ * API but omits the compatibility entry points. Keep the loader ABI complete;+ * calls are deliberately reported as unsupported until their SecItem-backed+ * translations are exercised by the restore path.+ */+OSStatus SecItemImport(const void *data, const void *name, void *format,+ void *type, uint32_t flags, const void *parameters,+ void *keychain, void *items)+{+ (void)data; (void)name; (void)format; (void)type; (void)flags;+ (void)parameters; (void)keychain; (void)items;+ return errSecUnimplemented;+}++OSStatus SecKeychainAddGenericPassword(void *keychain, uint32_t serviceLength,+ const char *service, uint32_t accountLength,+ const char *account, uint32_t passwordLength,+ const void *password, void *item)+{+ (void)keychain; (void)serviceLength; (void)service; (void)accountLength;+ (void)account; (void)passwordLength; (void)password; (void)item;+ return errSecUnimplemented;+}++OSStatus SecKeychainFindGenericPassword(void *keychain, uint32_t serviceLength,+ const char *service, uint32_t accountLength,+ const char *account, uint32_t *passwordLength,+ void **password, void *item)+{+ (void)keychain; (void)serviceLength; (void)service; (void)accountLength;+ (void)account; (void)passwordLength; (void)password; (void)item;+ return errSecUnimplemented;+}++OSStatus SecKeychainItemDelete(void *item)+{+ (void)item;+ return errSecUnimplemented;+}++OSStatus SecKeychainItemFreeContent(void *attributes, void *data)+{+ (void)attributes;+ free(data);+ return errSecSuccess;+}++OSStatus SecKeychainItemModifyContent(void *item, const void *attributes,+ uint32_t length, const void *data)+{+ (void)item; (void)attributes; (void)length; (void)data;+ return errSecUnimplemented;+}diff --git a/VirtualMac/vz/host/usb_restore_bridge.h b/VirtualMac/vz/host/usb_restore_bridge.hnew file mode 100644index 0000000..665954f--- /dev/null+++ b/VirtualMac/vz/host/usb_restore_bridge.h@@ -0,0 +1,47 @@+#ifndef VZ_USB_RESTORE_BRIDGE_H+#define VZ_USB_RESTORE_BRIDGE_H++#include <stdint.h>++#define VZ_USB_BRIDGE_SOCKET "/tmp/vz-usb-restore.sock"+#define VZ_USB_BRIDGE_MAGIC 0x565a5553U+#define VZ_USB_BRIDGE_VERSION 2U+#define VZ_USB_BRIDGE_MAX_PAYLOAD (64U * 1024U * 1024U)++enum vz_usb_bridge_operation {+ VZ_USB_BRIDGE_GET_STATE = 1,+ VZ_USB_BRIDGE_CONTROL = 2,+ VZ_USB_BRIDGE_BULK = 3,+ VZ_USB_BRIDGE_RESET = 4,+ VZ_USB_BRIDGE_CREATE_ENDPOINT = 5,+};++struct vz_usb_bridge_request {+ uint32_t magic;+ uint16_t version;+ uint16_t operation;+ uint32_t payload_length;+ uint32_t timeout_ms;+ uint8_t request_type;+ uint8_t request;+ uint16_t value;+ uint16_t index;+ uint16_t length;+ uint8_t endpoint;+ uint8_t reserved[3];+ uint32_t transfer_length;+};++struct vz_usb_bridge_response {+ uint32_t magic;+ int32_t status;+ uint32_t payload_length;+ uint32_t device_generation;+ uint16_t vendor_id;+ uint16_t product_id;+ uint8_t device_address;+ uint8_t ready;+ uint8_t reserved[6];+};++#endifdiff --git a/VirtualMac/vz/host/vmm-launchd.plist b/VirtualMac/vz/host/vmm-launchd.plistnew file mode 100644index 0000000..785eadb--- /dev/null+++ b/VirtualMac/vz/host/vmm-launchd.plist@@ -0,0 +1,53 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <!-- Register the iOS-ported VZ VMM as a launchd MachServices daemon under a custom+ name (launchd special-cases the real com.apple.Virtualization.VirtualMachine label+ as a user/foreground Application service). The interpose in the vmnet-stub dependency+ replaces xpc_main with a mach-service listener on org.jb.vmmservice and skips+ sandbox_init. The host maps xpc_connection_create("com.apple.Virtualization.+ VirtualMachine") -> this service.++ Loading (the only path that lands it in the system domain so a root host can reach+ the MachService): place this in /var/jb/Library/LaunchDaemons/ and `ldrestart`+ (userspace reboot). Dopamine's launchdhook hooks xpc_dictionary_get_value in launchd+ and injects /var/jb/{basebin,Library}/LaunchDaemons into launchd's "LaunchDaemons"+ dict + "Paths" scan, so they load in launchd's system context at (userspace) boot.+ Runtime `launchctl bootstrap system` from ssh instead lands in user/501 -> EX_CONFIG.+ UserName=root + ProgramArguments (array) match Dopamine's own working daemon plists+ (com.opa334.Dopamine.idownloadd); a system daemon without UserName fell to user/501. -->+ <key>Label</key>+ <string>org.jb.vmmservice</string>+ <!-- Mirror com.openssh.sshd (the one Library/LaunchDaemons daemon that IS in the system+ domain): POSIXSpawnType/ProcessType Interactive + SessionCreate + ExecuteAllowed. Also+ install in /var/jb/basebin/LaunchDaemons (where idownloadd, also system-domain, lives). -->+ <key>POSIXSpawnType</key>+ <string>Interactive</string>+ <key>ProcessType</key>+ <string>Interactive</string>+ <key>Program</key>+ <string>/var/root/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine</string>+ <key>ProgramArguments</key>+ <array>+ <string>/var/root/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine</string>+ </array>+ <key>UserName</key>+ <string>root</string>+ <key>MachServices</key>+ <dict>+ <key>org.jb.vmmservice</key>+ <true/>+ </dict>+ <key>SessionCreate</key>+ <true/>+ <key>ExecuteAllowed</key>+ <true/>+ <key>RunAtLoad</key>+ <false/>+ <key>StandardErrorPath</key>+ <string>/tmp/vmm.err</string>+ <key>StandardOutPath</key>+ <string>/tmp/vmm.out</string>+</dict>+</plist>diff --git a/VirtualMac/vz/host/vmmhook.m b/VirtualMac/vz/host/vmmhook.mnew file mode 100644index 0000000..08497ee--- /dev/null+++ b/VirtualMac/vz/host/vmmhook.m@@ -0,0 +1,2321 @@+// DYLD_INSERT hook for the iOS-ported VZ VMM service.+// The VMM's main() calls xpc_main(handler), but iOS xpc_main requires the launchd+// XPCService-domain context (it reads the job's "XPCService" config dict -> "Could not+// retrieve service name"); iOS launchd doesn't register framework XPCServices that way.+// We interpose xpc_main with a plain MACH-SERVICE listener instead: a MachServices+// launchd daemon (vmm-launchd.plist) gives us the receive right for+// "com.apple.Virtualization.VirtualMachine", and the host reaches us via+// xpc_connection_create_mach_service(name). The handler passed to xpc_main is invoked+// once per incoming peer connection (a bare function pointer in this libxpc).+//+// The iOS SDK marks xpc_main / xpc_connection_create_mach_service __API_UNAVAILABLE(ios),+// though iOS libxpc exports them, so we declare them ourselves and link with+// -undefined dynamic_lookup (resolved at runtime from libSystem/libxpc).+#import <objc/message.h>+#import <objc/runtime.h>++#include <IOKit/IOKitLib.h>+#include <CoreFoundation/CoreFoundation.h>+#include <dispatch/dispatch.h>+#include <errno.h>+#include <stdint.h>+#include <stdio.h>+#include <stdarg.h>+#include <stdlib.h>+#include <string.h>+#include <fcntl.h>+#include <limits.h>+#include <dlfcn.h>+#include <mach-o/dyld.h>+#include <mach/mach_time.h>+#include <ptrauth.h>+#include <pthread.h>+#include <sys/mman.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/un.h>+#include <unistd.h>++#include "usb_restore_bridge.h"++typedef void *xo_t; // xpc_object_t / xpc_connection_t (opaque pointers)+extern void xpc_main(void (*handler)(xo_t));+extern xo_t xpc_connection_create_mach_service(const char *, dispatch_queue_t, uint64_t);+extern xo_t xpc_connection_create(const char *name, dispatch_queue_t q);+extern xo_t xpc_endpoint_create(xo_t connection);+extern xo_t xpc_connection_create_from_endpoint(xo_t endpoint);+extern void xpc_connection_set_event_handler(xo_t, void (^)(xo_t));+extern void xpc_connection_resume(xo_t);+extern void xpc_connection_send_message(xo_t, xo_t);+extern void xpc_connection_send_message_with_reply(+ xo_t, xo_t, dispatch_queue_t, void (^)(xo_t));+extern void *xpc_get_type(xo_t);+extern const char *xpc_dictionary_get_string(xo_t, const char *);+extern xo_t xpc_dictionary_get_value(xo_t, const char *);+extern void xpc_dictionary_set_bool(xo_t, const char *, bool);+extern void xpc_dictionary_set_uint64(xo_t, const char *, uint64_t);+extern char *xpc_copy_description(xo_t);+extern char _xpc_type_connection[]; // XPC_TYPE_CONNECTION+extern char _xpc_type_dictionary[]; // XPC_TYPE_DICTIONARY+extern char _xpc_type_error[]; // XPC_TYPE_ERROR+extern int sandbox_init(const char *profile, uint64_t flags, char **errorbuf);++// xpc_endpoint object layout: the backing mach send-right is a uint32 at +0x18+// (confirmed on iPadOS 16.3.1 via vz/development/probes/epprobe.m). iPad hands the host's+// anonymous-listener port to us as an inherited send right (name in VMM_EP_PORT); we+// rebuild an endpoint by port-swap and connect back, peer-to-peer (no launchd).+#define XPC_ENDPOINT_PORT_OFF 0x18++// Custom name: launchd reserves/special-cases com.apple.Virtualization.VirtualMachine+// (an Application-type service it forces to user/foreground), refusing our system daemon+// with EX_CONFIG. A plain custom MachService name registers + spawns fine. The host+// interposes xpc_connection_create("com.apple.Virtualization.VirtualMachine") to connect here.+#define VMM_SERVICE "org.jb.vmmservice"+#define XPC_MACH_SERVICE_LISTENER 1ULL++static void logf_(const char *fmt, ...) {+ FILE *f = fopen("/tmp/vmmhook.log", "a"); if (!f) return;+ fchmod(fileno(f), 0666);+ va_list ap; va_start(ap, fmt); vfprintf(f, fmt, ap); va_end(ap);+ fputc('\n', f); fclose(f);+}++static void log_address(const char *label, void *address) {+ Dl_info info = {0};+ if (address && dladdr(address, &info) && info.dli_fbase) {+ logf_("[vmmhook] %s=%p image=%s +0x%llx symbol=%s",+ label, address, info.dli_fname ? info.dli_fname : "?",+ (unsigned long long)((uintptr_t)address -+ (uintptr_t)info.dli_fbase),+ info.dli_sname ? info.dli_sname : "?");+ } else {+ logf_("[vmmhook] %s=%p (dladdr failed)", label, address);+ }+}++static uint64_t xpc_trace_count;+static uint64_t xpc_digitizer_received;+static uint64_t xpc_digitizer_processed;+static uint64_t xpc_keyboard_received;+static uint64_t xpc_keyboard_processed;+static uint64_t xpc_frame_updates;+static uint64_t xpc_cursor_updates;+static uint64_t iosurface_create_count;+static void *vmm_vcpu_exits[64];+static uint64_t vmm_vcpu_exit_counts[64];+static uint64_t vmm_vcpu_exit_reason_counts[64][4];+static uint64_t vmm_vcpu_last_cntv_ctl[64];+static uint64_t vmm_vcpu_last_cntv_cval[64];+static uint64_t vmm_vcpu_last_mach_time[64];+static uint64_t vmm_vtimer_mask_calls[64];+static uint64_t vmm_vtimer_last_mask[64];+static uint64_t vmm_vtimer_offset_calls[64];+static uint64_t vmm_vtimer_last_offset[64];+static uint64_t vmm_vcpus_exit_calls;+static xo_t fake_usb_location_reply_connection;++static bool fake_usb_hci_enabled(void);++static uint32_t vmm_latest_exit_reason(size_t index) {+ void *exit = index < 64+ ? __atomic_load_n(&vmm_vcpu_exits[index], __ATOMIC_ACQUIRE)+ : NULL;+ return exit ? *(volatile uint32_t *)exit : UINT32_MAX;+}++static uint64_t vmm_latest_exit_syndrome(size_t index) {+ void *exit = index < 64+ ? __atomic_load_n(&vmm_vcpu_exits[index], __ATOMIC_ACQUIRE)+ : NULL;+ return exit ? *(volatile uint64_t *)((uint8_t *)exit + 8) : 0;+}++static const char *xpc_message_name(xo_t message) {+ if (!message || xpc_get_type(message) != (void *)_xpc_type_dictionary)+ return NULL;+ return xpc_dictionary_get_string(message, "name");+}++static void count_received_xpc(const char *name) {+ if (!name)+ return;+ if (strcmp(name, "process_digitizer_events") == 0)+ __atomic_add_fetch(&xpc_digitizer_received, 1, __ATOMIC_RELAXED);+ else if (strcmp(name, "process_keyboard_events") == 0)+ __atomic_add_fetch(&xpc_keyboard_received, 1, __ATOMIC_RELAXED);+}++static void count_processed_xpc(const char *name) {+ if (!name)+ return;+ if (strcmp(name, "process_digitizer_events") == 0)+ __atomic_add_fetch(&xpc_digitizer_processed, 1, __ATOMIC_RELAXED);+ else if (strcmp(name, "process_keyboard_events") == 0)+ __atomic_add_fetch(&xpc_keyboard_processed, 1, __ATOMIC_RELAXED);+}++static void count_sent_xpc(const char *name) {+ if (!name)+ return;+ if (strcmp(name, "process_frame_update") == 0)+ __atomic_add_fetch(&xpc_frame_updates, 1, __ATOMIC_RELAXED);+ else if (strcmp(name, "process_cursor_update") == 0)+ __atomic_add_fetch(&xpc_cursor_updates, 1, __ATOMIC_RELAXED);+}++typedef void *iosurface_ref_t;+extern iosurface_ref_t IOSurfaceCreate(CFDictionaryRef properties);+extern uint32_t IOSurfaceGetID(iosurface_ref_t surface);++// Ask iPadOS to register PVG's IOSurfaces globally before its native+// IOSurfaceCreateXPCObject path transfers the Mach right to the UIKit host.+static iosurface_ref_t vmm_IOSurfaceCreate(CFDictionaryRef properties) {+ CFMutableDictionaryRef globalProperties =+ CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, properties);+ CFDictionarySetValue(+ globalProperties, CFSTR("IOSurfaceIsGlobal"), kCFBooleanTrue);+ iosurface_ref_t surface = IOSurfaceCreate(globalProperties);+ uint32_t identifier = surface ? IOSurfaceGetID(surface) : 0;+ uint64_t count = __atomic_add_fetch(+ &iosurface_create_count, 1, __ATOMIC_RELAXED);+ if (count <= 12 || count % 300 == 0) {+ logf_("[vmmhook] IOSurfaceCreate #%llu requested-global=1 "+ "-> %p id=%u",+ (unsigned long long)count, surface, identifier);+ }+ CFRelease(globalProperties);+ return surface;+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_iosurface_create __attribute__((section("__DATA,__interpose"))) = {+ (const void *)&vmm_IOSurfaceCreate,+ (const void *)&IOSurfaceCreate,+};++static bool should_trace_xpc(uint64_t *sequence) {+ const char *limit_text = getenv("VMMHOOK_TRACE_XPC_LIMIT");+ uint64_t limit = limit_text ? strtoull(limit_text, NULL, 0) : 0;+ *sequence = __atomic_add_fetch(&xpc_trace_count, 1, __ATOMIC_RELAXED);+ return *sequence <= limit;+}++static void trace_xpc_message(const char *operation, xo_t connection,+ xo_t message) {+ const char *name = xpc_message_name(message);+ if (name && strcmp(name, "guest_did_post_trace_event") == 0)+ return;+ uint64_t sequence;+ if (!should_trace_xpc(&sequence))+ return;+ char *description = xpc_copy_description(message);+ logf_("[vmmhook] XPC #%llu %s connection=%p message=%s",+ (unsigned long long)sequence, operation, connection,+ description ? description : "?");+ if (description)+ free(description);+}++static void vmm_xpc_connection_send_message(xo_t connection, xo_t message) {+ if (fake_usb_hci_enabled() &&+ connection == fake_usb_location_reply_connection &&+ message && xpc_get_type(message) == (void *)_xpc_type_dictionary) {+ xo_t result = xpc_dictionary_get_value(message, "result");+ if (result && xpc_get_type(result) == (void *)_xpc_type_dictionary) {+ // Without AppleUSBUserHCIResources there is no IORegistry+ // AppleUSBUserHCIPort node from which VMM can recover locationID.+ // Preserve the value produced by Ventura's genuine virtual USB+ // controller so Installation/MobileDevice can bind to this AVP+ // transport.+ xpc_dictionary_set_bool(result, "has_value", true);+ xpc_dictionary_set_uint64(result, "value", 0x80100000U);+ fake_usb_location_reply_connection = NULL;+ logf_("[vmmhook] supplied fake USB controller location ID "+ "0x80100000");+ }+ }+ count_sent_xpc(xpc_message_name(message));+ trace_xpc_message("send", connection, message);+ xpc_connection_send_message(connection, message);+}++static void vmm_xpc_connection_send_message_with_reply(+ xo_t connection, xo_t message, dispatch_queue_t queue,+ void (^handler)(xo_t)) {+ count_sent_xpc(xpc_message_name(message));+ trace_xpc_message("send-with-reply", connection, message);+ xpc_connection_send_message_with_reply(+ connection, message, queue, handler);+}++static void vmm_xpc_connection_set_event_handler(+ xo_t connection, void (^handler)(xo_t)) {+ xpc_connection_set_event_handler(connection, ^(xo_t event) {+ const char *name = xpc_message_name(event);+ count_received_xpc(name);+ trace_xpc_message("receive", connection, event);+ if (fake_usb_hci_enabled() && name &&+ strcmp(name, "get_usb_controller_location_id") == 0)+ fake_usb_location_reply_connection = connection;+ handler(event);+ count_processed_xpc(name);+ });+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_xpc_send __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_xpc_connection_send_message,+ (const void *)&xpc_connection_send_message };+__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_xpc_send_with_reply __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_xpc_connection_send_message_with_reply,+ (const void *)&xpc_connection_send_message_with_reply };+__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_xpc_set_handler __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_xpc_connection_set_event_handler,+ (const void *)&xpc_connection_set_event_handler };++typedef id (*usb_hci_init_t)(id, SEL, id, id, uint64_t, id *, id, id, id);+static usb_hci_init_t original_usb_hci_init;+typedef bool (*usb_hci_enqueue_one_t)(id, SEL, const void *, id *);+typedef bool (*usb_hci_enqueue_one_expedite_t)(id, SEL, const void *, bool,+ id *);+typedef bool (*usb_hci_enqueue_many_t)(id, SEL, const void *, uintptr_t, id *);+typedef bool (*usb_hci_enqueue_many_expedite_t)(id, SEL, const void *,+ uintptr_t, bool, id *);+typedef void (*usb_hci_destroy_t)(id, SEL);+static usb_hci_enqueue_one_t original_usb_hci_enqueue_one;+static usb_hci_enqueue_one_expedite_t original_usb_hci_enqueue_one_expedite;+static usb_hci_enqueue_many_t original_usb_hci_enqueue_many;+static usb_hci_enqueue_many_expedite_t original_usb_hci_enqueue_many_expedite;+static usb_hci_destroy_t original_usb_hci_destroy;+static char fake_usb_hci_marker_key;+static char fake_usb_hci_doorbell_handler_key;+static uint64_t fake_usb_hci_interrupt_count;++typedef struct {+ uint32_t control;+ uint32_t data0;+ uint64_t data1;+} usb_hci_message_t;++typedef void (^usb_hci_command_handler_t)(id, usb_hci_message_t);+typedef void (^usb_hci_doorbell_handler_t)(id, const uint32_t *, uintptr_t);+extern void *_Block_copy(const void *block);++enum {+ FakeUSBHostStageIdle = 0,+ FakeUSBHostStageControllerPowerOn,+ FakeUSBHostStageControllerStart,+ FakeUSBHostStagePortPowerOn,+ FakeUSBHostStagePortStatus,+ FakeUSBHostStageWaitForConnect,+ FakeUSBHostStagePortReset,+ FakeUSBHostStageDeviceCreate,+ FakeUSBHostStageDeviceCreated,+ FakeUSBHostStageEndpointCreate,+ FakeUSBHostStageEndpointReset,+ FakeUSBHostStageEndpointSetNextTransfer,+ FakeUSBHostStageReadDeviceDescriptor,+ FakeUSBHostStageDeviceDescriptorRead,+ FakeUSBHostStageFailed,+};++static int fake_usb_host_stage;+static uint8_t fake_usb_host_device_address;+static id fake_usb_host_controller;+static usb_hci_command_handler_t fake_usb_host_command_handler;+static usb_hci_doorbell_handler_t fake_usb_host_doorbell_handler;+static dispatch_queue_t fake_usb_host_queue;+static unsigned fake_usb_descriptor_retry_count;++static uint8_t fake_usb_ep0_descriptor[7] __attribute__((aligned(16))) = {+ 7, 5, 0, 0, 64, 0, 0,+};+static uint8_t fake_usb_device_descriptor[64] __attribute__((aligned(16)));+static usb_hci_message_t fake_usb_device_descriptor_transfer[4]+ __attribute__((aligned(16)));++typedef struct {+ dispatch_semaphore_t command_done;+ dispatch_semaphore_t transfer_done;+ uint32_t command_type;+ usb_hci_message_t *terminal;+ int command_status;+ int transfer_status;+ uint32_t actual_length;+} fake_usb_bridge_pending_t;++static void fake_usb_bridge_pending_destroy(+ fake_usb_bridge_pending_t *pending) {+ if (pending->command_done) {+ dispatch_release(pending->command_done);+ pending->command_done = NULL;+ }+ if (pending->transfer_done) {+ dispatch_release(pending->transfer_done);+ pending->transfer_done = NULL;+ }+}++static pthread_mutex_t fake_usb_bridge_lock = PTHREAD_MUTEX_INITIALIZER;+static pthread_mutex_t fake_usb_bridge_command_lock =+ PTHREAD_MUTEX_INITIALIZER;+static pthread_mutex_t fake_usb_bridge_bulk_input_lock =+ PTHREAD_MUTEX_INITIALIZER;+static pthread_mutex_t fake_usb_bridge_bulk_output_lock =+ PTHREAD_MUTEX_INITIALIZER;+static fake_usb_bridge_pending_t *fake_usb_bridge_command_pending;+static fake_usb_bridge_pending_t *fake_usb_bridge_transfer_pending[256];+static bool fake_usb_bridge_started;+static uint32_t fake_usb_device_generation = 1;+static usb_hci_message_t *fake_usb_bridge_tail;+static usb_hci_message_t *fake_usb_bridge_retained_ring;+static bool fake_usb_bridge_endpoints[256];+// AVP's endpoint object retains the descriptor pointer supplied to the+// EndpointCreate command and reads fields such as wMaxPacketSize for every+// later transfer. These descriptors therefore must live until the USB+// personality is torn down; a command-local buffer becomes a delayed UAF on+// com.apple.virtualization.usb.hci once restore traffic reaches that endpoint.+static uint8_t fake_usb_bridge_endpoint_descriptors[256][7]+ __attribute__((aligned(16)));+static usb_hci_message_t *fake_usb_bridge_bulk_tails[256];+static usb_hci_message_t *fake_usb_bridge_bulk_rings[256];+static pthread_mutex_t fake_usb_bridge_mux_cache_lock =+ PTHREAD_MUTEX_INITIALIZER;+static uint8_t fake_usb_bridge_mux_reply[4096];+static uint32_t fake_usb_bridge_mux_reply_length;+static uint32_t fake_usb_bridge_mux_generation;+static unsigned fake_usb_bridge_mux_suppress_writes;++static void fake_usb_bridge_prepare_restoreos(uint32_t generation);++static bool fake_usb_read_full(int fd, void *buffer, size_t length) {+ uint8_t *bytes = buffer;+ while (length) {+ ssize_t count = read(fd, bytes, length);+ if (count == 0)+ return false;+ if (count < 0) {+ if (errno == EINTR)+ continue;+ return false;+ }+ bytes += count;+ length -= (size_t)count;+ }+ return true;+}++static bool fake_usb_write_full(int fd, const void *buffer, size_t length) {+ const uint8_t *bytes = buffer;+ while (length) {+ ssize_t count = write(fd, bytes, length);+ if (count < 0) {+ if (errno == EINTR)+ continue;+ return false;+ }+ bytes += count;+ length -= (size_t)count;+ }+ return true;+}++static bool fake_usb_hci_enabled(void) {+ const char *value = getenv("VMMHOOK_FAKE_USB");+ return value && value[0] != '\0' && strcmp(value, "0") != 0;+}++static bool fake_usb_trace_enabled(void) {+ const char *value = getenv("VMMHOOK_TRACE_USB");+ return value && value[0] != '\0' && strcmp(value, "0") != 0;+}++static bool is_fake_usb_hci(id object) {+ return objc_getAssociatedObject(object, &fake_usb_hci_marker_key) != nil;+}++static const char *fake_usb_host_stage_name(int stage) {+ switch (stage) {+ case FakeUSBHostStageIdle: return "idle";+ case FakeUSBHostStageControllerPowerOn: return "controller-power-on";+ case FakeUSBHostStageControllerStart: return "controller-start";+ case FakeUSBHostStagePortPowerOn: return "port-power-on";+ case FakeUSBHostStagePortStatus: return "port-status";+ case FakeUSBHostStageWaitForConnect: return "wait-for-connect";+ case FakeUSBHostStagePortReset: return "port-reset";+ case FakeUSBHostStageDeviceCreate: return "device-create";+ case FakeUSBHostStageDeviceCreated: return "device-created";+ case FakeUSBHostStageEndpointCreate: return "endpoint-create";+ case FakeUSBHostStageEndpointReset: return "endpoint-reset";+ case FakeUSBHostStageEndpointSetNextTransfer:+ return "endpoint-set-next-transfer";+ case FakeUSBHostStageReadDeviceDescriptor:+ return "read-device-descriptor";+ case FakeUSBHostStageDeviceDescriptorRead:+ return "device-descriptor-read";+ case FakeUSBHostStageFailed: return "failed";+ default: return "unknown";+ }+}++static void fake_usb_host_send_after(id controller, int stage,+ uint32_t type, uint32_t data0,+ uint64_t data1, uint64_t delay_ns) {+ usb_hci_command_handler_t handler = fake_usb_host_command_handler;+ dispatch_queue_t queue = fake_usb_host_queue;+ if (controller != fake_usb_host_controller || !handler || !queue) {+ logf_("[vmmhook] fake USB cannot send type=0x%02x: "+ "controller=%p active=%p handler=%p queue=%p", type,+ controller, fake_usb_host_controller, handler, queue);+ __atomic_store_n(&fake_usb_host_stage, FakeUSBHostStageFailed,+ __ATOMIC_RELEASE);+ return;+ }+ __atomic_store_n(&fake_usb_host_stage, stage, __ATOMIC_RELEASE);+ usb_hci_message_t message = {+ .control = 0x8000U | (type & 0x3fU),+ .data0 = data0,+ .data1 = data1,+ };+ logf_("[vmmhook] fake USB send stage=%s control=0x%08x "+ "data0=0x%08x data1=0x%016llx delay-ns=%llu",+ fake_usb_host_stage_name(stage), message.control, message.data0,+ (unsigned long long)message.data1,+ (unsigned long long)delay_ns);+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)delay_ns),+ queue, ^{+ handler(controller, message);+ });+}++static void fake_usb_host_send(id controller, int stage, uint32_t type,+ uint32_t data0, uint64_t data1) {+ fake_usb_host_send_after(controller, stage, type, data0, data1, 0);+}++static void fake_usb_host_prepare_device_descriptor_transfer(void) {+ memset(fake_usb_device_descriptor, 0,+ sizeof(fake_usb_device_descriptor));+ memset(fake_usb_device_descriptor_transfer, 0,+ sizeof(fake_usb_device_descriptor_transfer));+ // This is the exact first control-transfer ring emitted by+ // IOUSBHost.framework 1.2 on Ventura 13.2.1. Bit 15 owns the first three+ // messages on the controller side; the invalid terminator has the+ // opposite ownership bit (bit 14). Asking for only the traditional+ // eight-byte prefix, or reversing these bits, makes the AVP backend+ // return StallError before it sends anything to the restore device.+ fake_usb_device_descriptor_transfer[0].control = 0x8038;+ fake_usb_device_descriptor_transfer[0].data1 =+ 0x80ULL | (6ULL << 8) | (0x0100ULL << 16) | (18ULL << 48);+ fake_usb_device_descriptor_transfer[1].control = 0x8039;+ fake_usb_device_descriptor_transfer[1].data0 = 18;+ fake_usb_device_descriptor_transfer[1].data1 =+ (uintptr_t)fake_usb_device_descriptor;+ fake_usb_device_descriptor_transfer[2].control = 0x803a;+ fake_usb_device_descriptor_transfer[3].control = 0x403c;+}++static void fake_usb_host_ring_ep0_doorbell(id controller) {+ usb_hci_doorbell_handler_t handler = fake_usb_host_doorbell_handler;+ if (!handler) {+ logf_("[vmmhook] fake USB cannot ring EP0: missing handler");+ __atomic_store_n(&fake_usb_host_stage, FakeUSBHostStageFailed,+ __ATOMIC_RELEASE);+ return;+ }++ uint32_t doorbell = (uint32_t)fake_usb_host_device_address;+ __atomic_store_n(&fake_usb_host_stage,+ FakeUSBHostStageReadDeviceDescriptor,+ __ATOMIC_RELEASE);+ logf_("[vmmhook] fake USB ring EP0 doorbell=0x%08x transfer=%p "+ "buffer=%p", doorbell, fake_usb_device_descriptor_transfer,+ fake_usb_device_descriptor);+ handler(controller, &doorbell, 1);+}++static void fake_usb_log_device_descriptor(void) {+ char bytes[3 * 18 + 1] = {0};+ size_t offset = 0;+ for (size_t index = 0; index < 18; index++) {+ int written = snprintf(bytes + offset, sizeof(bytes) - offset,+ "%02x%s", fake_usb_device_descriptor[index],+ index == 17 ? "" : " ");+ if (written < 0)+ break;+ offset += (size_t)written;+ }+ logf_("[vmmhook] fake USB device descriptor: %s", bytes);+}++static uint16_t fake_usb_descriptor_u16(size_t offset) {+ return (uint16_t)fake_usb_device_descriptor[offset] |+ ((uint16_t)fake_usb_device_descriptor[offset + 1] << 8);+}++static bool fake_usb_bridge_wait(dispatch_semaphore_t semaphore,+ uint32_t timeout_ms) {+ uint64_t nanoseconds = (uint64_t)(timeout_ms ? timeout_ms : 30000) *+ NSEC_PER_MSEC;+ return dispatch_semaphore_wait(+ semaphore,+ dispatch_time(DISPATCH_TIME_NOW, (int64_t)nanoseconds)) == 0;+}++static int fake_usb_bridge_command(uint32_t type, uint32_t data0,+ uint64_t data1,+ fake_usb_bridge_pending_t *pending,+ uint32_t timeout_ms) {+ usb_hci_command_handler_t handler = fake_usb_host_command_handler;+ dispatch_queue_t queue = fake_usb_host_queue;+ id controller = fake_usb_host_controller;+ if (!handler || !queue || !controller)+ return ENODEV;++ pthread_mutex_lock(&fake_usb_bridge_command_lock);+ pending->command_type = type;+ pending->command_status = -1;+ __atomic_store_n(&fake_usb_bridge_command_pending, pending,+ __ATOMIC_RELEASE);+ usb_hci_message_t message = {+ .control = 0x8000U | (type & 0x3fU),+ .data0 = data0,+ .data1 = data1,+ };+ dispatch_async(queue, ^{+ handler(controller, message);+ });+ if (!fake_usb_bridge_wait(pending->command_done, timeout_ms)) {+ logf_("[vmmhook] USB bridge command 0x%x timed out", type);+ __atomic_store_n(&fake_usb_bridge_command_pending, NULL,+ __ATOMIC_RELEASE);+ pthread_mutex_unlock(&fake_usb_bridge_command_lock);+ return ETIMEDOUT;+ }+ __atomic_store_n(&fake_usb_bridge_command_pending, NULL,+ __ATOMIC_RELEASE);+ int result = pending->command_status == 1 ? 0 : EIO;+ pthread_mutex_unlock(&fake_usb_bridge_command_lock);+ return result;+}++static int fake_usb_bridge_reset_ep0(uint32_t timeout_ms) {+ fake_usb_bridge_pending_t pending = {+ .command_done = dispatch_semaphore_create(0),+ .transfer_done = dispatch_semaphore_create(0),+ };+ int result = fake_usb_bridge_command(+ 0x2d, fake_usb_host_device_address, 1, &pending, timeout_ms);+ logf_("[vmmhook] USB bridge reset endpoint 0 address=%u -> %d",+ fake_usb_host_device_address, result);+ fake_usb_bridge_pending_destroy(&pending);+ return result;+}++static int fake_usb_bridge_control(+ const struct vz_usb_bridge_request *request, uint8_t *payload,+ uint32_t *actual_length) {+ bool input = (request->request_type & 0x80U) != 0;+ if (!input && request->payload_length != request->length)+ return EINVAL;++ usb_hci_message_t *ring = NULL;+ uint8_t *transfer_buffer = NULL;+ if (posix_memalign((void **)&ring, 16, 4 * sizeof(*ring)) != 0)+ return ENOMEM;+ memset(ring, 0, 4 * sizeof(*ring));+ if (request->length &&+ posix_memalign((void **)&transfer_buffer, 16,+ request->length) != 0) {+ free(ring);+ return ENOMEM;+ }+ if (!input && request->length)+ memcpy(transfer_buffer, payload, request->length);++ ring[0].control = 0x8038;+ ring[0].data1 =+ (uint64_t)request->request_type |+ ((uint64_t)request->request << 8) |+ ((uint64_t)request->value << 16) |+ ((uint64_t)request->index << 32) |+ ((uint64_t)request->length << 48);+ usb_hci_message_t *terminal = NULL;+ if (request->length) {+ ring[1].control = 0x8039;+ ring[1].data0 = request->length;+ ring[1].data1 = (uintptr_t)transfer_buffer;+ ring[2].control = 0x803a;+ ring[3].control = 0x403c;+ terminal = &ring[2];+ } else {+ ring[1].control = 0x803a;+ ring[2].control = 0x403c;+ terminal = &ring[1];+ }++ fake_usb_bridge_pending_t pending = {+ .command_done = dispatch_semaphore_create(0),+ .transfer_done = dispatch_semaphore_create(0),+ .terminal = terminal,+ .transfer_status = -1,+ };+ usb_hci_message_t *previous_tail = fake_usb_bridge_tail;+ usb_hci_message_t *previous_ring = fake_usb_bridge_retained_ring;+ int result = 0;+ if (!previous_tail) {+ // ResetEndpoint invalidates the controller's saved dequeue pointer.+ // Hand the AVP backend a new ring exactly as IOUSBHost does before+ // ringing the endpoint doorbell again.+ result = fake_usb_bridge_command(+ 0x2e, fake_usb_host_device_address, (uintptr_t)ring, &pending,+ request->timeout_ms);+ }+ if (!result) {+ __atomic_store_n(&fake_usb_bridge_transfer_pending[0], &pending,+ __ATOMIC_RELEASE);+ uint32_t doorbell = fake_usb_host_device_address;+ usb_hci_doorbell_handler_t handler = fake_usb_host_doorbell_handler;+ id controller = fake_usb_host_controller;+ dispatch_queue_t queue = fake_usb_host_queue;+ dispatch_async(queue, ^{+ // IOUSBHost owns a persistent ring per endpoint. Appending is+ // performed by filling the previous InvalidTransfer link and+ // handing ownership to AVP; EndpointSetNextTransfer is only valid+ // for the first ring and returns InvalidState thereafter.+ if (previous_tail) {+ previous_tail->data1 = (uintptr_t)ring;+ __atomic_thread_fence(__ATOMIC_RELEASE);+ previous_tail->control = 0xc03c;+ }+ handler(controller, &doorbell, 1);+ });+ if (!fake_usb_bridge_wait(pending.transfer_done,+ request->timeout_ms)) {+ logf_("[vmmhook] USB bridge control request 0x%02x timed out",+ request->request);+ result = ETIMEDOUT;+ } else if (pending.transfer_status != 1) {+ result = EIO;+ }+ if (!result) {+ fake_usb_bridge_tail = request->length ? &ring[3] : &ring[2];+ fake_usb_bridge_retained_ring = ring;+ } else {+ // A STALL halts endpoint 0 in the real AVP device. Native+ // IOUSBHost clears it before the next DeviceRequest; without+ // that command all subsequent transfers merely time out.+ fake_usb_bridge_tail = NULL;+ fake_usb_bridge_retained_ring = NULL;+ }+ if (previous_ring)+ free(previous_ring);+ }+ __atomic_store_n(&fake_usb_bridge_transfer_pending[0], NULL,+ __ATOMIC_RELEASE);+ if (result && fake_usb_host_device_address)+ fake_usb_bridge_reset_ep0(request->timeout_ms);+ if (!result) {+ *actual_length = request->length+ ? pending.actual_length : 0;+ if (input && *actual_length)+ memcpy(payload, transfer_buffer, *actual_length);+ }+ free(transfer_buffer);+ if (!fake_usb_bridge_retained_ring ||+ fake_usb_bridge_retained_ring != ring)+ free(ring);+ fake_usb_bridge_pending_destroy(&pending);+ return result;+}++static int fake_usb_bridge_bulk(+ const struct vz_usb_bridge_request *request, uint8_t *payload,+ uint32_t *actual_length) {+ uint8_t endpoint = request->endpoint;+ bool input = (endpoint & 0x80U) != 0;+ uint32_t length = request->transfer_length;+ if (!endpoint || !fake_usb_bridge_endpoints[endpoint] ||+ length > VZ_USB_BRIDGE_MAX_PAYLOAD ||+ (!input && request->payload_length != length) ||+ (input && request->payload_length != 0))+ return EINVAL;++ static const uint8_t mux_greeting[20] = {+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08,+ 0x00, 0x00, 0x00, 0x00,+ };+ pthread_mutex_lock(&fake_usb_bridge_mux_cache_lock);+ bool cached_generation =+ fake_usb_bridge_mux_generation == fake_usb_device_generation;+ if (input && endpoint == 0x81 && cached_generation &&+ fake_usb_bridge_mux_reply_length) {+ uint32_t cached_length = fake_usb_bridge_mux_reply_length;+ if (cached_length > length) {+ pthread_mutex_unlock(&fake_usb_bridge_mux_cache_lock);+ return EOVERFLOW;+ }+ memcpy(payload, fake_usb_bridge_mux_reply, cached_length);+ fake_usb_bridge_mux_reply_length = 0;+ *actual_length = cached_length;+ pthread_mutex_unlock(&fake_usb_bridge_mux_cache_lock);+ logf_("[vmmhook] USB bridge replayed cached USBMux reply "+ "generation=%u length=%u", fake_usb_device_generation,+ cached_length);+ return 0;+ }+ bool suppress = false;+ if (!input && endpoint == 0x01 && cached_generation) {+ if (fake_usb_bridge_mux_suppress_writes == 2 && length == 0) {+ fake_usb_bridge_mux_suppress_writes = 1;+ suppress = true;+ } else if (fake_usb_bridge_mux_suppress_writes == 1 &&+ length == sizeof(mux_greeting) &&+ memcmp(payload, mux_greeting, sizeof(mux_greeting)) == 0) {+ fake_usb_bridge_mux_suppress_writes = 0;+ suppress = true;+ }+ }+ pthread_mutex_unlock(&fake_usb_bridge_mux_cache_lock);+ if (suppress) {+ *actual_length = length;+ logf_("[vmmhook] USB bridge suppressed replayed USBMux write "+ "generation=%u length=%u", fake_usb_device_generation,+ length);+ return 0;+ }++ usb_hci_message_t *ring = NULL;+ uint8_t *transfer_buffer = NULL;+ if (posix_memalign((void **)&ring, 16, 2 * sizeof(*ring)) != 0)+ return ENOMEM;+ memset(ring, 0, 2 * sizeof(*ring));+ if (posix_memalign((void **)&transfer_buffer, 16, length ?: 1) != 0) {+ free(ring);+ return ENOMEM;+ }+ if (!input && length)+ memcpy(transfer_buffer, payload, length);++ if (!input && length <= 64 && fake_usb_trace_enabled()) {+ char bytes[3 * 64 + 1] = {0};+ size_t offset = 0;+ for (uint32_t index = 0; index < length; index++) {+ int written = snprintf(bytes + offset, sizeof(bytes) - offset,+ "%02x%s", transfer_buffer[index],+ index + 1 == length ? "" : " ");+ if (written < 0)+ break;+ offset += (size_t)written;+ }+ logf_("[vmmhook] USB bridge bulk OUT endpoint=0x%02x "+ "length=%u bytes=%s", endpoint, length, bytes);+ }++ ring[0].control = 0x8039;+ ring[0].data0 = length;+ ring[0].data1 = (uintptr_t)transfer_buffer;+ ring[1].control = 0x403c;++ fake_usb_bridge_pending_t pending = {+ .command_done = dispatch_semaphore_create(0),+ .transfer_done = dispatch_semaphore_create(0),+ .terminal = &ring[0],+ .transfer_status = -1,+ };+ usb_hci_message_t *previous_tail =+ fake_usb_bridge_bulk_tails[endpoint];+ usb_hci_message_t *previous_ring =+ fake_usb_bridge_bulk_rings[endpoint];+ uint32_t endpoint_key = ((uint32_t)endpoint << 8) |+ fake_usb_host_device_address;+ int result = 0;+ if (!previous_tail) {+ result = fake_usb_bridge_command(+ 0x2e, endpoint_key, (uintptr_t)ring, &pending,+ request->timeout_ms);+ }+ if (!result) {+ __atomic_store_n(&fake_usb_bridge_transfer_pending[endpoint],+ &pending, __ATOMIC_RELEASE);+ usb_hci_doorbell_handler_t handler = fake_usb_host_doorbell_handler;+ id controller = fake_usb_host_controller;+ dispatch_queue_t queue = fake_usb_host_queue;+ dispatch_async(queue, ^{+ if (previous_tail) {+ previous_tail->data1 = (uintptr_t)ring;+ __atomic_thread_fence(__ATOMIC_RELEASE);+ previous_tail->control = 0xc03c;+ }+ handler(controller, &endpoint_key, 1);+ });+ if (!fake_usb_bridge_wait(pending.transfer_done,+ request->timeout_ms)) {+ logf_("[vmmhook] USB bridge bulk endpoint=0x%02x timed out",+ endpoint);+ result = ETIMEDOUT;+ } else if (pending.transfer_status != 1) {+ result = EIO;+ }+ if (!result) {+ fake_usb_bridge_bulk_tails[endpoint] = &ring[1];+ fake_usb_bridge_bulk_rings[endpoint] = ring;+ } else {+ fake_usb_bridge_bulk_tails[endpoint] = NULL;+ fake_usb_bridge_bulk_rings[endpoint] = NULL;+ }+ if (previous_ring)+ free(previous_ring);+ }+ __atomic_store_n(&fake_usb_bridge_transfer_pending[endpoint], NULL,+ __ATOMIC_RELEASE);+ if (result) {+ fake_usb_bridge_pending_t reset_pending = {+ .command_done = dispatch_semaphore_create(0),+ .transfer_done = dispatch_semaphore_create(0),+ };+ fake_usb_bridge_command(0x2d, endpoint_key, 1, &reset_pending,+ request->timeout_ms);+ fake_usb_bridge_pending_destroy(&reset_pending);+ } else {+ *actual_length = input ? pending.actual_length : length;+ if (*actual_length > length) {+ logf_("[vmmhook] USB bridge bulk endpoint=0x%02x returned "+ "oversize transfer %u > %u", endpoint, *actual_length,+ length);+ result = EOVERFLOW;+ *actual_length = 0;+ } else if (input && *actual_length) {+ memcpy(payload, transfer_buffer, *actual_length);+ if (*actual_length <= 64 && fake_usb_trace_enabled()) {+ char bytes[3 * 64 + 1] = {0};+ size_t offset = 0;+ for (uint32_t index = 0; index < *actual_length; index++) {+ int written = snprintf(+ bytes + offset, sizeof(bytes) - offset, "%02x%s",+ transfer_buffer[index],+ index + 1 == *actual_length ? "" : " ");+ if (written < 0)+ break;+ offset += (size_t)written;+ }+ logf_("[vmmhook] USB bridge bulk IN endpoint=0x%02x "+ "length=%u bytes=%s", endpoint, *actual_length,+ bytes);+ }+ }+ }+ free(transfer_buffer);+ if (fake_usb_bridge_bulk_rings[endpoint] != ring)+ free(ring);+ if (result || fake_usb_trace_enabled())+ logf_("[vmmhook] USB bridge bulk endpoint=0x%02x length=%u -> %d "+ "actual=%u", endpoint, length, result,+ result ? 0 : *actual_length);+ fake_usb_bridge_pending_destroy(&pending);+ return result;+}++static void fake_usb_bridge_drop_personality(void) {+ usb_hci_message_t *retained_ring = fake_usb_bridge_retained_ring;+ fake_usb_bridge_tail = NULL;+ fake_usb_bridge_retained_ring = NULL;+ if (retained_ring)+ free(retained_ring);+ for (unsigned endpoint = 0; endpoint < 256; endpoint++) {+ if (fake_usb_bridge_bulk_rings[endpoint])+ free(fake_usb_bridge_bulk_rings[endpoint]);+ fake_usb_bridge_bulk_rings[endpoint] = NULL;+ fake_usb_bridge_bulk_tails[endpoint] = NULL;+ }+ fake_usb_host_device_address = 0;+ memset(fake_usb_bridge_endpoints, 0,+ sizeof(fake_usb_bridge_endpoints));+ memset(fake_usb_bridge_endpoint_descriptors, 0,+ sizeof(fake_usb_bridge_endpoint_descriptors));+ pthread_mutex_lock(&fake_usb_bridge_mux_cache_lock);+ fake_usb_bridge_mux_reply_length = 0;+ fake_usb_bridge_mux_generation = 0;+ fake_usb_bridge_mux_suppress_writes = 0;+ pthread_mutex_unlock(&fake_usb_bridge_mux_cache_lock);+ fake_usb_descriptor_retry_count = 0;+ __atomic_add_fetch(&fake_usb_device_generation, 1, __ATOMIC_ACQ_REL);+}++static void fake_usb_bridge_prime_restoreos_mux(uint32_t generation) {+ static const uint8_t greeting[20] = {+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08,+ 0x00, 0x00, 0x00, 0x00,+ };+ __block struct {+ struct vz_usb_bridge_request request;+ uint8_t payload[32768];+ uint32_t actual;+ int result;+ } input = {+ .request = {+ .endpoint = 0x81,+ .transfer_length = 32768,+ .timeout_ms = 5000,+ },+ };+ dispatch_group_t group = dispatch_group_create();+ dispatch_group_async(group, dispatch_get_global_queue(+ QOS_CLASS_USER_INITIATED, 0), ^{+ input.result = fake_usb_bridge_bulk(&input.request, input.payload,+ &input.actual);+ });+ usleep(20000);++ struct vz_usb_bridge_request output = {+ .endpoint = 0x01,+ .timeout_ms = 5000,+ };+ uint32_t actual = 0;+ int result = fake_usb_bridge_bulk(&output, NULL, &actual);+ output.payload_length = sizeof(greeting);+ output.transfer_length = sizeof(greeting);+ if (!result)+ result = fake_usb_bridge_bulk(&output, (uint8_t *)greeting,+ &actual);+ dispatch_group_wait(group, DISPATCH_TIME_FOREVER);+ if (!result)+ result = input.result;+ if (result || generation != fake_usb_device_generation ||+ !input.actual || input.actual > sizeof(fake_usb_bridge_mux_reply)) {+ logf_("[vmmhook] RestoreOS USBMux handshake failed "+ "generation=%u output=%d input=%d actual=%u",+ generation, result, input.result, input.actual);+ return;+ }++ pthread_mutex_lock(&fake_usb_bridge_mux_cache_lock);+ memcpy(fake_usb_bridge_mux_reply, input.payload, input.actual);+ fake_usb_bridge_mux_reply_length = input.actual;+ fake_usb_bridge_mux_generation = generation;+ fake_usb_bridge_mux_suppress_writes = 2;+ pthread_mutex_unlock(&fake_usb_bridge_mux_cache_lock);+ logf_("[vmmhook] RestoreOS USBMux handshake cached generation=%u "+ "length=%u", generation, input.actual);+}++static int fake_usb_bridge_reset(uint32_t timeout_ms) {+ fake_usb_bridge_pending_t pending = {+ .command_done = dispatch_semaphore_create(0),+ .transfer_done = dispatch_semaphore_create(0),+ };+ int result = fake_usb_bridge_command(0x1c, 1, 0, &pending,+ timeout_ms);+ fake_usb_bridge_pending_destroy(&pending);+ if (result)+ return result;++ // USBDeviceReEnumerate asks the host controller to reset the actual+ // restore device. The personalized iBSS then disconnects/reconnects as a+ // new USB personality. Drop only our userspace EP0 ring and run the same+ // AVP port-status/enumeration sequence used for initial DFU discovery.+ fake_usb_bridge_drop_personality();+ fake_usb_host_send_after(fake_usb_host_controller,+ FakeUSBHostStagePortStatus, 0x1e, 1, 0,+ 500 * NSEC_PER_MSEC);+ logf_("[vmmhook] USB bridge reset real device; awaiting next "+ "personality generation=%u", fake_usb_device_generation);+ return 0;+}++static int fake_usb_bridge_create_endpoint(const uint8_t *descriptor,+ uint32_t length,+ uint32_t timeout_ms) {+ if (!descriptor || length < 7 || descriptor[0] < 7 ||+ descriptor[1] != 5 || !fake_usb_host_device_address)+ return EINVAL;+ uint8_t endpoint = descriptor[2];+ if (!endpoint)+ return EINVAL;+ if (fake_usb_bridge_endpoints[endpoint])+ return 0;+ fake_usb_bridge_pending_t pending = {+ .command_done = dispatch_semaphore_create(0),+ .transfer_done = dispatch_semaphore_create(0),+ };+ uint8_t *endpoint_descriptor =+ fake_usb_bridge_endpoint_descriptors[endpoint];+ memcpy(endpoint_descriptor, descriptor,+ sizeof(fake_usb_bridge_endpoint_descriptors[endpoint]));+ uint32_t endpoint_key = ((uint32_t)endpoint << 8) |+ fake_usb_host_device_address;+ int result = fake_usb_bridge_command(+ 0x28, endpoint_key, (uintptr_t)endpoint_descriptor, &pending,+ timeout_ms);+ if (!result)+ fake_usb_bridge_endpoints[endpoint] = true;+ logf_("[vmmhook] USB bridge create endpoint=0x%02x address=%u "+ "max-packet=%u -> %d", endpoint, fake_usb_host_device_address,+ (unsigned)endpoint_descriptor[4] |+ ((unsigned)endpoint_descriptor[5] << 8), result);+ fake_usb_bridge_pending_destroy(&pending);+ return result;+}++static int fake_usb_bridge_control_simple(uint8_t request_type,+ uint8_t request,+ uint16_t value,+ uint16_t index,+ uint8_t *payload,+ uint32_t length,+ uint32_t *actual_length) {+ struct vz_usb_bridge_request bridge_request = {+ .request_type = request_type,+ .request = request,+ .value = value,+ .index = index,+ .length = length,+ .payload_length = (request_type & 0x80U) ? 0 : length,+ .timeout_ms = 5000,+ };+ return fake_usb_bridge_control(&bridge_request, payload, actual_length);+}++static void fake_usb_bridge_prepare_restoreos(uint32_t generation) {+ // RestoreOS disconnects after only a few seconds if the host leaves its+ // USB device unconfigured. Native IOUSBHost configures it before+ // usbmuxd publishes the attachment. Do that time-critical part here;+ // MobileDevice still owns the subsequent USBMux/restore protocol.+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ pthread_mutex_lock(&fake_usb_bridge_lock);+ if (generation != fake_usb_device_generation ||+ fake_usb_descriptor_u16(10) != 0x12ac ||+ __atomic_load_n(&fake_usb_host_stage, __ATOMIC_ACQUIRE) !=+ FakeUSBHostStageDeviceDescriptorRead) {+ pthread_mutex_unlock(&fake_usb_bridge_lock);+ return;+ }++ uint8_t configuration[4096] = {0};+ uint32_t actual = 0;+ int result = fake_usb_bridge_control_simple(+ 0x80, 0x06, 0x0200, 0, configuration, 9, &actual);+ if (result || actual < 9) {+ logf_("[vmmhook] RestoreOS configuration header failed -> %d "+ "actual=%u", result, actual);+ pthread_mutex_unlock(&fake_usb_bridge_lock);+ return;+ }+ uint32_t total = (uint32_t)configuration[2] |+ ((uint32_t)configuration[3] << 8);+ if (total < 9 || total > sizeof(configuration)) {+ logf_("[vmmhook] RestoreOS invalid configuration length=%u",+ total);+ pthread_mutex_unlock(&fake_usb_bridge_lock);+ return;+ }+ memset(configuration, 0, total);+ result = fake_usb_bridge_control_simple(+ 0x80, 0x06, 0x0200, 0, configuration, total, &actual);+ if (result || actual < total) {+ logf_("[vmmhook] RestoreOS configuration read failed -> %d "+ "actual=%u expected=%u", result, actual, total);+ pthread_mutex_unlock(&fake_usb_bridge_lock);+ return;+ }+ char bytes[3 * sizeof(configuration) + 1] = {0};+ size_t text_offset = 0;+ for (uint32_t offset = 0; offset < total; offset++) {+ int written = snprintf(bytes + text_offset,+ sizeof(bytes) - text_offset,+ "%02x%s", configuration[offset],+ offset + 1 == total ? "" : " ");+ if (written < 0)+ break;+ text_offset += (size_t)written;+ }+ logf_("[vmmhook] RestoreOS configuration generation=%u length=%u: "+ "%s", generation, total, bytes);++ uint8_t configuration_value = configuration[5];+ actual = 0;+ result = fake_usb_bridge_control_simple(+ 0x00, 0x09, configuration_value, 0, NULL, 0, &actual);+ if (result) {+ logf_("[vmmhook] RestoreOS set configuration %u failed -> %d",+ configuration_value, result);+ pthread_mutex_unlock(&fake_usb_bridge_lock);+ return;+ }++ bool active_interface = false;+ for (uint32_t offset = 0; offset + 2 <= total;) {+ uint8_t descriptor_length = configuration[offset];+ uint8_t descriptor_type = configuration[offset + 1];+ if (descriptor_length < 2 || offset + descriptor_length > total)+ break;+ if (descriptor_type == 4 && descriptor_length >= 9)+ active_interface = configuration[offset + 3] == 0;+ else if (descriptor_type == 5 && descriptor_length >= 7 &&+ active_interface) {+ result = fake_usb_bridge_create_endpoint(+ configuration + offset, descriptor_length, 5000);+ if (result)+ break;+ }+ offset += descriptor_length;+ }+ logf_("[vmmhook] RestoreOS USB configured generation=%u value=%u "+ "endpoints-in=0x%02x endpoints-out=0x%02x -> %d",+ generation, configuration_value,+ fake_usb_bridge_endpoints[0x81] ? 0x81 : 0,+ fake_usb_bridge_endpoints[0x02] ? 0x02 : 0, result);+ pthread_mutex_unlock(&fake_usb_bridge_lock);+ if (!result)+ fake_usb_bridge_prime_restoreos_mux(generation);+ });+}++static void fake_usb_bridge_handle_client(int client) {+ struct vz_usb_bridge_request request = {0};+ if (!fake_usb_read_full(client, &request, sizeof(request)) ||+ request.magic != VZ_USB_BRIDGE_MAGIC ||+ request.version != VZ_USB_BRIDGE_VERSION ||+ request.payload_length > VZ_USB_BRIDGE_MAX_PAYLOAD ||+ (request.operation == VZ_USB_BRIDGE_BULK &&+ request.transfer_length > VZ_USB_BRIDGE_MAX_PAYLOAD))+ return;++ uint32_t payload_capacity = request.payload_length;+ if (request.operation == VZ_USB_BRIDGE_BULK &&+ (request.endpoint & 0x80U) &&+ request.transfer_length > payload_capacity)+ payload_capacity = request.transfer_length;+ else if ((request.request_type & 0x80U) &&+ request.length > payload_capacity)+ payload_capacity = request.length;+ uint8_t *payload = payload_capacity ? malloc(payload_capacity) : NULL;+ if (payload_capacity && !payload)+ return;+ if (request.payload_length) {+ if (!fake_usb_read_full(client, payload, request.payload_length)) {+ free(payload);+ return;+ }+ }++ struct vz_usb_bridge_response response = {+ .magic = VZ_USB_BRIDGE_MAGIC,+ .device_generation = fake_usb_device_generation,+ .vendor_id = fake_usb_descriptor_u16(8),+ .product_id = fake_usb_descriptor_u16(10),+ .device_address = fake_usb_host_device_address,+ .ready = __atomic_load_n(&fake_usb_host_stage, __ATOMIC_ACQUIRE) ==+ FakeUSBHostStageDeviceDescriptorRead,+ };+ pthread_mutex_t *operation_lock = &fake_usb_bridge_lock;+ if (request.operation == VZ_USB_BRIDGE_BULK) {+ operation_lock = (request.endpoint & 0x80U)+ ? &fake_usb_bridge_bulk_input_lock+ : &fake_usb_bridge_bulk_output_lock;+ }+ pthread_mutex_lock(operation_lock);+ if (request.operation == VZ_USB_BRIDGE_GET_STATE) {+ response.status = response.ready ? 0 : ENODEV;+ } else if (request.operation == VZ_USB_BRIDGE_CONTROL && response.ready) {+ uint32_t actual = 0;+ response.status = fake_usb_bridge_control(&request, payload, &actual);+ response.payload_length =+ (request.request_type & 0x80U) ? actual : 0;+ logf_("[vmmhook] USB bridge control type=0x%02x request=0x%02x "+ "value=0x%04x index=0x%04x length=%u -> %d actual=%u",+ request.request_type, request.request, request.value,+ request.index, request.length, response.status, actual);+ } else if (request.operation == VZ_USB_BRIDGE_RESET && response.ready) {+ response.status = fake_usb_bridge_reset(request.timeout_ms);+ response.ready = 0;+ response.device_generation = fake_usb_device_generation;+ logf_("[vmmhook] USB bridge re-enumerate -> %d generation=%u",+ response.status, response.device_generation);+ } else if (request.operation == VZ_USB_BRIDGE_CREATE_ENDPOINT &&+ response.ready) {+ response.status = fake_usb_bridge_create_endpoint(+ payload, request.payload_length, request.timeout_ms);+ } else if (request.operation == VZ_USB_BRIDGE_BULK && response.ready) {+ uint32_t actual = 0;+ response.status = fake_usb_bridge_bulk(&request, payload, &actual);+ response.payload_length = (request.endpoint & 0x80U) ? actual : 0;+ } else {+ response.status = response.ready ? ENOTSUP : ENODEV;+ }+ pthread_mutex_unlock(operation_lock);++ if (fake_usb_write_full(client, &response, sizeof(response)) &&+ response.payload_length)+ fake_usb_write_full(client, payload, response.payload_length);+ free(payload);+}++static void fake_usb_bridge_start(void) {+ if (__atomic_exchange_n(&fake_usb_bridge_started, true,+ __ATOMIC_ACQ_REL))+ return;+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ unlink(VZ_USB_BRIDGE_SOCKET);+ int server = socket(AF_UNIX, SOCK_STREAM, 0);+ if (server < 0) {+ logf_("[vmmhook] USB bridge socket failed: %s", strerror(errno));+ return;+ }+ struct sockaddr_un address = { .sun_family = AF_UNIX };+ strlcpy(address.sun_path, VZ_USB_BRIDGE_SOCKET,+ sizeof(address.sun_path));+ if (bind(server, (struct sockaddr *)&address, sizeof(address)) < 0 ||+ chmod(VZ_USB_BRIDGE_SOCKET, 0666) < 0 ||+ listen(server, SOMAXCONN) < 0) {+ logf_("[vmmhook] USB bridge listen failed: %s", strerror(errno));+ close(server);+ return;+ }+ logf_("[vmmhook] USB bridge ready at %s", VZ_USB_BRIDGE_SOCKET);+ for (;;) {+ int client = accept(server, NULL, NULL);+ if (client < 0) {+ if (errno == EINTR)+ continue;+ break;+ }+ dispatch_async(dispatch_get_global_queue(+ QOS_CLASS_USER_INITIATED, 0), ^{+ fake_usb_bridge_handle_client(client);+ close(client);+ });+ }+ close(server);+ unlink(VZ_USB_BRIDGE_SOCKET);+ });+}++static void fake_usb_host_poll_port(id controller) {+ id retained_controller = controller;+ dispatch_queue_t queue = fake_usb_host_queue;+ if (!queue)+ return;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), queue, ^{+ int stage = __atomic_load_n(&fake_usb_host_stage, __ATOMIC_ACQUIRE);+ if (stage == FakeUSBHostStageWaitForConnect) {+ fake_usb_host_send(retained_controller,+ FakeUSBHostStagePortStatus, 0x1e, 1, 0);+ }+ });+}++static void fake_usb_host_process_interrupt(id controller,+ const usb_hci_message_t *message) {+ uint32_t type = message->control & 0x3fU;+ uint32_t status = (message->control >> 8) & 0xfU;+ int stage = __atomic_load_n(&fake_usb_host_stage, __ATOMIC_ACQUIRE);+ fake_usb_bridge_pending_t *command_pending = __atomic_load_n(+ &fake_usb_bridge_command_pending, __ATOMIC_ACQUIRE);++ if (command_pending && type == command_pending->command_type) {+ command_pending->command_status = (int)status;+ dispatch_semaphore_signal(command_pending->command_done);+ return;+ }++ if (type == 0x08) {+ logf_("[vmmhook] fake USB port event port=%u stage=%s",+ message->data0 & 0xfU, fake_usb_host_stage_name(stage));+ if (stage == FakeUSBHostStageDeviceDescriptorRead) {+ // iBoot's `go` disconnects Recovery and later reconnects as the+ // RestoreOS USB personality. This port-change is not initiated+ // by USBDeviceReEnumerate, so begin a fresh enumeration here and+ // publish a new generation to the IOUSBLib façade.+ fake_usb_bridge_drop_personality();+ fake_usb_host_send(controller, FakeUSBHostStagePortStatus,+ 0x1e, message->data0 & 0xfU, 0);+ } else if (stage >= FakeUSBHostStagePortPowerOn &&+ stage <= FakeUSBHostStageWaitForConnect) {+ fake_usb_host_send(controller, FakeUSBHostStagePortStatus,+ 0x1e, message->data0 & 0xfU, 0);+ }+ return;+ }++ if (type < 0x10 || type > 0x37)+ goto transfer_interrupt;+ if (status != 1) {+ logf_("[vmmhook] fake USB command failed stage=%s type=0x%02x "+ "status=0x%x", fake_usb_host_stage_name(stage), type,+ status);+ __atomic_store_n(&fake_usb_host_stage, FakeUSBHostStageFailed,+ __ATOMIC_RELEASE);+ return;+ }++ switch (type) {+ case 0x10:+ if (stage == FakeUSBHostStageControllerPowerOn)+ fake_usb_host_send(controller, FakeUSBHostStageControllerStart,+ 0x12, 0, 0);+ break;+ case 0x12:+ if (stage == FakeUSBHostStageControllerStart)+ fake_usb_host_send(controller, FakeUSBHostStagePortPowerOn,+ 0x18, 1, 0);+ break;+ case 0x18:+ if (stage == FakeUSBHostStagePortPowerOn)+ fake_usb_host_send(controller, FakeUSBHostStagePortStatus,+ 0x1e, 1, 0);+ break;+ case 0x1e:+ if (stage == FakeUSBHostStagePortStatus) {+ bool connected = (message->data1 & (1ULL << 2)) != 0;+ unsigned speed = (unsigned)((message->data1 >> 8) & 0x7U);+ logf_("[vmmhook] fake USB port status=0x%016llx "+ "connected=%d speed=%u",+ (unsigned long long)message->data1, connected, speed);+ if (connected) {+ fake_usb_host_send(controller, FakeUSBHostStagePortReset,+ 0x1c, 1, 0);+ } else {+ __atomic_store_n(&fake_usb_host_stage,+ FakeUSBHostStageWaitForConnect,+ __ATOMIC_RELEASE);+ fake_usb_host_poll_port(controller);+ }+ }+ break;+ case 0x1c:+ if (stage == FakeUSBHostStagePortReset)+ fake_usb_host_send(controller, FakeUSBHostStageDeviceCreate,+ 0x20, 1, 0);+ break;+ case 0x20:+ if (stage == FakeUSBHostStageDeviceCreate) {+ fake_usb_host_device_address = (uint8_t)(message->data1 & 0xffU);+ logf_("[vmmhook] fake USB device created address=%u",+ fake_usb_host_device_address);+ fake_usb_host_send(+ controller, FakeUSBHostStageEndpointCreate, 0x28,+ fake_usb_host_device_address,+ (uintptr_t)fake_usb_ep0_descriptor);+ }+ break;+ case 0x28:+ if (stage == FakeUSBHostStageEndpointCreate) {+ fake_usb_host_prepare_device_descriptor_transfer();+ fake_usb_host_send(+ controller, FakeUSBHostStageEndpointSetNextTransfer, 0x2e,+ fake_usb_host_device_address,+ (uintptr_t)fake_usb_device_descriptor_transfer);+ }+ break;+ case 0x2d:+ if (stage == FakeUSBHostStageEndpointReset) {+ fake_usb_host_send(+ controller, FakeUSBHostStageEndpointSetNextTransfer, 0x2e,+ fake_usb_host_device_address,+ (uintptr_t)fake_usb_device_descriptor_transfer);+ }+ break;+ case 0x2e:+ if (stage == FakeUSBHostStageEndpointSetNextTransfer)+ fake_usb_host_ring_ep0_doorbell(controller);+ break;+ default:+ break;+ }+ return;++transfer_interrupt:+ if (type == 0x3d) {+ uint8_t address = (uint8_t)((message->control >> 16) & 0xffU);+ uint8_t endpoint = (uint8_t)((message->control >> 24) & 0xffU);+ fake_usb_bridge_pending_t *pending = __atomic_load_n(+ &fake_usb_bridge_transfer_pending[endpoint], __ATOMIC_ACQUIRE);+ usb_hci_message_t *completed =+ (usb_hci_message_t *)(uintptr_t)message->data1;+ if (status != 1 || fake_usb_trace_enabled())+ logf_("[vmmhook] fake USB transfer complete address=%u "+ "endpoint=0x%02x status=0x%x length=%u transfer=%p "+ "stage=%s", address, endpoint, status,+ message->data0 & 0x0fffffffU,+ (void *)(uintptr_t)message->data1,+ fake_usb_host_stage_name(stage));+ if (pending) {+ if (status != 1) {+ pending->transfer_status = (int)status;+ dispatch_semaphore_signal(pending->transfer_done);+ return;+ }+ uint32_t length = message->data0 & 0x0fffffffU;+ if (length)+ pending->actual_length = length;+ if (completed == pending->terminal) {+ pending->transfer_status = (int)status;+ dispatch_semaphore_signal(pending->transfer_done);+ }+ return;+ }+ if (stage == FakeUSBHostStageReadDeviceDescriptor &&+ completed == &fake_usb_device_descriptor_transfer[1]) {+ if (status == 1 && (message->data0 & 0x0fffffffU) == 18) {+ fake_usb_log_device_descriptor();+ __atomic_store_n(&fake_usb_host_stage,+ FakeUSBHostStageDeviceDescriptorRead,+ __ATOMIC_RELEASE);+ fake_usb_bridge_tail =+ &fake_usb_device_descriptor_transfer[3];+ fake_usb_bridge_retained_ring = NULL;+ fake_usb_bridge_start();+ if (fake_usb_descriptor_u16(10) == 0x12ac)+ fake_usb_bridge_prepare_restoreos(+ fake_usb_device_generation);+ } else if (status == 0xb &&+ fake_usb_descriptor_retry_count < 15) {+ fake_usb_descriptor_retry_count++;+ logf_("[vmmhook] fake USB descriptor stalled; "+ "reset/retry %u in one second",+ fake_usb_descriptor_retry_count);+ fake_usb_host_send_after(+ controller, FakeUSBHostStageEndpointReset, 0x2d,+ fake_usb_host_device_address, 1, NSEC_PER_SEC);+ }+ }+ }+}++static void trace_fake_usb_interrupts(id controller,+ const usb_hci_message_t *messages,+ uintptr_t count, bool expedite) {+ if (!messages)+ return;+ for (uintptr_t index = 0; index < count; index++) {+ const usb_hci_message_t *message = &messages[index];+ uint64_t sequence = __atomic_add_fetch(+ &fake_usb_hci_interrupt_count, 1, __ATOMIC_RELAXED);+ if (fake_usb_trace_enabled())+ logf_("[vmmhook] fake USB interrupt #%llu index=%llu/%llu "+ "expedite=%d control=0x%08x type=0x%02x status=0x%x "+ "data0=0x%08x data1=0x%016llx",+ (unsigned long long)sequence,+ (unsigned long long)(index + 1),+ (unsigned long long)count, expedite,+ message->control, message->control & 0x3f,+ (message->control >> 8) & 0xf, message->data0,+ (unsigned long long)message->data1);+ fake_usb_host_process_interrupt(controller, message);+ }+}++static bool fake_usb_hci_enqueue_one(id self, SEL command,+ const void *interrupt, id *error) {+ if (!is_fake_usb_hci(self))+ return original_usb_hci_enqueue_one(self, command, interrupt, error);+ if (error)+ *error = nil;+ trace_fake_usb_interrupts(self, interrupt, 1, false);+ return true;+}++static bool fake_usb_hci_enqueue_one_expedite(id self, SEL command,+ const void *interrupt,+ bool expedite, id *error) {+ if (!is_fake_usb_hci(self)) {+ return original_usb_hci_enqueue_one_expedite(+ self, command, interrupt, expedite, error);+ }+ if (error)+ *error = nil;+ trace_fake_usb_interrupts(self, interrupt, 1, expedite);+ return true;+}++static bool fake_usb_hci_enqueue_many(id self, SEL command,+ const void *interrupts,+ uintptr_t count, id *error) {+ if (!is_fake_usb_hci(self)) {+ return original_usb_hci_enqueue_many(+ self, command, interrupts, count, error);+ }+ if (error)+ *error = nil;+ trace_fake_usb_interrupts(self, interrupts, count, false);+ return true;+}++static bool fake_usb_hci_enqueue_many_expedite(id self, SEL command,+ const void *interrupts,+ uintptr_t count,+ bool expedite, id *error) {+ if (!is_fake_usb_hci(self)) {+ return original_usb_hci_enqueue_many_expedite(+ self, command, interrupts, count, expedite, error);+ }+ if (error)+ *error = nil;+ trace_fake_usb_interrupts(self, interrupts, count, expedite);+ return true;+}++static void fake_usb_hci_destroy(id self, SEL command) {+ if (!is_fake_usb_hci(self)) {+ original_usb_hci_destroy(self, command);+ return;+ }+ logf_("[vmmhook] fake IOUSBHostControllerInterface destroy");+}++static id send_object(id object, const char *selector) {+ return ((id (*)(id, SEL))objc_msgSend)(object, sel_registerName(selector));+}++static const char *object_utf8(id object) {+ id description = object ? send_object(object, "description") : nil;+ return description+ ? ((const char *(*)(id, SEL))objc_msgSend)(+ description, sel_registerName("UTF8String"))+ : "(none)";+}++static id traced_usb_hci_init(id self, SEL command, id capabilities, id queue,+ uint64_t interrupt_rate_hz, id *error,+ id command_handler, id doorbell_handler,+ id interest_handler) {+ if (fake_usb_hci_enabled()) {+ self = ((id (*)(id, SEL))objc_msgSend)(+ self, sel_registerName("init"));+ if (!self) {+ logf_("[vmmhook] fake USB NSObject initialization failed");+ return nil;+ }+ objc_setAssociatedObject(self, &fake_usb_hci_marker_key, self,+ OBJC_ASSOCIATION_ASSIGN);+ if (doorbell_handler) {+ objc_setAssociatedObject(self, &fake_usb_hci_doorbell_handler_key,+ doorbell_handler,+ OBJC_ASSOCIATION_COPY_NONATOMIC);+ }+ dispatch_queue_t host_queue = (dispatch_queue_t)queue;+ if (!host_queue) {+ host_queue = dispatch_queue_create(+ "org.jb.vmmservice.fake-usb-host", DISPATCH_QUEUE_SERIAL);+ }+ if (!host_queue) {+ host_queue = dispatch_get_global_queue(+ QOS_CLASS_USER_INITIATED, 0);+ }+ fake_usb_host_controller = self;+ fake_usb_host_command_handler = command_handler+ ? (usb_hci_command_handler_t)_Block_copy(command_handler)+ : nil;+ fake_usb_host_doorbell_handler = doorbell_handler+ ? (usb_hci_doorbell_handler_t)_Block_copy(doorbell_handler)+ : nil;+ fake_usb_host_queue = host_queue;++ // Preserve the userspace half of IOUSBHostControllerInterface's real+ // initializer. The omitted half only allocates interrupt buffers and+ // opens AppleUSBUserHCIResources in the kernel. VMM's command path+ // relies on these state-machine ivars even when enqueueInterrupt: is+ // interposed, so returning an otherwise raw allocated object makes the+ // first ControllerPowerOn command fail validation.+ id capabilities_data = capabilities+ ? ((id (*)(id, SEL))objc_msgSend)(+ capabilities, sel_registerName("mutableCopy"))+ : nil;+ Ivar capabilities_ivar = class_getInstanceVariable(+ object_getClass(self), "_capabilitiesData");+ if (capabilities_ivar && capabilities_data)+ object_setIvar(self, capabilities_ivar, capabilities_data);+ const void *capability_bytes = capabilities_data+ ? ((const void *(*)(id, SEL))objc_msgSend)(+ capabilities_data, sel_registerName("bytes"))+ : NULL;+ ((void (*)(id, SEL, const void *))objc_msgSend)(+ self, sel_registerName("setCapabilities:"), capability_bytes);+ ((void (*)(id, SEL, id))objc_msgSend)(+ self, sel_registerName("setQueue:"), (id)host_queue);+ ((void (*)(id, SEL, uint64_t))objc_msgSend)(+ self, sel_registerName("setInterruptRateHz:"),+ interrupt_rate_hz);+ ((void (*)(id, SEL, id))objc_msgSend)(+ self, sel_registerName("setCommandHandler:"), command_handler);+ ((void (*)(id, SEL, id))objc_msgSend)(+ self, sel_registerName("setDoorbellHandler:"), doorbell_handler);+ ((void (*)(id, SEL, void *))objc_msgSend)(+ self, sel_registerName("setInterestHandler:"), interest_handler);++ id controller_state_class =+ (id)objc_getClass("IOUSBHostCIControllerStateMachine");+ id controller_state = controller_state_class+ ? ((id (*)(id, SEL))objc_msgSend)(+ controller_state_class, sel_registerName("alloc"))+ : nil;+ id state_error = nil;+ controller_state = controller_state+ ? ((id (*)(id, SEL, id, id *))objc_msgSend)(+ controller_state,+ sel_registerName("initWithInterface:error:"), self,+ &state_error)+ : nil;+ if (controller_state) {+ ((void (*)(id, SEL, id))objc_msgSend)(+ self, sel_registerName("setControllerStateMachine:"),+ controller_state);+ }+ if (error)+ *error = state_error;+ uintptr_t capability_length = capabilities+ ? ((uintptr_t (*)(id, SEL))objc_msgSend)(+ capabilities, sel_registerName("length"))+ : 0;+ logf_("[vmmhook] faking IOUSBHostControllerInterface v3=%p "+ "capability-bytes=%llu rate=%llu queue=%p command=%p "+ "doorbell=%p interest=%p state-machine=%p error=%s",+ self, (unsigned long long)capability_length,+ (unsigned long long)interrupt_rate_hz, host_queue,+ command_handler, doorbell_handler, interest_handler,+ controller_state, object_utf8(state_error));+ if (command_handler) {+ void *usb_controller = *(void **)(+ (uint8_t *)(void *)command_handler + 0x20);+ void **backend_vtable = usb_controller+ ? *(void ***)usb_controller : NULL;+ logf_("[vmmhook] fake USB backend controller=%p vtable=%p",+ usb_controller, backend_vtable);+ for (unsigned index = 0; backend_vtable && index < 8; index++) {+ char label[64];+ snprintf(label, sizeof(label), "fake USB backend[%u]", index);+ void *target = ptrauth_strip(+ backend_vtable[index], ptrauth_key_function_pointer);+ log_address(label, target);+ }+ }+ if (!controller_state) {+ __atomic_store_n(&fake_usb_host_stage,+ FakeUSBHostStageFailed, __ATOMIC_RELEASE);+ return nil;+ }+ fake_usb_host_device_address = 0;+ fake_usb_descriptor_retry_count = 0;+ fake_usb_host_send_after(self, FakeUSBHostStageControllerPowerOn,+ 0x10, 0, 0, 100 * NSEC_PER_MSEC);+ return self;+ }+ id local_error = nil;+ id *error_out = error ? error : &local_error;+ id result = original_usb_hci_init(+ self, command, capabilities, queue, interrupt_rate_hz, error_out,+ command_handler, doorbell_handler, interest_handler);+ id actual_error = error ? *error : local_error;+ logf_("[vmmhook] IOUSBHostControllerInterface init -> %p "+ "rate=%llu error=%s",+ result, (unsigned long long)interrupt_rate_hz,+ object_utf8(actual_error));+ if (actual_error) {+ id domain = send_object(actual_error, "domain");+ long code = ((long (*)(id, SEL))objc_msgSend)(+ actual_error, sel_registerName("code"));+ id user_info = send_object(actual_error, "userInfo");+ logf_("[vmmhook] USB HCI NSError domain=%s code=%ld userInfo=%s",+ object_utf8(domain), code, object_utf8(user_info));+ }+ return result;+}++static void install_usb_hci_trace(void) {+ if (!getenv("VMMHOOK_TRACE_USB") && !fake_usb_hci_enabled())+ return;+ Class controller = objc_getClass("IOUSBHostControllerInterface");+ SEL initializer = sel_registerName(+ "initWithCapabilities:queue:interruptRateHz:error:commandHandler:"+ "doorbellHandler:interestHandler:");+ Method method = controller ? class_getInstanceMethod(controller, initializer)+ : NULL;+ if (!method) {+ logf_("[vmmhook] USB HCI trace unavailable: class=%p method=%p",+ controller, method);+ return;+ }+ original_usb_hci_init =+ (usb_hci_init_t)method_setImplementation(method,+ (IMP)traced_usb_hci_init);+ Method enqueue_one = class_getInstanceMethod(+ controller, sel_registerName("enqueueInterrupt:error:"));+ Method enqueue_one_expedite = class_getInstanceMethod(+ controller, sel_registerName("enqueueInterrupt:expedite:error:"));+ Method enqueue_many = class_getInstanceMethod(+ controller, sel_registerName("enqueueInterrupts:count:error:"));+ Method enqueue_many_expedite = class_getInstanceMethod(+ controller,+ sel_registerName("enqueueInterrupts:count:expedite:error:"));+ Method destroy = class_getInstanceMethod(controller,+ sel_registerName("destroy"));+ if (enqueue_one) {+ original_usb_hci_enqueue_one =+ (usb_hci_enqueue_one_t)method_setImplementation(+ enqueue_one, (IMP)fake_usb_hci_enqueue_one);+ }+ if (enqueue_one_expedite) {+ original_usb_hci_enqueue_one_expedite =+ (usb_hci_enqueue_one_expedite_t)method_setImplementation(+ enqueue_one_expedite,+ (IMP)fake_usb_hci_enqueue_one_expedite);+ }+ if (enqueue_many) {+ original_usb_hci_enqueue_many =+ (usb_hci_enqueue_many_t)method_setImplementation(+ enqueue_many, (IMP)fake_usb_hci_enqueue_many);+ }+ if (enqueue_many_expedite) {+ original_usb_hci_enqueue_many_expedite =+ (usb_hci_enqueue_many_expedite_t)method_setImplementation(+ enqueue_many_expedite,+ (IMP)fake_usb_hci_enqueue_many_expedite);+ }+ if (destroy) {+ original_usb_hci_destroy =+ (usb_hci_destroy_t)method_setImplementation(+ destroy, (IMP)fake_usb_hci_destroy);+ }+ logf_("[vmmhook] tracing IOUSBHostControllerInterface initializer "+ "types=%s original=%p fake=%d",+ method_getTypeEncoding(method), original_usb_hci_init,+ fake_usb_hci_enabled());+}++static bool trace_iokit(void) {+ return getenv("VMMHOOK_TRACE_IOKIT") != NULL;+}++static CFMutableDictionaryRef traced_IOServiceMatching(const char *name) {+ CFMutableDictionaryRef matching = IOServiceMatching(name);+ if (trace_iokit())+ logf_("[vmmhook] IOServiceMatching(%s) -> %p",+ name ? name : "(null)", matching);+ return matching;+}++static CFMutableDictionaryRef traced_IOServiceNameMatching(const char *name) {+ CFMutableDictionaryRef matching = IOServiceNameMatching(name);+ if (trace_iokit())+ logf_("[vmmhook] IOServiceNameMatching(%s) -> %p",+ name ? name : "(null)", matching);+ return matching;+}++static io_service_t traced_IOServiceGetMatchingService(+ mach_port_t main_port, CFDictionaryRef matching) {+ if (trace_iokit() && matching)+ logf_("[vmmhook] IOServiceGetMatchingService matching=%s",+ object_utf8((id)matching));+ io_service_t service = IOServiceGetMatchingService(main_port, matching);+ if (trace_iokit())+ logf_("[vmmhook] IOServiceGetMatchingService -> 0x%x", service);+ return service;+}++static kern_return_t traced_IOServiceOpen(io_service_t service,+ task_port_t owning_task,+ uint32_t type,+ io_connect_t *connect) {+ io_name_t class_name = {0};+ io_name_t entry_name = {0};+ IOObjectGetClass(service, class_name);+ IORegistryEntryGetName(service, entry_name);+ kern_return_t result =+ IOServiceOpen(service, owning_task, type, connect);+ if (trace_iokit())+ logf_("[vmmhook] IOServiceOpen(service=0x%x class=%s name=%s "+ "type=%u) -> 0x%x connect=0x%x",+ service, class_name, entry_name, type, result,+ connect ? *connect : 0);+ return result;+}++__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_io_service_matching __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&traced_IOServiceMatching,+ (const void *)&IOServiceMatching };+__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_io_service_name_matching __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&traced_IOServiceNameMatching,+ (const void *)&IOServiceNameMatching };+__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_io_get_matching_service __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&traced_IOServiceGetMatchingService,+ (const void *)&IOServiceGetMatchingService };+__attribute__((used)) static struct {+ const void *replacement;+ const void *replacee;+} _ip_io_service_open __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&traced_IOServiceOpen, (const void *)&IOServiceOpen };+++static dispatch_source_t vmm_health_timer;++static void start_health_timer(void) {+ dispatch_queue_t queue = dispatch_get_global_queue(+ QOS_CLASS_UTILITY, 0);+ vmm_health_timer = dispatch_source_create(+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);+ dispatch_source_set_timer(+ vmm_health_timer,+ dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),+ 10 * NSEC_PER_SEC,+ NSEC_PER_SEC / 2);+ dispatch_source_set_event_handler(vmm_health_timer, ^{+ logf_("[vmmhook] health vcpu=%llu,%llu digitizer=%llu/%llu "+ "keyboard=%llu/%llu frame=%llu cursor=%llu surfaces=%llu",+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_counts[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_counts[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &xpc_digitizer_processed, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &xpc_digitizer_received, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &xpc_keyboard_processed, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &xpc_keyboard_received, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &xpc_frame_updates, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &xpc_cursor_updates, __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &iosurface_create_count, __ATOMIC_RELAXED));+ logf_("[vmmhook] health exit=%u/0x%llx,%u/0x%llx "+ "vtimer-mask=%llu(%llu),%llu(%llu) "+ "vtimer-offset=0x%llx(%llu),0x%llx(%llu) vcpus-exit=%llu",+ vmm_latest_exit_reason(0),+ (unsigned long long)vmm_latest_exit_syndrome(0),+ vmm_latest_exit_reason(1),+ (unsigned long long)vmm_latest_exit_syndrome(1),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_last_mask[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_mask_calls[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_last_mask[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_mask_calls[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_last_offset[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_offset_calls[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_last_offset[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vtimer_offset_calls[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpus_exit_calls, __ATOMIC_RELAXED));+ logf_("[vmmhook] health exit-reasons "+ "vcpu0=%llu/%llu/%llu/%llu vcpu1=%llu/%llu/%llu/%llu "+ "cntv0=0x%llx/0x%llx/0x%llx cntv1=0x%llx/0x%llx/0x%llx",+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[0][0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[0][1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[0][2], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[0][3], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[1][0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[1][1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[1][2], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_exit_reason_counts[1][3], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_last_cntv_ctl[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_last_cntv_cval[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_last_mach_time[0], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_last_cntv_ctl[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_last_cntv_cval[1], __ATOMIC_RELAXED),+ (unsigned long long)__atomic_load_n(+ &vmm_vcpu_last_mach_time[1], __ATOMIC_RELAXED));+ });+ dispatch_resume(vmm_health_timer);+}++__attribute__((constructor)) static void hook_init(void) {+ logf_("[vmmhook] loaded pid %d", getpid());+ // macOS configures its host audio endpoint through CoreAudio HAL. On iOS,+ // the same endpoint needs an explicit per-process AVAudioSession before+ // input buffers contain microphone samples. The VMM owns the actual host+ // streams, so activating only the UIKit parent is insufficient.+ // Resolve this dynamically: including AVFAudio's header also pulls+ // in modern typed XPC declarations, which conflict with this Ventura+ // binary-ABI shim's intentionally opaque XPC declarations above.+ Class audioSessionClass = objc_getClass("AVAudioSession");+ id audioSession = audioSessionClass+ ? ((id(*)(id, SEL))objc_msgSend)(+ (id)audioSessionClass, sel_registerName("sharedInstance"))+ : nil;+ id *categorySymbol = dlsym(RTLD_DEFAULT,+ "AVAudioSessionCategoryPlayAndRecord");+ id *modeSymbol = dlsym(RTLD_DEFAULT, "AVAudioSessionModeDefault");+ id audioError = nil;+ NSUInteger audioOptions = 0x1U | 0x4U | 0x8U;+ BOOL categoryOK = audioSession && categorySymbol && modeSymbol &&+ ((BOOL(*)(id, SEL, id, id, NSUInteger, id *))objc_msgSend)(+ audioSession,+ sel_registerName("setCategory:mode:options:error:"),+ *categorySymbol, *modeSymbol, audioOptions, &audioError);+ BOOL rateOK = audioSession &&+ ((BOOL(*)(id, SEL, double, id *))objc_msgSend)(+ audioSession, sel_registerName("setPreferredSampleRate:error:"),+ 48000, &audioError);+ BOOL activeOK = audioSession &&+ ((BOOL(*)(id, SEL, BOOL, id *))objc_msgSend)(+ audioSession, sel_registerName("setActive:error:"), YES,+ &audioError);+ NSUInteger permission = audioSession+ ? ((NSUInteger(*)(id, SEL))objc_msgSend)(+ audioSession, sel_registerName("recordPermission")) : 0;+ double sampleRate = audioSession+ ? ((double(*)(id, SEL))objc_msgSend)(+ audioSession, sel_registerName("sampleRate")) : 0;+ id errorDescription = audioError+ ? ((id(*)(id, SEL))objc_msgSend)(+ audioError, sel_registerName("localizedDescription")) : nil;+ const char *errorText = errorDescription+ ? ((const char *(*)(id, SEL))objc_msgSend)(+ errorDescription, sel_registerName("UTF8String")) : "none";+ logf_("[vmmhook] audio session category=%d rate=%d active=%d "+ "permission=%lu sample-rate=%.0f error=%s",+ categoryOK, rateOK, activeOK,+ (unsigned long)permission, sampleRate, errorText);+ start_health_timer();+ install_usb_hci_trace();+ // Optional debug delay: set VMMHOOK_DEBUG_SLEEP=N to give lldb time to attach+ // before the VMM accepts the host's connection (catch breakpoints in the open/hv path).+ const char *s = getenv("VMMHOOK_DEBUG_SLEEP");+ if (s) { int n = atoi(s); if (n > 0) { logf_("[vmmhook] sleeping %ds for lldb attach", n); sleep(n); } }+}++void vmm_xpc_main(void (*handler)(xo_t)) {+ // VMM = listener, matching VZ's host-sends-first model: create an anonymous+ // xpc listener (no launchd check-in needed) whose event handler is the VMM's real connection+ // handler, then PUBLISH our endpoint's mach port name to a file. The host (which has+ // task_for_pid on us) mach_port_extract_right's that port, rebuilds the endpoint, and+ // connects in as the client — the host then sends the config and our handler services it.+ logf_("[vmmhook] vmm_xpc_main (strategy-B listener) handler=%p", (void *)handler);+ xo_t L = xpc_connection_create(NULL, dispatch_get_main_queue());+ xpc_connection_set_event_handler(L, ^(xo_t ev) {+ void *t = xpc_get_type(ev);+ if (t == (void *)_xpc_type_connection) { logf_("[vmmhook] host PEER %p -> handler", ev); handler(ev); }+ else { char *d = xpc_copy_description(ev); logf_("[vmmhook] L event: %s", d ? d : "?"); if (d) free(d); }+ });+ xpc_connection_resume(L);+ xo_t E = xpc_endpoint_create(L);+ uint32_t myport = *(uint32_t *)((char *)E + XPC_ENDPOINT_PORT_OFF);+ logf_("[vmmhook] listener L=%p E=%p myport=0x%x", L, E, myport);+ const char *endpointFile = getenv("VZ_VMM_ENDPOINT_FILE");+ if (!endpointFile || !endpointFile[0])+ endpointFile = "/tmp/vmm_ep.txt";+ FILE *f = fopen(endpointFile, "w");+ if (f) {+ fprintf(f, "0x%x\n", myport);+ fclose(f);+ logf_("[vmmhook] published listener port to %s", endpointFile);+ } else {+ logf_("[vmmhook] failed to publish listener port to %s errno=%d",+ endpointFile, errno);+ _exit(70);+ }+ dispatch_main();+}++// The VMM compiles + applies its .sb sandbox profile via sandbox_init(); iOS doesn't+// support runtime SBPL compilation ("profile compilation not supported") -> FATAL.+// We run with the no-sandbox entitlement, so report success and skip it.+int vmm_sandbox_init(const char *profile, uint64_t flags, char **errorbuf) {+ logf_("[vmmhook] sandbox_init bypassed (flags=%llu)", (unsigned long long)flags);+ if (errorbuf) *errorbuf = NULL;+ return 0;+}++__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_xpc_main __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_xpc_main, (const void *)&xpc_main };+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_sandbox_init __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_sandbox_init, (const void *)&sandbox_init };++// The VMM opens AVPBooter ROM at the macOS framework path:+// /System/Library/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vmapple2.bin+// which doesn't exist on iOS. Redirect anything ending in /AVPBooter.* to /var/root/.+// Call __open directly (libsystem_kernel's leaf syscall wrapper) because dlsym(RTLD_NEXT,"open")+// returns our own interposer here -> infinite recursion. __open is the real syscall stub+// and is NOT itself interposed.+extern int __open(const char *, int, int);+static int vmm_open(const char *path, int oflag, ...) {+ int mode = 0;+ if (oflag & O_CREAT) { va_list ap; va_start(ap, oflag); mode = va_arg(ap, int); va_end(ap); }+ if (path) {+ const char *slash = strrchr(path, '/');+ const char *base = slash ? slash + 1 : path;+ if (strncmp(base, "AVPBooter.", 10) == 0) {+ const char *configured = getenv("VZ_AVP_BOOTER");+ char fb[1024];+ if (configured && configured[0])+ snprintf(fb, sizeof(fb), "%s", configured);+ else+ snprintf(fb, sizeof(fb),+ "/var/root/VirtualMac/payload/%s", base);+ int fd = __open(fb, oflag, mode);+ void *ret0 = __builtin_return_address(0);+ void *ret1 = __builtin_return_address(1);+ logf_("[vmmhook] open(%s, oflag=0x%x) -> %s fd=%d caller=%p caller2=%p",+ path, oflag, fb, fd, ret0, ret1);+ log_address("open caller", ret0);+ log_address("open caller2", ret1);+ return fd;+ }+ }+ return __open(path, oflag, mode);+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_open __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_open, (const void *)&open };++// Trace hv_vcpu_config_get_feature_reg: the start path queries each of ~10 features per+// vCPU and aborts (hv_vm_destroy) if any returns non-zero. We log reg-index, return value,+// and the out-value to identify which one triggers the abort.+extern int hv_vcpu_config_get_feature_reg(void *config, uint64_t reg, uint64_t *value);+static int vmm_hv_vcpu_config_get_feature_reg(void *config, uint64_t reg, uint64_t *value) {+ int rc = hv_vcpu_config_get_feature_reg(config, reg, value);+ uint64_t v = (rc == 0 && value) ? *value : 0;+ logf_("[vmmhook] hv_vcpu_config_get_feature_reg(reg=%llu) -> rc=%d *out=0x%llx",+ (unsigned long long)reg, rc, (unsigned long long)v);+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_feat __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vcpu_config_get_feature_reg,+ (const void *)&hv_vcpu_config_get_feature_reg };++// Trace the post-AVPBooter startup path: pin down whether teardown fires, whether+// vCPU creation is reached, and whether guest execution begins. Signatures match+// the Hypervisor.framework public headers.+extern int hv_vm_destroy(void);+static int vmm_hv_vm_destroy(void) {+ void *ret0 = __builtin_return_address(0);+ void *ret1 = __builtin_return_address(1);+ logf_("[vmmhook] hv_vm_destroy CALLED caller=%p caller2=%p", ret0, ret1);+ log_address("hv_vm_destroy caller", ret0);+ log_address("hv_vm_destroy caller2", ret1);+ int rc = hv_vm_destroy();+ logf_("[vmmhook] hv_vm_destroy -> rc=%d", rc);+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vm_destroy __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vm_destroy, (const void *)&hv_vm_destroy };++extern int hv_vm_create(void *config);+static int vmm_hv_vm_create(void *config) {+ int rc = hv_vm_create(config);+ logf_("[vmmhook] hv_vm_create(config=%p) -> rc=%d", config, rc);+ if (rc != 0) log_address("hv_vm_create caller", __builtin_return_address(0));+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vm_create __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vm_create, (const void *)&hv_vm_create };++extern int hv_vm_map(void *addr, uint64_t ipa, size_t size, uint64_t flags);+static int vmm_hv_vm_map(void *addr, uint64_t ipa, size_t size, uint64_t flags) {+ int rc = hv_vm_map(addr, ipa, size, flags);+ logf_("[vmmhook] hv_vm_map(addr=%p ipa=0x%llx size=0x%zx flags=0x%llx) -> rc=%d",+ addr, (unsigned long long)ipa, size, (unsigned long long)flags, rc);+ if (rc != 0) log_address("hv_vm_map caller", __builtin_return_address(0));+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vm_map __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vm_map, (const void *)&hv_vm_map };++extern int hv_vm_protect(uint64_t ipa, size_t size, uint64_t flags);+static int vmm_hv_vm_protect(uint64_t ipa, size_t size, uint64_t flags) {+ int rc = hv_vm_protect(ipa, size, flags);+ logf_("[vmmhook] hv_vm_protect(ipa=0x%llx size=0x%zx flags=0x%llx) -> rc=%d",+ (unsigned long long)ipa, size, (unsigned long long)flags, rc);+ if (rc != 0) log_address("hv_vm_protect caller", __builtin_return_address(0));+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vm_protect __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vm_protect, (const void *)&hv_vm_protect };++extern int hv_vcpu_create(uint64_t *vcpu, void **exit_out, void *config);+typedef struct {+ uint32_t reason;+ uint32_t reserved;+ uint64_t syndrome;+ uint64_t virtual_address;+ uint64_t physical_address;+} vmm_hv_vcpu_exit_t;++static int vmm_hv_vcpu_create(uint64_t *vcpu, void **exit_out, void *config) {+ logf_("[vmmhook] hv_vcpu_create CALLED vcpu_out=%p exit_out=%p cfg=%p",+ vcpu, exit_out, config);+ int rc = hv_vcpu_create(vcpu, exit_out, config);+ logf_("[vmmhook] hv_vcpu_create -> rc=%d vcpu=0x%llx",+ rc, (unsigned long long)(vcpu ? *vcpu : 0));+ if (rc == 0 && vcpu && *vcpu < 64 && exit_out)+ vmm_vcpu_exits[*vcpu] = (vmm_hv_vcpu_exit_t *)*exit_out;+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vcpu_create __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vcpu_create, (const void *)&hv_vcpu_create };++extern int hv_vcpu_run(uint64_t vcpu);+extern int hv_vcpu_get_reg(uint64_t vcpu, uint32_t reg, uint64_t *value);+extern int hv_vcpu_get_sys_reg(uint64_t vcpu, uint32_t reg, uint64_t *value);+static int vmm_hv_vcpu_run(uint64_t vcpu) {+ static uint64_t seen_vcpus;+ uint64_t bit = vcpu < 64 ? (1ULL << vcpu) : 0;+ bool trace_all = getenv("VMMHOOK_TRACE_VCPU") != NULL;+ bool first_run = bit && !(__atomic_fetch_or(+ &seen_vcpus, bit, __ATOMIC_RELAXED) & bit);+ if (trace_all || first_run)+ logf_("[vmmhook] hv_vcpu_run CALLED vcpu=0x%llx%s",+ (unsigned long long)vcpu, first_run ? " (first)" : "");+ int rc = hv_vcpu_run(vcpu);+ const char *limit_text = getenv("VMMHOOK_TRACE_VCPU_LIMIT");+ uint64_t trace_limit = limit_text ? strtoull(limit_text, NULL, 0) : 0;+ uint64_t exit_count = vcpu < 64+ ? __atomic_add_fetch(&vmm_vcpu_exit_counts[vcpu], 1,+ __ATOMIC_RELAXED)+ : 0;+ vmm_hv_vcpu_exit_t *exit = vcpu < 64 ? vmm_vcpu_exits[vcpu] : NULL;+ if (vcpu < 64 && exit) {+ uint32_t reason_bucket = exit->reason < 3 ? exit->reason : 3;+ __atomic_add_fetch(+ &vmm_vcpu_exit_reason_counts[vcpu][reason_bucket], 1,+ __ATOMIC_RELAXED);+ uint32_t exception_class = (uint32_t)(exit->syndrome >> 26);+ if (exit->reason == 1 && exception_class == 1 &&+ exit_count % 4096 == 0) {+ uint64_t control = 0;+ uint64_t compare = 0;+ if (hv_vcpu_get_sys_reg(+ vcpu, 0xdf19 /* HV_SYS_REG_CNTV_CTL_EL0 */,+ &control) == 0 &&+ hv_vcpu_get_sys_reg(+ vcpu, 0xdf1a /* HV_SYS_REG_CNTV_CVAL_EL0 */,+ &compare) == 0) {+ __atomic_store_n(&vmm_vcpu_last_cntv_ctl[vcpu], control,+ __ATOMIC_RELAXED);+ __atomic_store_n(&vmm_vcpu_last_cntv_cval[vcpu], compare,+ __ATOMIC_RELAXED);+ __atomic_store_n(&vmm_vcpu_last_mach_time[vcpu],+ mach_absolute_time(), __ATOMIC_RELAXED);+ }+ }+ }+ if (vcpu < 64 && exit_count <= trace_limit) {+ uint64_t pc = 0;+ int pc_rc = hv_vcpu_get_reg(vcpu, 31 /* HV_REG_PC */, &pc);+ logf_("[vmmhook] vcpu=0x%llx exit#%llu rc=%d reason=%u "+ "pc=0x%llx pc_rc=%d esr=0x%llx va=0x%llx ipa=0x%llx",+ (unsigned long long)vcpu, (unsigned long long)exit_count, rc,+ exit ? exit->reason : UINT32_MAX,+ (unsigned long long)pc, pc_rc,+ (unsigned long long)(exit ? exit->syndrome : 0),+ (unsigned long long)(exit ? exit->virtual_address : 0),+ (unsigned long long)(exit ? exit->physical_address : 0));+ }+ if (trace_all || rc != 0)+ logf_("[vmmhook] hv_vcpu_run -> rc=%d vcpu=0x%llx",+ rc, (unsigned long long)vcpu);+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vcpu_run __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vcpu_run, (const void *)&hv_vcpu_run };++extern int hv_vcpu_set_vtimer_mask(uint64_t vcpu, bool masked);+static int vmm_hv_vcpu_set_vtimer_mask(uint64_t vcpu, bool masked) {+ int rc = hv_vcpu_set_vtimer_mask(vcpu, masked);+ uint64_t count = 0;+ if (vcpu < 64) {+ __atomic_store_n(&vmm_vtimer_last_mask[vcpu], masked,+ __ATOMIC_RELAXED);+ count = __atomic_add_fetch(&vmm_vtimer_mask_calls[vcpu], 1,+ __ATOMIC_RELAXED);+ }+ if (count <= 12 || (count && count % 1000000 == 0) || rc != 0)+ logf_("[vmmhook] hv_vcpu_set_vtimer_mask vcpu=0x%llx "+ "masked=%d call=%llu -> rc=%d",+ (unsigned long long)vcpu, masked,+ (unsigned long long)count, rc);+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vcpu_set_vtimer_mask __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vcpu_set_vtimer_mask,+ (const void *)&hv_vcpu_set_vtimer_mask };++extern int hv_vcpu_set_vtimer_offset(uint64_t vcpu, uint64_t offset);+static int vmm_hv_vcpu_set_vtimer_offset(uint64_t vcpu, uint64_t offset) {+ int rc = hv_vcpu_set_vtimer_offset(vcpu, offset);+ uint64_t count = 0;+ if (vcpu < 64) {+ __atomic_store_n(&vmm_vtimer_last_offset[vcpu], offset,+ __ATOMIC_RELAXED);+ count = __atomic_add_fetch(&vmm_vtimer_offset_calls[vcpu], 1,+ __ATOMIC_RELAXED);+ }+ if (count <= 12 || (count && count % 1000000 == 0) || rc != 0)+ logf_("[vmmhook] hv_vcpu_set_vtimer_offset vcpu=0x%llx "+ "offset=0x%llx call=%llu -> rc=%d",+ (unsigned long long)vcpu, (unsigned long long)offset,+ (unsigned long long)count, rc);+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vcpu_set_vtimer_offset __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vcpu_set_vtimer_offset,+ (const void *)&hv_vcpu_set_vtimer_offset };++extern int hv_vcpus_exit(uint64_t *vcpus, uint32_t vcpu_count);+static int vmm_hv_vcpus_exit(uint64_t *vcpus, uint32_t vcpu_count) {+ int rc = hv_vcpus_exit(vcpus, vcpu_count);+ uint64_t count = __atomic_add_fetch(&vmm_vcpus_exit_calls, 1,+ __ATOMIC_RELAXED);+ if (count <= 12 || count % 100000 == 0 || rc != 0)+ logf_("[vmmhook] hv_vcpus_exit vcpus=%p count=%u call=%llu -> rc=%d",+ vcpus, vcpu_count, (unsigned long long)count, rc);+ return rc;+}+__attribute__((used)) static struct { const void *replacement; const void *replacee; }+_ip_hv_vcpus_exit __attribute__((section("__DATA,__interpose"))) =+ { (const void *)&vmm_hv_vcpus_exit, (const void *)&hv_vcpus_exit };diff --git a/VirtualMac/vz/host/vzboot.m b/VirtualMac/vz/host/vzboot.mnew file mode 100644index 0000000..ec1eeb7--- /dev/null+++ b/VirtualMac/vz/host/vzboot.m@@ -0,0 +1,158 @@+// Headless iPad host for the extracted Virtualization stack. Mirrors the macOS sample's+// MacOSVirtualMachineConfigurationHelper config (boot loader, block device, graphics,+// trackpad, keyboard) built against the guest bundle copied from the Mac host, but:+// - loads the 3 extracted frameworks via dlopen (they aren't linkable: custom layout ++// stale export trie), so VZ classes are reached through objc_getClass + objc_msgSend;+// - drops the NAT network device (vmnet is absent on iOS);+// - no AppKit VZVirtualMachineView (iOS) -> headless: validate + start, report via the+// completion handler + a state observer. Rendering (PVG -> CAMetalLayer) comes next.+#import <Foundation/Foundation.h>+#include <dlfcn.h>+#include <objc/runtime.h>+#include <objc/message.h>+#include <string.h>++static id CLS(const char *n) { return (id)objc_getClass(n); }+static SEL S(const char *n) { return sel_registerName(n); }+static id m0(id o, const char *sel) { return ((id(*)(id, SEL))objc_msgSend)(o, S(sel)); }+static id m1(id o, const char *sel, id a) { return ((id(*)(id, SEL, id))objc_msgSend)(o, S(sel), a); }+static id NEW(const char *c) { return m0(m0(CLS(c), "alloc"), "init"); }+static void setObj(id o, const char *sel, id a) { ((void(*)(id, SEL, id))objc_msgSend)(o, S(sel), a); }+static NSURL *fileURL(NSString *p) { return [NSURL fileURLWithPath:p]; }+static BOOL envEnabled(const char *name) {+ const char *value = getenv(name);+ return value && value[0] && strcmp(value, "0") != 0;+}++int main(int argc, char **argv) {+ @autoreleasepool {+ setvbuf(stdout, NULL, _IONBF, 0);+ // args: [framework.dylib ...] <VM.bundle>. Frameworks loaded in dependency order; on the+ // matching VM only Virtualization is needed (system Hypervisor/PVG resolve via its deps).+ NSString *B = @"/var/root/VM.bundle";+ if (argc > 1) {+ B = [NSString stringWithUTF8String:argv[argc - 1]];+ for (int i = 1; i < argc - 1; i++)+ if (!dlopen(argv[i], RTLD_NOW | RTLD_GLOBAL)) { printf("dlopen %s FAIL: %s\n", argv[i], dlerror()); return 1; }+ } else {+ const char *fw[] = {"/var/root/Hypervisor.ios", "/var/root/ParavirtualizedGraphics.ios", "/var/root/Virtualization.ios"};+ for (int i = 0; i < 3; i++)+ if (!dlopen(fw[i], RTLD_NOW | RTLD_GLOBAL)) { printf("dlopen %s FAIL: %s\n", fw[i], dlerror()); return 1; }+ }++ // ---- platform (from the guest bundle) ----+ id platform = NEW("VZMacPlatformConfiguration");+ id aux = ((id(*)(id, SEL, id))objc_msgSend)(m0(CLS("VZMacAuxiliaryStorage"), "alloc"),+ S("initWithContentsOfURL:"), fileURL([B stringByAppendingPathComponent:@"AuxiliaryStorage"]));+ setObj(platform, "setAuxiliaryStorage:", aux);+ NSData *hmData = [NSData dataWithContentsOfFile:[B stringByAppendingPathComponent:@"HardwareModel"]];+ id hwModel = ((id(*)(id, SEL, id))objc_msgSend)(m0(CLS("VZMacHardwareModel"), "alloc"),+ S("initWithDataRepresentation:"), hmData);+ printf("hardwareModel: %p supported=%d\n", (void *)hwModel,+ ((BOOL(*)(id, SEL))objc_msgSend)(hwModel, S("isSupported")));+ setObj(platform, "setHardwareModel:", hwModel);+ NSData *midData = [NSData dataWithContentsOfFile:[B stringByAppendingPathComponent:@"MachineIdentifier"]];+ id mid = ((id(*)(id, SEL, id))objc_msgSend)(m0(CLS("VZMacMachineIdentifier"), "alloc"),+ S("initWithDataRepresentation:"), midData);+ setObj(platform, "setMachineIdentifier:", mid);++ // ---- machine config ----+ id config = NEW("VZVirtualMachineConfiguration");+ setObj(config, "setPlatform:", platform);+ ((void(*)(id, SEL, NSUInteger))objc_msgSend)(config, S("setCPUCount:"), 2);+ ((void(*)(id, SEL, unsigned long long))objc_msgSend)(config, S("setMemorySize:"), 4ULL << 30);+ setObj(config, "setBootLoader:", NEW("VZMacOSBootLoader"));++ if (!envEnabled("VZ_NO_GRAPHICS")) {+ id gfx = NEW("VZMacGraphicsDeviceConfiguration");+ id disp = ((id(*)(id, SEL, NSInteger, NSInteger, NSInteger))objc_msgSend)(+ m0(CLS("VZMacGraphicsDisplayConfiguration"), "alloc"),+ S("initWithWidthInPixels:heightInPixels:pixelsPerInch:"), 1920, 1200, 80);+ setObj(gfx, "setDisplays:", @[disp]);+ setObj(config, "setGraphicsDevices:", @[gfx]);+ printf("graphics=%p display=%p\n", (void *)gfx, (void *)disp);+ } else {+ printf("graphics: SKIPPED\n");+ }++ NSError *err = nil;+ if (!envEnabled("VZ_NO_STORAGE")) { // skippable to isolate startup paths+ printf("platform+config props+graphics done; creating disk attachment...\n");+ id diskAtt = ((id(*)(id, SEL, id, BOOL, NSError **))objc_msgSend)(+ m0(CLS("VZDiskImageStorageDeviceAttachment"), "alloc"),+ S("initWithURL:readOnly:error:"), fileURL([B stringByAppendingPathComponent:@"Disk.img"]), NO, &err);+ if (!diskAtt) { printf("disk attach FAIL: %s\n", [[err localizedDescription] UTF8String]); return 1; }+ id block = ((id(*)(id, SEL, id))objc_msgSend)(m0(CLS("VZVirtioBlockDeviceConfiguration"), "alloc"),+ S("initWithAttachment:"), diskAtt);+ setObj(config, "setStorageDevices:", @[block]);+ printf("storage set; keyboard/pointing...\n");+ } else printf("storage: SKIPPED\n");++ // 13.2.1 uses the USB input devices (VZMac{Keyboard,Trackpad} are macOS 14+); guard nil.+ if (!envEnabled("VZ_NO_INPUT")) {+ id kbd = NEW("VZUSBKeyboardConfiguration");+ if (kbd) setObj(config, "setKeyboards:", @[kbd]);+ id pdev = NEW("VZUSBScreenCoordinatePointingDeviceConfiguration");+ if (pdev) setObj(config, "setPointingDevices:", @[pdev]);+ printf("keyboard=%p pointing=%p\n", (void *)kbd, (void *)pdev);+ } else {+ printf("input: SKIPPED\n");+ }++ // ---- validate (skippable: the config is built from a known-good bundle, and VZ's+ // validator exercises deep C++ filesystem-path code that hits extraction edge cases) ----+ if (!envEnabled("VZ_SKIP_VALIDATE")) {+ BOOL ok = ((BOOL(*)(id, SEL, NSError **))objc_msgSend)(config, S("validateWithError:"), &err);+ printf("validateWithError: ok=%d%s\n", ok, ok ? "" : [[NSString stringWithFormat:@" -- %@", [err localizedDescription]] UTF8String]);+ if (!ok) return 1;+ } else printf("validate: SKIPPED\n");++ // ---- create + start (on the VM's queue = main) ----+ id vm = ((id(*)(id, SEL, id))objc_msgSend)(m0(CLS("VZVirtualMachine"), "alloc"),+ S("initWithConfiguration:"), config);+ printf("VZVirtualMachine = %p; starting...\n", (void *)vm);+ dispatch_async(dispatch_get_main_queue(), ^{+ void (^done)(NSError *) = ^(NSError *e) {+ if (e) {+ printf("VM start FAILED: %s\n",+ [[e localizedDescription] UTF8String]);+ exit(1);+ } else {+ printf("VM STARTED (state=%ld)\n",+ (long)((NSInteger(*)(id, SEL))objc_msgSend)(+ vm, S("state")));+ }+ };+ ((void(*)(id, SEL, id))objc_msgSend)(vm, S("startWithCompletionHandler:"), done);+ });+ // Poll state long enough to observe a real boot. Override for bounded+ // smoke tests without recompiling.+ const char *runSecondsValue = getenv("VZ_RUN_SECONDS");+ int runSeconds = runSecondsValue ? atoi(runSecondsValue) : 600;+ if (runSeconds < 1) runSeconds = 1;+ for (int t = 0; t < runSeconds; t++) {+ [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];+ if (t % 5 == 4) printf(" [t=%ds] VM state=%ld\n", t + 1,+ (long)((NSInteger(*)(id, SEL))objc_msgSend)(vm, S("state")));+ }++ // Tear down through Virtualization so PVG queues and IOSurfaces are drained+ // before the short-lived SSH test host exits.+ NSInteger state =+ ((NSInteger(*)(id, SEL))objc_msgSend)(vm, S("state"));+ if (state == 1 || state == 2) {+ __block BOOL stopDone = NO;+ void (^stopped)(NSError *) = ^(NSError *e) {+ printf("VM stop: %s\n",+ e ? [[e localizedDescription] UTF8String] : "complete");+ stopDone = YES;+ };+ ((void(*)(id, SEL, id))objc_msgSend)(+ vm, S("stopWithCompletionHandler:"), stopped);+ for (int t = 0; t < 15 && !stopDone; t++)+ [[NSRunLoop mainRunLoop]+ runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];+ }+ }+ return 0;+}diff --git a/VirtualMac/vz/host/vzxpchook.m b/VirtualMac/vz/host/vzxpchook.mnew file mode 100644index 0000000..006d1b3--- /dev/null+++ b/VirtualMac/vz/host/vzxpchook.m@@ -0,0 +1,929 @@+// Host-side DYLD_INSERT interpose for the iOS-ported VZ host.+//+// [VZVirtualMachine start] does xpc_connection_create("com.apple.Virtualization.+// VirtualMachine", q). On rootless iOS that name resolves to nothing, and a launchd+// MachServices daemon for it can't reach the system domain (it falls to user/501 — see+// the vmm-xpc-service notes). So instead of launchd, we spawn the VMM ourselves and+// rendezvous over an anonymous xpc endpoint (validated primitive: vz/development/probes/epprobe.m):+// - create an anonymous listener L (no launchd check-in needed) on a private queue+// - E = xpc_endpoint_create(L); the backing mach send-right is at E+0x18+// - posix_spawn the VMM .xpc binary SUSPENDED+// - task_for_pid(child) + mach_port_insert_right(L's port, COPY_SEND) under a known+// name (passed in env VMM_EP_PORT); resume the child+// - the child's vmmhook rebuilds the endpoint from that port and connects back; L's+// handler captures the peer P, which we return as the result of xpc_connection_create+//+// Build: clang -dynamiclib -arch arm64e -miphoneos-version-min=16.0+// -Wl,-undefined,dynamic_lookup vzxpchook.m -o vzxpchook.dylib ; ldid -S<ent>+// Use: DYLD_INSERT_LIBRARIES=/var/root/vzxpchook.ios <host>+#include <dispatch/dispatch.h>+#include <errno.h>+#include <string.h>+#include <dlfcn.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <unistd.h>+#include <signal.h>+#include <spawn.h>+#include <fcntl.h>+#include <limits.h>+#include <sys/stat.h>+#include <mach/mach.h>+#include <mach/arm/thread_status.h>+#include <ptrauth.h>+#include <pthread.h>+#include <sys/wait.h>+#include <time.h>+#include <Block.h>++typedef void *xo_t;+extern xo_t xpc_connection_create(const char *name, dispatch_queue_t targetq);+extern xo_t xpc_endpoint_create(xo_t connection);+extern xo_t xpc_connection_create_from_endpoint(xo_t endpoint);+extern void xpc_connection_set_event_handler(xo_t, void (^)(xo_t));+extern void xpc_connection_resume(xo_t);+extern void xpc_connection_send_message(xo_t, xo_t);+extern void xpc_connection_send_message_with_reply(+ xo_t, xo_t, dispatch_queue_t, void (^)(xo_t));+extern xo_t xpc_retain(xo_t);+extern void xpc_release(xo_t);+extern const char *xpc_dictionary_get_string(xo_t, const char *);+extern xo_t xpc_dictionary_get_value(xo_t, const char *);+extern uint64_t xpc_dictionary_get_uint64(xo_t, const char *);+extern size_t xpc_array_get_count(xo_t);+extern const void *xpc_data_get_bytes_ptr(xo_t);+extern size_t xpc_data_get_length(xo_t);+extern void xpc_dictionary_set_uint64(xo_t, const char *, uint64_t);+extern xo_t xpc_array_get_value(xo_t, size_t);+extern char *xpc_copy_description(xo_t);+extern mach_port_t xpc_mach_send_get_right(xo_t);+extern void *xpc_get_type(xo_t);+extern char _xpc_type_dictionary[];+extern char _xpc_type_mach_send[];+extern char **environ;++#define VMM_NAME "com.apple.Virtualization.VirtualMachine"+#define DEFAULT_VMM_BIN "/var/root/VirtualMac/payload/VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"+#define INSTALLATION_NAME "com.apple.Virtualization.Installation"+#define DEFAULT_INSTALLATION_BIN "/var/root/VirtualMac/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation"+#define EP_PORT_OFF 0x18+#define DEFAULT_EP_FILE "/tmp/vmm_ep.txt"+#define DEFAULT_INSTALLATION_EP_FILE "/tmp/installation_ep.txt"++static volatile int gVMMStarted;+static xo_t gPendingFramebufferConnection;+static xo_t gPendingFramebufferMessage;+static xo_t gPendingFrameUpdate;+static void (^gPendingFrameHandler)(xo_t);+static dispatch_queue_t gVZConnectionQueue;+static uint64_t gHostEventCount;+static uint64_t gInputSendCount;+static uint64_t gFrameAckCount;+// A launchd-backed XPC service is a single listener process. Virtualization+// opens several peer connections to that listener during one installation;+// spawning a fresh helper for every xpc_connection_create call split the DFU+// state across unrelated MobileDevice instances. Preserve one reconstructed+// listener endpoint and create as many peer connections from it as VZ asks for.+static pthread_mutex_t gInstallationLock = PTHREAD_MUTEX_INITIALIZER;+static xo_t gInstallationEndpoint;+static xo_t gInstallationConnections[16];+static size_t gInstallationConnectionCount;+static pid_t gInstallationPID;++static const char *session_file(const char *environmentName,+ const char *defaultPath,+ char storage[PATH_MAX]) {+ const char *configured = getenv(environmentName);+ const char *slash = strrchr(defaultPath, '/');+ const char *name = slash ? slash + 1 : defaultPath;+ if (configured && configured[0]) {+ // A setuid restore inherits the UIKit host's environment. Do not let+ // the root host reuse a generated mobile rendezvous path: its child+ // would replace that file with a root-owned one and poison subsequent+ // VM starts. Explicit, non-generated developer paths remain valid.+ const char *configuredSlash = strrchr(configured, '/');+ const char *configuredName =+ configuredSlash ? configuredSlash + 1 : configured;+ size_t nameLength = strlen(name);+ if (strncmp(configuredName, name, nameLength) != 0 ||+ configuredName[nameLength] != '.')+ return configured;+ const char *uidStart = configuredName + nameLength + 1;+ char *uidEnd = NULL;+ unsigned long encodedUID = strtoul(uidStart, &uidEnd, 10);+ if (uidEnd == uidStart || *uidEnd != '.' ||+ encodedUID == (unsigned long)geteuid())+ return configured;+ }+ snprintf(storage, PATH_MAX, "/tmp/%s.%u.%d", name,+ (unsigned)geteuid(), getpid());+ setenv(environmentName, storage, 1);+ return storage;+}++static const char *vmm_endpoint_file(void) {+ static char path[PATH_MAX];+ return session_file("VZ_VMM_ENDPOINT_FILE", DEFAULT_EP_FILE, path);+}++static const char *installation_endpoint_file(void) {+ static char path[PATH_MAX];+ return session_file("VZ_INSTALLATION_ENDPOINT_FILE",+ DEFAULT_INSTALLATION_EP_FILE, path);+}++static void L(const char *fmt, ...) {+ FILE *f = fopen("/tmp/vzxpchook.log", "a"); if (!f) return;+ fchmod(fileno(f), 0666);+ struct timespec now = {0};+ clock_gettime(CLOCK_MONOTONIC, &now);+ fprintf(f, "[%lld.%06ld] ", (long long)now.tv_sec,+ now.tv_nsec / 1000);+ va_list ap; va_start(ap, fmt); vfprintf(f, fmt, ap); va_end(ap); fputc('\n', f); fclose(f);+}++// Stale files are diagnostic debris, not a reason to make a VM unusable. If+// another identity owns a rendezvous file (or a PID was reused), move this+// launch to a fresh path and propagate it to the child through its environment.+static const char *prepare_endpoint_file(const char *environmentName,+ const char *defaultPath,+ const char *candidate,+ char replacement[PATH_MAX]) {+ if (unlink(candidate) == 0 || errno == ENOENT)+ return candidate;++ int originalError = errno;+ const char *slash = strrchr(defaultPath, '/');+ const char *name = slash ? slash + 1 : defaultPath;+ for (int attempt = 0; attempt < 8; attempt++) {+ snprintf(replacement, PATH_MAX, "/tmp/%s.%u.%d.%08x", name,+ (unsigned)geteuid(), getpid(), arc4random());+ if (unlink(replacement) == 0 || errno == ENOENT) {+ setenv(environmentName, replacement, 1);+ L("[vzxpchook] endpoint cleanup path=%s errno=%d; "+ "continuing with path=%s", candidate, originalError,+ replacement);+ return replacement;+ }+ }+ L("[vzxpchook] endpoint cleanup path=%s errno=%d; could not "+ "allocate a fallback path", candidate, originalError);+ return NULL;+}++static void cleanup_installation_child(void) {+ pid_t pid = __atomic_exchange_n(&gInstallationPID, 0,+ __ATOMIC_ACQ_REL);+ if (pid > 0) {+ int result = kill(pid, SIGKILL);+ L("[vzxpchook] installation cleanup pid=%d result=%d errno=%d",+ pid, result, result == 0 ? 0 : errno);+ }+}++__attribute__((constructor)) static void _init(void) {+ L("[vzxpchook] loaded pid %d", getpid());+ atexit(cleanup_installation_child);+}++static void log_factory_result_register(task_t task, int stopCount) {+ if (!MACH_PORT_VALID(task))+ return;+ thread_act_array_t threads = NULL;+ mach_msg_type_number_t threadCount = 0;+ kern_return_t kr = task_threads(task, &threads, &threadCount);+ if (kr != KERN_SUCCESS) {+ L("[vzxpchook] VMM factory stop %d task_threads kr=%d",+ stopCount, kr);+ return;+ }+ BOOL found = NO;+ for (mach_msg_type_number_t i = 0; i < threadCount; i++) {+ arm_thread_state64_t state = {0};+ mach_msg_type_number_t count = ARM_THREAD_STATE64_COUNT;+ kr = thread_get_state(+ threads[i], ARM_THREAD_STATE64,+ (thread_state_t)&state, &count);+ if (kr != KERN_SUCCESS)+ continue;+ // The patched factory thread has just returned from kill(SIGSTOP).+ // x16 remains SYS_kill (the kernel clears x1); x26 still contains+ // the factory's tagged result, whose low bit is the success flag.+ if (state.__x[16] == 37) {+ found = YES;+ L("[vzxpchook] VMM factory stop %d result=0x%llx "+ "success-bit=%llu pc=0x%llx",+ stopCount, (unsigned long long)state.__x[26],+ (unsigned long long)(state.__x[26] & 1),+ (unsigned long long)arm_thread_state64_get_pc(state));+ }+ }+ if (!found)+ L("[vzxpchook] VMM factory stop %d result thread not found",+ stopCount);+ for (mach_msg_type_number_t i = 0; i < threadCount; i++)+ mach_port_deallocate(mach_task_self(), threads[i]);+ vm_deallocate(+ mach_task_self(), (vm_address_t)threads,+ (vm_size_t)(threadCount * sizeof(thread_t)));+}++// child env = our env minus DYLD_INSERT_LIBRARIES (the VMM loads vmmhook via a linked dep,+// not via DYLD_INSERT — we don't want our host hook in the child).+static char **child_env(void) {+ int n = 0; for (char **e = environ; *e; e++) n++;+ char **out = (char **)malloc(sizeof(char *) * (n + 1));+ int j = 0;+ for (char **e = environ; *e; e++)+ if (strncmp(*e, "DYLD_INSERT_LIBRARIES=", 22) != 0) out[j++] = *e;+ out[j] = NULL;+ return out;+}++static xo_t spawn_vmm_and_connect(dispatch_queue_t cq) {+ gVZConnectionQueue = cq;+ const char *endpointFile = vmm_endpoint_file();+ static char replacementEndpointFile[PATH_MAX];+ endpointFile = prepare_endpoint_file(+ "VZ_VMM_ENDPOINT_FILE", DEFAULT_EP_FILE, endpointFile,+ replacementEndpointFile);+ if (!endpointFile)+ return NULL;+ const char *vmm_bin = getenv("VZ_VMM_BIN");+ if (!vmm_bin || !vmm_bin[0]) vmm_bin = DEFAULT_VMM_BIN;+ // A restore runs through the setuid launcher while ordinary VM boots run+ // as mobile. Keep their stderr files separate: otherwise the root restore+ // recreates /tmp/vmm.stderr.log as 0644 and every later mobile+ // posix_spawn fails with EACCES before the VMM executable is reached.+ const char *stderrPath = getenv("VZ_VMM_STDERR_LOG");+ if (!stderrPath || !stderrPath[0])+ stderrPath = "/tmp/vmm.stderr.log";+ char **envp = child_env();+ // propagate VMMHOOK_DEBUG_SLEEP to the child by NOT stripping it (child_env keeps everything+ // except DYLD_INSERT_LIBRARIES; getenv VMMHOOK_DEBUG_SLEEP set on host inherits to child)+ char *argv[] = { (char *)vmm_bin, NULL };+ // Redirect the VMM's stdout and stderr so launch failures remain visible.+ posix_spawn_file_actions_t fa; posix_spawn_file_actions_init(&fa);+ posix_spawn_file_actions_addopen(&fa, 1, stderrPath, O_WRONLY|O_CREAT|O_TRUNC, 0644);+ posix_spawn_file_actions_addopen(&fa, 2, stderrPath, O_WRONLY|O_CREAT|O_APPEND, 0644);+ pid_t pid = 0;+ int rc = posix_spawn(&pid, vmm_bin, &fa, NULL, argv, envp);+ posix_spawn_file_actions_destroy(&fa);+ free(envp);+ L("[vzxpchook] posix_spawn rc=%d pid=%d stderr=%s",+ rc, pid, stderrPath);+ if (rc != 0) return NULL;+ task_t ctask = MACH_PORT_NULL;+ kern_return_t kr = task_for_pid(mach_task_self(), pid, &ctask);+ L("[vzxpchook] early task_for_pid kr=%d ctask=0x%x", kr, ctask);+ useconds_t factorySettleUsec = 2000000;+ useconds_t factoryLongSettleUsec = 0;+ int factoryLongStop = 0;+ const char *factorySettleString = getenv("VMM_FACTORY_SETTLE_USEC");+ if (factorySettleString && factorySettleString[0]) {+ unsigned long parsed = strtoul(factorySettleString, NULL, 10);+ if (parsed >= 1000 && parsed <= 30000000)+ factorySettleUsec = (useconds_t)parsed;+ }+ const char *factoryLongStopString = getenv("VMM_FACTORY_LONG_STOP");+ if (factoryLongStopString && factoryLongStopString[0])+ factoryLongStop = atoi(factoryLongStopString);+ const char *factoryLongSettleString =+ getenv("VMM_FACTORY_LONG_SETTLE_USEC");+ if (factoryLongSettleString && factoryLongSettleString[0]) {+ unsigned long parsed = strtoul(factoryLongSettleString, NULL, 10);+ if (parsed >= 1000 && parsed <= 30000000)+ factoryLongSettleUsec = (useconds_t)parsed;+ }+ // The VMM factory patch stops the whole child after each serialized+ // device factory, reproducing LLDB's successful all-thread stop. Resume it+ // periodically while start is in flight; SIGCONT is harmless when running.+ dispatch_async(+ dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ L("[vzxpchook] VMM factory supervisor started pid=%d", pid);+ L("[vzxpchook] VMM factory settle interval usec=%u",+ factorySettleUsec);+ L("[vzxpchook] VMM factory long stop=%d usec=%u",+ factoryLongStop, factoryLongSettleUsec);+ int stopCount = 0;+ for (int i = 0; i < 6000; i++) {+ int status = 0;+ pid_t changed = waitpid(pid, &status, WNOHANG | WUNTRACED);+ if (changed == pid && WIFSTOPPED(status)) {+ stopCount++;+ L("[vzxpchook] VMM factory stop %d signal=%d",+ stopCount, WSTOPSIG(status));+ log_factory_result_register(ctask, stopCount);+ useconds_t delay =+ stopCount == factoryLongStop && factoryLongSettleUsec+ ? factoryLongSettleUsec : factorySettleUsec;+ L("[vzxpchook] VMM factory stop %d settle-usec=%u",+ stopCount, delay);+ usleep(delay);+ kill(pid, SIGCONT);+ } else if (changed == pid &&+ (WIFEXITED(status) || WIFSIGNALED(status))) {+ L("[vzxpchook] VMM exited status=%d signal=%d",+ WIFEXITED(status) ? WEXITSTATUS(status) : -1,+ WIFSIGNALED(status) ? WTERMSIG(status) : 0);+ break;+ } else {+ usleep(10000);+ }+ }+ L("[vzxpchook] VMM factory supervisor finished pid=%d stops=%d",+ pid, stopCount);+ });++ // wait for the VMM (its vmmhook listener) to publish its endpoint port name+ uint32_t myport = 0;+ // Keep the rendezvous window generous enough for a debugger attachment.+ // Normal launches publish in well under a second.+ for (int i = 0; i < 1200 && !myport; i++) {+ FILE *f = fopen(endpointFile, "r");+ if (f) { if (fscanf(f, "%x", &myport) != 1) myport = 0; fclose(f); }+ if (!myport) usleep(50000); // 50ms; up to ~60s+ }+ if (!myport) {+ L("[vzxpchook] TIMEOUT waiting for VMM to publish port path=%s",+ endpointFile);+ return NULL;+ }+ L("[vzxpchook] VMM published listener port 0x%x", myport);++ // extract a send-right to the VMM's listener port into OUR namespace (we have task_for_pid)+ if (kr != KERN_SUCCESS) return NULL;+ mach_port_t hsend = MACH_PORT_NULL; mach_msg_type_name_t aq = 0;+ kr = mach_port_extract_right(ctask, myport, MACH_MSG_TYPE_COPY_SEND, &hsend, &aq);+ L("[vzxpchook] extract_right kr=%d hsend=0x%x", kr, hsend);+ if (kr != KERN_SUCCESS) return NULL;++ // rebuild the VMM's endpoint (port-swap) and connect in as the client+ dispatch_queue_t lq = dispatch_queue_create("vmm.shape", DISPATCH_QUEUE_SERIAL);+ xo_t dummy = xpc_connection_create(NULL, lq);+ xpc_connection_set_event_handler(dummy, ^(xo_t e) {});+ xpc_connection_resume(dummy);+ xo_t ep = xpc_endpoint_create(dummy);+ *(uint32_t *)((char *)ep + EP_PORT_OFF) = hsend;+ xo_t conn = xpc_connection_create_from_endpoint(ep);+ L("[vzxpchook] reconstructed VMM endpoint -> conn=%p (returning to VZ)", conn);+ return conn;+}++static xo_t spawn_installation_and_connect(dispatch_queue_t cq) {+ (void)cq;+ pthread_mutex_lock(&gInstallationLock);+ if (gInstallationEndpoint) {+ xo_t connection =+ xpc_connection_create_from_endpoint(gInstallationEndpoint);+ if (connection && gInstallationConnectionCount <+ sizeof(gInstallationConnections) /+ sizeof(gInstallationConnections[0]))+ gInstallationConnections[gInstallationConnectionCount++] =+ connection;+ L("[vzxpchook] reused installation listener endpoint=%p "+ "connection=%p peer=%zu",+ gInstallationEndpoint, connection,+ gInstallationConnectionCount);+ pthread_mutex_unlock(&gInstallationLock);+ return connection;+ }+ const char *endpointFile = installation_endpoint_file();+ static char replacementEndpointFile[PATH_MAX];+ endpointFile = prepare_endpoint_file(+ "VZ_INSTALLATION_ENDPOINT_FILE", DEFAULT_INSTALLATION_EP_FILE,+ endpointFile, replacementEndpointFile);+ if (!endpointFile) {+ pthread_mutex_unlock(&gInstallationLock);+ return NULL;+ }+ const char *binary = getenv("VZ_INSTALLATION_BIN");+ if (!binary || !binary[0])+ binary = DEFAULT_INSTALLATION_BIN;+ char **envp = child_env();+ char *argv[] = { (char *)binary, NULL };+ posix_spawn_file_actions_t actions;+ posix_spawn_file_actions_init(&actions);+ posix_spawn_file_actions_addopen(+ &actions, 1, "/tmp/installation.stderr.log",+ O_WRONLY | O_CREAT | O_TRUNC, 0644);+ posix_spawn_file_actions_addopen(+ &actions, 2, "/tmp/installation.stderr.log",+ O_WRONLY | O_CREAT | O_APPEND, 0644);+ pid_t pid = 0;+ int rc = posix_spawn(&pid, binary, &actions, NULL, argv, envp);+ posix_spawn_file_actions_destroy(&actions);+ free(envp);+ L("[vzxpchook] installation posix_spawn rc=%d pid=%d path=%s",+ rc, pid, binary);+ if (rc != 0) {+ pthread_mutex_unlock(&gInstallationLock);+ return NULL;+ }+ __atomic_store_n(&gInstallationPID, pid, __ATOMIC_RELEASE);++ task_t childTask = MACH_PORT_NULL;+ kern_return_t kr = task_for_pid(mach_task_self(), pid, &childTask);+ L("[vzxpchook] installation task_for_pid kr=%d task=0x%x",+ kr, childTask);+ if (kr != KERN_SUCCESS) {+ pthread_mutex_unlock(&gInstallationLock);+ return NULL;+ }++ uint32_t childPort = 0;+ for (int i = 0; i < 1200 && !childPort; i++) {+ FILE *file = fopen(endpointFile, "r");+ if (file) {+ if (fscanf(file, "%x", &childPort) != 1)+ childPort = 0;+ fclose(file);+ }+ if (!childPort) {+ int status = 0;+ if (waitpid(pid, &status, WNOHANG) == pid) {+ L("[vzxpchook] installation exited before endpoint "+ "status=%d signal=%d",+ WIFEXITED(status) ? WEXITSTATUS(status) : -1,+ WIFSIGNALED(status) ? WTERMSIG(status) : 0);+ pthread_mutex_unlock(&gInstallationLock);+ return NULL;+ }+ usleep(50000);+ }+ }+ if (!childPort) {+ L("[vzxpchook] timeout waiting for installation endpoint");+ pthread_mutex_unlock(&gInstallationLock);+ return NULL;+ }+ L("[vzxpchook] installation published port 0x%x", childPort);++ mach_port_t sendRight = MACH_PORT_NULL;+ mach_msg_type_name_t acquiredType = 0;+ kr = mach_port_extract_right(+ childTask, childPort, MACH_MSG_TYPE_COPY_SEND,+ &sendRight, &acquiredType);+ L("[vzxpchook] installation extract_right kr=%d send=0x%x",+ kr, sendRight);+ if (kr != KERN_SUCCESS) {+ pthread_mutex_unlock(&gInstallationLock);+ return NULL;+ }++ dispatch_queue_t shapeQueue =+ dispatch_queue_create("installation.shape", DISPATCH_QUEUE_SERIAL);+ xo_t dummy = xpc_connection_create(NULL, shapeQueue);+ xpc_connection_set_event_handler(dummy, ^(xo_t event) { (void)event; });+ xpc_connection_resume(dummy);+ xo_t endpoint = xpc_endpoint_create(dummy);+ *(uint32_t *)((char *)endpoint + EP_PORT_OFF) = sendRight;+ gInstallationEndpoint = xpc_retain(endpoint);+ xo_t connection = xpc_connection_create_from_endpoint(endpoint);+ if (connection)+ gInstallationConnections[gInstallationConnectionCount++] = connection;+ L("[vzxpchook] reconstructed installation listener endpoint=%p "+ "connection=%p peer=%zu",+ gInstallationEndpoint, connection, gInstallationConnectionCount);+ dispatch_async(+ dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{+ int status = 0;+ pid_t changed;+ do {+ changed = waitpid(pid, &status, 0);+ } while (changed < 0 && errno == EINTR);+ if (changed == pid) {+ pid_t expected = pid;+ __atomic_compare_exchange_n(+ &gInstallationPID, &expected, 0, false,+ __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);+ L("[vzxpchook] installation child exited status=%d signal=%d",+ WIFEXITED(status) ? WEXITSTATUS(status) : -1,+ WIFSIGNALED(status) ? WTERMSIG(status) : 0);+ } else {+ L("[vzxpchook] installation waitpid failed pid=%d errno=%d",+ pid, errno);+ }+ });+ pthread_mutex_unlock(&gInstallationLock);+ return connection;+}++static BOOL is_installation_connection(xo_t connection) {+ BOOL found = NO;+ pthread_mutex_lock(&gInstallationLock);+ for (size_t i = 0; i < gInstallationConnectionCount; i++) {+ if (gInstallationConnections[i] == connection) {+ found = YES;+ break;+ }+ }+ pthread_mutex_unlock(&gInstallationLock);+ return found;+}++// Export the exact weak flat-namespace name used by the extracted+// Virtualization framework. This works both when the hook is injected at+// process launch and when a UIKit host dlopens it before Virtualization.+xo_t xpc_connection_create(const char *name, dispatch_queue_t q) {+ L("[vzxpchook] xpc_connection_create(%s)", name ? name : "(null)");+ static xo_t (*real)(const char *, dispatch_queue_t) = NULL;+ if (!real) real = dlsym(RTLD_NEXT, "xpc_connection_create");+ if (name && strcmp(name, VMM_NAME) == 0) {+ xo_t connection = spawn_vmm_and_connect(q);+ if (connection)+ return connection;+ L("[vzxpchook] VMM rendezvous failed; returning a real XPC "+ "connection so Virtualization reports an error instead of "+ "dereferencing NULL");+ }+ if (name && strcmp(name, INSTALLATION_NAME) == 0) {+ xo_t connection = spawn_installation_and_connect(q);+ if (connection)+ return connection;+ L("[vzxpchook] Installation rendezvous failed; returning a real XPC "+ "connection so Virtualization reports an error instead of "+ "dereferencing NULL");+ }+ return real ? real(name, q) : NULL;+}++static void vz_xpc_connection_send_message_with_reply(+ xo_t connection, xo_t message, dispatch_queue_t queue,+ void (^handler)(xo_t)) {+ const char *name = xpc_dictionary_get_string(message, "name");+ if (is_installation_connection(connection)) {+ char *requestDescription = xpc_copy_description(message);+ L("[vzxpchook] installation request %s",+ requestDescription ?: "(no description)");+ free(requestDescription);+ xpc_connection_send_message_with_reply(+ connection, message, queue, ^(xo_t reply) {+ char *replyDescription = xpc_copy_description(reply);+ L("[vzxpchook] installation reply %s",+ replyDescription ?: "(no description)");+ free(replyDescription);+ xo_t result = xpc_dictionary_get_value(reply, "result");+ xo_t value = result+ ? xpc_dictionary_get_value(result, "value") : NULL;+ const void *bytes = value ? xpc_data_get_bytes_ptr(value) : NULL;+ size_t byteCount = value ? xpc_data_get_length(value) : 0;+ if (bytes && byteCount) {+ FILE *dump = fopen("/tmp/installation-reply.bin", "wb");+ if (dump) {+ fwrite(bytes, 1, byteCount, dump);+ fclose(dump);+ L("[vzxpchook] dumped installation reply bytes=%zu",+ byteCount);+ }+ }+ handler(reply);+ });+ return;+ }+ if (name && (strstr(name, "keyboard") || strstr(name, "digitizer") ||+ strstr(name, "pointing") || strstr(name, "trackpad"))) {+ uint64_t count = __sync_add_and_fetch(&gInputSendCount, 1);+ if (count <= 12) {+ char *description = xpc_copy_description(message);+ L("[vzxpchook] input %llu send-with-reply %s %s",+ (unsigned long long)count, name,+ description ?: "(no description)");+ free(description);+ }+ }+ if (name && strcmp(name, "start_virtual_machine") == 0) {+ char *description = xpc_copy_description(message);+ L("[vzxpchook] VMM start request %s",+ description ?: "(no description)");+ free(description);+ xo_t arguments = xpc_dictionary_get_value(message, "arguments");+ xo_t options = arguments ? xpc_array_get_value(arguments, 0) : NULL;+ xo_t rates = options+ ? xpc_dictionary_get_value(options, "framebuffer_frame_rates")+ : NULL;+ xo_t rate = rates && xpc_array_get_count(rates) > 0+ ? xpc_array_get_value(rates, 0) : NULL;+ if (rate) {+ uint64_t original =+ xpc_dictionary_get_uint64(rate, "frame_rate");+ L("[vzxpchook] preserving initial framebuffer rate %llu",+ (unsigned long long)original);+ }+ }+ xpc_connection_send_message_with_reply(+ connection, message, queue, handler);+}++static void send_retained_framebuffer_message_after_start(+ xo_t connection, xo_t message) {+ dispatch_after(+ dispatch_time(DISPATCH_TIME_NOW, 750 * NSEC_PER_MSEC),+ dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ xpc_connection_send_message(connection, message);+ xpc_release(message);+ xpc_release(connection);+ });+}++void vz_host_vm_started(void) {+ __atomic_store_n(&gVMMStarted, 1, __ATOMIC_RELEASE);+ xo_t connection = gPendingFramebufferConnection;+ xo_t message = gPendingFramebufferMessage;+ gPendingFramebufferConnection = NULL;+ gPendingFramebufferMessage = NULL;+ L("[vzxpchook] host marked VM started pending-frame=%p", message);+ if (connection && message)+ send_retained_framebuffer_message_after_start(connection, message);+ xo_t update = gPendingFrameUpdate;+ void (^handler)(xo_t) = gPendingFrameHandler;+ gPendingFrameUpdate = NULL;+ gPendingFrameHandler = NULL;+ if (update && handler) {+ dispatch_queue_t queue = gVZConnectionQueue+ ?: dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);+ dispatch_async(queue, ^{+ handler(update);+ xpc_release(update);+ Block_release(handler);+ });+ }+}++static void vz_xpc_connection_send_message(xo_t connection, xo_t message) {+ const char *name = xpc_dictionary_get_string(message, "name");+ if (name && (strstr(name, "keyboard") || strstr(name, "digitizer") ||+ strstr(name, "pointing") || strstr(name, "trackpad"))) {+ uint64_t count = __sync_add_and_fetch(&gInputSendCount, 1);+ if (count <= 12) {+ char *description = xpc_copy_description(message);+ L("[vzxpchook] input %llu send %s %s",+ (unsigned long long)count, name,+ description ?: "(no description)");+ free(description);+ }+ }+ if (name && strstr(name, "frame") != NULL) {+ xo_t retainedConnection = xpc_retain(connection);+ xo_t retainedMessage = xpc_retain(message);+ if (!__atomic_load_n(&gVMMStarted, __ATOMIC_ACQUIRE)) {+ if (gPendingFramebufferMessage) {+ xpc_release(gPendingFramebufferMessage);+ xpc_release(gPendingFramebufferConnection);+ }+ gPendingFramebufferConnection = retainedConnection;+ gPendingFramebufferMessage = retainedMessage;+ L("[vzxpchook] holding pre-start framebuffer control message %s",+ name);+ } else {+ // did_process_frame_update is the VMM's buffer-credit ACK. Delaying+ // every ACK exhausts its finite in-flight surface pool after the+ // first few frames, leaving a perfectly live guest behind a stale+ // desktop. Startup may still need the one pre-start message held,+ // but steady-state acknowledgements must retain their ordering and+ // return synchronously to XPC.+ xpc_release(retainedMessage);+ xpc_release(retainedConnection);+ uint64_t count = __sync_add_and_fetch(&gFrameAckCount, 1);+ if (count <= 8 || count % 300 == 0)+ L("[vzxpchook] framebuffer ACK %llu %s immediate",+ (unsigned long long)count, name);+ xpc_connection_send_message(connection, message);+ }+ return;+ }+ xpc_connection_send_message(connection, message);+}++static void vz_xpc_connection_set_event_handler(+ xo_t connection, void (^handler)(xo_t)) {+ xpc_connection_set_event_handler(connection, ^(xo_t event) {+ const char *name = xpc_dictionary_get_string(event, "name");+ uint64_t count = __sync_add_and_fetch(&gHostEventCount, 1);+ BOOL important = name &&+ (strcmp(name, "guest_did_panic") == 0 ||+ strcmp(name, "guest_did_stop_virtual_machine") == 0 ||+ strcmp(name, "guest_did_reset_virtual_machine") == 0);+ if (important || count <= 12 || count % 300 == 0) {+ char *description = xpc_copy_description(event);+ L("[vzxpchook] host event %llu name=%s %s",+ (unsigned long long)count, name ?: "(null)",+ description ?: "(no description)");+ free(description);+ }+ if (name && strcmp(name, "process_frame_update") == 0 &&+ !__atomic_load_n(&gVMMStarted, __ATOMIC_ACQUIRE)) {+ if (gPendingFrameUpdate)+ xpc_release(gPendingFrameUpdate);+ if (gPendingFrameHandler)+ Block_release(gPendingFrameHandler);+ gPendingFrameUpdate = xpc_retain(event);+ gPendingFrameHandler = Block_copy(handler);+ L("[vzxpchook] holding pre-start process_frame_update");+ return;+ }+ handler(event);+ });+}++// The frame RPC decoder returns false when IOSurfaceLookupFromXPCObject+// rejects the cross-process object. Rebind this one import while porting so+// every device run records the exact object and whether the native iOS+// IOSurface implementation accepted it.+static void *vz_IOSurfaceLookupFromXPCObject(xo_t object) {+ static void *(*realLookup)(xo_t);+ static void *(*lookupFromMachPort)(mach_port_t);+ static void *(*lookupFromID)(uint32_t);+ if (!realLookup) {+ void *image = dlopen(+ "/System/Library/Frameworks/IOSurface.framework/IOSurface",+ RTLD_NOW | RTLD_LOCAL);+ realLookup = image+ ? (void *(*)(xo_t))dlsym(image, "IOSurfaceLookupFromXPCObject")+ : NULL;+ lookupFromMachPort = image+ ? (void *(*)(mach_port_t))dlsym(+ image, "IOSurfaceLookupFromMachPort")+ : NULL;+ lookupFromID = image+ ? (void *(*)(uint32_t))dlsym(image, "IOSurfaceLookup")+ : NULL;+ }+ char *description = xpc_copy_description(object);+ void *type = xpc_get_type(object);+ void *surface = realLookup ? realLookup(object) : NULL;+ mach_port_t port = MACH_PORT_NULL;+ if (!surface && type == (void *)_xpc_type_mach_send &&+ lookupFromMachPort) {+ port = xpc_mach_send_get_right(object);+ if (MACH_PORT_VALID(port))+ surface = lookupFromMachPort(port);+ }+ uint64_t identifier = type == (void *)_xpc_type_dictionary+ ? xpc_dictionary_get_uint64(+ object, "virtual_mac_surface_id")+ : 0;+ if (!surface && identifier && identifier <= UINT32_MAX && lookupFromID)+ surface = lookupFromID((uint32_t)identifier);+ L("[vzxpchook] IOSurfaceLookupFromXPCObject(%s) -> %p "+ "real=%p port=0x%x fallback=%p global-id=%llu lookup-id=%p",+ description ?: "(no description)", surface, realLookup,+ port, lookupFromMachPort, (unsigned long long)identifier,+ lookupFromID);+ free(description);+ return surface;+}++// VZ's start path calls sandbox_extension_issue_generic_to_process to issue per-device+// sandbox extensions (e.g. "com.apple.virtualization.extension.audio-output") that the VMM+// child would consume. On iOS the symbol is weak-import and returns 0 -> VZ throws+// VZErrorInternal ("Failed to retrieve cache directory.", a misleading generic message; the+// real cause is the failed extension issue at Virtualization.ios+0x37dc8). Our spawned VMM+// runs with the no-sandbox entitlement, so the extension is moot. Return a+// dummy token string so VZ proceeds; pair with a no-op release. NB: if the VMM later+// validates the token via sandbox_extension_consume, the same interpose pair must also live+// in the VMM (vmnetstub.ios) — added there if/when that next layer surfaces.+// EXPORT the symbols (not __interpose) — the framework's auth-bind is FLAT-NAMESPACE+// weak-import (per dyld_info), unresolved on iOS, so __interpose can't redirect a NULL GOT.+// dyld's flat lookup over all loaded images WILL find our export and bind the framework's+// auth-GOT slot to it. Same trick covers any future flat weak-imports.+typedef long sxh_t;+char *sandbox_extension_issue_generic_to_process(const char *name, unsigned int flags, void *audit_token) {+ // The private API returns a malloc-owned C string, not an integer handle.+ // Virtualization stores this pointer and later serializes it with strlen(),+ // then frees it. Returning integer 1 happened to pass its NULL check but+ // crashed at _platform_strlen when the extension list was encoded.+ static const char dummy[] = "VirtualMac-no-sandbox";+ char *token = strdup(dummy);+ L("[vzxpchook] sandbox_extension_issue_generic_to_process(%s, flags=%u, audit=%p) -> %p '%s'",+ name ? name : "(null)", flags, audit_token, token, dummy);+ return token;+}+int sandbox_extension_release(sxh_t h) {+ L("[vzxpchook] sandbox_extension_release(%ld) -> 0", (long)h);+ return 0;+}++// The extracted framework is the macOS 13.2.1 22D68 image, but an unmodified+// sysctl on the iPad reports the iPadOS 16.3.1 build (20D67). Virtualization+// serializes that value as host_build in the VMM configuration. Keep the+// framework and VMM on their own compatibility path by overriding only this+// one read-only sysctl; all other names retain native iPadOS behavior.+static int vz_sysctlbyname(const char *name, void *oldp, size_t *oldlenp,+ void *newp, size_t newlen) {+ if (name && strcmp(name, "kern.osversion") == 0 && newp == NULL) {+ static const char build[] = "22D68";+ if (!oldlenp) {+ errno = EFAULT;+ return -1;+ }+ size_t available = *oldlenp;+ *oldlenp = sizeof(build);+ if (!oldp) {+ L("[vzxpchook] sysctlbyname(kern.osversion) size -> %zu",+ sizeof(build));+ return 0;+ }+ if (available < sizeof(build)) {+ if (available)+ memcpy(oldp, build, available);+ errno = ENOMEM;+ return -1;+ }+ memcpy(oldp, build, sizeof(build));+ L("[vzxpchook] sysctlbyname(kern.osversion) -> %s", build);+ return 0;+ }+ static int (*real_sysctlbyname)(const char *, void *, size_t *,+ void *, size_t);+ if (!real_sysctlbyname)+ real_sysctlbyname = dlsym(RTLD_NEXT, "sysctlbyname");+ return real_sysctlbyname+ ? real_sysctlbyname(name, oldp, oldlenp, newp, newlen)+ : -1;+}++// The extracted 22D68 Virtualization image retains authenticated GOT slots+// from its dyld-shared-cache layout. dyld_dynamic_interpose cannot enumerate+// those cache-origin entries after extraction, so a UIKit host that dlopens+// this hook must explicitly rebind the small host-compatibility surface.+// Each stub uses BRAA x16,x17; sign the replacement with IA and the slot+// address as its discriminator.+int vz_rebind_virtualization(void *imageBase) {+#if __has_feature(ptrauth_calls)+ struct Rebind {+ uintptr_t offset;+ void *replacement;+ const char *name;+ } rebinds[] = {+ {0x147288, (void *)&vz_IOSurfaceLookupFromXPCObject,+ "IOSurfaceLookupFromXPCObject"},+ {0x147648, (void *)&confstr, "confstr"},+ {0x147ae0, (void *)&vz_sysctlbyname, "sysctlbyname"},+ {0x147a80, (void *)&sandbox_extension_issue_generic_to_process,+ "sandbox_extension_issue_generic_to_process"},+ {0x147a88, (void *)&sandbox_extension_release,+ "sandbox_extension_release"},+ {0x147b98, (void *)&xpc_connection_create,+ "xpc_connection_create"},+ {0x147bb8, (void *)&vz_xpc_connection_send_message,+ "xpc_connection_send_message"},+ {0x147bc0, (void *)&vz_xpc_connection_send_message_with_reply,+ "xpc_connection_send_message_with_reply"},+ {0x147bc8, (void *)&vz_xpc_connection_set_event_handler,+ "xpc_connection_set_event_handler"},+ };+ uintptr_t base = (uintptr_t)imageBase;+ uintptr_t page = (base + rebinds[0].offset) & ~(uintptr_t)0x3fff;+ uintptr_t end =+ (base + rebinds[sizeof(rebinds) / sizeof(rebinds[0]) - 1].offset ++ sizeof(void *) + 0x3fff) &+ ~(uintptr_t)0x3fff;+ kern_return_t kr = vm_protect(+ mach_task_self(), (vm_address_t)page, (vm_size_t)(end - page),+ false, VM_PROT_READ | VM_PROT_WRITE);+ L("[vzxpchook] rebind VZ base=%p protect [%p,%p) kr=%d",+ imageBase, (void *)page, (void *)end, kr);+ if (kr != KERN_SUCCESS)+ return (int)kr;++ for (size_t i = 0; i < sizeof(rebinds) / sizeof(rebinds[0]); i++) {+ void **slot = (void **)(base + rebinds[i].offset);+ void *old = *slot;+ void *raw = ptrauth_strip(+ rebinds[i].replacement, ptrauth_key_function_pointer);+ void *signedReplacement = ptrauth_sign_unauthenticated(+ raw, ptrauth_key_asia, (uintptr_t)slot);+ *slot = signedReplacement;+ L("[vzxpchook] rebound %s slot=%p old=%p new=%p",+ rebinds[i].name, slot, old, signedReplacement);+ }+ return 0;+#else+ L("[vzxpchook] rebind unavailable: hook was not built arm64e");+ return -1;+#endif+}++// Virtualization asks confstr for Darwin's per-user temp/cache roots before+// starting the VMM. iPadOS exposes the selectors but returns 0 for them to+// this non-containerized root process. Supply a real writable root for only+// those selectors and preserve libc behavior for every other name.+size_t confstr(int name, char *buffer, size_t length) {+ if (name == 65537 || name == 65538) {+ static const char path[] = "/tmp/";+ size_t required = sizeof(path);+ if (buffer && length) {+ size_t copied = required < length ? required : length;+ memcpy(buffer, path, copied);+ buffer[length - 1] = '\0';+ }+ L("[vzxpchook] confstr(%d) -> %s", name, path);+ return required;+ }+ static size_t (*real_confstr)(int, char *, size_t);+ if (!real_confstr)+ real_confstr = dlsym(RTLD_NEXT, "confstr");+ return real_confstr ? real_confstr(name, buffer, length) : 0;+}diff --git a/VirtualMac/vz/install/install_launcher.c b/VirtualMac/vz/install/install_launcher.cnew file mode 100644index 0000000..0e6bc4e--- /dev/null+++ b/VirtualMac/vz/install/install_launcher.c@@ -0,0 +1,162 @@+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>+#include <signal.h>+#include <sys/stat.h>+#include <unistd.h>++static int has_prefix(const char *value, const char *prefix)+{+ return strncmp(value, prefix, strlen(prefix)) == 0;+}++static int is_decimal(const char *value)+{+ if (!*value)+ return 0;+ for (; *value; value++) {+ if (*value < '0' || *value > '9')+ return 0;+ }+ return 1;+}++static int has_suffix(const char *value, const char *suffix)+{+ size_t value_length = strlen(value);+ size_t suffix_length = strlen(suffix);+ return value_length >= suffix_length &&+ strcasecmp(value + value_length - suffix_length, suffix) == 0;+}++static int is_direct_child(const char *value, const char *parent)+{+ size_t parent_length = strlen(parent);+ return strncmp(value, parent, parent_length) == 0 &&+ value[parent_length] == '/' && value[parent_length + 1] != '\0' &&+ strchr(value + parent_length + 1, '/') == NULL;+}++int main(int argc, char **argv)+{+ if (argc == 4 && strcmp(argv[1], "--cancel-install") == 0) {+ const char *attempt = argv[3];+ if (!is_decimal(argv[2]) || !has_prefix(attempt,+ "/var/mobile/Media/VirtualMac/Installations/") ||+ !has_suffix(attempt, ".installation") ||+ strchr(attempt, '\n') || strchr(attempt, '\r') ||+ strstr(attempt, "/../") || has_suffix(attempt, "/..")) {+ fprintf(stderr, "install-launcher: invalid cancellation request\n");+ return 2;+ }+ if (setgid(0) != 0 || setuid(0) != 0) {+ fprintf(stderr, "install-launcher: cannot become root: %s\n",+ strerror(errno));+ return 1;+ }+ pid_t process = (pid_t)strtol(argv[2], NULL, 10);+ if (process > 1)+ kill(-process, SIGTERM);+ usleep(500000);+ execl("/var/jb/bin/rm", "rm", "-rf", "--", attempt,+ (char *)NULL);+ return 1;+ }+ if (argc == 3 && strcmp(argv[1], "--delete-artifact") == 0) {+ const char *path = argv[2];+ const char *installations =+ "/var/mobile/Media/VirtualMac/Installations/";+ const char *images =+ "/var/mobile/Media/VirtualMac/Restore Images/";+ int allowed =+ (has_prefix(path, installations) &&+ strlen(path) > strlen(installations)) ||+ (has_prefix(path, images) && strlen(path) > strlen(images));+ if (!allowed || strchr(path, '\n') || strchr(path, '\r') ||+ strstr(path, "/../") || has_suffix(path, "/..")) {+ fprintf(stderr, "install-launcher: invalid artifact path\n");+ return 2;+ }+ if (setgid(0) != 0 || setuid(0) != 0) {+ fprintf(stderr, "install-launcher: cannot become root: %s\n",+ strerror(errno));+ return 1;+ }+ execl("/var/jb/bin/rm", "rm", "-rf", "--", path,+ (char *)NULL);+ fprintf(stderr, "install-launcher: cleanup exec failed: %s\n",+ strerror(errno));+ return 1;+ }+ if (argc != 8) {+ fprintf(stderr, "install-launcher: expected seven arguments\n");+ return 2;+ }+ if (!has_prefix(argv[1],+ "/var/mobile/Media/VirtualMac/Restore Images/") ||+ !(has_suffix(argv[1], ".ipsw") || has_suffix(argv[1], ".zip")) ||+ !has_prefix(argv[2],+ "/var/mobile/Media/VirtualMac/Installations/") ||+ !has_suffix(argv[2], ".bundle.installing") ||+ !is_direct_child(argv[3], "/var/mobile/Media/VirtualMac") ||+ !has_suffix(argv[3], ".bundle") ||+ !has_prefix(argv[4],+ "/var/mobile/Media/VirtualMac/Installations/") ||+ !has_suffix(argv[4], ".install.log") ||+ !is_decimal(argv[5]) || !is_decimal(argv[6]) ||+ !is_decimal(argv[7])) {+ fprintf(stderr, "install-launcher: invalid output path\n");+ return 2;+ }+ for (int index = 1; index < argc; index++) {+ if (strchr(argv[index], '\n') || strchr(argv[index], '\r')) {+ fprintf(stderr, "install-launcher: newline in argument\n");+ return 2;+ }+ if (strstr(argv[index], "/../") ||+ has_suffix(argv[index], "/..")) {+ fprintf(stderr, "install-launcher: parent traversal in argument\n");+ return 2;+ }+ }+ int log_fd = open(argv[4], O_WRONLY | O_CREAT | O_APPEND, 0644);+ if (log_fd < 0)+ return 2;+ dup2(log_fd, STDOUT_FILENO);+ dup2(log_fd, STDERR_FILENO);+ close(log_fd);+ setlinebuf(stdout);+ setlinebuf(stderr);+ printf("INSTALL_LAUNCHER_BEGIN\tipsw=%s\n", argv[1]);++ struct stat info;+ if (stat(argv[1], &info) != 0 || !S_ISREG(info.st_mode)) {+ fprintf(stderr,+ "INSTALL_FAILED\tlauncher IPSW is not a regular file: %s\n",+ strerror(errno));+ return 2;+ }+ if (setgid(0) != 0 || setuid(0) != 0) {+ fprintf(stderr, "INSTALL_FAILED\tlauncher cannot become root: %s\n",+ strerror(errno));+ return 1;+ }+ if (setenv("PATH",+ "/var/jb/usr/bin:/var/jb/bin:/usr/bin:/bin:/usr/sbin:/sbin",+ 1) != 0) {+ fprintf(stderr, "INSTALL_FAILED\tlauncher cannot set PATH: %s\n",+ strerror(errno));+ return 1;+ }+ execl("/var/jb/bin/sh", "sh",+ "/var/root/VirtualMac/install/start-install.sh", argv[1],+ argv[2], argv[3], argv[4], argv[5], argv[6], argv[7],+ (char *)NULL);+ fprintf(stderr, "INSTALL_FAILED\tlauncher exec failed: %s\n",+ strerror(errno));+ return 1;+}diff --git a/VirtualMac/vz/install/install_macos.m b/VirtualMac/vz/install/install_macos.mnew file mode 100644index 0000000..b1a71fc--- /dev/null+++ b/VirtualMac/vz/install/install_macos.m@@ -0,0 +1,370 @@+#import <Foundation/Foundation.h>+#import <objc/message.h>+#import <objc/runtime.h>+#include <dlfcn.h>+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <stdlib.h>+#include <sys/stat.h>+#include <unistd.h>+#import "../host/NSViewShim.h"++static id gVirtualMachine;+static id gInstaller;+static dispatch_source_t gProgressTimer;+static NSString *gStagingBundlePath;+static NSString *gFinalBundlePath;++static SEL S(const char *name) { return sel_registerName(name); }+static Class C(const char *name) { return objc_getClass(name); }+static id New(const char *name)+{+ return ((id (*)(id, SEL))objc_msgSend)(C(name), S("new"));+}+static id Alloc(const char *name)+{+ return ((id (*)(id, SEL))objc_msgSend)(C(name), S("alloc"));+}+static void SetObject(id object, const char *selector, id value)+{+ ((void (*)(id, SEL, id))objc_msgSend)(object, S(selector), value);+}+static NSURL *FileURL(NSString *path)+{+ return [NSURL fileURLWithPath:path];+}++static uint64_t EnvironmentUInt64(const char *name, uint64_t fallback,+ uint64_t minimum, uint64_t maximum)+{+ const char *text = getenv(name);+ if (!text || !*text)+ return fallback;+ char *end = NULL;+ errno = 0;+ unsigned long long value = strtoull(text, &end, 10);+ if (errno || !end || *end || value < minimum || value > maximum)+ return fallback;+ return value;+}++static void FinishWithError(NSString *stage, NSError *error)+{+ fprintf(stderr, "INSTALL_FAILED\tstage=%s\terror=%s\n",+ stage.UTF8String ?: "(unknown)",+ error.description.UTF8String ?: "(unknown)");+ fflush(NULL);+ exit(1);+}++static BOOL LoadImage(NSString *path)+{+ void *image = dlopen(path.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);+ if (!image) {+ fprintf(stderr, "DLOPEN_FAILED\t%s\t%s\n",+ path.fileSystemRepresentation, dlerror());+ return NO;+ }+ printf("DLOPEN_OK\t%s\n", path.fileSystemRepresentation);+ return YES;+}++static BOOL WriteData(id object, const char *selector, NSString *path)+{+ NSData *data = ((id (*)(id, SEL))objc_msgSend)(object, S(selector));+ NSError *error = nil;+ BOOL result = [data writeToURL:FileURL(path)+ options:NSDataWritingAtomic error:&error];+ if (!result)+ FinishWithError(@"write-metadata", error);+ return result;+}++static BOOL SetBundleFileAccess(NSString *path, mode_t mode, NSError **error)+{+ const char *fileSystemPath = path.fileSystemRepresentation;+ if (chown(fileSystemPath, 501, 501) == 0 &&+ chmod(fileSystemPath, mode) == 0)+ return YES;+ int savedError = errno;+ if (error)+ *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:savedError+ userInfo:nil];+ return NO;+}++static BOOL PrepareBundleForMobile(NSError **error)+{+ if (!SetBundleFileAccess(gStagingBundlePath, 0755, error))+ return NO;+ for (NSString *name in @[@"Disk.img", @"AuxiliaryStorage"]) {+ if (!SetBundleFileAccess(+ [gStagingBundlePath stringByAppendingPathComponent:name],+ 0600, error))+ return NO;+ }+ for (NSString *name in @[@"HardwareModel", @"MachineIdentifier"]) {+ if (!SetBundleFileAccess(+ [gStagingBundlePath stringByAppendingPathComponent:name],+ 0644, error))+ return NO;+ }+ return YES;+}++static id CreateConfiguration(id requirements, NSError **error)+{+ NSString *auxiliaryPath =+ [gStagingBundlePath stringByAppendingPathComponent:@"AuxiliaryStorage"];+ NSString *diskPath =+ [gStagingBundlePath stringByAppendingPathComponent:@"Disk.img"];+ NSString *hardwarePath =+ [gStagingBundlePath stringByAppendingPathComponent:@"HardwareModel"];+ NSString *identifierPath =+ [gStagingBundlePath stringByAppendingPathComponent:@"MachineIdentifier"];++ id hardwareModel = [requirements valueForKey:@"hardwareModel"];+ id platform = New("VZMacPlatformConfiguration");+ id auxiliary = ((id (*)(id, SEL, id, id, NSUInteger, NSError **))objc_msgSend)(+ Alloc("VZMacAuxiliaryStorage"),+ S("initCreatingStorageAtURL:hardwareModel:options:error:"),+ FileURL(auxiliaryPath), hardwareModel, (NSUInteger)1, error);+ if (!auxiliary)+ return nil;+ id machineIdentifier = New("VZMacMachineIdentifier");+ SetObject(platform, "setHardwareModel:", hardwareModel);+ SetObject(platform, "setAuxiliaryStorage:", auxiliary);+ SetObject(platform, "setMachineIdentifier:", machineIdentifier);+ WriteData(hardwareModel, "dataRepresentation", hardwarePath);+ WriteData(machineIdentifier, "dataRepresentation", identifierPath);++ uint64_t cpuCount = EnvironmentUInt64(+ "VZ_INSTALL_CPU_COUNT", 4, 2,+ MAX((NSUInteger)2, NSProcessInfo.processInfo.activeProcessorCount));+ uint64_t memorySize = EnvironmentUInt64(+ "VZ_INSTALL_MEMORY_SIZE", 4ULL << 30, 2ULL << 30, 8ULL << 30);+ uint64_t storageSize = EnvironmentUInt64(+ "VZ_INSTALL_STORAGE_SIZE", 64ULL << 30, 32ULL << 30,+ (uint64_t)LLONG_MAX);++ int disk = open(diskPath.fileSystemRepresentation,+ O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);+ if (disk == -1) {+ *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno+ userInfo:nil];+ return nil;+ }+ if (ftruncate(disk, (off_t)storageSize) != 0) {+ int savedError = errno;+ close(disk);+ *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:savedError+ userInfo:nil];+ return nil;+ }+ close(disk);++ id attachment = ((id (*)(id, SEL, id, BOOL, NSError **))objc_msgSend)(+ Alloc("VZDiskImageStorageDeviceAttachment"),+ S("initWithURL:readOnly:error:"), FileURL(diskPath), NO, error);+ if (!attachment)+ return nil;+ id blockDevice = ((id (*)(id, SEL, id))objc_msgSend)(+ Alloc("VZVirtioBlockDeviceConfiguration"),+ S("initWithAttachment:"), attachment);++ id configuration = New("VZVirtualMachineConfiguration");+ SetObject(configuration, "setPlatform:", platform);+ ((void (*)(id, SEL, NSUInteger))objc_msgSend)(+ configuration, S("setCPUCount:"), (NSUInteger)cpuCount);+ ((void (*)(id, SEL, uint64_t))objc_msgSend)(+ configuration, S("setMemorySize:"), memorySize);+ SetObject(configuration, "setBootLoader:", New("VZMacOSBootLoader"));+ SetObject(configuration, "setStorageDevices:", @[blockDevice]);++ // The display is install-time only; the user's configured native-resolution display remains the runtime device.+ id display = ((id (*)(id, SEL, NSInteger, NSInteger, NSInteger))+ objc_msgSend)(Alloc("VZMacGraphicsDisplayConfiguration"),+ S("initWithWidthInPixels:heightInPixels:pixelsPerInch:"),+ 1920, 1200, 80);+ id graphics = New("VZMacGraphicsDeviceConfiguration");+ SetObject(graphics, "setDisplays:", @[display]);+ SetObject(configuration, "setGraphicsDevices:", @[graphics]);+ printf("INSTALL_GRAPHICS\t1920x1200@80\n");++ BOOL valid = ((BOOL (*)(id, SEL, NSError **))objc_msgSend)(+ configuration, S("validateWithError:"), error);+ if (!valid)+ return nil;+ printf("INSTALL_CONFIGURATION_OK\tcpu=%llu\tmemory=%llu\t"+ "disk-bytes=%llu\n", cpuCount, memorySize, storageSize);+ return configuration;+}++static void StartInstall(id restoreImage, NSURL *ipswURL)+{+ id requirements =+ [restoreImage valueForKey:@"mostFeaturefulSupportedConfiguration"];+ id hardwareModel = [requirements valueForKey:@"hardwareModel"];+ BOOL modelSupported = ((BOOL (*)(id, SEL))objc_msgSend)(+ hardwareModel, S("isSupported"));+ if (!requirements || !hardwareModel || !modelSupported) {+ FinishWithError(@"requirements",+ [NSError errorWithDomain:@"VirtualMac" code:1 userInfo:nil]);+ }++ NSError *error = nil;+ if (![[NSFileManager defaultManager]+ createDirectoryAtPath:gStagingBundlePath+ withIntermediateDirectories:NO attributes:nil error:&error])+ FinishWithError(@"create-bundle", error);++ id configuration = CreateConfiguration(requirements, &error);+ if (!configuration)+ FinishWithError(@"create-configuration", error);++ gVirtualMachine = ((id (*)(id, SEL, id))objc_msgSend)(+ Alloc("VZVirtualMachine"), S("initWithConfiguration:"), configuration);+ if (!gVirtualMachine) {+ FinishWithError(@"create-virtual-machine",+ [NSError errorWithDomain:@"VirtualMac" code:2 userInfo:nil]);+ }+ gInstaller = ((id (*)(id, SEL, id, id))objc_msgSend)(+ Alloc("VZMacOSInstaller"),+ S("initWithVirtualMachine:restoreImageURL:"),+ gVirtualMachine, ipswURL);+ if (!gInstaller) {+ FinishWithError(@"create-installer",+ [NSError errorWithDomain:@"VirtualMac" code:3 userInfo:nil]);+ }++ id progress = [gInstaller valueForKey:@"progress"];+ gProgressTimer = dispatch_source_create(+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());+ dispatch_source_set_timer(+ gProgressTimer, dispatch_time(DISPATCH_TIME_NOW, 0),+ NSEC_PER_SEC, NSEC_PER_MSEC * 100);+ dispatch_source_set_event_handler(gProgressTimer, ^{+ double fraction = [[progress valueForKey:@"fractionCompleted"] doubleValue];+ printf("INSTALL_PROGRESS\t%.6f\n", fraction);+ fflush(NULL);+ });+ dispatch_resume(gProgressTimer);++ printf("INSTALL_BEGIN\t%s\n", ipswURL.path.UTF8String);+ ((void (*)(id, SEL, id))objc_msgSend)(+ gInstaller, S("installWithCompletionHandler:"), ^(NSError *installError) {+ dispatch_source_cancel(gProgressTimer);+ if (installError)+ FinishWithError(@"install", installError);++ NSError *moveError = nil;+ if (!PrepareBundleForMobile(&moveError))+ FinishWithError(@"prepare-bundle-access", moveError);+ if (![[NSFileManager defaultManager]+ moveItemAtPath:gStagingBundlePath+ toPath:gFinalBundlePath error:&moveError])+ FinishWithError(@"finalize-bundle", moveError);+ printf("INSTALL_SUCCEEDED\tbundle=%s\n",+ gFinalBundlePath.UTF8String);+ fflush(NULL);+ exit(0);+ });+}++int main(int argc, const char *argv[])+{+ @autoreleasepool {+ setlinebuf(stdout);+ setlinebuf(stderr);+ if (argc != 4) {+ fprintf(stderr,+ "usage: install-macos <restore.ipsw> <staging.bundle.installing> <final.bundle>\n");+ return 2;+ }+ NSString *ipswPath = [[NSString alloc] initWithUTF8String:argv[1]];+ gStagingBundlePath =+ [[NSString alloc] initWithUTF8String:argv[2]];+ gFinalBundlePath = [[NSString alloc] initWithUTF8String:argv[3]];+ if (![gStagingBundlePath hasSuffix:@".bundle.installing"] ||+ ![gStagingBundlePath hasPrefix:+ @"/var/mobile/Media/VirtualMac/Installations/"] ||+ ![gFinalBundlePath.stringByDeletingLastPathComponent+ isEqualToString:@"/var/mobile/Media/VirtualMac"] ||+ ![gFinalBundlePath hasSuffix:@".bundle"] ||+ [[NSFileManager defaultManager]+ fileExistsAtPath:gStagingBundlePath] ||+ [[NSFileManager defaultManager]+ fileExistsAtPath:gFinalBundlePath]) {+ fprintf(stderr, "INVALID_INSTALL_PATHS\t%s\t%s\n",+ gStagingBundlePath.UTF8String,+ gFinalBundlePath.UTF8String);+ return 2;+ }++ printf("FAKE_CLASS\tNSView\tsuperclass=%s\tinstance-size=%zu\n",+ class_getName(class_getSuperclass([NSView class])),+ class_getInstanceSize([NSView class]));++ NSString *root = @"/var/root/VirtualMac";+ setenv("VZ_INSTALLATION_BIN", [[root stringByAppendingPathComponent:+ @"payload/Installation.xpc/Contents/MacOS/"+ "com.apple.Virtualization.Installation"] fileSystemRepresentation], 1);+ setenv("VZ_VMM_BIN", [[root stringByAppendingPathComponent:+ @"payload/VirtualMachine.xpc/Contents/MacOS/"+ "com.apple.Virtualization.VirtualMachine"] fileSystemRepresentation], 1);+ setenv("VZ_AVP_BOOTER", [[root stringByAppendingPathComponent:+ @"payload/Frameworks/Virtualization.framework/Resources/"+ "AVPBooter.vmapple2.bin"] fileSystemRepresentation], 1);+ setenv("VMM_FACTORY_SETTLE_USEC", "100000", 1);+ setenv("VMM_FACTORY_LONG_STOP", "6", 1);+ setenv("VMM_FACTORY_LONG_SETTLE_USEC", "5000000", 1);++ NSArray<NSString *> *images = @[+ [root stringByAppendingPathComponent:+ @"install/VZHostCompat.dylib"],+ [root stringByAppendingPathComponent:+ @"payload/Frameworks/Hypervisor.framework/Hypervisor"],+ [root stringByAppendingPathComponent:+ @"payload/Frameworks/ParavirtualizedGraphics.framework/"+ "ParavirtualizedGraphics"],+ [root stringByAppendingPathComponent:+ @"payload/Frameworks/Virtualization.framework/Virtualization"],+ ];+ for (NSString *image in images)+ if (!LoadImage(image))+ return 1;++ Method startMethod = class_getInstanceMethod(+ C("VZVirtualMachine"), S("startWithCompletionHandler:"));+ Dl_info info = {0};+ if (!startMethod ||+ !dladdr((const void *)method_getImplementation(startMethod), &info) ||+ !info.dli_fbase)+ return 1;+ int (*rebind)(void *) =+ (int (*)(void *))dlsym(RTLD_DEFAULT, "vz_rebind_virtualization");+ int rebindResult = rebind ? rebind(info.dli_fbase) : -1;+ printf("VZ_REBIND\tbase=%p\tresult=%d\n", info.dli_fbase,+ rebindResult);+ if (rebindResult != 0)+ return 1;++ NSURL *ipswURL = FileURL(ipswPath);+ Class restoreClass = C("VZMacOSRestoreImage");+ printf("RESTORE_LOAD_BEGIN\t%s\n", ipswPath.UTF8String);+ ((void (*)(id, SEL, id, id))objc_msgSend)(+ restoreClass, S("loadFileURL:completionHandler:"), ipswURL,+ ^(id restoreImage, NSError *loadError) {+ if (!restoreImage)+ FinishWithError(@"load-restore-image", loadError);+ printf("RESTORE_LOAD_OK\tbuild=%s\n",+ [[[restoreImage valueForKey:@"buildVersion"] description]+ UTF8String]);+ dispatch_async(dispatch_get_main_queue(), ^{+ StartInstall(restoreImage, ipswURL);+ });+ });+ dispatch_main();+ }+}diff --git a/VirtualMac/vz/install/start-install.sh b/VirtualMac/vz/install/start-install.shnew file mode 100644index 0000000..9d3f157--- /dev/null+++ b/VirtualMac/vz/install/start-install.sh@@ -0,0 +1,134 @@+#!/var/jb/bin/sh++# On-device launcher shared by the UIKit app and SSH automation. It prewarms+# DeviceSupport's usbmuxd before VZMacOSInstaller reaches the RestoreOS USB+# handoff, then starts the real Apple installation stack in the background.++set -eu+# System applications do not inherit the interactive jailbreak shell PATH.+# Keep every utility used below resolvable when this script is exec'd by the+# setuid install-launcher from UIKit.+PATH=/var/jb/usr/bin:/var/jb/bin:/usr/bin:/bin:/usr/sbin:/sbin+export PATH+trap 'status=$?; if [ "$status" -ne 0 ] && { [ -z "${log:-}" ] || ! grep -q "INSTALL_FAILED" "$log" 2>/dev/null; }; then echo "INSTALL_FAILED launcher status=$status"; fi' EXIT++if [ "$#" -ne 7 ]; then+ echo "usage: start-install.sh IPSW STAGING_BUNDLE FINAL_BUNDLE LOG CPU MEMORY_BYTES DISK_BYTES" >&2+ exit 2+fi++remote=/var/root/VirtualMac+ipsw=$1+staging=$2+final=$3+log=$4+cpu=$5+memory=$6+disk=$7+usbmuxd="$remote/payload/Installation.xpc/Contents/Frameworks/MobileDevice.framework/Versions/A/Resources/usbmuxd"++test -f "$ipsw"+test ! -e "$staging"+test ! -e "$final"+echo "INSTALL_PREPARE_BEGIN ipsw=$ipsw"+case "$staging" in+ /var/mobile/Media/VirtualMac/Installations/*.bundle.installing) ;;+ *) echo "staging bundle must be in Virtual Mac installation storage" >&2; exit 2 ;;+esac+test "${final%/*}" = /var/mobile/Media/VirtualMac || {+ echo "final bundle must be directly in /var/mobile/Media/VirtualMac" >&2+ exit 2+}+case "$final" in+ *.bundle) ;;+ *) echo "final bundle must have a .bundle suffix" >&2; exit 2 ;;+esac++# Darwin truncates the process name used by killall, so the Installation.xpc+# executable's full bundle name is never matched reliably. Kill only helpers+# whose complete command path belongs to this payload; otherwise an orphaned+# listener can retain global usbmux/endpoint state across restore attempts.+ps -axo pid=,command= | while read -r stale_pid stale_command; do+ case "$stale_command" in+ "$remote/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation")+ kill "$stale_pid" 2>/dev/null || true+ ;;+ esac+done+sleep 0.1+ps -axo pid=,command= | while read -r stale_pid stale_command; do+ case "$stale_command" in+ "$remote/payload/Installation.xpc/Contents/MacOS/com.apple.Virtualization.Installation")+ kill -9 "$stale_pid" 2>/dev/null || true+ ;;+ esac+done+killall install-macos 2>/dev/null || true+killall usbmuxd 2>/dev/null || true+if test -f /tmp/vz-usbmuxd-launch.pid; then+ kill "$(cat /tmp/vz-usbmuxd-launch.pid)" 2>/dev/null || true+fi+rm -f /var/run/usbmuxd /tmp/vzusbmuxd /tmp/vz-usbmuxd-enable+rm -f /tmp/installation_ep.txt /tmp/vmm_ep.txt \+ /tmp/installation.stderr.log /tmp/installationhook.log \+ /tmp/installation-usb.log /tmp/restore-vmm.stderr.log \+ /tmp/vmm.stderr.log /tmp/vmmhook.log \+ /tmp/vzxpchook.log /tmp/vz-usbmuxd.log++DYLD_INSERT_LIBRARIES="$remote/payload/Installation.xpc/Contents/Frameworks/InstallationCompat.dylib" \+INSTALL_USB_POLL_US=250000 \+INSTALL_USB_ENABLE_FILE=/tmp/vz-usbmuxd-enable \+ "$usbmuxd" -debug 5 >/tmp/vz-usbmuxd.log 2>&1 &+echo $! >/tmp/vz-usbmuxd.pid++attempt=0+while ! test -S /tmp/vzusbmuxd; do+ attempt=$((attempt + 1))+ test "$attempt" -lt 30 || {+ echo "usbmuxd did not create /tmp/vzusbmuxd" >&2+ exit 1+ }+ sleep 0.1+done++installer_pid=$$+(+ while ! grep -q 'fake USB device descriptor: .* ac 05 ac 12' \+ /tmp/vmmhook.log 2>/dev/null; do+ kill -0 "$installer_pid" 2>/dev/null || exit 0+ sleep 0.01+ done+ while ! grep -q 'RestoreOS USBMux handshake cached generation=' \+ /tmp/vmmhook.log 2>/dev/null; do+ kill -0 "$installer_pid" 2>/dev/null || exit 0+ sleep 0.01+ done+ touch /tmp/vz-usbmuxd-enable+ ln -s /tmp/vzusbmuxd /var/run/usbmuxd+) >/tmp/vz-usbmuxd-launch.log 2>&1 &+echo $! >/tmp/vz-usbmuxd-launch.pid++# iPadOS cannot create Ventura's kernel-backed IOUSBHostControllerInterface.+# The userspace controller bridge carries the genuine virtual DFU endpoint+# traffic to MobileDevice and is required for unattended on-device restores.+export VZ_INSTALL_CPU_COUNT="$cpu"+export VZ_INSTALL_MEMORY_SIZE="$memory"+export VZ_INSTALL_STORAGE_SIZE="$disk"+export VZ_VMM_STDERR_LOG=/tmp/restore-vmm.stderr.log+# The setuid restore host must create its own rendezvous names. Inheriting the+# UIKit app's mobile-owned names lets the root VMM replace them and can prevent+# every later VM from starting. The host hook generates root-scoped paths.+unset VZ_VMM_ENDPOINT_FILE VZ_INSTALLATION_ENDPOINT_FILE+export VMMHOOK_TRACE_USB="${VMMHOOK_TRACE_USB:-0}"+export VMMHOOK_TRACE_IOKIT="${VMMHOOK_TRACE_IOKIT:-1}"+export VMMHOOK_TRACE_XPC_LIMIT="${VMMHOOK_TRACE_XPC_LIMIT:-200}"+export VMMHOOK_FAKE_USB="${VMMHOOK_FAKE_USB:-1}"+export INSTALL_USB_DEBUG_DELAY_MS="${INSTALL_USB_DEBUG_DELAY_MS:-}"+export INSTALL_USB_TRACE_TRANSFERS="${INSTALL_USB_TRACE_TRANSFERS:-0}"++# Keep install-macos as the validated setuid launcher's main process. The+# successful visible restore proved that a separate launchd coalition is not+# required; exec preserves errors and termination directly in the UI log.+echo $$ >/tmp/install-macos.pid+echo "INSTALL_LAUNCHED pid=$$ log=$log"+exec "$remote/install/install-macos" "$ipsw" "$staging" "$final" >>"$log" 2>&1diff --git a/VirtualMac/vz/ipsw_patches/dyld_a2sb.go b/VirtualMac/vz/ipsw_patches/dyld_a2sb.gonew file mode 100644index 0000000..ec7d4fb--- /dev/null+++ b/VirtualMac/vz/ipsw_patches/dyld_a2sb.go@@ -0,0 +1,65 @@+package dyld++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"++ "github.com/blacktop/ipsw/internal/commands/dsc"+ "github.com/blacktop/ipsw/internal/utils"+ "github.com/blacktop/ipsw/pkg/dyld"+ "github.com/blacktop/ipsw/pkg/symbols"+ "github.com/spf13/cobra"+ "github.com/spf13/viper"+)++func init() {+ DyldCmd.AddCommand(A2SBatchCmd)+ A2SBatchCmd.Flags().String("cache", "", "Path to .a2s addr to sym cache file")+ viper.BindPFlag("dyld.a2sb.cache", A2SBatchCmd.Flags().Lookup("cache"))+}++// A2SBatchCmd batch-resolves many unslid addresses (DSC opened once).+// Output: one "0xADDR\tSYMBOL\tIMAGE" line per input address.+var A2SBatchCmd = &cobra.Command{+ Use: "a2sb <DSC> <ADDRFILE>",+ Short: "Batch lookup symbols at unslid addresses (one per line in ADDRFILE)",+ Args: cobra.ExactArgs(2),+ SilenceErrors: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ f, err := dyld.Open(filepath.Clean(args[0]))+ if err != nil {+ return err+ }+ defer f.Close()+ cacheFile := viper.GetString("dyld.a2sb.cache")+ if len(cacheFile) > 0 {+ if err := f.OpenOrCreateA2SCache(cacheFile); err != nil {+ return err+ }+ }+ data, err := os.ReadFile(args[1])+ if err != nil {+ return err+ }+ for _, line := range strings.Fields(string(data)) {+ a, e := utils.ConvertStrToInt(line)+ if e != nil {+ continue+ }+ var s *dsc.SymbolLookup+ if len(cacheFile) > 0 {+ s, e = dsc.LookupSymbol(f, a)+ } else {+ s, e = dsc.DirectLookupSymbol(f, a)+ }+ if e != nil || s == nil {+ fmt.Printf("%#x\t\t\n", a)+ continue+ }+ fmt.Printf("%#x\t%s\t%s\n", a, symbols.FormatSymbol(s.Symbol, false), s.Image)+ }+ return nil+ },+}diff --git a/VirtualMac/vz/patches/add_macho_dylib.py b/VirtualMac/vz/patches/add_macho_dylib.pynew file mode 100644index 0000000..cd0ab45--- /dev/null+++ b/VirtualMac/vz/patches/add_macho_dylib.py@@ -0,0 +1,104 @@+#!/usr/bin/env python3+"""Add one LC_LOAD_DYLIB to a thin 64-bit Mach-O using header slack.++The file is not relocated: the new command must fit between the existing load+commands and the first file-backed section. The caller must re-sign the Mach-O+afterward. This deliberately small patcher is sufficient for the matching VMM+and asserts every structural assumption before writing.+"""++import os+import struct+import sys+++MH_MAGIC_64 = 0xFEEDFACF+LC_SEGMENT_64 = 0x19+LC_LOAD_DYLIB = 0xC+++def align(value: int, alignment: int) -> int:+ return (value + alignment - 1) & ~(alignment - 1)+++def main(path: str, install_name: str) -> None:+ with open(path, "rb") as source:+ data = bytearray(source.read())++ if len(data) < 32:+ raise SystemExit(f"{path}: file is smaller than a Mach-O header")+ magic, _, _, _, command_count, command_bytes, _, _ = struct.unpack_from(+ "<8I", data, 0+ )+ if magic != MH_MAGIC_64:+ raise SystemExit(f"{path}: expected thin little-endian 64-bit Mach-O")++ cursor = 32+ first_section_offset = len(data)+ existing_names: list[str] = []+ for _ in range(command_count):+ if cursor + 8 > 32 + command_bytes:+ raise SystemExit(f"{path}: truncated load-command table")+ command, command_size = struct.unpack_from("<2I", data, cursor)+ if command_size < 8 or cursor + command_size > 32 + command_bytes:+ raise SystemExit(f"{path}: invalid load command at 0x{cursor:x}")+ if command == LC_LOAD_DYLIB:+ name_offset = struct.unpack_from("<I", data, cursor + 8)[0]+ name_start = cursor + name_offset+ name_end = data.find(b"\0", name_start, cursor + command_size)+ if name_end != -1:+ existing_names.append(data[name_start:name_end].decode())+ if command == LC_SEGMENT_64:+ section_count = struct.unpack_from("<I", data, cursor + 64)[0]+ section_cursor = cursor + 72+ if section_cursor + section_count * 80 > cursor + command_size:+ raise SystemExit(f"{path}: invalid LC_SEGMENT_64 sections")+ for index in range(section_count):+ section = section_cursor + index * 80+ section_offset = struct.unpack_from("<I", data, section + 48)[0]+ section_size = struct.unpack_from("<Q", data, section + 40)[0]+ if section_offset and section_size:+ first_section_offset = min(first_section_offset,+ section_offset)+ cursor += command_size++ if cursor != 32 + command_bytes:+ raise SystemExit(f"{path}: load-command size mismatch")+ if install_name in existing_names:+ print(f"{path}: already loads {install_name}")+ return++ encoded_name = install_name.encode() + b"\0"+ command_size = align(24 + len(encoded_name), 8)+ new_end = cursor + command_size+ if new_end > first_section_offset:+ raise SystemExit(+ f"{path}: need {command_size} bytes of header slack, have "+ f"{first_section_offset - cursor}"+ )+ if any(data[cursor:new_end]):+ raise SystemExit(f"{path}: prospective header slack is not zero-filled")++ command = bytearray(command_size)+ struct.pack_into("<6I", command, 0, LC_LOAD_DYLIB, command_size,+ 24, 2, 0x10000, 0x10000)+ command[24:24 + len(encoded_name)] = encoded_name+ data[cursor:new_end] = command+ struct.pack_into("<I", data, 16, command_count + 1)+ struct.pack_into("<I", data, 20, command_bytes + command_size)++ temporary = f"{path}.add-dylib.tmp"+ with open(temporary, "wb") as output:+ output.write(data)+ os.chmod(temporary, os.stat(path).st_mode)+ os.replace(temporary, path)+ print(+ f"patched {path}: LC_LOAD_DYLIB {install_name} "+ f"({command_size} bytes at 0x{cursor:x})"+ )+++if __name__ == "__main__":+ if len(sys.argv) != 3:+ raise SystemExit(f"usage: {sys.argv[0]} MACHO INSTALL_NAME")+ main(sys.argv[1], sys.argv[2])diff --git a/VirtualMac/vz/patches/installation.ents.xml b/VirtualMac/vz/patches/installation.ents.xmlnew file mode 100644index 0000000..9a34194--- /dev/null+++ b/VirtualMac/vz/patches/installation.ents.xml@@ -0,0 +1,30 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.diskimages.attach</key>+ <true/>+ <key>com.apple.private.DeviceSupportUpdater.requestor</key>+ <true/>+ <key>com.apple.private.amfi.can-execute-cdhash</key>+ <true/>+ <key>com.apple.private.security.message-filter</key>+ <true/>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.private.virtualization</key>+ <true/>+ <key>com.apple.security.network.client</key>+ <true/>+ <key>com.apple.security.virtualization</key>+ <true/>+ <key>com.apple.usb.hostcontrollerinterface</key>+ <true/>+ <key>get-task-allow</key>+ <true/>+ <key>platform-application</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/patches/internet-sharing.ents.xml b/VirtualMac/vz/patches/internet-sharing.ents.xmlnew file mode 100644index 0000000..4da5c83--- /dev/null+++ b/VirtualMac/vz/patches/internet-sharing.ents.xml@@ -0,0 +1,32 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>platform-application</key>+ <true/>+ <key>jb.pmap_cs.custom_trust</key>+ <string>PMAP_CS_IN_STATIC_TRUST_CACHE</string>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.SystemConfiguration.SCDynamicStore-write-access</key>+ <true/>+ <key>com.apple.SystemConfiguration.SCPreferences-write-access</key>+ <array>+ <string>com.apple.vmnet.plist</string>+ </array>+ <key>com.apple.pf.allow</key>+ <true/>+ <key>com.apple.networking.ethernet.user-access</key>+ <true/>+ <key>com.apple.security.exception.iokit-user-client-class</key>+ <array>+ <string>IOUserEthernetResourceUserClient</string>+ </array>+ <key>com.apple.discoveryd.dnsproxy</key>+ <true/>+ <key>com.apple.mDNSResponder.dnsproxy</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/patches/network-helper.ents.xml b/VirtualMac/vz/patches/network-helper.ents.xmlnew file mode 100644index 0000000..280aaa3--- /dev/null+++ b/VirtualMac/vz/patches/network-helper.ents.xml@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>platform-application</key>+ <true/>+ <key>jb.pmap_cs.custom_trust</key>+ <string>PMAP_CS_IN_STATIC_TRUST_CACHE</string>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.security.network.client</key>+ <true/>+ <key>com.apple.security.network.server</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/patches/patch_internet_sharing.py b/VirtualMac/vz/patches/patch_internet_sharing.pynew file mode 100644index 0000000..b77c58e--- /dev/null+++ b/VirtualMac/vz/patches/patch_internet_sharing.py@@ -0,0 +1,122 @@+#!/usr/bin/env python3+"""Apply narrowly verified iPad compatibility patches to InternetSharing."""++import pathlib+import sys+++def main(path_text: str) -> None:+ path = pathlib.Path(path_text)+ data = bytearray(path.read_bytes())++ # Ventura 13.2.1's startup prerequisite at 0x10001cc54 configures only+ # com.apple.NS-logging.plist through SCPreferences. That desktop-only+ # preference domain is unavailable on iPadOS, and the daemon otherwise+ # treats its absence as fatal. Return success while leaving all network,+ # DHCP, NAT, and packet-filter initialization unchanged.+ offset = 0x1CC54+ expected = bytes.fromhex("7f2303d5ffc300d1") # pacibsp; sub sp,sp,#0x30+ replacement = bytes.fromhex("20008052c0035fd6") # mov w0,#1; ret+ actual = bytes(data[offset:offset + len(expected)])+ if actual != expected:+ raise SystemExit(+ f"{path}: unexpected logging initializer bytes at {offset:#x}: "+ f"{actual.hex()}"+ )+ data[offset:offset + len(replacement)] = replacement++ # InternetSharing enables bootpd by launchd label through+ # SMJobSetEnabled. Reusing com.apple.bootpd causes ServiceManagement on+ # iPadOS to replace our matching Ventura helper with the sandboxed stock+ # iPadOS job; that binary cannot see /var/db/dhcpd_leases and never answers+ # the guest's otherwise-valid DHCP discovers. Use a private, equal-length+ # label registered by our deployment plist. Equal length is required+ # because the literal backs a constant CFString with a fixed length.+ old = b"com.apple.bootpd"+ new = b"vzi.apple.bootpd"+ if len(old) != len(new):+ raise AssertionError("bootpd launchd labels must remain equal length")+ count = data.count(old)+ if count != 1:+ raise SystemExit(+ f"{path}: expected one bootpd launchd label, found {count}"+ )+ data = bytearray(data.replace(old, new))++ # The desktop daemon verifies that bootpd exists at the sealed-system path+ # before enabling its launchd job. On rootless iPadOS the matching helper is+ # deployed under /var/jb, while the job itself remains com.apple.bootpd.+ # Skip only the path-existence failure; notification and launchd setup still+ # execute and therefore surface real helper failures.+ offset = 0x18470+ expected = bytes.fromhex("80010034") # cbz w0, success+ replacement = bytes.fromhex("0c000014") # b success+ actual = bytes(data[offset:offset + len(expected)])+ if actual != expected:+ raise SystemExit(+ f"{path}: unexpected bootpd path-check bytes at {offset:#x}: "+ f"{actual.hex()}"+ )+ data[offset:offset + len(replacement)] = replacement++ # rtadvd is likewise staged under /var/jb on a rootless jailbreak. Preserve+ # all IPv6 setup while accepting the relocated matching Ventura helper.+ offset = 0x1BCCC+ expected = bytes.fromhex("40feff34") # cbz w0, success+ replacement = bytes.fromhex("f2ffff17") # b success+ actual = bytes(data[offset:offset + len(expected)])+ if actual != expected:+ raise SystemExit(+ f"{path}: unexpected rtadvd path-check bytes at {offset:#x}: "+ f"{actual.hex()}"+ )+ data[offset:offset + len(replacement)] = replacement++ # NAT-PMP is an optional port-mapping service, but the desktop initializer+ # treats its sealed-system helper-path probe as fatal to the whole shared+ # network. Allow network creation to continue when the relocated helper is+ # not requested; outbound NAT and DHCP do not depend on NAT-PMP.+ offset = 0x19A0C+ expected = bytes.fromhex("60010034") # cbz w0, available+ replacement = bytes.fromhex("0b000014") # b available+ actual = bytes(data[offset:offset + len(expected)])+ if actual != expected:+ raise SystemExit(+ f"{path}: unexpected natpmpd path-check bytes at {offset:#x}: "+ f"{actual.hex()}"+ )+ data[offset:offset + len(replacement)] = replacement++ # The iPad root filesystem is sealed, so NetworkSharing cannot update the+ # desktop DHCP configuration under /etc. Keep the filename and binary+ # layout unchanged while moving it to a writable transient location. The+ # matching bootpd helper receives the same path rewrite.+ old = b"/etc/bootpd.plist"+ new = b"/tmp/bootpd.plist"+ count = data.count(old)+ if count != 1:+ raise SystemExit(+ f"{path}: expected one bootpd config path, found {count}"+ )+ data = bytearray(data.replace(old, new))++ old = b"/etc/com.apple.mis.rtadvd.conf"+ new = b"/tmp/com.apple.mis.rtadvd.conf"+ count = data.count(old)+ if count != 1:+ raise SystemExit(+ f"{path}: expected one rtadvd config path, found {count}"+ )+ data = bytearray(data.replace(old, new))++ path.write_bytes(data)+ print(+ f"patched {path}: bypassed desktop logging preferences and "+ "rootless network-helper path checks and selected matching bootpd"+ )+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(f"usage: {sys.argv[0]} INTERNET_SHARING_BINARY")+ main(sys.argv[1])diff --git a/VirtualMac/vz/patches/patch_macho_cstring.py b/VirtualMac/vz/patches/patch_macho_cstring.pynew file mode 100644index 0000000..b193239--- /dev/null+++ b/VirtualMac/vz/patches/patch_macho_cstring.py@@ -0,0 +1,36 @@+#!/usr/bin/env python3+"""Replace one Mach-O load-command string without moving chained fixups."""++import sys+++def main(path: str, old_text: str, new_text: str, expected_count: int = 1) -> None:+ old = old_text.encode() + b"\0"+ new = new_text.encode() + b"\0"+ if len(new) > len(old):+ raise SystemExit(+ f"replacement is longer than original: {len(new)} > {len(old)}"+ )+ with open(path, "rb") as source:+ data = bytearray(source.read())+ count = data.count(old)+ if count != expected_count:+ raise SystemExit(+ f"{path}: expected {expected_count} copies of {old_text!r}, "+ f"found {count}"+ )+ padded = new + bytes(len(old) - len(new))+ data = data.replace(old, padded)+ with open(path, "wb") as output:+ output.write(data)+ print(f"patched {path}: {old_text} -> {new_text}")+++if __name__ == "__main__":+ if len(sys.argv) not in (4, 5):+ raise SystemExit(+ f"usage: {sys.argv[0]} MACHO OLD_CSTRING NEW_CSTRING "+ "[EXPECTED_COUNT]"+ )+ expected = int(sys.argv[4]) if len(sys.argv) == 5 else 1+ main(*sys.argv[1:4], expected)diff --git a/VirtualMac/vz/patches/patch_netrb_lookup.py b/VirtualMac/vz/patches/patch_netrb_lookup.pynew file mode 100644index 0000000..c8603ec--- /dev/null+++ b/VirtualMac/vz/patches/patch_netrb_lookup.py@@ -0,0 +1,35 @@+#!/usr/bin/env python3+"""Patch iPadOS 16.3.1 Netrb to use its current bootstrap namespace."""++import pathlib+import sys+++def main(path_text: str) -> None:+ path = pathlib.Path(path_text)+ data = bytearray(path.read_bytes())+ expected = bytes.fromhex("42008052") # mov w2, #2+ replacement = bytes.fromhex("02008052") # mov w2, #0+ # 22D68 macOS Netrb is the production input. The iPadOS offset remains+ # accepted so this diagnostic patcher can also validate the native copy.+ candidates = [0xC3C, 0x16B4]+ matches = [+ offset for offset in candidates+ if bytes(data[offset:offset + len(expected)]) == expected+ ]+ if len(matches) != 1:+ raise SystemExit(+ f"{path}: expected one NETRBXPCCreate lookup instruction; "+ f"matched offsets {[hex(offset) for offset in matches]}"+ )+ offset = matches[0]+ data[offset:offset + 4] = replacement++ path.write_bytes(data)+ print(f"patched {path}: Netrb lookup uses current bootstrap domain")+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(f"usage: {sys.argv[0]} NETRB_BINARY")+ main(sys.argv[1])diff --git a/VirtualMac/vz/patches/patch_network_helper.py b/VirtualMac/vz/patches/patch_network_helper.pynew file mode 100644index 0000000..a74c1e4--- /dev/null+++ b/VirtualMac/vz/patches/patch_network_helper.py@@ -0,0 +1,38 @@+#!/usr/bin/env python3+"""Apply rootless path compatibility patches to Ventura network helpers."""++import pathlib+import sys+++def main(path_text: str) -> None:+ path = pathlib.Path(path_text)+ data = bytearray(path.read_bytes())+ old = b"/etc/bootpd.plist"+ new = b"/tmp/bootpd.plist"+ count = data.count(old)+ if count != 1:+ raise SystemExit(+ f"{path}: expected one bootpd config path, found {count}"+ )+ data = bytearray(data.replace(old, new))++ # Ventura binds the desktop symbol variant while iPadOS 16 exports the+ # same ABI as plain syslog. Rewrite both symbol-table/string-pool copies+ # in place so Mach-O offsets remain unchanged.+ old = b"_syslog$DARWIN_EXTSN"+ new = b"_syslog" + b"\0" * (len(old) - len(b"_syslog"))+ count = data.count(old)+ if count != 2:+ raise SystemExit(+ f"{path}: expected two extended syslog symbol strings, found {count}"+ )+ data = bytearray(data.replace(old, new))+ path.write_bytes(data)+ print(f"patched {path}: writable DHCP config and iPad syslog ABI")+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(f"usage: {sys.argv[0]} NETWORK_HELPER_BINARY")+ main(sys.argv[1])diff --git a/VirtualMac/vz/patches/patch_pvg_exception_log.py b/VirtualMac/vz/patches/patch_pvg_exception_log.pynew file mode 100644index 0000000..740e342--- /dev/null+++ b/VirtualMac/vz/patches/patch_pvg_exception_log.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""Disable macOS PVG exception logs that are unsafe in the iOS process.++The 22D68 PGFIFO command dispatchers catch Objective-C exceptions and log them+with a ``%@`` argument before running their normal recovery paths. On iPadOS,+libsystem_trace attempts to authenticate/dereference a macOS exception+object while flattening the log argument and crashes the VMM in objc_msgSend.+Replacing only those logging calls with NOPs falls through to each existing+branch back to exception recovery.+"""++from __future__ import annotations++import argparse+import struct+from pathlib import Path+++LOG_CALL_OFFSETS = (+ 0x1C7F4,+ 0x1C9F0,+ 0x1CC04,+ 0x1CE00,+ 0x1CFFC,+ 0x1D1FC,+ 0x1D438,+ 0x1D840,+ 0x1DA70,+ 0x1DC20,+ 0x1DE40,+ 0x1E040,+ 0x1E23C,+ 0x1E524,+ 0x1E770,+ 0x1E9BC,+ 0x1EBBC,+ 0x1EEB0,+ 0x1F240,+ 0x1F498,+ 0x1F8F4,+ 0x1F9C8,+ 0x201BC,+ 0x203BC,+ 0x20584,+ 0x20788,+ 0x20984,+ 0x20B30,+ 0x20EFC,+ 0x21268,+ 0x21570,+)+OS_LOG_ERROR_STUB_OFFSET = 0x28278+NOP = 0xD503201F+++def branch_target(instruction: int, offset: int) -> int | None:+ if instruction & 0xFC000000 != 0x94000000:+ return None+ immediate = instruction & 0x03FFFFFF+ if immediate & 0x02000000:+ immediate -= 0x04000000+ return offset + immediate * 4+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("binary", type=Path)+ args = parser.parse_args()++ data = bytearray(args.binary.read_bytes())+ if len(data) < max(LOG_CALL_OFFSETS) + 4:+ raise SystemExit(f"{args.binary}: file is too small")++ patched = 0+ for offset in LOG_CALL_OFFSETS:+ current = struct.unpack_from("<I", data, offset)[0]+ if current == NOP:+ continue+ target = branch_target(current, offset)+ if target != OS_LOG_ERROR_STUB_OFFSET:+ target_text = "not a BL" if target is None else f"0x{target:x}"+ raise SystemExit(+ f"{args.binary}: unexpected instruction at 0x{offset:x}: "+ f"0x{current:08x} targets {target_text}, expected "+ f"0x{OS_LOG_ERROR_STUB_OFFSET:x}"+ )+ struct.pack_into("<I", data, offset, NOP)+ patched += 1++ if not patched:+ print(f"{args.binary}: all PVG exception logs already disabled")+ return+ args.binary.write_bytes(data)+ print(+ f"{args.binary}: disabled {patched} unsafe PGFIFO exception object "+ "log calls"+ )+++if __name__ == "__main__":+ main()diff --git a/VirtualMac/vz/patches/patch_virt_ios.py b/VirtualMac/vz/patches/patch_virt_ios.pynew file mode 100755index 0000000..17937e6--- /dev/null+++ b/VirtualMac/vz/patches/patch_virt_ios.py@@ -0,0 +1,58 @@+#!/usr/bin/env python3+"""Apply iOS-specific binary patches to the post-extracted Virtualization framework.++The extracted framework expects symbols not available on iOS (or that behave wrong).+Rather than runtime-hook every one, we patch the auth-stubs / call sites directly:++ +0xed980 confstr stub → returns 8, writes 8 NUL bytes if buf!=NULL+ (iOS confstr returns 0 for _CS_DARWIN_USER_TEMP_DIR+ -> framework throws "Failed to retrieve cache dir")+ +0xee1f0 sandbox_extension_issue_generic_to_process stub → returns 1+ +0xee200 sandbox_extension_release stub → returns 0+ (iOS sandbox_extension_* are weak-import unresolved+ via flat-namespace; export trick gets shadowed.)+ +0x39ab4..+0x39ab8 device-iter loop in VZ_START -> store xzr into sp+0x528/0x530+ instead of LOAD. The vtable method that's+ supposed to populate that iterator-pair leaves+ them stale, so the loop walks bogus memory &+ strlen-crashes on a `*x19 == 0x1` garbage byte.+ A destructor later re-reads the SAME slots, so+ we must zero the actual memory (not just regs)+ or get a free-of-bogus SIGABRT. C++ vtable+ dispatch may still be partly mis-wired — worth+ revisiting once VMM-side dependencies are in.++These offsets are tied to the specific macOS 13.2.1 Virtualization.framework slice.+"""+import struct, sys, pathlib++def main(path):+ p = pathlib.Path(path)+ b = bytearray(p.read_bytes())+ # confstr stub: cbz x1,+8 ; str xzr,[x1] ; mov x0,#8 ; ret+ struct.pack_into('<IIII', b, 0xed980, 0xb4000041, 0xf900003f, 0xd2800100, 0xd65f03c0)+ # sandbox_extension_issue stub: mov x0,#1 ; ret ; brk ; brk+ struct.pack_into('<IIII', b, 0xee1f0, 0xd2800020, 0xd65f03c0, 0xd4200020, 0xd4200020)+ # sandbox_extension_release stub: mov x0,#0 ; ret ; brk ; brk+ struct.pack_into('<IIII', b, 0xee200, 0xd2800000, 0xd65f03c0, 0xd4200020, 0xd4200020)+ # device-iter loop skip + destructor skip:+ # +0x39ab4/ab8: STR xzr into sp+0x528/0x530 (so the later destructor at +0x39f98+ # reads 0 and cbz x20 → skip free; otherwise stack garbage → SIGABRT)+ # +0x39ac0 : force-branch to +0x39b30 (loop-exit) regardless of cmp x19, x20.+ # The orig was `b.eq #0x39b30`; turning the LOADS into STORES leaves+ # x19/x20 with stale values and the cmp doesn't reliably fall through.+ struct.pack_into('<II', b, 0x39ab4, 0xf90297ff, 0xf9029bff) # str xzr,[sp,#0x528/0x530]+ struct.pack_into('<I', b, 0x39ac0, 0x1400001c) # b #+0x70 (=> +0x39b30)++ # Function at +0x3d3fc validates a sandbox-extension struct and throws via NSException+ # when [x1+0x30]==0 (or other validation failures); the localized helper at +0x879b0+ # returns nil for ANY key (Localizable.strings bundle absent on iPad) so the throw turns+ # into "__NSPlaceholderDictionary attempt to insert nil object". The struct fields it+ # validates were populated by the device-iter loop we skipped, so we make it return+ # success (x0=0) immediately. Caller doesn't consume x0.+ struct.pack_into('<II', b, 0x3d3fc, 0xd2800000, 0xd65f03c0) # mov x0,#0 ; ret+ p.write_bytes(b)+ print(f"patched {path}: confstr/sandbox-ext stubs + VZ_START device-iter skip")++if __name__ == "__main__":+ main(sys.argv[1])diff --git a/VirtualMac/vz/patches/patch_vmm.sh b/VirtualMac/vz/patches/patch_vmm.shnew file mode 100755index 0000000..c03f2b5--- /dev/null+++ b/VirtualMac/vz/patches/patch_vmm.sh@@ -0,0 +1,24 @@+#!/bin/bash+# Patch the on-disk VMM binary: NOP the cbz at unnamed_734+4580 (file offset 0x1d3e4) so+# the failure path after unnamed_3450 isn't taken. Re-sign with original entitlements so+# AMFI still loads the arm64e binary (ldid -S without ents strips entitlements and the+# binary then can't run with com.apple.private.hypervisor).+#+# Bypassing this check leaves downstream code with uninitialised state (next observed crash:+# pthread_mutex_lock(NULL+0x18) at unnamed_4067+40). The real fix is to figure out what unnamed_3450+# checks and make our hv_trap return values it accepts; this patch just unblocks the immediate symptom.+set -e+VMM="${1:?usage: $0 /path/to/com.apple.Virtualization.VirtualMachine}"+ENTS="$(dirname "$0")/vmm.ents.xml"+python3 - "$VMM" <<'PY'+import struct, sys+p = sys.argv[1]+b = bytearray(open(p,'rb').read())+orig = struct.unpack_from('<I', b, 0x1d3e4)[0]+assert orig == 0x340000a8, f"unexpected at +0x1d3e4: {orig:08x}"+struct.pack_into('<I', b, 0x1d3e4, 0xd503201f) # nop+open(p,'wb').write(b)+print(f"patched {p}: cbz w8,#+20 -> nop at +0x1d3e4")+PY+ldid -S"$ENTS" "$VMM"+echo "re-signed with $ENTS"diff --git a/VirtualMac/vz/patches/patch_vmm_optional_devices.py b/VirtualMac/vz/patches/patch_vmm_optional_devices.pynew file mode 100644index 0000000..02b98c9--- /dev/null+++ b/VirtualMac/vz/patches/patch_vmm_optional_devices.py@@ -0,0 +1,56 @@+#!/usr/bin/env python3+"""Allow the macOS 13.2.1 VMM to omit unavailable host-side devices.++The iPadOS kernel does not contain macOS's AppleUSBUserHCI kext or its related+AppleUSBUserHCIResources service. Consequently, IOUSBHostControllerInterface+returns nil while creating com.apple.virtualization.avp.usb-device-controller.++The VMM's device-factory loop already represents devices as nullable pointers,+and its success path explicitly handles a null pointer before continuing to the+next descriptor. Remove only the branch that converts a null device into an+immediate failure. This does not bypass the platform initializer: all remaining+device descriptors are still initialized, and the factory's finalization runs.++The exact instruction and its neighbors are asserted for the 22D68 arm64e VMM+after iOS stamping/install-name rewriting, preventing accidental application to+another binary.+"""++import struct+import sys+++PATCH_OFFSET = 0x154F20+EXPECTED = (+ 0x9101E3E0, # add x0, sp, #0x78+ 0x97FB8F92, # call device-result cleanup+ 0x3600017A, # tbz w26, #0, failure+ 0xA97723BA, # success: ldp x26, x8, [x29, #-0x90]+)+NOP = 0xD503201F+++def main(path: str) -> None:+ with open(path, "rb") as source:+ data = bytearray(source.read())+ actual = struct.unpack_from("<4I", data, PATCH_OFFSET - 8)+ if actual != EXPECTED:+ expected_text = " ".join(f"{word:08x}" for word in EXPECTED)+ actual_text = " ".join(f"{word:08x}" for word in actual)+ raise SystemExit(+ f"{path}: optional-device site mismatch at 0x{PATCH_OFFSET - 8:x}: "+ f"expected {expected_text}, got {actual_text}"+ )+ struct.pack_into("<I", data, PATCH_OFFSET, NOP)+ with open(path, "wb") as output:+ output.write(data)+ print(+ f"patched {path}: nullable host devices continue at "+ f"0x{PATCH_OFFSET:x}"+ )+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(f"usage: {sys.argv[0]} VMM_BINARY")+ main(sys.argv[1])diff --git a/VirtualMac/vz/patches/patch_vmm_pci_address.py b/VirtualMac/vz/patches/patch_vmm_pci_address.pynew file mode 100644index 0000000..1427972--- /dev/null+++ b/VirtualMac/vz/patches/patch_vmm_pci_address.py@@ -0,0 +1,103 @@+#!/usr/bin/env python3+"""Repair 22D68 VMM PCI address allocation on iPadOS.++On iPadOS a PCI device can retain the automatic-address sentinel 0x7ff. The+macOS VMM uses it directly as a 256-entry table index, reading and+occasionally writing about 16 KiB beyond the bus. That makes startup alternate+between a phantom occupied-slot failure and heap-corrupting apparent success.+Preserve an explicit address when it is free; otherwise allocate the first free+slot before the table access.++The arm64e VMM is a thin image whose virtual addresses map to identical file+offsets above its 0x100000000 base. The helper occupies the tail of a long+VirtioSocket diagnostic string; this VM deliberately configures no socket+devices. Both the call site and the complete original string are asserted so+this build-specific patch fails closed on any other binary.++The helper avoids new Mach-O imports in the extracted executable.+"""++import struct+import sys+++PCI_ADDRESS_CALL_OFFSET = 0x179DF0+STRING_OFFSET = 0x1A5F4A+ORIGINAL_STRING = (+ b"VirtioSocketDevice: Unexpected error sending data from guest to host: %s.\0"+)+HELPER_OFFSET = STRING_OFFSET + 2 # preserve 4-byte instruction alignment+++def encode_bl(source: int, target: int) -> int:+ delta = target - source+ if delta & 3 or not -(1 << 27) <= delta < (1 << 27):+ raise ValueError(f"BL target out of range: 0x{source:x} -> 0x{target:x}")+ return 0x94000000 | ((delta >> 2) & 0x03FFFFFF)+++def pci_address_helper_words() -> tuple[int, ...]:+ # Replace "add x8, x24, x8, lsl #3". Preserve a free explicit address;+ # otherwise select the first free slot.+ return (+ 0xF11FFD1F, # cmp x8, #0x7ff+ 0x54000080, # b.eq scan+ 0x8B080F08, # add x8, x24, x8, lsl #3+ 0xF940250A, # ldr x10, [x8, #0x48]+ 0xB400012A, # cbz x10, ready+ 0xAA1803E8, # scan: mov x8, x24+ 0xD280200B, # mov x11, #0x100+ 0xF940250A, # loop: ldr x10, [x8, #0x48]+ 0xB40000AA, # cbz x10, ready+ 0x91002108, # add x8, x8, #8+ 0xF100056B, # subs x11, x11, #1+ 0x54FFFF81, # b.ne loop+ 0xAA1803E8, # full: mov x8, x24 (preserve occupied failure)+ 0xD65F03C0, # ret+ )+++def main(path: str) -> None:+ with open(path, "rb") as source:+ data = bytearray(source.read())++ actual_string = bytes(+ data[STRING_OFFSET : STRING_OFFSET + len(ORIGINAL_STRING)]+ )+ if actual_string != ORIGINAL_STRING:+ raise SystemExit(+ f"{path}: helper storage mismatch at 0x{STRING_OFFSET:x}"+ )++ helper = struct.pack(+ f"<{len(pci_address_helper_words())}I",+ *pci_address_helper_words()+ )+ available = len(ORIGINAL_STRING) - (HELPER_OFFSET - STRING_OFFSET)+ if len(helper) > available:+ raise SystemExit("PCI address helper does not fit asserted storage")+ pci_address_instruction = struct.unpack_from(+ "<I", data, PCI_ADDRESS_CALL_OFFSET+ )[0]+ if pci_address_instruction != 0x8B080F08:+ raise SystemExit(+ f"{path}: PCI address site mismatch at "+ f"0x{PCI_ADDRESS_CALL_OFFSET:x}: {pci_address_instruction:08x}"+ )+ data[HELPER_OFFSET : HELPER_OFFSET + len(helper)] = helper+ struct.pack_into(+ "<I", data, PCI_ADDRESS_CALL_OFFSET,+ encode_bl(PCI_ADDRESS_CALL_OFFSET, HELPER_OFFSET)+ )+ with open(path, "wb") as output:+ output.write(data)+ print(+ f"patched {path}: PciBus address 0x{PCI_ADDRESS_CALL_OFFSET:x} -> "+ f"free-slot allocator 0x{HELPER_OFFSET:x}"+ )+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(f"usage: {sys.argv[0]} VMM_BINARY")+ main(sys.argv[1])diff --git a/VirtualMac/vz/patches/patch_vmm_trusthash.sh b/VirtualMac/vz/patches/patch_vmm_trusthash.shnew file mode 100755index 0000000..fa90603--- /dev/null+++ b/VirtualMac/vz/patches/patch_vmm_trusthash.sh@@ -0,0 +1,35 @@+#!/bin/bash+# Workaround for the device-type registry lookup miss (PG-GPU): the VMM's inlined libc+++# string-equality on the find path returns not-equal for the byte-identical 61-char key+# "com.apple.virtualization.avp.paravirtualized-graphics-gpu-arm" when this macOS-compiled+# arm64e binary runs on iOS (workaround for transplant fidelity issue).+#+# Since the 41 registry keys have DISTINCT 64-bit hashes, a stored-hash match uniquely+# identifies the entry. Two patches:+# (1) In unnamed_4871's two inlined find copies, on a hash match branch straight to the+# found+extract-value path (0x154c18), skipping the buggy byte compare.+# (2) unnamed_4871 is a recursive resolver: the per-entry success flag w20 comes from a+# recursive call's boolean return, which (1) alone doesn't flip. NOP the per-iter gate+# tbz w20 at 0x15517c so every entry is treated as resolved (factory already extracted+# by (1)). Result: VMM gets past the registry and reaches hv_vcpu_create.+# Re-sign with the original entitlements (ldid -S<ents>) so AMFI still loads the arm64e bin.+set -e+VMM="${1:?usage: $0 /path/to/com.apple.Virtualization.VirtualMachine}"+ENTS="$(dirname "$0")/vmm.ents.xml"+python3 - "$VMM" <<'PY'+import struct,sys+p=sys.argv[1]; b=bytearray(open(p,'rb').read())+def patch(off,orig,new):+ cur=struct.unpack_from('<I',b,off)[0]+ assert cur==orig, f'0x{off:x}: expected {orig:08x} got {cur:08x}'+ struct.pack_into('<I',b,off,new); print(f' 0x{off:x}: {orig:08x} -> {new:08x}')+patch(0x154ae0,0x39409ee8,0x1400004e) # find copy1: hash-match -> b 0x154c18 (found)+patch(0x154b80,0x39409ee8,0x14000026) # find copy2: hash-match -> b 0x154c18 (found)+patch(0x15517c,0x36000dd4,0xd503201f) # per-iter w20 gate -> nop+patch(0xdf398, 0xdac11a30,0xdac147f0) # device-setup autda x16,x17 -> xpacd x16 (PAC+ # fault site unnamed_3573+112; surgical strip,+ # NOT global de-PAC which breaks the syslib ABI)+open(p,'wb').write(b); print(f'patched {p}')+PY+ldid -S"$ENTS" "$VMM"+echo "re-signed with $ENTS"diff --git a/VirtualMac/vz/patches/vmm.ents.xml b/VirtualMac/vz/patches/vmm.ents.xmlnew file mode 100644index 0000000..7f89924--- /dev/null+++ b/VirtualMac/vz/patches/vmm.ents.xml@@ -0,0 +1,74 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.private.hypervisor</key>+ <true/>+ <key>com.apple.security.hypervisor</key>+ <true/>+ <key>com.apple.vm.networking</key>+ <true/>+ <key>com.apple.private.virtualization</key>+ <true/>+ <key>com.apple.virtualization.avp.videotoolbox</key>+ <true/>+ <key>com.apple.security.virtualization</key>+ <true/>+ <key>com.apple.vm.device-access</key>+ <true/>+ <key>com.apple.private.IOSurface.wiredSendRights</key>+ <true/>+ <key>com.apple.private.iokit.IOServiceSetAuthorizationID</key>+ <true/>+ <key>com.apple.security.exception.iokit-user-client-class</key>+ <array>+ <string>AGXCommandQueue</string>+ <string>AGXDevice</string>+ <string>AGXDeviceUserClient</string>+ <string>AGXSharedUserClient</string>+ <string>IOSurfaceRootUserClient</string>+ <string>IOAccelContext</string>+ <string>IOAccelContext2</string>+ <string>IOAccelDevice</string>+ <string>IOAccelDevice2</string>+ <string>IOAccelSharedUserClient</string>+ <string>IOAccelSharedUserClient2</string>+ <string>IOAccelSubmitter2</string>+ </array>+ <key>com.apple.developer.kernel.increased-memory-limit</key>+ <true/>+ <key>com.apple.developer.kernel.extended-virtual-addressing</key>+ <true/>+ <key>com.apple.private.memorystatus</key>+ <true/>+ <key>com.apple.private.proreshw</key>+ <true/>+ <key>com.apple.aned.private.allow</key>+ <true/>+ <key>com.apple.ane.iokit-user-access</key>+ <true/>+ <key>com.apple.private.vfs.open-by-id</key>+ <true/>+ <key>com.apple.usb.hostcontrollerinterface</key>+ <true/>+ <key>com.apple.private.security.message-filter</key>+ <true/>+ <key>com.apple.private.FairPlayIOKitUserClient.access</key>+ <true/>+ <key>com.apple.private.tcc.allow</key>+ <array>+ <string>kTCCServiceMicrophone</string>+ </array>+ <key>com.apple.private.security.no-sandbox</key>+ <true/>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>platform-application</key>+ <true/>+ <key>com.apple.private.amfi.can-execute-cdhash</key>+ <true/>+ <key>get-task-allow</key>+ <true/>+</dict>+</plist>diff --git a/VirtualMac/vz/shaders/pvg_display.metal b/VirtualMac/vz/shaders/pvg_display.metalnew file mode 100644index 0000000..d17112a--- /dev/null+++ b/VirtualMac/vz/shaders/pvg_display.metal@@ -0,0 +1,70 @@+#include <metal_stdlib>+using namespace metal;++// Reconstructed from the AIR and reflection metadata in the unmodified+// macOS 13.2.1 (22D68) ParavirtualizedGraphics default.metallib. Keep names,+// resource indices, types, and math identical so the extracted PVG framework+// can create its pipelines with an iOS-targeted library.++kernel void BlitInRGB_2P_XR10_A8(+ texture2d<half, access::read> srcColor [[texture(0)]],+ texture2d<half, access::read> srcAlpha [[texture(1)]],+ texture2d<half, access::write> dst [[texture(2)]],+ uint2 index [[thread_position_in_grid]],+ uint2 size [[threads_per_grid]]) {+ (void)size;+ half4 color = srcColor.read(index);+ half4 alpha = srcAlpha.read(index);+ dst.write(half4(color.rgb, alpha.r), index);+}++kernel void BlitOutRGB_2P_XR10_A8(+ texture2d<half, access::read> src [[texture(0)]],+ texture2d<half, access::write> dstColor [[texture(1)]],+ texture2d<half, access::write> dstAlpha [[texture(2)]],+ uint2 index [[thread_position_in_grid]]) {+ half4 color = src.read(index);+ dstColor.write(half4(color.rgb, 0.0h), index);+ dstAlpha.write(color.aaaa, index);+}++struct PGDisplayVertexOutput {+ float4 pos [[position]];+ float2 tex;+};++vertex PGDisplayVertexOutput displayPresentVertex(+ constant float4 *positions [[buffer(0)]],+ constant float2 *textureCoordinates [[buffer(1)]],+ uint vertexID [[vertex_id]]) {+ return {positions[vertexID], textureCoordinates[vertexID]};+}++constexpr sampler displaySampler(+ coord::normalized, address::clamp_to_edge, filter::linear);+constexpr sampler gammaSampler(+ coord::normalized, address::clamp_to_edge, filter::linear);++fragment float4 displayPresentFragment(+ PGDisplayVertexOutput input [[stage_in]],+ texture2d<float, access::sample> texture [[texture(0)]]) {+ return texture.sample(displaySampler, input.tex);+}++struct PGDisplayFragmentShaderProperties {+ float4x3 colorMatrix;+};++fragment float4 displayPresentFragmentWithGammaTableAndColorMatrix(+ PGDisplayVertexOutput input [[stage_in]],+ texture2d<float, access::sample> texture [[texture(0)]],+ texture1d_array<float, access::sample> gammaTable [[texture(1)]],+ constant PGDisplayFragmentShaderProperties &properties [[buffer(0)]]) {+ float4 color = texture.sample(displaySampler, input.tex);+ float4 gammaColor(+ gammaTable.sample(gammaSampler, color.r, 0).r,+ gammaTable.sample(gammaSampler, color.g, 1).r,+ gammaTable.sample(gammaSampler, color.b, 2).r,+ 1.0f);+ return float4(properties.colorMatrix * gammaColor, 1.0f);+}diff --git a/VirtualMac/vz/shims/pvg_metallib_shim.m b/VirtualMac/vz/shims/pvg_metallib_shim.mnew file mode 100644index 0000000..e3123b4--- /dev/null+++ b/VirtualMac/vz/shims/pvg_metallib_shim.m@@ -0,0 +1,156 @@+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#import <objc/runtime.h>+#import <dlfcn.h>+#import <errno.h>+#import <os/log.h>+#import <ptrauth.h>+#import <stdint.h>+#import <stdlib.h>+#import <string.h>+#import <sys/mman.h>+#import <unistd.h>++static dispatch_data_t gSerializedMetallib;+static os_log_t gLog;++static id NewLibraryFromPreloadedData(id device,+ SEL selector,+ NSBundle *bundle,+ NSError **error)+ __attribute__((ns_returns_retained));++static id NewLibraryFromPreloadedData(id device,+ SEL selector,+ NSBundle *bundle,+ NSError **error) {+ (void)selector;+ (void)bundle;+ if (gSerializedMetallib == nil) {+ if (error != NULL) {+ *error = [NSError errorWithDomain:@"PVGMetallibShim"+ code:1+ userInfo:@{+ NSLocalizedDescriptionKey:+ @"default.metallib was not preloaded"+ }];+ }+ return nil;+ }+ return [device newLibraryWithData:gSerializedMetallib error:error];+}++static BOOL PreloadMetallib(void) {+ NSURL *url = [[NSBundle mainBundle]+ URLForResource:@"default"+ withExtension:@"metallib"];+ if (url == nil) {+ Class pvgDevice = NSClassFromString(@"_PGDevice");+ url = [[NSBundle bundleForClass:pvgDevice]+ URLForResource:@"default"+ withExtension:@"metallib"];+ }++ NSData *data = [NSData dataWithContentsOfURL:url];+ if (data.length == 0) {+ os_log_error(gLog, "could not preload default.metallib");+ return NO;+ }++ void *bytes = malloc(data.length);+ if (bytes == NULL) {+ os_log_error(gLog, "could not allocate %lu metallib bytes", data.length);+ return NO;+ }+ memcpy(bytes, data.bytes, data.length);+ gSerializedMetallib =+ dispatch_data_create(bytes,+ data.length,+ NULL,+ DISPATCH_DATA_DESTRUCTOR_FREE);+ os_log(gLog, "preloaded %lu default.metallib bytes", data.length);+ return gSerializedMetallib != nil;+}++static BOOL PatchCall(void *imageBase,+ uintptr_t offset,+ uint32_t expectedInstruction,+ uintptr_t targetAddress) {+ uint32_t *instruction = (uint32_t *)((uintptr_t)imageBase + offset);+ if (*instruction != expectedInstruction) {+ os_log_error(gLog,+ "PVG instruction mismatch at 0x%lx: %08x != %08x",+ offset,+ *instruction,+ expectedInstruction);+ return NO;+ }++ uintptr_t callAddress = (uintptr_t)instruction;+ intptr_t delta = (intptr_t)targetAddress - (intptr_t)callAddress;+ if ((delta & 3) != 0 ||+ delta < -(1LL << 27) ||+ delta >= (1LL << 27)) {+ os_log_error(gLog,+ "PVG shim branch is out of range: %p -> %p",+ instruction,+ (void *)targetAddress);+ return NO;+ }++ uintptr_t page =+ callAddress & ~((uintptr_t)getpagesize() - 1);+ if (mprotect((void *)page,+ (size_t)getpagesize(),+ PROT_READ | PROT_WRITE) != 0) {+ os_log_error(gLog, "PVG text write failed: errno %d", errno);+ return NO;+ }++ *instruction =+ 0x94000000U | ((uint32_t)(delta >> 2) & 0x03ffffffU);+ __builtin___clear_cache(+ (char *)instruction,+ (char *)instruction + sizeof(*instruction));+ if (mprotect((void *)page,+ (size_t)getpagesize(),+ PROT_READ | PROT_EXEC) != 0) {+ os_log_error(gLog, "PVG text protect failed: errno %d", errno);+ return NO;+ }+ return YES;+}++__attribute__((constructor))+static void InstallPVGMetallibShim(void) {+ @autoreleasepool {+ gLog = os_log_create("com.mac.virtual", "pvg-metallib-shim");+ if (!PreloadMetallib()) {+ return;+ }++ Class cls = NSClassFromString(@"_PGDevice");+ Method setup = class_getInstanceMethod(+ cls, NSSelectorFromString(@"setupBlitPipelines"));+ Dl_info image = {0};+ if (setup == NULL ||+ dladdr((const void *)method_getImplementation(setup), &image) == 0) {+ os_log_error(gLog, "could not locate ParavirtualizedGraphics");+ return;+ }++ uintptr_t target = (uintptr_t)ptrauth_strip(+ (void *)NewLibraryFromPreloadedData,+ ptrauth_key_function_pointer);++ // macOS 13.2.1 (22D68), PVG UUID+ // 732073AB-34E5-38C9-A919-53B628977BDB.+ BOOL displayPatched =+ PatchCall(image.dli_fbase, 0xe6d8, 0x9400bffaU, target);+ BOOL blitPatched =+ PatchCall(image.dli_fbase, 0xed24, 0x9400be67U, target);+ if (displayPatched && blitPatched) {+ os_log(gLog, "installed macOS 13.2.1 PVG metallib shim");+ }+ }+}diff --git a/VirtualMac/vz/stamp_ios.py b/VirtualMac/vz/stamp_ios.pynew file mode 100644index 0000000..1ecfb99--- /dev/null+++ b/VirtualMac/vz/stamp_ios.py@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""stamp_ios: post-process an uncache (compact) output into an iOS-loadable, signed dylib.++uncache emits a loadable arm64e Mach-O but leaves the macOS LC_BUILD_VERSION in place and+doesn't sign. This step:+ - rewrites LC_BUILD_VERSION (0x32): platform -> IOS (2), minos/sdk -> <ver> (default 16.0)+ - ad-hoc signs (codesign -f -s -), preserving the LC_DYLD_CHAINED_FIXUPS blob+ (do NOT use ldid -S here: it rebuilds LINKEDIT and drops the chained-fixups command)++vmnet/MetalSerializer weakening is done in uncache via VZ_WEAKEN (LC_LOAD_DYLIB->WEAK).++Usage: stamp_ios.py <in> <out> [minos] e.g. stamp_ios.py /tmp/Virt.proto /tmp/Virt.ios 16.0+"""+import sys, struct, subprocess, shutil++LC_BUILD_VERSION = 0x32+PLATFORM_IOS = 2+++def stamp(buf, minos="16.0"):+ maj, _, mn = minos.partition(".")+ ver = (int(maj) << 16) | ((int(mn) if mn else 0) << 8)+ ncmds = struct.unpack_from("<I", buf, 16)[0]+ sizeofcmds = struct.unpack_from("<I", buf, 20)[0]+ off, found = 32, 0+ commands = []+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ command = bytearray(buf[off:off + sz])+ if cmd == LC_BUILD_VERSION:+ if found:+ off += sz+ continue+ struct.pack_into(+ "<III", command, 8, PLATFORM_IOS, ver, ver+ ) # platform, minos, sdk+ found = 1+ commands.append(command)+ off += sz+ rebuilt = b"".join(commands)+ if len(rebuilt) > sizeofcmds:+ raise ValueError("rebuilt load commands grew unexpectedly")+ struct.pack_into("<II", buf, 16, len(commands), len(rebuilt))+ buf[32:32 + sizeofcmds] = rebuilt + bytes(sizeofcmds - len(rebuilt))+ return found+++def main(inp, outp, minos="16.0"):+ buf = bytearray(open(inp, "rb").read())+ n = stamp(buf, minos)+ if not n:+ raise SystemExit("no LC_BUILD_VERSION found")+ open(outp, "wb").write(buf)+ subprocess.run(["codesign", "-f", "-s", "-", outp], check=True)+ cd = subprocess.run(["codesign", "-dvvv", outp], capture_output=True, text=True).stderr+ cdhash = next((l.split("=", 1)[1] for l in cd.splitlines() if l.startswith("CDHash=")), "?")+ print(f"stamped {outp}: platform=iOS minos={minos} ({n} LC_BUILD_VERSION), signed; CDHash={cdhash}")+++if __name__ == "__main__":+ main(*sys.argv[1:])diff --git a/VirtualMac/vz/tweak/VZKeyboardPassthrough.m b/VirtualMac/vz/tweak/VZKeyboardPassthrough.mnew file mode 100644index 0000000..56abfde--- /dev/null+++ b/VirtualMac/vz/tweak/VZKeyboardPassthrough.m@@ -0,0 +1,331 @@+#import <Foundation/Foundation.h>+#import <objc/message.h>+#import <objc/runtime.h>++#include <dlfcn.h>+#include <stdint.h>+#include <stdio.h>+#include <unistd.h>++static IMP gOriginalKeyCommands;+static IMP gOriginalApplicationKeyCommands;+static IMP gOriginalHandleKeyHIDEvent;+static IMP gOriginalShouldEnableSystemGesture;+static IMP gOriginalShouldEnableSystemGesturePrivate;+static IMP gOriginalFluidGestureShouldBegin;+static IMP gOriginalFluidGestureShouldReceiveTouch;+static BOOL gCommandIsDown;+static uint64_t gRelayingShortcutUsages;+static const char *gTargetBundleID = "com.mac.virtual";+static const char *gOpenAfterRespring =+ "/tmp/virtual-mac-open-after-respring";+static const char *gVMActiveMarker = "/tmp/virtual-mac-vm-active";+static NSString * const gSettingsPath = @"/var/mobile/Media/VirtualMac/Settings.plist";+static NSDictionary *gSettings;++static BOOL VZSettingEnabled(NSString *key)+{+ id value = gSettings[key];+ return value ? [value boolValue] : YES;+}++static void VZReloadSettings(void)+{+ NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:gSettingsPath];+ [gSettings release];+ gSettings = [[settings isKindOfClass:NSDictionary.class] ? settings : @{} retain];+}++static void VZSettingsChanged(CFNotificationCenterRef center, void *observer,+ CFStringRef name, const void *object,+ CFDictionaryRef userInfo)+{+ (void)center; (void)observer; (void)name; (void)object; (void)userInfo;+ VZReloadSettings();+}++// IOHIDEventTypeKeyboard is 3. Keyboard fields occupy its 0x30000 field+// namespace: usage page, usage, down, and repeat, in that order. These SPI+// constants are stable across the iPadOS releases supported by this project,+// but are kept local so the tweak builds with an unmodified public SDK.+enum {+ VZHIDKeyboardUsagePageField = 0x30000,+ VZHIDKeyboardUsageField = 0x30001,+ VZHIDKeyboardDownField = 0x30002,+};++typedef int64_t (*VZIOHIDEventGetIntegerValue)(CFTypeRef, uint32_t);++static void Log(const char *message)+{+ FILE *file = fopen("/tmp/vz-springboard-shortcuts.log", "a");+ if (!file)+ return;+ fprintf(file, "%s\n", message);+ fclose(file);+}++static BOOL VirtualMacIsFrontmost(id springBoard)+{+ SEL frontSelector = sel_registerName("_accessibilityFrontMostApplication");+ if (![springBoard respondsToSelector:frontSelector])+ return NO;+ id application = ((id (*)(id, SEL))objc_msgSend)(+ springBoard, frontSelector);+ SEL bundleSelector = sel_registerName("bundleIdentifier");+ if (![application respondsToSelector:bundleSelector])+ return NO;+ NSString *bundleIdentifier = ((id (*)(id, SEL))objc_msgSend)(+ application, bundleSelector);+ return [bundleIdentifier isEqualToString:+ [NSString stringWithUTF8String:gTargetBundleID]];+}++static BOOL VirtualMacVMIsActive(id springBoard)+{+ return access(gVMActiveMarker, F_OK) == 0 &&+ VirtualMacIsFrontmost(springBoard);+}++static BOOL VZSharedApplicationIsTarget(void)+{+ id application = ((id (*)(id, SEL))objc_msgSend)(+ objc_getClass("UIApplication"), sel_registerName("sharedApplication"));+ return application && VirtualMacVMIsActive(application);+}++static BOOL VZShouldEnableSystemGesture(id self, SEL selector,+ unsigned long long type)+{+ if (VZSharedApplicationIsTarget() &&+ VZSettingEnabled(@"SystemGestureSuppression")) {+ static unsigned long count;+ if (count++ < 12)+ Log("suppressed an iPadOS system gesture for frontmost Virtual Mac");+ return NO;+ }+ IMP original = selector == sel_registerName("_shouldEnableSystemGestureWithType:")+ ? gOriginalShouldEnableSystemGesturePrivate+ : gOriginalShouldEnableSystemGesture;+ return ((BOOL (*)(id, SEL, unsigned long long))original)(+ self, selector, type);+}++static BOOL VZFluidGestureShouldBegin(id self, SEL selector, id recognizer)+{+ if (VZSharedApplicationIsTarget() &&+ VZSettingEnabled(@"MultitaskingGestureSuppression")) {+ static unsigned long count;+ if (count++ < 12)+ Log("suppressed a fluid multitasking gesture for active VM display");+ return NO;+ }+ return ((BOOL (*)(id, SEL, id))gOriginalFluidGestureShouldBegin)(+ self, selector, recognizer);+}++static BOOL VZFluidGestureShouldReceiveTouch(id self, SEL selector,+ id recognizer, id touch)+{+ if (VZSharedApplicationIsTarget() &&+ VZSettingEnabled(@"MultitaskingGestureSuppression"))+ return NO;+ return ((BOOL (*)(id, SEL, id, id))+ gOriginalFluidGestureShouldReceiveTouch)(+ self, selector, recognizer, touch);+}++static id VZKeyCommands(id self, SEL selector)+{+ if (VirtualMacVMIsActive(self) &&+ VZSettingEnabled(@"KeyboardShortcutCapture")) {+ static unsigned long count;+ if (count++ < 8)+ Log("suppressed SpringBoard key commands for Virtual Mac");+ // Returning no system-shell UIKeyCommands lets the foreground app's+ // pressesBegan:/pressesEnded: path receive Command-Q, Command-Space,+ // Command-Tab, screenshot chords, and the other Mac guest shortcuts.+ return @[];+ }+ return ((id (*)(id, SEL))gOriginalKeyCommands)(self, selector);+}++static id VZApplicationKeyCommands(id self, SEL selector)+{+ if (VirtualMacVMIsActive(self) &&+ VZSettingEnabled(@"KeyboardShortcutCapture")) {+ static unsigned long count;+ if (count++ < 8)+ Log("suppressed UIApplication system-shell key commands for Virtual Mac");+ // SpringBoard's implementation calls this superclass method, but+ // UIKit can also query the UISystemShellApplication/UIApplication+ // layer directly. Command-Space is registered in that superclass+ // path on iPadOS 16, unlike Command-Q and the screenshot commands+ // that SpringBoard itself contributes.+ return @[];+ }+ return ((id (*)(id, SEL))gOriginalApplicationKeyCommands)(self, selector);+}++static void VZPostCommandShortcut(int64_t usage, BOOL pressed)+{+ NSString *shortcut = usage == 0x2c ? @"command-space"+ : usage == 0x2b ? @"command-tab" : @"command-grave";+ NSString *name = [NSString stringWithFormat:+ @"com.mac.virtual.%@.%@", shortcut,+ pressed ? @"down" : @"up"];+ CFNotificationCenterPostNotification(+ CFNotificationCenterGetDarwinNotifyCenter(),+ (CFStringRef)name, NULL, NULL, YES);+ Log(pressed ? "relayed consumed Command shortcut down to Virtual Mac"+ : "relayed consumed Command shortcut up to Virtual Mac");+}++static void VZHandleKeyHIDEvent(id self, SEL selector, CFTypeRef event)+{+ static VZIOHIDEventGetIntegerValue getIntegerValue;+ if (!getIntegerValue) {+ getIntegerValue = (VZIOHIDEventGetIntegerValue)dlsym(+ RTLD_DEFAULT, "IOHIDEventGetIntegerValue");+ }++ if (getIntegerValue && VirtualMacVMIsActive(self) &&+ VZSettingEnabled(@"KeyboardShortcutCapture")) {+ int64_t usagePage = getIntegerValue(+ event, VZHIDKeyboardUsagePageField);+ int64_t usage = getIntegerValue(event, VZHIDKeyboardUsageField);+ BOOL pressed = getIntegerValue(event, VZHIDKeyboardDownField) != 0;+ if (usagePage == 0x07 && (usage == 0xe3 || usage == 0xe7)) {+ gCommandIsDown = pressed;+ } else if (usagePage == 0x07 &&+ (usage == 0x2c || usage == 0x2b || usage == 0x35)) {+ uint64_t bit = 1ULL << (usage & 63);+ if (gCommandIsDown || (gRelayingShortcutUsages & bit)) {+ // These three shell shortcuts are consumed below UIKit on+ // iPadOS. Relay only the non-modifier key; the physical+ // Command key already reaches the foreground VM app.+ if (pressed)+ gRelayingShortcutUsages |= bit;+ else+ gRelayingShortcutUsages &= ~bit;+ VZPostCommandShortcut(usage, pressed);+ return;+ }+ }+ }++ ((void (*)(id, SEL, CFTypeRef))gOriginalHandleKeyHIDEvent)(+ self, selector, event);+}++static void VZScheduleOneShotOpen(void)+{+ if (access(gOpenAfterRespring, F_OK) != 0)+ return;+ Log("scheduled one-shot unlock and Virtual Mac launch");+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC),+ dispatch_get_main_queue(), ^{+ // sbreload can briefly start more than one SpringBoard process. Leave+ // the sentinel present until a process survives the delay, then let+ // exactly one winner consume it.+ if (unlink(gOpenAfterRespring) != 0)+ return;+ Class managerClass = objc_getClass("SBLockScreenManager");+ id manager = ((id (*)(id, SEL))objc_msgSend)(+ managerClass, sel_registerName("sharedInstance"));+ BOOL locked = manager && ((BOOL (*)(id, SEL))objc_msgSend)(+ manager, sel_registerName("isUILocked"));+ BOOL unlocked = YES;+ if (locked) {+ unlocked = ((BOOL (*)(id, SEL, int, id))objc_msgSend)(+ manager, sel_registerName("unlockUIFromSource:withOptions:"),+ 17, nil);+ }++ id springBoard = ((id (*)(id, SEL))objc_msgSend)(+ objc_getClass("UIApplication"),+ sel_registerName("sharedApplication"));+ BOOL launched = ((BOOL (*)(id, SEL, id, BOOL))objc_msgSend)(+ springBoard,+ sel_registerName("launchApplicationWithIdentifier:suspended:"),+ [NSString stringWithUTF8String:gTargetBundleID], NO);+ char message[160];+ snprintf(message, sizeof(message),+ "one-shot open locked=%d unlocked=%d launched=%d",+ locked, unlocked, launched);+ Log(message);+ });+}++__attribute__((constructor))+static void VZInstallKeyboardPassthrough(void)+{+ VZReloadSettings();+ CFNotificationCenterAddObserver(+ CFNotificationCenterGetDarwinNotifyCenter(), NULL,+ VZSettingsChanged, CFSTR("com.mac.virtual.settings-changed"),+ NULL, CFNotificationSuspensionBehaviorDeliverImmediately);+ Class springBoard = objc_getClass("SpringBoard");+ VZScheduleOneShotOpen();+ Method method = class_getInstanceMethod(+ springBoard, sel_registerName("keyCommands"));+ if (!method) {+ Log("SpringBoard keyCommands method unavailable");+ return;+ }+ gOriginalKeyCommands = method_setImplementation(+ method, (IMP)VZKeyCommands);++ Method hidMethod = class_getInstanceMethod(+ springBoard, sel_registerName("handleKeyHIDEvent:"));+ if (hidMethod) {+ gOriginalHandleKeyHIDEvent = method_setImplementation(+ hidMethod, (IMP)VZHandleKeyHIDEvent);+ Log("installed raw HID Command-Space relay");+ } else {+ Log("SpringBoard handleKeyHIDEvent: unavailable");+ }++ Class application = objc_getClass("UIApplication");+ Method applicationMethod = class_getInstanceMethod(+ application, sel_registerName("keyCommands"));+ if (applicationMethod) {+ gOriginalApplicationKeyCommands = method_setImplementation(+ applicationMethod, (IMP)VZApplicationKeyCommands);+ Log("installed Virtual Mac SpringBoard and UIApplication key-command passthrough");+ } else {+ Log("UIApplication keyCommands method unavailable");+ Log("installed Virtual Mac SpringBoard key-command passthrough");+ }+++ Class gestureManager = objc_getClass("SBSystemGestureManager");+ Method gestureMethod = class_getInstanceMethod(+ gestureManager, sel_registerName("shouldEnableSystemGestureWithType:"));+ if (gestureMethod) {+ gOriginalShouldEnableSystemGesture = method_setImplementation(+ gestureMethod, (IMP)VZShouldEnableSystemGesture);+ }+ Method privateGestureMethod = class_getInstanceMethod(+ gestureManager, sel_registerName("_shouldEnableSystemGestureWithType:"));+ if (privateGestureMethod) {+ gOriginalShouldEnableSystemGesturePrivate = method_setImplementation(+ privateGestureMethod, (IMP)VZShouldEnableSystemGesture);+ }+ Log("installed frontmost-only iPadOS system-gesture suppression");++ Class fluidManager = objc_getClass("SBFluidSwitcherGestureManager");+ Method fluidBeginMethod = class_getInstanceMethod(+ fluidManager, sel_registerName("gestureRecognizerShouldBegin:"));+ if (fluidBeginMethod)+ gOriginalFluidGestureShouldBegin = method_setImplementation(+ fluidBeginMethod, (IMP)VZFluidGestureShouldBegin);+ Method fluidTouchMethod = class_getInstanceMethod(+ fluidManager,+ sel_registerName("gestureRecognizer:shouldReceiveTouch:"));+ if (fluidTouchMethod)+ gOriginalFluidGestureShouldReceiveTouch = method_setImplementation(+ fluidTouchMethod, (IMP)VZFluidGestureShouldReceiveTouch);+ Log("installed active-VM fluid multitasking-gesture suppression");++}diff --git a/VirtualMac/vz/tweak/VZKeyboardPassthrough.plist b/VirtualMac/vz/tweak/VZKeyboardPassthrough.plistnew file mode 100644index 0000000..2367728--- /dev/null+++ b/VirtualMac/vz/tweak/VZKeyboardPassthrough.plist@@ -0,0 +1,5 @@+{+ Filter = {+ Bundles = ("com.apple.springboard");+ };+}diff --git a/VirtualMac/vz/uncache.py b/VirtualMac/vz/uncache.pynew file mode 100644index 0000000..c285027--- /dev/null+++ b/VirtualMac/vz/uncache.py@@ -0,0 +1,1669 @@+#!/usr/bin/env python3+"""uncache: regenerate loadable arm64e LC_DYLD_CHAINED_FIXUPS for a cache image.++Takes DyldExtractor's (RE-only) output and makes it loadable:+ - collect the image's own slide-info-v3 fixups (location-filtered)+ - classify rebase (in-image) vs bind (cross-image); resolve binds via `ipsw dyld a2s`+ - emit DYLD_CHAINED_PTR_ARM64E_USERLAND chains (auth-preserving), weave into __DATA*+ - add LC_DYLD_CHAINED_FIXUPS, clear MH_DYLIB_IN_CACHE+Validate with `dyld_info -fixups`, then stamp iOS + sign.++Usage: uncache.py <main-cache> <image-substr> <dyldextractor-output> <final-output>+"""+import sys, struct, logging, subprocess, re, os+import progressbar+from DyldExtractor.extraction_context import ExtractionContext+from DyldExtractor.macho.macho_context import MachOContext+from DyldExtractor.dyld.dyld_context import DyldContext+from DyldExtractor.dyld.dyld_structs import dyld_cache_slide_pointer3+from DyldExtractor.macho.macho_structs import mach_header_64+from DyldExtractor.converter import slide_info++LC_SEGMENT_64, LC_LOAD_DYLIB = 0x19, 0xC+LC_SYMTAB, LC_DYSYMTAB = 0x2, 0xB+LC_FUNCTION_STARTS, LC_DATA_IN_CODE = 0x26, 0x29+LC_DYLD_CHAINED_FIXUPS = 0x80000034+LC_DYLD_EXPORTS_TRIE = 0x80000033+MH_DYLIB_IN_CACHE = 0x80000000+PF_ARM64E_USERLAND = 9+START_NONE = 0xFFFF+PAGE = 0x4000++DSC = None # set in main+++IPSW = os.environ.get("VZ_IPSW", "ipsw") # path to ipsw binary (VZ_IPSW for the rebuilt batch one)+++def a2s_batch(targets):+ """Resolve many unslid addresses -> {addr: (symbol, image)} in ONE ipsw call+ (DSC + a2s cache opened once). Uses the rebuilt `ipsw dyld a2sb`."""+ if not targets:+ return {}+ import tempfile+ tf = tempfile.NamedTemporaryFile("w", delete=False, suffix=".addrs")+ for t in targets:+ tf.write(hex(t) + "\n")+ tf.close()+ out = subprocess.run([IPSW, "--no-color", "dyld", "a2sb", "--cache", DSC + ".a2s", DSC, tf.name],+ capture_output=True, text=True).stdout+ out = re.sub(r"\x1b\[[0-9;]*m", "", out)+ os.unlink(tf.name)+ m = {}+ for line in out.splitlines():+ p = line.split("\t")+ if len(p) >= 2 and p[0].startswith("0x"):+ m[int(p[0], 16)] = (p[1] or None, p[2] if len(p) > 2 else None)+ return m+++def build_local_str_va(buf):+ """{cstring_bytes: vmaddr} for every CstringLiterals section in buf (selectors,+ class names, method types, __cstring). Used to localize objc selref pointers that+ the cache uniqued into libobjc's shared __OBJC_RO pool."""+ smap = {}+ ncmds = struct.unpack_from("<I", buf, 16)[0]+ off = 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ nsects = struct.unpack_from("<I", buf, off+64)[0]+ so = off + 72+ for _ in range(nsects):+ addr, size = struct.unpack_from("<QQ", buf, so+32)+ foff = struct.unpack_from("<I", buf, so+48)[0]+ flags = struct.unpack_from("<I", buf, so+64)[0]+ if (flags & 0xff) == 0x2 and size: # S_CSTRING_LITERALS+ blob = bytes(buf[foff:foff+size])+ p = 0+ while p < len(blob):+ e = blob.find(b"\x00", p)+ if e < 0: break+ s = blob[p:e]+ if s and s not in smap: smap[s] = addr + p+ p = e + 1+ so += 80+ off += sz+ return smap+++def read_cache_cstrs(dsc, targets):+ """{target_addr: cstring_bytes} read from the cache (reopens it; handles subcaches)."""+ import pathlib+ out = {}+ with open(dsc, "rb") as f:+ dc = DyldContext(f)+ subs = dc.addSubCaches(pathlib.Path(dsc))+ try:+ for t in targets:+ try:+ o, ctx = dc.convertAddr(t)+ out[t] = bytes(ctx.getBytes(o, 256)).split(b"\x00")[0]+ except Exception:+ out[t] = None+ finally:+ for sf in subs:+ sf.close()+ return out+++# ---- arm64e USERLAND chain-entry packers (64-bit little-endian) ----+def pack_rebase(runtimeOffset, nxt, high8=0):+ return (runtimeOffset & ((1 << 43) - 1)) | ((high8 & 0xFF) << 43) | ((nxt & 0x7FF) << 51) | (0 << 62) | (0 << 63)+def pack_auth_rebase(runtimeOffset, div, addrDiv, key, nxt):+ return ((runtimeOffset & 0xFFFFFFFF) | ((div & 0xFFFF) << 32) | ((addrDiv & 1) << 48)+ | ((key & 3) << 49) | ((nxt & 0x7FF) << 51) | (0 << 62) | (1 << 63))+def pack_bind(ordinal, addend, nxt):+ return ((ordinal & 0xFFFF) | (0 << 16) | ((addend & 0x7FFFF) << 32)+ | ((nxt & 0x7FF) << 51) | (1 << 62) | (0 << 63))+def pack_auth_bind(ordinal, div, addrDiv, key, nxt):+ return ((ordinal & 0xFFFF) | (0 << 16) | ((div & 0xFFFF) << 32) | ((addrDiv & 1) << 48)+ | ((key & 3) << 49) | ((nxt & 0x7FF) << 51) | (1 << 62) | (1 << 63))+++def rewrite_dylib_paths(buf):+ """Rewrite macOS framework dylib paths to iOS-flat form (strip Versions/X/).+ e.g. .../CoreFoundation.framework/Versions/A/CoreFoundation -> .../CoreFoundation.framework/CoreFoundation"""+ import re as _re+ ncmds = struct.unpack_from("<I", buf, 16)[0]; off = 32+ DYLIB_CMDS = {0xC, 0xD, 0x80000018, 0x8000001F, 0x80000023} # LOAD/ID/WEAK/REEXPORT/UPWARD+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd in DYLIB_CMDS:+ noff = struct.unpack_from("<I", buf, off+8)[0]+ old = buf[off+noff:off+sz].split(b"\0")[0]+ new = _re.sub(rb"(\.framework/)Versions/[^/]+/", rb"\1", old)+ if new != old:+ region = sz - noff+ buf[off+noff:off+sz] = new + b"\0"*(region-len(new))+ off += sz+ return buf+++def weaken_absent_dylibs(buf, markers):+ """Demote LC_LOAD_DYLIB -> LC_LOAD_WEAK_DYLIB for deps whose path matches any marker.+ Used for frameworks absent on iOS (e.g. MetalSerializer, vmnet) that we import NO+ symbols from: a missing weak dylib is fine, so dyld won't fail the load."""+ LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB = 0xC, 0x80000018 # 0x8000001F is REEXPORT, not weak!+ ncmds = struct.unpack_from("<I", buf, 16)[0]; off = 32+ weakened = []+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_LOAD_DYLIB:+ noff = struct.unpack_from("<I", buf, off+8)[0]+ path = buf[off+noff:off+sz].split(b"\0")[0].decode("utf-8", "replace")+ if any(m in path for m in markers):+ struct.pack_into("<I", buf, off, LC_LOAD_WEAK_DYLIB)+ weakened.append(path)+ off += sz+ if weakened:+ print(f"weakened {len(weakened)} iOS-absent dep(s): {[p.split('/')[-1] for p in weakened]}")+ return buf+++def reorder_segments(buf):+ """dyld requires LC_SEGMENT_64 in ascending vmaddr order. Reorder the segment+ load commands (same total size) without moving segment file content."""+ ncmds, scmds = struct.unpack_from("<II", buf, 16)+ lcs, off = [], 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ lcs.append((cmd, bytes(buf[off:off+sz])))+ off += sz+ seg_blobs = [b for c, b in lcs if c == LC_SEGMENT_64]+ seg_blobs.sort(key=lambda b: struct.unpack_from("<Q", b, 24)[0]) # by vmaddr+ out, k = bytearray(), 0+ for c, b in lcs:+ if c == LC_SEGMENT_64:+ out += seg_blobs[k]; k += 1+ else:+ out += b+ buf[32:32+len(out)] = out+ return buf+++def relayout(buf):+ """Repack file so segment fileoffs are monotonic in vmaddr order (dyld requires+ it). Moves segment content, patches seg.fileoff + section offsets + LINKEDIT-+ internal LC offsets. Assumes segment LCs already vmaddr-sorted (reorder_segments)."""+ ncmds, scmds = struct.unpack_from("<II", buf, 16)+ segs, off = [], 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ name = buf[off+8:off+24].split(b"\0")[0].decode()+ _, _, fo, fs = struct.unpack_from("<QQQQ", buf, off+24)+ nsects = struct.unpack_from("<I", buf, off+64)[0]+ segs.append((off, name, fo, fs, nsects))+ off += sz+ place, cur = [], 0+ for i, (lc, nm, fo, fs, ns) in enumerate(segs):+ nf = 0 if i == 0 else ((cur + 0x3FFF) & ~0x3FFF)+ place.append(nf); cur = nf + fs+ new = bytearray(cur)+ ld = 0+ for (lc, nm, fo, fs, ns), nf in zip(segs, place):+ new[nf:nf+fs] = buf[fo:fo+fs]+ for (lc, nm, fo, fs, ns), nf in zip(segs, place):+ delta = nf - fo+ struct.pack_into("<Q", new, lc+40, nf) # seg.fileoff+ for k in range(ns):+ fld = lc+72+k*80+48 # section_64.offset+ o = struct.unpack_from("<I", new, fld)[0]+ if o: struct.pack_into("<I", new, fld, o+delta)+ if nm == "__LINKEDIT":+ ld = delta+ # patch LINKEDIT-internal file offsets in LCs (all live in __TEXT header @0)+ off = 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", new, off)+ if cmd == LC_SYMTAB:+ for fo_field in (8, 16):+ v = struct.unpack_from("<I", new, off+fo_field)[0]+ if v: struct.pack_into("<I", new, off+fo_field, v+ld)+ elif cmd == LC_DYSYMTAB:+ for fo_field in (32, 40, 48, 56, 64, 72): # toc/modtab/extref/indirect/extrel/locrel+ v = struct.unpack_from("<I", new, off+fo_field)[0]+ if v: struct.pack_into("<I", new, off+fo_field, v+ld)+ elif cmd in (LC_DYLD_EXPORTS_TRIE, LC_FUNCTION_STARTS, LC_DATA_IN_CODE):+ v = struct.unpack_from("<I", new, off+8)[0]+ if v: struct.pack_into("<I", new, off+8, v+ld)+ off += sz+ return new+++def relayout_pad(buf):+ """PAD mode: lay each segment at fileoff = vmaddr - base (file mirrors vm).+ Preserves vmaddrs so code/ADRP refs are untouched. Produces a huge (sparse-+ ish) file but satisfies dyld's hasSwiftOrObjC (content=addr+slide). Proof only."""+ ncmds, scmds = struct.unpack_from("<II", buf, 16)+ segs, off = [], 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ nm = buf[off+8:off+24].split(b"\0")[0].decode()+ va, vs, fo, fs = struct.unpack_from("<QQQQ", buf, off+24)+ ns = struct.unpack_from("<I", buf, off+64)[0]+ segs.append((off, nm, va, vs, fo, fs, ns))+ off += sz+ base = min(s[2] for s in segs)+ total = max(s[2]+s[5] for s in segs) - base # by filesize+ new = bytearray(total)+ ld = 0+ for lc, nm, va, vs, fo, fs, ns in segs:+ new[va-base:va-base+fs] = buf[fo:fo+fs] # content at vmaddr-base (left-pad precedes)+ for lc, nm, va, vs, fo, fs, ns in segs:+ av = va & ~0x3FFF; pad = va - av # page-align vmaddr down, left-pad+ struct.pack_into("<Q", new, lc+24, av) # seg.vmaddr -> aligned+ struct.pack_into("<Q", new, lc+32, vs+pad) # seg.vmsize += pad+ struct.pack_into("<Q", new, lc+40, av-base) # seg.fileoff -> aligned-base (page-aligned)+ struct.pack_into("<Q", new, lc+48, fs+pad) # seg.filesize += pad+ for k in range(ns):+ so = lc+72+k*80+ saddr = struct.unpack_from("<Q", new, so+32)[0]+ if struct.unpack_from("<I", new, so+48)[0]:+ struct.pack_into("<I", new, so+48, saddr-base) # sect.offset = addr-base+ if nm == "__LINKEDIT": ld = (va-base) - fo+ off = 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", new, off)+ if cmd == LC_SYMTAB:+ for f in (8, 16):+ v = struct.unpack_from("<I", new, off+f)[0]+ if v: struct.pack_into("<I", new, off+f, v+ld)+ elif cmd == LC_DYSYMTAB:+ for f in (32, 40, 48, 56, 64, 72):+ v = struct.unpack_from("<I", new, off+f)[0]+ if v: struct.pack_into("<I", new, off+f, v+ld)+ elif cmd in (LC_DYLD_EXPORTS_TRIE, LC_FUNCTION_STARTS, LC_DATA_IN_CODE):+ v = struct.unpack_from("<I", new, off+8)[0]+ if v: struct.pack_into("<I", new, off+8, v+ld)+ off += sz+ return new+++def _find_section(buf, lc, ns, segname_unused, sectname):+ """Return (sect_lc_off, addr, size) of sectname within the segment at load-command lc."""+ for k in range(ns):+ so = lc+72+k*80+ if buf[so:so+16].split(b"\0")[0] == sectname:+ sa, ssz = struct.unpack_from("<QQ", buf, so+32)+ return so, sa, ssz+ return None, 0, 0+++def _section_segment(buf, sectname):+ """Return the name of the segment containing section `sectname` (bytes), or None."""+ ncmds = struct.unpack_from("<I", buf, 16)[0]; off = 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ ns = struct.unpack_from("<I", buf, off+64)[0]+ for k in range(ns):+ so = off+72+k*80+ if buf[so:so+16].split(b"\0")[0] == sectname:+ return buf[off+8:off+24].split(b"\0")[0].decode()+ off += sz+ return None+++def relayout_compact(buf, newbase=0x100000000, insert=None):+ """COMPACT: relocate segments to small 16KB-page-aligned slots (fileoffset==+ vmaddr-newbase, the mach header stays at file 0). Cache segments are >=4KB-aligned+ so each segment delta is a 4KB-multiple, which preserves ADD immediates (12-bit);+ only ADRP page bits need rewriting. Returns (new_buf, deltas=[(lo,hi,delta)]).++ insert=(seg_name, sect_name, nbytes): grow that segment by `shift` (nbytes rounded to+ 16KB) and open a `shift`-byte gap right after sect_name's content, extending sect_name's+ size by nbytes (used to append objc selref-slot pool into __objc_selrefs so objc uniques+ them). The gap shifts the rest of that segment; its delta is split into two ranges.+ Returns (new_buf, deltas, pool_va) -- pool_va is the new vmaddr of the gap start."""+ ncmds, scmds = struct.unpack_from("<II", buf, 16)+ segs, off = [], 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ nm = buf[off+8:off+24].split(b"\0")[0].decode()+ va, vs, fo, fs = struct.unpack_from("<QQQQ", buf, off+24)+ ns = struct.unpack_from("<I", buf, off+64)[0]+ segs.append([off, nm, va, vs, fo, fs, ns])+ off += sz+ if insert:+ ins_seg, ins_sect, ins_n = insert[0], insert[1], insert[2]+ ins_grow = insert[3] if len(insert) > 3 else ins_n # how much to extend the section+ else:+ ins_seg = ins_sect = None; ins_n = ins_grow = 0+ shift = ((ins_n + 0x3FFF) & ~0x3FFF) if insert else 0 # gap holds selref pool + GOT pool+ # pack each segment into a 16KB-aligned slot (no left-pad: header must stay at file 0)+ deltas = []; cur = newbase; place = []; pool_va = None+ for lc, nm, va, vs, fo, fs, ns in segs:+ nf = cur+ place.append(nf)+ if nm == ins_seg:+ _, sa_sr, sz_sr = _find_section(buf, lc, ns, nm, ins_sect.encode())+ split_va = sa_sr + sz_sr # gap opens right after the section+ deltas.append((va, split_va, nf - va))+ deltas.append((split_va, va + max(vs, fs), nf - va + shift))+ pool_va = split_va + (nf - va) # new vmaddr of the gap (pool) start+ cur = nf + ((max(vs, fs) + shift + 0x3FFF) & ~0x3FFF)+ else:+ deltas.append((va, va + max(vs, fs), nf - va))+ cur = nf + ((max(vs, fs) + 0x3FFF) & ~0x3FFF)+ new = bytearray(cur - newbase)+ for (lc, nm, va, vs, fo, fs, ns), nf in zip(segs, place):+ if nm == ins_seg:+ _, sa_sr, sz_sr = _find_section(buf, lc, ns, nm, ins_sect.encode())+ soff = (sa_sr + sz_sr) - va # split offset within the segment+ new[nf-newbase:nf-newbase+soff] = buf[fo:fo+soff]+ new[nf-newbase+soff+shift:nf-newbase+fs+shift] = buf[fo+soff:fo+fs]+ else:+ new[nf-newbase:nf-newbase+fs] = buf[fo:fo+fs]+ ld = 0+ for (lc, nm, va, vs, fo, fs, ns), nf in zip(segs, place):+ delta = nf - va+ extra = shift if nm == ins_seg else 0+ split_va = (struct.unpack_from("<Q", buf, _find_section(buf, lc, ns, nm, ins_sect.encode())[0]+32)[0]+ + _find_section(buf, lc, ns, nm, ins_sect.encode())[2]) if nm == ins_seg else None+ struct.pack_into("<Q", new, lc+24, nf) # vmaddr (16KB-aligned)+ struct.pack_into("<Q", new, lc+32, (vs+extra+0x3FFF) & ~0x3FFF) # vmsize+ struct.pack_into("<Q", new, lc+40, nf-newbase) # fileoff+ fsz = fs+extra if nm == "__LINKEDIT" else ((fs+extra+0x3FFF) & ~0x3FFF)+ struct.pack_into("<Q", new, lc+48, fsz) # filesize+ for k in range(ns):+ so = lc+72+k*80+ sa = struct.unpack_from("<Q", new, so+32)[0]+ if sa == 0: # zerofill / no-address section: nothing to relocate+ continue+ if not (va <= sa < va+vs): # real section out of range would be a bug -> surface it+ print(f" WARN: section addr {sa:#x} outside {nm} [{va:#x},{va+vs:#x}] (relocating anyway)")+ sd = delta + (shift if (split_va is not None and sa >= split_va) else 0)+ struct.pack_into("<Q", new, so+32, sa+sd) # sect.addr += (split-aware) delta+ if struct.unpack_from("<I", new, so+48)[0]:+ struct.pack_into("<I", new, so+48, (sa+sd)-newbase) # sect.offset = addr-base+ if nm == ins_seg and buf[so:so+16].split(b"\0")[0] == ins_sect.encode():+ struct.pack_into("<Q", new, so+40, sz_sr + ins_grow) # extend section over selref pool only+ if nm == "__LINKEDIT": ld = (nf-newbase) - fo+ off = 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", new, off)+ if cmd == LC_SYMTAB:+ for f in (8, 16):+ v = struct.unpack_from("<I", new, off+f)[0]+ if v: struct.pack_into("<I", new, off+f, v+ld)+ elif cmd == LC_DYSYMTAB:+ for f in (32, 40, 48, 56, 64, 72):+ v = struct.unpack_from("<I", new, off+f)[0]+ if v: struct.pack_into("<I", new, off+f, v+ld)+ elif cmd in (LC_DYLD_EXPORTS_TRIE, LC_FUNCTION_STARTS, LC_DATA_IN_CODE):+ v = struct.unpack_from("<I", new, off+8)[0]+ if v: struct.pack_into("<I", new, off+8, v+ld)+ off += sz+ return (new, deltas, pool_va) if insert else (new, deltas)+++def collect_got_refs(buf, dsc):+ """Scan __text + __objc_stubs for ADRP+consumer references whose target is OUT of the+ extracted image. The cache uniqued the image's GOT into a shared GOT (out of image): system+ data globals (__stack_chk_guard, __NSConcrete*Block, CF allocators...) accessed via a plain+ LDR of the slot, and function pointers (objc_msgSend in __objc_stubs) accessed via an ADD to+ the slot address then ldr+braa. rewrite_adrp can't relocate those. Resolve each via a2s and+ return {old_target_addr: (symbol, is_auth)} -- is_auth (ADD consumer -> braa) means the slot+ holds a signed fn ptr (auth bind); plain LDR means a data pointer (plain bind)."""+ import capstone+ osegs, _, _ = parse_segments(buf)+ inimg = lambda a: any(va <= a < va+vs for nm, va, vs, fo, fs, lc in osegs)+ t = next(s for s in osegs if s[0] == "__TEXT")+ nsects = struct.unpack_from("<I", buf, t[5]+64)[0]+ md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM); md.detail = True+ targets = {} # old_target -> is_auth+ for k in range(nsects):+ so = t[5]+72+k*80+ if buf[so:so+16].split(b"\0")[0] not in (b"__text", b"__objc_stubs"): continue+ sa, ssz = struct.unpack_from("<QQ", buf, so+32)+ soff = struct.unpack_from("<I", buf, so+48)[0]+ regs = {}; pos = 0+ while pos < ssz:+ adv = pos+ for ins in md.disasm(bytes(buf[soff+pos:soff+ssz]), sa+pos):+ adv = (ins.address - sa) + ins.size; m, ops = ins.mnemonic, ins.operands+ if m == "adrp" and len(ops) == 2:+ regs[ops[0].reg] = [ops[1].imm, False]+ elif ops:+ base = disp = None; is_add = (m == "add")+ if is_add and len(ops) == 3 and ops[2].type == capstone.CS_OP_IMM:+ base, disp = ops[1].reg, ops[2].imm+ else:+ for op in ops:+ if op.type == capstone.CS_OP_MEM:+ base, disp = op.mem.base, op.mem.disp; break+ if base in regs and not regs[base][1]:+ tt = regs[base][0] + (disp or 0)+ if not inimg(tt): targets[tt] = is_add # ADD-to-slot => auth (braa)+ regs[base][1] = True+ pos = adv+4 if adv == pos else adv+ if not targets: return {}+ sm = a2s_batch(list(targets))+ out = {}+ for a, is_auth in targets.items():+ nm = sm.get(a, (None,))[0]+ if nm and nm.startswith("_ptr."): nm = nm[5:]+ if nm: out[a] = (nm, is_auth)+ return out+++def _find_sect(buf, name):+ osegs, _, _ = parse_segments(buf)+ for nm, va, vs, fo, fs, lc in osegs:+ for k in range(struct.unpack_from("<I", buf, lc+64)[0]):+ so = lc+72+k*80+ if buf[so:so+16].split(b"\0")[0] == name:+ sa, sz = struct.unpack_from("<QQ", buf, so+32)+ return sa, sz, struct.unpack_from("<I", buf, so+48)[0]+ return None+++def collect_unwind_personalities(buf, dsc):+ """__unwind_info's personality array references the C++/objc personality routine via a GOT+ slot (a 32-bit offset relative to the image's mach header). The cache uniqued that GOT out+ of the image, so the offset points out-of-image -> libunwind reads garbage when unwinding an+ exception through our frames. Return the ORDERED personality symbols so they can be bound in+ the GOT pool and the offsets repointed."""+ osegs, _, _ = parse_segments(buf)+ base = next(va for nm, va, vs, fo, fs, lc in osegs if nm == "__TEXT")+ s = _find_sect(buf, b"__unwind_info")+ if not s: return []+ sa, sz, fo = s+ pao, pac = struct.unpack_from("<II", buf, fo+12) # personalityArraySectionOffset, count+ targets = [base + struct.unpack_from("<I", buf, fo+pao+i*4)[0] for i in range(pac)]+ if not targets: return []+ sm = a2s_batch(targets); out = []+ for t in targets:+ nm = sm.get(t, (None,))[0]+ if nm and nm.startswith("_ptr."): nm = nm[5:]+ out.append(nm)+ return out+++def rewrite_unwind_personalities(buf, syms, got_slot, nbase):+ s = _find_sect(buf, b"__unwind_info")+ if not s: return 0+ sa, sz, fo = s+ pao, pac = struct.unpack_from("<II", buf, fo+12)+ n = 0+ for i, sym in enumerate(syms):+ if i < pac and sym and sym in got_slot:+ struct.pack_into("<I", buf, fo+pao+i*4, got_slot[sym] - nbase) # -> in-image GOT slot+ n += 1+ return n+++def _read_uleb(buf, offset):+ value = shift = 0+ while True:+ byte = buf[offset]+ offset += 1+ value |= (byte & 0x7f) << shift+ if not byte & 0x80:+ return value, offset+ shift += 7+++def _read_sleb(buf, offset):+ value = shift = 0+ while True:+ byte = buf[offset]+ offset += 1+ value |= (byte & 0x7f) << shift+ shift += 7+ if not byte & 0x80:+ if byte & 0x40:+ value -= 1 << shift+ return value, offset+++def _read_eh_value(buf, offset, encoding):+ form = encoding & 0x0f+ if form == 0x01:+ return _read_uleb(buf, offset)+ if form == 0x03:+ return struct.unpack_from("<I", buf, offset)[0], offset + 4+ if form == 0x04:+ return struct.unpack_from("<Q", buf, offset)[0], offset + 8+ if form == 0x09:+ return _read_sleb(buf, offset)+ if form == 0x0b:+ return struct.unpack_from("<i", buf, offset)[0], offset + 4+ if form == 0x0c:+ return struct.unpack_from("<q", buf, offset)[0], offset + 8+ raise ValueError(f"unsupported DW_EH_PE encoding {encoding:#x}")+++def collect_lsda_type_refs(buf, dsc):+ """Collect indirect PC-relative catch-type references in LSDA tables.++ dyld shared caches leave these signed offsets pointing at cache-uniqued GOT+ slots (usually ``_OBJC_EHTYPE_$_NSException``). Compact relayout moves the+ framework but a normal chained-fixup rebuild does not visit bytes inside+ ``__gcc_except_tab``. The stale offset only becomes visible when a native+ framework exception is thrown: libc++abi follows it out of the image and+ crashes while looking up the catch type.++ Return ``(field_va, old_target_va, symbol_or_none)`` for every type-table+ entry reached by an action record. External targets are resolved in one+ a2sb batch so the caller can allocate ordinary rebuilt GOT slots for them.+ """+ unwind = _find_sect(buf, b"__unwind_info")+ if not unwind:+ return []+ unwind_va, unwind_size, unwind_off = unwind+ if unwind_size < 28:+ return []++ osegs, _, _ = parse_segments(buf)+ image_base = min(va for _nm, va, _vs, _fo, _fs, _lc in osegs)++ def va_to_off(address):+ for _nm, va, _vs, fileoff, filesize, _lc in osegs:+ if va <= address < va + filesize:+ return fileoff + address - va+ raise ValueError(f"LSDA address outside file-backed image: {address:#x}")++ def off_to_va(offset):+ for _nm, va, _vs, fileoff, filesize, _lc in osegs:+ if fileoff <= offset < fileoff + filesize:+ return va + offset - fileoff+ raise ValueError(f"LSDA file offset outside image: {offset:#x}")++ (_version, _common_off, _common_count, _personality_off,+ _personality_count, index_off, index_count) = struct.unpack_from(+ "<7I", buf, unwind_off)+ indices = [+ struct.unpack_from("<III", buf, unwind_off + index_off + index * 12)+ for index in range(index_count)+ ]+ lsda_offsets = []+ for index in range(max(0, index_count - 1)):+ first = indices[index][2]+ limit = indices[index + 1][2]+ if not first or limit < first:+ continue+ for entry in range(first, limit, 8):+ _function_offset, lsda_offset = struct.unpack_from(+ "<II", buf, unwind_off + entry)+ if lsda_offset:+ lsda_offsets.append(lsda_offset)++ raw_refs = []+ for lsda_offset in sorted(set(lsda_offsets)):+ offset = va_to_off(image_base + lsda_offset)+ lpstart_encoding = buf[offset]+ offset += 1+ if lpstart_encoding != 0xff:+ _unused, offset = _read_eh_value(+ buf, offset, lpstart_encoding)++ type_encoding = buf[offset]+ offset += 1+ if type_encoding == 0xff:+ type_table_end = None+ else:+ type_table_delta, offset = _read_uleb(buf, offset)+ type_table_end = offset + type_table_delta++ call_site_encoding = buf[offset]+ offset += 1+ call_site_length, offset = _read_uleb(buf, offset)+ call_site_end = offset + call_site_length+ actions = []+ while offset < call_site_end:+ _start, offset = _read_eh_value(+ buf, offset, call_site_encoding)+ _length, offset = _read_eh_value(+ buf, offset, call_site_encoding)+ _landing_pad, offset = _read_eh_value(+ buf, offset, call_site_encoding)+ action, offset = _read_uleb(buf, offset)+ if action:+ actions.append(action)+ if offset != call_site_end or type_table_end is None:+ continue++ action_table = call_site_end+ max_type_index = 0+ pending = [action_table + action - 1 for action in actions]+ visited = set()+ while pending:+ action_entry = pending.pop()+ if action_entry in visited:+ continue+ visited.add(action_entry)+ type_filter, next_field = _read_sleb(buf, action_entry)+ next_offset, next_end = _read_sleb(buf, next_field)+ if type_filter > max_type_index:+ max_type_index = type_filter+ if next_offset:+ pending.append(next_field + next_offset)++ form = type_encoding & 0x0f+ width = {0x03: 4, 0x04: 8, 0x0b: 4, 0x0c: 8}.get(form)+ if max_type_index and (width is None or type_encoding & 0x70 != 0x10):+ raise ValueError(+ f"unsupported LSDA type encoding {type_encoding:#x} "+ f"at {image_base + lsda_offset:#x}")+ for type_index in range(1, max_type_index + 1):+ field_off = type_table_end - type_index * width+ if width == 4:+ relative = struct.unpack_from("<i", buf, field_off)[0]+ else:+ relative = struct.unpack_from("<q", buf, field_off)[0]+ field_va = off_to_va(field_off)+ raw_refs.append((field_va, field_va + relative, width))++ external_targets = sorted({+ target for _field, target, _width in raw_refs+ if not any(va <= target < va + vsize+ for _nm, va, vsize, _fo, _fs, _lc in osegs)+ })+ symbols = a2s_batch(external_targets)+ refs = []+ for field, target, width in raw_refs:+ symbol = symbols.get(target, (None, None))[0]+ if symbol and symbol.startswith("_ptr."):+ symbol = symbol[5:]+ if target in external_targets and not symbol:+ raise ValueError(+ f"unresolved external LSDA type target {target:#x}")+ refs.append((field, target, symbol, width))+ return refs+++def rewrite_lsda_type_refs(buf, refs, amap, got_slot, nbase):+ rewritten = 0+ for old_field, old_target, symbol, width in refs:+ new_field = amap(old_field)+ new_target = got_slot.get(symbol) if symbol else amap(old_target)+ if new_field is None or new_target is None:+ raise ValueError(+ f"cannot relocate LSDA type ref {old_field:#x} -> "+ f"{old_target:#x} ({symbol})")+ relative = new_target - new_field+ if width == 4 and not -(1 << 31) <= relative < (1 << 31):+ raise ValueError(f"LSDA sdata4 target is out of range: {relative}")+ struct.pack_into("<i" if width == 4 else "<q",+ buf, new_field - nbase, relative)+ rewritten += 1+ return rewritten+++def fix_export_trie(buf, amap, nbase, deltas):+ """DyldExtractor leaves the export trie's symbol offsets at the ORIGINAL cache/RE image+ offsets; uncache's compact relayout moves every segment, so those offsets now point at the+ wrong place. dyld resolves imports (and ld links) against the trie -> a flat/two-level lookup+ of e.g. `operator new` or `hv_vm_*` lands on a stale-offset address (a different in-image+ function) -> wrong call. Walk the trie and remap each export offset through amap (re-encoding+ the uleb to its ORIGINAL byte length so node/child offsets stay valid)."""+ re_base = next(lo for lo, hi, d in deltas if lo + d == nbase)+ ncmds = struct.unpack_from("<I", buf, 16)[0]; off = 32; trie_off = 0+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == 0x80000033: # LC_DYLD_EXPORTS_TRIE+ trie_off = struct.unpack_from("<I", buf, off+8)[0]+ off += sz+ if not trie_off: return 0+ def ruleb(p):+ r = s = 0+ while True:+ b = buf[p]; r |= (b & 0x7f) << s; p += 1; s += 7+ if not (b & 0x80): break+ return r, p+ def ulen(p):+ n = 1+ while buf[p] & 0x80: p += 1; n += 1+ return n+ def wpad(p, val, length): # re-encode val as a uleb of exactly `length` bytes+ for i in range(length):+ buf[p+i] = ((val >> (7*i)) & 0x7f) | (0x80 if i < length-1 else 0)+ def fixoff(p):+ L = ulen(p); old, _ = ruleb(p); na = amap(re_base + old)+ if na is not None: wpad(p, na - nbase, L); return 1+ return 0+ fixed = 0; stack = [trie_off]; seen = set()+ while stack:+ node = stack.pop()+ if node in seen: continue+ seen.add(node)+ tsize, p = ruleb(node)+ if tsize:+ flags, q = ruleb(p)+ if not (flags & 0x08) and (flags & 0x03) != 0x02: # not reexport, not absolute+ fixed += fixoff(q)+ if flags & 0x10: # stub-and-resolver: 2nd offset+ fixed += fixoff(q + ulen(q))+ p += tsize # children follow the terminal blob+ cc = buf[p]; cp = p + 1+ for _ in range(cc):+ while buf[cp]: cp += 1+ cp += 1+ child, cp = ruleb(cp)+ stack.append(trie_off + child)+ print(f"fix_export_trie: remapped {fixed} export offsets")+ return fixed+++def rewrite_adrp(buf, osegs, deltas, got_ref_slot=None):+ """Rewrite cross-segment ADRP page immediates in __TEXT after compact relocation.+ Follow register definitions through the control-flow graph so one ADRP can safely+ feed consumers on both sides of a branch. A linear scan loses the alternate-path+ state after the fall-through path reuses the register (Netrb's synchronous XPC+ connection load is one concrete example)."""+ import capstone+ def seg_delta_old(a):+ for lo, hi, d in deltas:+ if lo <= a < hi: return d+ return None+ def set_consumer_disp(foff, new_off): # rewrite the ldr/add low-12 byte offset+ w = struct.unpack_from("<I", buf, foff)[0]+ if (w & 0x7F800000) == 0x11000000: # ADD (immediate)+ w = (w & ~((1 << 22) | (0xFFF << 10))) | ((new_off & 0xFFF) << 10)+ elif (w & 0x3B000000) == 0x39000000: # LDR/STR (unsigned imm)+ scale = (w >> 30) & 3+ if new_off & ((1 << scale) - 1): return False # not scale-aligned+ w = (w & ~(0xFFF << 10)) | (((new_off >> scale) & 0xFFF) << 10)+ else:+ return False+ struct.pack_into("<I", buf, foff, w); return True+ t = next(s for s in osegs if s[0] == "__TEXT")+ tva, tlc = t[1], t[5]+ text_delta = next(d for lo, hi, d in deltas if lo + d == tva)+ trace_window = None+ if os.environ.get("VZ_DBG_ADRP_WINDOW"):+ trace_window = tuple(+ int(value, 0)+ for value in os.environ["VZ_DBG_ADRP_WINDOW"].split(":", 1)+ )+ if os.environ.get("VZ_DBG_ADRP"):+ print(" DELTAS:", [(hex(lo), hex(hi), hex(d)) for lo, hi, d in deltas])+ for probe in (0x216b4d000, 0x216b4ddd8, 0x216b4da00, 0x216b4d488):+ print(f" seg_delta_old({probe:#x}) = {seg_delta_old(probe)} -> {probe + (seg_delta_old(probe) or 0):#x}")+ md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)+ md.detail = True+ def _is_caller_saved(rid): # x0-x18 (incl. x16/x17 PAC scratch) clobbered by calls+ n = md.reg_name(rid) or ""+ return n[:1] == "x" and n[1:].isdigit() and int(n[1:]) <= 18+ def function_starts():+ dataoff = datasize = 0+ ncmds = struct.unpack_from("<I", buf, 16)[0]+ off = 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_FUNCTION_STARTS:+ dataoff, datasize = struct.unpack_from("<II", buf, off + 8)+ break+ off += sz+ starts = []+ if not dataoff or not datasize:+ return starts+ p, end, value = dataoff, dataoff + datasize, 0+ while p < end:+ delta = shift = 0+ while p < end:+ byte = buf[p]; p += 1+ delta |= (byte & 0x7f) << shift+ if not (byte & 0x80): break+ shift += 7+ if delta == 0: break+ value += delta+ starts.append(tva + value)+ return starts++ all_function_starts = function_starts()+ nsects = struct.unpack_from("<I", buf, tlc+64)[0]+ fixed_offsets = set(); scanned = 0+ for k in range(nsects):+ so = tlc + 72 + k*80+ sname = buf[so:so+16].split(b"\0")[0].decode()+ saddr, ssize = struct.unpack_from("<QQ", buf, so+32)+ soff = struct.unpack_from("<I", buf, so+48)[0]+ sflags = struct.unpack_from("<I", buf, so+64)[0]+ if sname == "__auth_stubs": continue # fix_auth_stubs owns these (needs the original cache imm)+ is_code = (sflags & 0x80000000) or (sflags & 0x400) or sname in ("__text", "__stubs")+ if os.environ.get("VZ_DBG_ADRP"):+ print(f" ADRP sect {sname:20} flags={sflags:#x} code={bool(is_code)} addr={saddr:#x} size={ssize:#x}")+ if not (is_code and soff and ssize):+ continue+ old_sa = saddr - text_delta # section's old addr+ sec_fixed0 = len(fixed_offsets)+ scanned += 1+ instructions = {}+ for pos in range(0, ssize - (ssize % 4), 4):+ decoded = list(md.disasm(+ bytes(buf[soff+pos:soff+pos+4]), old_sa+pos, count=1))+ instructions[pos] = decoded[0] if decoded else None++ incoming = {}; work = []+ def merge_state(pos, state):+ if pos not in instructions: return+ previous = incoming.get(pos)+ if previous is None:+ merged = dict(state)+ else:+ merged = {}+ for reg, previous_value in previous.items():+ current_value = state.get(reg)+ if current_value is None:+ continue+ previous_page, previous_defs = previous_value+ current_page, current_defs = current_value+ if previous_page != current_page:+ continue+ merged[reg] = (+ previous_page,+ tuple(sorted(+ set(previous_defs) | set(current_defs))))+ if previous is None or merged != previous:+ incoming[pos] = merged; work.append(pos)++ seeds = [a - saddr for a in all_function_starts+ if saddr <= a < saddr + ssize]+ if not seeds: seeds = [0]+ for seed in seeds: merge_state(seed, {})+ adrp_pages = {} # instruction fileoff -> rewritten page++ while True:+ if not work:+ # An indirect switch branch has no statically enumerable+ # successors, so case blocks are not necessarily reachable+ # from a function-start seed. Seed the first still-unreached+ # ADRP, drain that whole connected component, then repeat.+ # Seeding every ADRP up front is incorrect: its empty state+ # intersects with a legitimate incoming state and discards+ # callee-saved definitions that cross the ADRP (for example+ # libcrypto's OBJ_NAME_init x19 table pointer).+ seed = next((candidate for candidate, instruction+ in instructions.items()+ if candidate not in incoming and instruction and+ instruction.mnemonic == "adrp"), None)+ if seed is None:+ break+ merge_state(seed, {})+ continue+ pos = work.pop()+ state = dict(incoming[pos])+ ins = instructions[pos]+ word = struct.unpack_from("<I", buf, soff + pos)[0]+ trace = (trace_window is not None and+ trace_window[0] <= saddr + pos - tva < trace_window[1])+ if trace:+ rendered = ins.op_str if ins else f"{word:#x}"+ print(f" TRACE {saddr + pos - tva:#x} "+ f"{ins.mnemonic if ins else '<undecoded>'} "+ f"{rendered} state={state}")+ successors = [pos + 4]+ if ins is None:+ if word in (0xD65F0BFF, 0xD65F0FFF): # retab/retaa+ successors = []+ elif (word & 0xFF000000) == 0xD7000000: # authenticated branch/call+ for reg in [r for r in state if _is_caller_saved(r)]:+ del state[reg]+ elif (word & 0xFFFF0000) == 0xDAC10000: # pac*/aut*/xpac* writes Rd+ rd = word & 0x1F+ for reg in [r for r in state if md.reg_name(r) == f"x{rd}"]:+ del state[reg]+ else:+ m, ops = ins.mnemonic, ins.operands+ if m == "adrp" and len(ops) == 2:+ old_page = ops[1].imm+ instruction_offset = soff + pos+ # Repair page-only definitions eagerly when the complete+ # page moves by a page-aligned segment delta. Waiting for+ # a consumer misses loop-carried definitions: CFG state+ # merging intentionally drops a register when two ADRPs+ # from different back-edges define it, even when both+ # definitions name the same Objective-C reference page.+ # The displacement of every eventual consumer remains+ # valid for a page-aligned relocation, so no consumer is+ # needed to prove this rewrite.+ page_delta = seg_delta_old(old_page)+ if trace and got_ref_slot:+ page_refs = [+ (old, new) for old, new in got_ref_slot.items()+ if (old & ~0xFFF) == old_page+ ]+ if page_refs:+ print(f" page refs={page_refs[:16]}")+ if (page_delta is not None and+ page_delta != text_delta and+ (page_delta & 0xFFF) == 0):+ new_page = old_page + page_delta+ new_pc = ins.address + text_delta+ adrp_word = struct.unpack_from(+ "<I", buf, instruction_offset)[0]+ struct.pack_into(+ "<I", buf, instruction_offset,+ _set_adrp(adrp_word, new_pc, new_page))+ adrp_pages[instruction_offset] = new_page+ fixed_offsets.add(instruction_offset)+ state[ops[0].reg] = (+ old_page, ((ins.address, instruction_offset),))+ else:+ base = disp = None+ if (m == "add" and len(ops) == 3 and+ ops[1].type == capstone.CS_OP_REG and+ ops[2].type == capstone.CS_OP_IMM):+ base, disp = ops[1].reg, ops[2].imm+ else:+ for op in ops:+ if op.type == capstone.CS_OP_MEM:+ base, disp = op.mem.base, op.mem.disp; break+ if base in state:+ page, definitions = state[base]+ old_t = page + (disp or 0)+ dt = seg_delta_old(old_t)+ new_target = None+ if dt is not None and dt != text_delta:+ new_target = old_t + dt+ elif dt is None and got_ref_slot and old_t in got_ref_slot:+ new_target = got_ref_slot[old_t]+ if trace:+ print(f" consumer target={old_t:#x} delta={dt} "+ f"new={new_target}")+ if new_target is not None:+ page_aligned = (+ dt is not None and (dt & 0xFFF) == 0)+ desired_page = ((page + dt) if page_aligned+ else (new_target & ~0xFFF))+ for aaddr, foff in definitions:+ new_page = adrp_pages.get(foff)+ if new_page is None:+ new_page = desired_page+ new_pc = aaddr + text_delta+ adrp_word = struct.unpack_from(+ "<I", buf, foff)[0]+ struct.pack_into(+ "<I", buf, foff,+ _set_adrp(+ adrp_word, new_pc, new_page))+ adrp_pages[foff] = new_page+ fixed_offsets.add(foff)+ elif new_page != desired_page:+ raise RuntimeError(+ "ADRP consumers require different "+ f"pages at {aaddr:#x}")+ new_disp = new_target - desired_page+ if not (0 <= new_disp < 0x1000):+ raise RuntimeError(+ "ADRP consumer displacement does not fit "+ f"at {ins.address:#x}")+ if (not page_aligned or new_disp != (disp or 0)):+ if not set_consumer_disp(soff + pos, new_disp):+ raise RuntimeError(+ f"cannot rewrite ADRP consumer at {ins.address:#x}")++ is_call = m in ("bl", "blr") or m.startswith("blra")+ if is_call:+ for reg in [r for r in state if _is_caller_saved(r)]:+ del state[reg]+ else:+ written = set()+ try: written.update(ins.regs_access()[1])+ except Exception: pass+ if (ops and ops[0].type == capstone.CS_OP_REG and+ (m == "add" or m.startswith("ld") or+ m.startswith("mov"))):+ written.add(ops[0].reg)+ for reg in written: state.pop(reg, None)++ # TBZ/TBNZ have two immediate operands: the tested bit number+ # and then the branch destination. The destination is always+ # the final immediate for the branch forms handled below.+ # Taking the first one made the CFG stop at bit 0/1 and skip+ # relocation of entire success paths (notably vmnet's event+ # callback setup and packet I/O globals).+ branch_immediates = [+ op.imm - old_sa for op in ops+ if op.type == capstone.CS_OP_IMM+ ]+ branch_target = (branch_immediates[-1]+ if branch_immediates else None)+ if m == "b":+ successors = ([branch_target]+ if branch_target is not None else [])+ elif (m.startswith("b.") or+ m in ("cbz", "cbnz", "tbz", "tbnz")):+ if branch_target is not None:+ successors.append(branch_target)+ elif m in ("ret", "br") or m.startswith("bra"):+ successors = []+ for successor in successors:+ merge_state(successor, state)+ if os.environ.get("VZ_DBG_ADRP"):+ print(f" -> {sname}: {len(fixed_offsets) - sec_fixed0} rewritten")+ print(f"rewrote {len(fixed_offsets)} cross-segment ADRP ({scanned} code sections)")+++def _adrp_target(word, pc):+ immlo = (word >> 29) & 3+ immhi = (word >> 5) & 0x7FFFF+ imm = (immhi << 2) | immlo+ if imm & (1 << 20): imm -= (1 << 21) # sign-extend 21-bit+ return (pc & ~0xFFF) + (imm << 12)++def _set_adrp(word, pc, target):+ imm = ((target & ~0xFFF) - (pc & ~0xFFF)) >> 12+ word &= ~((3 << 29) | (0x7FFFF << 5))+ return word | ((imm & 3) << 29) | (((imm >> 2) & 0x7FFFF) << 5)++def _add_imm(word):+ return ((word >> 10) & 0xFFF) << (12 if (word >> 22) & 1 else 0)++def _set_add_imm(word, imm): # assume shift=0, imm fits 12 bits+ word &= ~((1 << 22) | (0xFFF << 10))+ return word | ((imm & 0xFFF) << 10)+++def fix_auth_stubs(buf, osegs, text_delta, dsc, amap):+ """The cache uniques every GOT binding into a shared GOT and EMPTIES the image's own+ __auth_got (all slots zeroed). __auth_stubs come in two flavours: some still ADRP+ADD to a+ slot in the image's own (now-empty) __auth_got; others ADRP at the shared GOT (out of image).+ Both need their slot bound. Decode each stub's ORIGINAL (cache) GOT target and a2s it:+ - in-image target -> bind the EXISTING slot (amap of the target); the stub keeps pointing+ there (we repoint it; rewrite_adrp skips __auth_stubs so the cache imm is intact here).+ - out-of-image target -> allocate a FREE __auth_got slot (one NOT claimed by an in-image+ stub) and repoint the stub to it.+ Crucially the out-of-image allocator must avoid the in-image slots, else e.g. operator new's+ slot gets clobbered with another symbol. Returns [(slot_new_addr, symbol)] auth-binds."""+ def find(sect):+ for nm, va, vs, fo, fs, lc in osegs:+ ns = struct.unpack_from("<I", buf, lc+64)[0]+ for k in range(ns):+ so = lc+72+k*80+ if buf[so:so+16].split(b"\0")[0] == sect:+ sa, ssz = struct.unpack_from("<QQ", buf, so+32)+ return sa, ssz, struct.unpack_from("<I", buf, so+48)[0]+ return None+ st = find(b"__auth_stubs"); ag = find(b"__auth_got")+ if not st or not ag: return []+ sa, ssz, sfo = st+ ag_va, ag_sz, _ = ag+ stubs = [] # (fo, A, cache_got)+ for o in range(0, ssz - 12, 16): # 16-byte arm64e auth stubs+ fo = sfo + o; A = sa + o+ adrp = struct.unpack_from("<I", buf, fo)[0]+ add = struct.unpack_from("<I", buf, fo+4)[0]+ if (adrp & 0x9F000000) != 0x90000000: continue # not ADRP+ cache_got = _adrp_target(adrp, A - text_delta) + _add_imm(add) # original target (cache addr)+ stubs.append((fo, A, cache_got))+ if not stubs: return []+ sym_map = a2s_batch([g for _, _, g in stubs])+ claimed = {amap(cg) for _, _, cg in stubs if amap(cg) is not None} # in-image slots in use+ free = (ag_va + j*8 for j in range(ag_sz // 8) if (ag_va + j*8) not in claimed)+ binds = []; nin = nout = 0+ for fo, A, cg in stubs:+ name = sym_map.get(cg, (None,))[0]+ if name and name.startswith("_ptr."): name = name[5:]+ if not name: continue+ slot = amap(cg)+ if slot is not None:+ nin += 1 # in-image: bind the stub's own (empty) slot+ else:+ slot = next(free, None) # out-of-image: a fresh, unclaimed slot+ if slot is None: continue+ nout += 1+ struct.pack_into("<I", buf, fo, _set_adrp(struct.unpack_from("<I", buf, fo)[0], A, slot))+ struct.pack_into("<I", buf, fo+4, _set_add_imm(struct.unpack_from("<I", buf, fo+4)[0], slot & 0xFFF))+ binds.append((slot, name))+ print(f" ({nin} in-image-slot, {nout} fresh-slot)", end="")+ print(f"fix_auth_stubs: repointed {len(binds)}/{len(stubs)} stubs to rebuilt __auth_got")+ return binds+++def objc_collect_relmethods(buf):+ """Walk the objc class/category/protocol graph on the ORIGINAL (pre-relayout)+ buffer and collect every arm64e RELATIVE method-list field. Returns+ (ti_recs, name_recs):+ ti_recs = [(field_vmaddr, target_vmaddr)] for the types & imp fields+ (they target in-image type-strings / functions; fixed by amap).+ name_recs = [(field_vmaddr, old_target_vmaddr, direct_bool)] for the name+ field. In the cache the name targets the shared selector pool+ (out of image) so it can't be amap'd; it must be redirected to an+ in-image selref slot (see objc_build_selref_pool). direct_bool is+ the method-list's RELATIVE_METHOD_SELECTORS_ARE_DIRECT flag, which+ says whether old_target is the selector string (direct) or a selref+ slot holding a pointer to it."""+ segs, off = [], 32+ ncmds = struct.unpack_from("<I", buf, 16)[0]+ sects = {}+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ va, vs, fo, fs = struct.unpack_from("<QQQQ", buf, off+24)+ segs.append((va, va+vs, fo))+ ns = struct.unpack_from("<I", buf, off+64)[0]+ for k in range(ns):+ so = off+72+k*80+ nm = buf[so:so+16].split(b"\0")[0].decode()+ sa, ssz = struct.unpack_from("<QQ", buf, so+32)+ sects[nm] = (sa, ssz)+ off += sz+ def o2(a):+ for lo, hi, fo in segs:+ if lo <= a < hi: return fo + (a-lo)+ return None+ inimg = lambda a: any(lo <= a < hi for lo, hi, _ in segs)+ def rdp(a):+ o = o2(a); return struct.unpack_from("<Q", buf, o)[0] if o is not None else 0+ def rdu(a):+ o = o2(a); return struct.unpack_from("<I", buf, o)[0] if o is not None else 0+ def rdi(a):+ o = o2(a); return struct.unpack_from("<i", buf, o)[0] if o is not None else 0++ recs = []; name_recs = []+ def do_ml(ml):+ if not ml or not inimg(ml): return+ ef = rdu(ml); count = rdu(ml+4)+ if not (ef & 0x80000000): return # pointer-based -> entries are fixups+ # Lists carry the low-2 "fixed_up/sorted" flag from the cache, so objc trusts the cache's+ # SEL-address sort order and binary-searches by it — but objc re-uniques our selref pool+ # at load to canonical SELs in a DIFFERENT order, so the search misses (respondsToSelector+ # fails). Clear the flag so objc re-fixes-up + re-sorts the list against the canonical SELs.+ # (This needs the GOT/protoref/__EXTRA_OBJC fixes to be in place first, else realization+ # crashes earlier -- those are now done.) macOS objc tolerated the stale flag; iOS doesn't.+ struct.pack_into("<I", buf, o2(ml), ef & ~0x3)+ ent = (ef & 0xFFFC) or 12+ for i in range(count):+ e = ml + 8 + i*ent+ for fo in (4, 8): # types, imp -> relative-offset fix (work as-is)+ fa = e + fo; rel = rdi(fa)+ if rel: recs.append((fa, fa+rel))+ # name (offset 0) -> DyldExtractor selref slot -> selector string. objc only uniques+ # selrefs that live in the real __objc_selrefs section (small lists are assumed+ # pre-uniqued), and our slot sits in synthetic __EXTRA_OBJC -> never uniqued ->+ # dispatch-by-SEL misses. Record (name_field, selector_string) so we can repoint the+ # name at a freshly-built slot inside the (extended) __objc_selrefs pool.+ rel = rdi(e)+ if rel:+ slot = e + rel+ if inimg(slot):+ sp = rdp(slot)+ if inimg(sp): name_recs.append((e, sp))+ def do_methods(raw):+ # class_ro baseMethods is a PointerUnion<method_list_t, relative_list_list_t>; the low+ # bit tags a list-of-lists (pre-attached categories). Walk both forms.+ raw &= 0x00FFFFFFFFFFFFFF # strip PAC top byte+ if not raw: return+ if raw & 1: # list-of-lists+ lol = raw & ~0x7+ if not inimg(lol): return+ cnt = rdu(lol+4)+ for i in range(cnt):+ entry = lol + 8 + i*8 # {imageIndex:16, listOffset:48 (rel to entry)}+ if not inimg(entry): continue+ v = struct.unpack_from("<q", buf, o2(entry))[0]+ do_ml(entry + (v >> 16))+ else:+ do_ml(raw & ~0x7)+ def do_class(c):+ if not c or not inimg(c): return+ for cls in (c, rdp(c)): # class + metaclass(isa)+ if not inimg(cls): continue+ ro = rdp(cls+32) & 0x00007ffffffffff8+ if inimg(ro): do_methods(rdp(ro+32)) # baseMethods (single list OR list-of-lists)+ if "__objc_classlist" in sects:+ sa, ssz = sects["__objc_classlist"]+ for i in range(ssz//8): do_class(rdp(sa+i*8))+ if "__objc_catlist" in sects:+ sa, ssz = sects["__objc_catlist"]+ for i in range(ssz//8):+ cat = rdp(sa+i*8)+ if inimg(cat):+ do_ml(rdp(cat+16)); do_ml(rdp(cat+24)) # instanceMethods, classMethods+ if "__objc_protolist" in sects: # protocols carry rel method lists too+ sa, ssz = sects["__objc_protolist"] # (fixupProtocol reads them -> must be valid)+ for i in range(ssz//8):+ p = rdp(sa+i*8)+ if inimg(p):+ for moff in (24, 32, 40, 48): # {inst,class,optInst,optClass}Methods+ do_ml(rdp(p+moff))+ return recs, name_recs+++def make_amap(deltas):+ def amap(a):+ for lo, hi, d in deltas:+ if lo <= a < hi: return a + d+ return None+ return amap+++def parse_segments(buf):+ """[(name, vmaddr, vmsize, fileoff, filesize, lc_off)] from a mach-o buffer."""+ magic, cputype, cpusub, ft, ncmds, scmds, flags, _ = struct.unpack_from("<IIIIIIII", buf, 0)+ segs, off = [], 32+ for _ in range(ncmds):+ cmd, sz = struct.unpack_from("<II", buf, off)+ if cmd == LC_SEGMENT_64:+ name = buf[off+8:off+24].split(b"\0")[0].decode()+ vmaddr, vmsize, fileoff, filesize = struct.unpack_from("<QQQQ", buf, off+24)+ segs.append([name, vmaddr, vmsize, fileoff, filesize, off])+ off += sz+ return segs, ncmds, scmds+++def main(dsc, image_substr, dex_out, final_out, mode="compact"):+ global DSC; DSC = dsc+ logging.basicConfig(level=100)+ sb = progressbar.ProgressBar(prefix="{variables.unit}", variables={"unit": "", "status": ""},+ widgets=[progressbar.widgets.AnimatedMarker()], redirect_stdout=True)+ logger = logging.getLogger()++ # ---- collect fixups from the cache ----+ with open(dsc, "rb") as f:+ dyldCtx = DyldContext(f)+ subs = dyldCtx.addSubCaches(__import__("pathlib").Path(dsc))+ try:+ img = next(im for im in dyldCtx.images+ if image_substr in dyldCtx.readString(im.pathFileOffset)[:-1].decode())+ mOff, mctx = dyldCtx.convertAddr(img.address)+ machoCtx = MachOContext(mctx.fileObject, mOff, True)+ if dyldCtx.hasSubCaches():+ mp = dyldCtx.mappings+ mainMap = next(m[0] for m in mp if m[1] == mctx)+ machoCtx.addSubfiles(mainMap, ((m, c.makeCopy(copyMode=True)) for m, c in mp))+ ectx = ExtractionContext(dyldCtx, machoCtx, sb, logger)+ segs = [(s.seg.vmaddr, s.seg.vmaddr+s.seg.vmsize) for s in machoCtx.segmentsI]+ base = min(s[0] for s in segs)+ in_img = lambda a: any(lo <= a < hi for lo, hi in segs)+ dylibs = []+ o = mOff+32+ for _ in range(mach_header_64(mctx.file, mOff).ncmds):+ cmd, sz = struct.unpack_from("<II", mctx.file, o)+ if cmd == LC_LOAD_DYLIB:+ no = struct.unpack_from("<I", mctx.file, o+8)[0]+ dylibs.append(mctx.file[o+no:o+sz].split(b"\0")[0].decode())+ o += sz++ fx = [] # (addr, target, auth, key, div, addrdiv)+ class C(slide_info._V3Rebaser):+ def _rebasePage(self, ctx, pageOffset, delta):+ loc = pageOffset+ while True:+ loc += delta+ li = dyld_cache_slide_pointer3(self.dyldCtx.file, loc)+ delta = li.plain.offsetToNextPointer * 8+ a = self.mapping.address + (loc - self.mapping.fileOffset)+ if in_img(a):+ if li.auth.authenticated:+ t = li.auth.offsetFromSharedCacheBase + self.slideInfo.auth_value_add+ fx.append([a, t, 1, int(li.auth.key), int(li.auth.diversityData),+ int(li.auth.hasAddressDiversity)])+ else:+ v = li.plain.pointerValue+ t = ((v & 0x0007F80000000000) << 13) | (v & 0x000007FFFFFFFFFF)+ fx.append([a, t, 0, 0, 0, 0])+ if delta == 0:+ break+ for info in slide_info._getMappingInfo(ectx):+ if info.slideInfo.version == 3:+ C(ectx, info).run()+ finally:+ for sf in subs:+ sf.close()+ print(f"collected {len(fx)} fixups; base={base:#x}; dylibs={len(dylibs)}")+ if os.environ.get("VZ_DBG_AUTH"):+ from collections import Counter+ c = Counter((k, d, ad) for a, t, au, k, d, ad in fx if au)+ print(" AUTH (key,div,addrDiv) histogram:", c.most_common(12))+ print(" div=0xa65 entries (key,addrDiv):", Counter((k, ad) for a, t, au, k, d, ad in fx if au and d == 0xa65))++ # ---- load DyldExtractor output + relayout (gives addr map old->new) ----+ buf = bytearray(open(dex_out, "rb").read())+ objc_recs, objc_names = objc_collect_relmethods(buf) if mode == "compact" else ([], [])+ got_targets = collect_got_refs(buf, dsc) if mode == "compact" else {} # {addr:(sym,is_auth)}+ unwind_pers = collect_unwind_personalities(buf, dsc) if mode == "compact" else []+ lsda_type_refs = collect_lsda_type_refs(buf, dsc) if mode == "compact" else []+ got_auth = {} # symbol -> is_auth (consistent per symbol)+ for _a, (s, au) in got_targets.items(): got_auth[s] = got_auth.get(s, False) or au+ for s in unwind_pers: # personality routines are autia'd -> auth+ if s: got_auth[s] = True+ for _field, _target, symbol, _width in lsda_type_refs:+ if symbol: got_auth[symbol] = got_auth.get(symbol, False)+ got_syms = sorted(got_auth)+ if got_syms: print(f"out-of-image GOT: {len(got_targets)} slots -> {len(got_syms)} symbols "+ f"({sum(got_auth.values())} auth fn, {len(got_syms)-sum(got_auth.values())} data)")+ if not os.environ.get("VZ_MAC"): # VZ_MAC: keep macOS Versions/A paths for host dlopen test+ rewrite_dylib_paths(buf)+ # iOS-absent deps we import nothing from (verified: 0 bind targets land in them).+ weaken_absent_dylibs(buf, os.environ.get("VZ_WEAKEN", "MetalSerializer").split(","))+ # objc selref pool: one slot per unique selector used by relative method lists, appended+ # into __objc_selrefs so objc uniques them at load (small lists are assumed pre-uniqued).+ uniq_sel = sorted({s for _, s in objc_names})+ pool_sect = None+ pool_seg = None+ if mode == "compact" and (uniq_sel or got_syms):+ # ObjC images need selector slots inside __objc_selrefs so objc uniques+ # them. Plain C dylibs such as vmnet have no ObjC section; append their+ # rebuilt external-data GOT pool to the existing __got instead.+ candidates = (["__objc_selrefs"] if uniq_sel else []) + [+ "__got", "__data"]+ for candidate in candidates:+ pool_seg = _section_segment(buf, candidate.encode())+ if pool_seg:+ pool_sect = candidate+ break+ if mode == "compact":+ if pool_seg:+ pool_size = (len(uniq_sel) + len(got_syms)) * 8+ # With selector slots, only that prefix belongs to the ObjC+ # section. A C dylib's whole pool is ordinary GOT data.+ section_growth = len(uniq_sel) * 8 if uniq_sel else pool_size+ buf, deltas, pool_va = relayout_compact(+ buf, insert=(pool_seg, pool_sect, pool_size,+ section_growth))+ else:+ buf, deltas = relayout_compact(buf); pool_va = None+ amap = make_amap(deltas); nbase = 0x100000000+ elif mode == "pad":+ reorder_segments(buf); buf = relayout_pad(buf); amap = lambda a: a; nbase = base+ else:+ reorder_segments(buf); buf = relayout(buf); amap = lambda a: a; nbase = base+ osegs, ncmds, scmds = parse_segments(buf)+ objc_slot_reb = [] # (new_slot_addr, new_string_addr) objc selref-pool rebases+ auth_stub_binds = [] # (slot_addr, symbol) rebuilt __auth_got auth-binds+ got_slot = {} # {symbol: new_slot_addr} rebuilt in-image GOT pool+ if mode == "compact" and pool_va is not None and got_syms:+ got_pool_va = pool_va + len(uniq_sel) * 8 # GOT pool sits right after the selref pool+ got_slot = {s: got_pool_va + i * 8 for i, s in enumerate(got_syms)}+ got_ref_slot = {t: got_slot[s] for t, (s, au) in got_targets.items() if s in got_slot}+ if mode == "compact" and unwind_pers and got_slot: # repoint __unwind_info personalities+ npr = rewrite_unwind_personalities(buf, unwind_pers, got_slot, nbase)+ if npr: print(f"repointed {npr} __unwind_info personality ref(s) to rebuilt GOT")+ if mode == "compact" and lsda_type_refs:+ nlr = rewrite_lsda_type_refs(+ buf, lsda_type_refs, amap, got_slot, nbase)+ if nlr:+ print(f"repointed {nlr} LSDA catch-type ref(s) to rebuilt GOT")+ if mode == "compact":+ rewrite_adrp(buf, osegs, deltas, got_ref_slot)+ text_delta = next(d for lo, hi, d in deltas if lo + d == nbase)+ auth_stub_binds = fix_auth_stubs(buf, osegs, text_delta, dsc, amap)+ nfix = 0 # fix objc relative method-list types/imp offsets+ for fa, tgt in objc_recs:+ na, nt = amap(fa), amap(tgt)+ if na is None or nt is None: continue+ struct.pack_into("<i", buf, na - nbase, nt - na)+ nfix += 1+ print(f"fixed {nfix} objc relative method-list offsets")+ # build the selref pool: each unique selector gets a slot (rebased to the string),+ # and each relative method's name field is repointed at its slot.+ if pool_va is not None:+ str_slot = {s: pool_va + i*8 for i, s in enumerate(uniq_sel)}+ for s, slot in str_slot.items():+ nt = amap(s)+ if nt is not None: objc_slot_reb.append((slot, nt))+ nrep = 0+ for nf, s in objc_names:+ na = amap(nf)+ if na is None: continue+ struct.pack_into("<i", buf, na - nbase, str_slot[s] - na) # name -> pool slot (rel)+ nrep += 1+ print(f"objc selref pool: {len(uniq_sel)} slots, repointed {nrep} method names")+ # Clear dyld-preoptimized flags in __objc_imageinfo, else objc map_images takes+ # the shared-cache preopt path (getPreoptimizedHeaderRW -> garbage ptr -> crash).+ # OptimizedByDyld(0x8) | OptimizedByDyldClosure(0x80) | DyldCategoriesOptimized(0x1)+ o3 = 32+ for _ in range(ncmds):+ c3, s3 = struct.unpack_from("<II", buf, o3)+ if c3 == LC_SEGMENT_64:+ for k in range(struct.unpack_from("<I", buf, o3+64)[0]):+ so3 = o3+72+k*80+ if buf[so3:so3+16].split(b"\0")[0] == b"__objc_imageinfo":+ ioff = struct.unpack_from("<I", buf, so3+48)[0]+ fl = struct.unpack_from("<I", buf, ioff+4)[0]+ struct.pack_into("<I", buf, ioff+4, fl & ~(0x1 | 0x8 | 0x80))+ print(f"objc_imageinfo flags {fl:#x} -> {fl & ~(0x1|0x8|0x80):#x}")+ o3 += s3+ def addr2off(a):+ for nm, va, vs, fo, fs, _ in osegs:+ if va <= a < va+vs: return fo + (a-va)+ raise KeyError(hex(a))++ # ---- classify + resolve binds; emit in NEW (relocated) addr space ----+ # a2s sometimes returns an objc-class alias not exported on iOS; map to the+ # concrete-block symbol that IS exported (same address, libSystem).+ ALIAS = {+ "_OBJC_CLASS_$___NSGlobalBlock__": "__NSConcreteGlobalBlock",+ "_OBJC_CLASS_$___NSStackBlock__": "__NSConcreteStackBlock",+ "_OBJC_CLASS_$___NSMallocBlock__": "__NSConcreteMallocBlock",+ # ipsw a2s names XPC type singleton objects after the adjacent ObjC+ # class aliases. Code using xpc_get_type compares against the+ # singleton (`_xpc_type_*`), not the OS_xpc_* class object. Binding+ # these rebuilt external-data GOT slots to the class leaves the type+ # test false (or NULL when the private class export is unavailable).+ "_OBJC_CLASS_$_OS_xpc_connection": "__xpc_type_connection",+ "_OBJC_CLASS_$_OS_xpc_dictionary": "__xpc_type_dictionary",+ "_OBJC_CLASS_$_OS_xpc_error": "__xpc_type_error",+ "_OBJC_CLASS_$_OS_xpc_string": "__xpc_type_string",+ "_OBJC_CLASS_$_OS_xpc_uint64": "__xpc_type_uint64",+ }+ imports = []; impidx = {}+ entries = {} # new_loc -> (kind, val, auth, key, div, addrdiv, high8)+ # PLAIN pointers carry a TBI/high8 byte in bits 56-63 (arm64e plain-rebase has a+ # dedicated high8 field). Strip it for in-image classification + target math, then+ # re-apply on emit. AUTH targets (offsetFromSharedCacheBase + auth_value_add) never+ # have high8.+ def real_t(t, auth):+ return t if auth else (t & 0x00FFFFFFFFFFFFFF)+ bind_tgts = sorted({real_t(t, auth) for _, t, auth, *_ in fx if not in_img(real_t(t, auth))})+ if os.environ.get("VZ_DUMP_BINDS"):+ open(os.environ["VZ_DUMP_BINDS"], "w").write("\n".join(hex(t) for t in bind_tgts))+ print(f"resolving {len(bind_tgts)} unique bind targets (batch a2sb)...")+ sym_map = a2s_batch(bind_tgts)+ # objc selref/string localization: the cache uniques selector & class-name strings+ # into libobjc's shared __OBJC_RO pool, so a2sb can't name them ("?"). DyldExtractor+ # already copied the strings into our local CstringLiterals sections, so repoint these+ # pointers at the local copy (in-image rebase) instead of an (impossible) named bind.+ unnamed = [rt for rt in bind_tgts if not sym_map.get(rt, (None,))[0] or sym_map[rt][0] == "?"]+ localize = {}+ if unnamed:+ local_str_va = build_local_str_va(buf)+ cstrs = read_cache_cstrs(dsc, unnamed)+ for rt in unnamed:+ s = cstrs.get(rt)+ if s and s in local_str_va:+ localize[rt] = local_str_va[s]+ miss = [rt for rt in unnamed if rt not in localize]+ print(f"localized {len(localize)}/{len(unnamed)} unnamed objc string targets")+ if miss:+ print(f" UNLOCALIZED: {[(hex(rt), cstrs.get(rt)) for rt in miss[:8]]}")+ nreb = nbind = 0+ for addr, t, auth, key, div, ad in fx:+ nloc = amap(addr)+ high8 = 0 if auth else (t >> 56) & 0xFF+ rt = real_t(t, auth)+ if os.environ.get("VZ_DBG_PROTOREF") and addr == int(os.environ["VZ_DBG_PROTOREF"], 16):+ print(f" PROTOREF fx: addr={addr:#x} t={t:#x} auth={auth} rt={rt:#x} in_img={in_img(rt)} sym={sym_map.get(rt)}")+ if in_img(rt):+ entries[nloc] = ("rebase", amap(rt)-nbase, auth, key, div, ad, high8); nreb += 1+ elif rt in localize:+ entries[nloc] = ("rebase", localize[rt]-nbase, auth, key, div, ad, high8); nreb += 1+ else:+ name = sym_map.get(rt, (None, None))[0]+ if name and name.startswith("_ptr."):+ name = name[5:] # ipsw GOT-slot notation -> the real symbol+ name = ALIAS.get(name, name)+ if name == "_OBJC_CLASS_$_Protocol":+ # Protocol-uniquing reference: the cache redirects every @protocol / adopted-+ # protocol pointer to libobjc's canonical protocol_t (whose isa is+ # _OBJC_CLASS_$_Protocol), so a2sb names the slot the Protocol *class* and we'd+ # otherwise BIND it there -> objc reads class+8 as a protocol mangledName ->+ # getProtocol/_mapStrHash SIGSEGV (conformsToProtocol). DyldExtractor's objc_fixer+ # rewrote the slot to THIS image's local same-name protocol_t; trust that file+ # value. Covers protorefs, class baseProtocols, protocol incorporated-protocols,+ # category protocols — every protocol-ref site, uniformly.+ fv = struct.unpack_from("<Q", buf, nloc - nbase)[0] & 0x00FFFFFFFFFFFFFF+ dt = amap(fv)+ if dt is not None:+ entries[nloc] = ("rebase", dt - nbase, auth, key, div, ad, high8); nreb += 1+ continue+ print(f" WARNING: protocol ref @{nloc:#x} file-value {fv:#x} not in-image (external?) — binding to Protocol class")+ if not name: raise SystemExit(f"unresolved bind {rt:#x} (no symbol name)")+ # Flat-namespace lookup: dyld searches ALL of PVG's loaded dylibs by name.+ # Per-symbol dylib attribution is unreliable here — the cache uniques GOTs and+ # local symbols (e.g. _OBJC_CLASS_$_NSException is a *local* CoreFoundation+ # symbol that a2sb/image_for mis-home to libc++). All deps are in LC_LOAD_DYLIB,+ # so flat lookup resolves every symbol to its true exporting image.+ ordv = 0xFE+ k = (ordv, name)+ if k not in impidx:+ impidx[k] = len(imports); imports.append(k)+ entries[nloc] = ("bind", impidx[k], auth, key, div, ad, high8); nbind += 1+ for ns, nt in objc_slot_reb: # objc selref slots (plain in-image rebases)+ entries[ns] = ("rebase", nt - nbase, 0, 0, 0, 0, 0); nreb += 1+ for slot, name in auth_stub_binds: # rebuilt __auth_got: auth-binds (braa: key IA, addrDiv)+ name = ALIAS.get(name, name)+ k = (0xFE, name)+ if k not in impidx:+ impidx[k] = len(imports); imports.append(k)+ entries[slot] = ("bind", impidx[k], 1, 0, 0, 1, 0); nbind += 1+ for name, slot in got_slot.items(): # rebuilt GOT pool: data (plain) + fn ptrs (auth, braa)+ au = got_auth[name]+ name = ALIAS.get(name, name)+ k = (0xFE, name)+ if k not in impidx:+ impidx[k] = len(imports); imports.append(k)+ entries[slot] = ("bind", impidx[k], 1, 0, 0, 1, 0) if au else ("bind", impidx[k], 0, 0, 0, 0, 0)+ nbind += 1+ # (Protocol references — __objc_protorefs, class baseProtocols, protocol incorporated-protocols,+ # category protocols — are handled uniformly in the main fixup loop above: any slot that would+ # bind to _OBJC_CLASS_$_Protocol is rebased to DyldExtractor's localized file value instead.+ # That relies on the DyldExtractor objc_fixer protocol-localization patch, see+ # patches/dyldextractor-2.2.2-arm64e.patch.)+ # __EXTRA_OBJC: DyldExtractor relocates objc metadata (protocols/categories) into this synthetic+ # segment with FLAT absolute RE-addr pointers, but the cache slide-info (our only fixup source)+ # doesn't cover it -> the pointers stay stale RE addresses. iOS objc reads protocol mangledName+ # etc. EAGERLY at load and derefs them -> crash (macOS read them lazily so the VM never hit it).+ # Rebase every 8-byte slot whose value lands in an original-image segment (amap != None); small+ # fields (flags/sizes), relative-list int32 pairs, and cstring bytes fall outside that range.+ neo = 0+ if mode == "compact":+ for nm, va, vs, fo, fs, lc in osegs:+ if nm != "__EXTRA_OBJC": continue+ for p in range(0, fs - 7, 8):+ v = struct.unpack_from("<Q", buf, fo + p)[0]+ if v < 0x100000000: continue+ t = amap(v)+ if t is not None and (va + p) not in entries:+ entries[va + p] = ("rebase", t - nbase, 0, 0, 0, 0, 0); nreb += 1; neo += 1+ print(f"{nreb} rebases ({len(objc_slot_reb)} selref + {neo} __EXTRA_OBJC), {nbind} binds ({len(auth_stub_binds)} auth-stub), {len(imports)} imports")+ if mode == "compact":+ fix_export_trie(buf, amap, nbase, deltas) # remap stale export offsets (dyld/ld symbol resolution)++ # group by output segment; build per-segment page chains+ seg_fixups = {i: [] for i in range(len(osegs))}+ for addr in entries:+ for i, (nm, va, vs, fo, fs, lc) in enumerate(osegs):+ if va <= addr < va+vs:+ seg_fixups[i].append(addr); break++ # weave: write packed entries with next deltas (per PAGE within segment)+ seg_starts = {} # segidx -> list of page_start (uint16)+ for i, (nm, va, vs, fo, fs, lc) in enumerate(osegs):+ addrs = sorted(seg_fixups[i])+ if not addrs: continue+ npages = (vs + PAGE - 1)//PAGE+ pstart = [START_NONE]*npages+ # bucket by page+ from collections import defaultdict+ bypage = defaultdict(list)+ for a in addrs: bypage[(a-va)//PAGE].append(a)+ for pg, plist in bypage.items():+ plist.sort()+ pstart[pg] = (plist[0]-va) - pg*PAGE # offset within page+ for j, a in enumerate(plist):+ nxt = ((plist[j+1]-a)//8) if j+1 < len(plist) else 0+ kind, v, auth, key, div, ad, high8 = entries[a]+ if kind == "rebase":+ word = pack_auth_rebase(v, div, ad, key, nxt) if auth else pack_rebase(v, nxt, high8)+ else:+ word = pack_auth_bind(v, div, ad, key, nxt) if auth else pack_bind(v, 0, nxt)+ struct.pack_into("<Q", buf, addr2off(a), word)+ seg_starts[i] = pstart++ # ---- build LC_DYLD_CHAINED_FIXUPS blob ----+ def align(b, n):+ while len(b) % n: b += b"\0"+ return b+ # symbols pool+ sympool = bytearray(); symoff = {}+ for lo, n in imports:+ symoff[n] = len(sympool); sympool += n.encode()+b"\0"+ # imports (DYLD_CHAINED_IMPORT: lib_ordinal:8, weak:1, name_offset:23)+ # weak_import=1: porting a macOS framework onto iOS, a handful of imports are macOS-only+ # APIs absent from the iOS cache (e.g. AppKit's NSBitmapImageRep). Weak makes dyld bind+ # them to NULL instead of failing the load; present symbols still resolve normally.+ weak = 0 if os.environ.get("VZ_NO_WEAK_IMPORTS") else 1+ imp_blob = bytearray()+ for lo, n in imports:+ imp_blob += struct.pack("<I", (lo & 0xFF) | (weak << 8) | ((symoff[n] & 0x7FFFFF) << 9))+ # starts_in_image + per-seg starts_in_segment+ seg_count = len(osegs)+ sii = bytearray(struct.pack("<I", seg_count)) # seg_count+ sii += b"\0\0\0\0"*seg_count # seg_info_offset[] (fill later)+ seg_seg_blobs = {}+ for i in seg_starts:+ ps = seg_starts[i]+ b = struct.pack("<IHHQIH", 0, PAGE, PF_ARM64E_USERLAND, osegs[i][1]-nbase, 0, len(ps))+ b += b"".join(struct.pack("<H", x) for x in ps)+ b = bytearray(b)+ struct.pack_into("<I", b, 0, len(b)) # size field+ seg_seg_blobs[i] = b+ # lay out seg blobs after the seg_info_offset array+ cur = len(sii)+ for i in sorted(seg_seg_blobs):+ while cur % 4: cur += 1; sii += b"\0"+ struct.pack_into("<I", sii, 4 + i*4, cur) # seg_info_offset[i]+ sii += seg_seg_blobs[i]; cur = len(sii)++ blob = bytearray(struct.pack("<IIIIIII", 0, 0, 0, 0, len(imports), 1, 0)) # header (fill offsets)+ blob = align(blob, 4); starts_off = len(blob); blob += sii+ blob = align(blob, 4); imports_off = len(blob); blob += imp_blob+ symbols_off = len(blob); blob += sympool+ struct.pack_into("<IIIIIII", blob, 0, 0, starts_off, imports_off, symbols_off, len(imports), 1, 0)+ blob = align(blob, 8)++ # ---- splice: place blob at the file end, point LC at it, extend last seg ----+ li = max(osegs, key=lambda s: s[3]) # highest fileoff = last segment (must be __LINKEDIT)+ assert li[0] == "__LINKEDIT", f"last segment is {li[0]} not __LINKEDIT"+ while len(buf) % 8: buf += b"\0"+ dataoff = len(buf) # blob goes exactly here+ buf += blob+ # extend __LINKEDIT to cover [fileoff .. end of blob] (gap before blob is harmless zeros)+ li[4] = len(buf) - li[3] # filesize+ vmsize = (li[4] + 0x3FFF) & ~0x3FFF+ struct.pack_into("<Q", buf, li[5]+32, vmsize) # vmsize+ struct.pack_into("<Q", buf, li[5]+48, li[4]) # filesize (fileoff @+40 intact)++ # find space for new LC: drop LC_FUNCTION_STARTS + LC_DATA_IN_CODE if needed, then append our LC+ # simplest: append after last LC; ensure header region has room before first section data.+ first_sec_off = min((s[3] for s in osegs if s[3] > 0), default=0x4000)+ lc_end = 32 + scmds+ newlc = struct.pack("<IIII", LC_DYLD_CHAINED_FIXUPS, 16, dataoff, len(blob))+ if lc_end + 16 <= first_sec_off:+ buf[lc_end:lc_end] = b"" # write in place+ buf[lc_end:lc_end+16] = newlc+ struct.pack_into("<I", buf, 16, ncmds+1) # ncmds+ struct.pack_into("<I", buf, 20, scmds+16) # sizeofcmds+ else:+ raise SystemExit(f"no header room: lc_end={lc_end:#x} first_sec={first_sec_off:#x}")++ # clear MH_DYLIB_IN_CACHE (correct metadata: the dylib is no longer in the cache;+ # tolerated-if-set on 13.2/16.3.1 dyld, but cleared for correctness, as dsce does)+ flags = struct.unpack_from("<I", buf, 24)[0]+ struct.pack_into("<I", buf, 24, flags & ~MH_DYLIB_IN_CACHE)++ open(final_out, "wb").write(buf)+ print(f"wrote {final_out} ({len(buf)} bytes); blob@{dataoff:#x} size={len(blob)}")+++if __name__ == "__main__":+ main(*sys.argv[1:])