Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat: restore opt-in iOS 16 scanout, touch and fresh-lab desktop

黑曜猫773c10883f87
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 3bd0a839..96427ec2 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -5993,253 +5993,56 @@ vertex outputs, render targets); an argument kind the reflection reads in a
layout the completion does not produce could still crash the compiler
service. With primitive restart no longer sent, an OpenGL ES 2 strip that draws
vertex 65535 is cut there.
-## Local iPhone 14 Pro / iOS 16.6.1 experiment
-
-The isolated experiment uses iPhone15,2 16.6.1 (20G81) with cloudOS 26.1 (23B85).
-Existing older-userland SwapEnd, thread-guard and paravirtual-user-client patch
-gates and the BSD-only Skywalk boot argument are enabled for this experiment.
-The iOS 17 SpringBoard workaround remains gated to 17 until 16's own startup
-blockers are measured. No boot or display success is claimed at this stage.
-
-First normal boot exits PID 1 with "could not set up inheritance port".
-The 20G81 launchd calls `_mach_ports_register` at 0x10001682C and branches
-on error at 0x100016830 to the fatal string block at 0x100016958.
-XNU 12377.41.6 `osfmk/mach/task.defs` uses three inline port descriptors for
-task RPCs 3403/3404; the 16.x public API still sends an OOL port array.
-Opt-in `system-launchd-exp-ios16_mach_ports` installs a marker that selects
-register/lookup translation in launchdhook and SystemHook. MIG generates the
-two modern client messages; the existing kobject Mach-message transport sends
-them. No launchd or kernel instruction is skipped. Removing the marker and
-restarting returns to the native APIs. A native self-task round-trip passes;
-guest console confirms register3 succeeds and launchd completes early boot.
-
-The next failure precedes inserted-library constructors: libxpc's initializer
-calls `_mach_ports_lookup` at 0x1E6ECBCA4 and traps in cold.6 at 0x1E6EE647C.
-New opt-in `dyld-exp-ios16_mach_ports_lookup` rewrites only the bounded
-388-byte client at 0x1C5FFC078 in libsystem_kernel. The generated ARM64 payload
-decodes the modern fixed-three-descriptor reply and allocates the old public
-port array. Existing PC-relative request instructions stay in place; saved
-registers keep their FP-relative unwind locations. Reply IDs, sizes and port
-dispositions are checked, and transport/allocation errors retain cleanup.
-Page hashes are re-attested; the normal dyld undo log restores original bytes
-on opt-out. Initial real-cache dry run resolves the site and fits exactly;
-normal-boot validation is pending.
-
-The cache client passes a real boot: libxpc initializes, services spawn and
-vphoned answers RPC. All 70 patch-model tests pass. Offline application,
-idempotence and undo were checked against a full cache copy; the affected
-chunk matches its pristine input byte-for-byte after undo, including hashes.
-SpringBoard now waits on backboardd, whose startup queue waits in
-`_DMPerformMigration` at +300. The migrator itself waits while PreBoard runs;
-SEP keybag errors appear on serial. Opt-in
-`system-backboard-exp-ios16_migration` injects a process/version-scoped library
-into backboardd. The measured method is DMClientAPIController's
-`_migrateWithConnection:checkNecessity:lastRelevantPlugin:testMigrationInfrastructureOnly:`
-with encoding `B40@0:8@16B24@28B36`; the lab hook returns YES to release only
-this startup wait. It does not unlock the keybag or mark global migration
-complete. Removal restores the backed-up executable and removes its library.
-This is a fresh-lab desktop experiment, not general data-migration support.
-
-The non-waiting system-shell check-in releases SpringBoard's
-FBSystemShellInitialize. Its next main-thread wait is MediaExperience's system
-controller because mediaserverd repeatedly exits before main with
-OS_REASON_EXEC/EXEC_EXIT_REASON_SECURITY_POLICY (8). Two temporary copies
-isolate the failure: re-signing with the complete original entitlements still
-gets SIGKILL; removing only `seatbelt-profiles` reaches executable code and
-then aborts when its unmanaged probe cannot register the real service's XPC
-endpoints. New opt-in `system-mediaserver-exp-ios16_profile` re-signs only
-mediaserverd without this legacy profile entitlement, preserving its remaining
-entitlements and its pristine backup. This deliberately removes that guest
-service's sandbox profile in a fresh experimental VM; it is not a sandbox
-compatibility implementation. Opt-out restores the original signed binary.
-
-The managed media daemon next aborts before dyld maps images:
-LIBIGNITION (35), code 2, "failed to close filesystem [optional]: fd = 3: 1".
-The actual installed binary and original UUIDs were inspected on a stopped,
-read-only disk mount. The 20G81 standalone dyld's `_closefd_optional` at
-0x671A8 calls close at 0x671D8, branches to its fatal path at 0x67200 on any
-error, and reports exactly this message. New opt-in
-`system-dyld-exp-ios16_closefd` rewrites only that bounded 60-byte cold block:
-EPERM on FD 3 returns through the existing cleanup; all other errors and FDs
-retain ignition_halt with the original reason, errno, flags and diagnostic.
-It leaves that optional descriptor open rather than defeating its kernel guard.
-The payload uses native encoders, is byte-idempotent on the real dyld, and is
-restored from the standard executable backup on opt-out. Guest retest pending.
-
-The standalone-only guest test still reaches the same ignition abort. The
-shared cache also contains `/usr/lib/dyld`; its `_closefd_optional` resolves to
-0x1A66361A8 and the cold block to 0x1A6636200. Paired opt-in
-`dyld-exp-ios16_closefd` applies the same native payload builder there and
-records the 60 original bytes in the normal cache undo log. Real-cache apply,
-idempotence and undo pass; chunk .11 is identical to pristine after undo.
-A Capstone-driven guard check confirms only FD 3/EPERM reaches the optional
-return; FD 0/4 with EPERM and FD 3 with errno 0/2/9 retain the fatal path.
-
-The paired guest test advances past FD 3 and now reports the same EPERM while
-closing the optional OS cryptex FD 5. The compatibility guard is therefore
-expanded to optional descriptors >=3 on EPERM; stdin/stdout/stderr and every
-other errno retain the native failure. The kernel's close guard remains in
-force, and these optional boot descriptors remain open. This avoids special
-casing a series of filesystem/cryptex handles by arbitrary assigned numbers.
-
-The next real boot passes optional filesystem and OS cryptex closes, and now
-fails on the mandatory shared-cache FD 7. The same shape-checked, 60-byte cold
-handler is applied to both `_closefd_optional` (cold +0x58) and `_closefd`
-(cold +0x54), with their distinct native success returns. This remains limited
-to dyld's boot-resource helpers, EPERM and descriptors above stderr; it does not
-change the general close syscall. Both sites are validated before cache writes.
-The exact-symbol mode added to MachOParser prevents `_closefd` from matching
-`_closefd_optional` by substring. The two original runs and hashes remain
-reversible through the normal backup/undo mechanisms.
-
-With both close helpers adapted, mediaserverd reaches SIGABRT in early process
-initialization instead of LIBIGNITION. No post-initialization hook trace appears.
-An explicit weak load of SystemHook is included in the experimental media-profile
-selection. A temporary C++ throw interposer interfered with other guest services
-and was removed. A speculative platform/no-container/no-sandbox entitlement
-test was also reverted. Native exception-port tracing instead locates the
-pre-constructor failure. No iOS 16 desktop success is claimed yet.
-
-The native inherited EXC_CRASH port captures the actual early media abort:
-`abort <- cc_abort <- ccrng_getentropy_generate <- ccrng_process_init <-
-arc4random_buf <- libobjc initialization`. The 20G81 function at 0x1E6E30FF0
-calls getentropy at +0x34, branches on -1 at +0x3C, and aborts at +0x68.
-An independent native C probe successfully calls getentropy and arc4random_buf
-as both UID 0 and UID 501, so the entropy provider is present; the failure is
-specific to the service's execution policy. Existing research notes document
-that `kernel-boot-syscallmask` misses some per-process filters.
-
-The existing opt-in `kernel-exp-frida_syscall_filter_off` is now structurally
-verified on the actual 23B85/vphone600 original: trap accessor 0xB3E1D0,
-kobject accessor 0xB3E260, MACF Unix syscall check 0x12D0640. All three are unique
-and pass the native prologue checks; the offline run emits six records. Only
-this existing Frida declaration gains cloudOS 26.1 applicability; the other
-Frida relaxations retain 26.4+. Standard remains off. Guest validation pending.
-The unsuccessful temporary C++ throw interposer and speculative extra media
-entitlements have been removed; the native crash observer is diagnostic only.
-
-The crashing media thread's measured 20G81 `__error` TLS layout reports errno 1
-(EPERM). A probe signed with the same retained media entitlements still passes
-getentropy/arc4random as UID 501. The first kernel test only changed the restore
-tree and therefore did not exercise the new patch: normal boot loads Preboot.
-`cfw update-kernel` then re-patched from FirmwareOriginals and replaced the actual
-43,997,230-byte Preboot IMG4 while preserving its manifest and every data volume.
-That replacement is the kernel validation boundary for the next boot.
-
-With the filter change actually in Preboot, `keybagd --init` can execute its
-fatal-path reboot instead of merely logging it. 20G81 lacks the newer MKB
-keybag-less platform path. Its main at 0x100015864 already has an alternative:
-the call to `os_variant_uses_ephemeral_storage` at 0x100015C4C exits successfully
-before loading a system bag. The new opt-in `system-keybag-exp-ios16_ephemeral`
-weak-loads SystemHook and installs its own marker; a C interposer selects that
-native path only for keybagd, exactly `--init`, and its exact subsystem string.
-The manifest is limited to iOS 16.6/cloudOS 26.1 and the firmware preparer still
-limits this experiment to 16.6.1/20G81. All bundled presets leave it off. Opt-out
-restores the executable backup and removes the marker. It does not create keys,
-unlock a bag, or enable passcodes. Guest validation is pending.
-
-The ephemeral keybag path passes on the real guest. mediaserverd now passes
-corecrypto and reaches its constructor, confirming the live syscall-filter
-change removes its entropy EPERM. It later crashes in CFDictionaryGetValue(NULL)
-from FigNotificationListenerStartNotifications while launchd logs denied Mach
-lookups and IOUserClient sandbox failures for that service. The media-profile
-experiment now explicitly grants platform/no-container/no-sandbox booleans along
-with removing seatbelt-profiles, retaining all other original entitlements.
-Unlike the earlier reverted attempt, this test uses the patched Preboot kernel.
-The privilege expansion is isolated to the opt-in media patch, remains guest-only,
-and reverses through the executable backup. Validation pending.
-
-The added media boolean entitlements are confirmed in the pulled guest executable
-but do not change its sandbox denials or null notification dictionary crash, so
-that speculative expansion is removed again. Restoring the original executable
-with its mediaserverd seatbelt profile still produces EXEC namespace 9/code 8.
-SpringBoard's measured main-thread wait is specifically -[AVSystemController init]
--> FigSystemControllerRemoteCreate -> synchronous XPC. The new opt-in
-system-springboard-exp-ios16_desktop weak-loads a separate, process/version-scoped
-library that returns nil from the measured @16@0:8 init method. This targets a
-desktop-only experiment; it does not claim working audio. All presets leave it
-off, and the original SpringBoard is restored by deselection. Validation pending.
-
-The first desktop-library test did not load the library: remote TASK_DYLD_INFO
-shows only SystemHook, and the pulled SpringBoard has no custom weak load. The
-later MISFix cleanup restored SpringBoard from the shared backup; its exception
-only preserved the iOS 17 desktop selection. That preservation condition now
-also covers the iOS 16 desktop selection. The native probe confirms the actual
-guest reports 16.6.1 and AVSystemController init has encoding @16@0:8.
-
-With the weak load preserved, SpringBoard passes AVSystemController startup and
-blocks building home icons in CHSWidgetDescriptorProvider's
-_lock_loadContentInitiallySynchronouslyIfNecessary. This differs from the iOS 17
-class name. A native guest probe confirms its v16@0:8 method encoding; the iOS 16
-desktop library now skips only that synchronous descriptor fetch. No functioning
-widget content is claimed.
-
-The widget guard passes: SpringBoard reaches CoverSheet construction, then waits
-in FigFlashlightRemoteCreate. The guest probe confirms AVFlashlight init @16@0:8
-and +hasFlashlight B16@0:8; the iOS 16 desktop library now returns nil/NO for these
-unavailable physical-light paths. Temporary inherited exception/signal traces,
-forced launchd console/lifecycle logging and vphoned console redirection have
-been removed. The task-port bridge retains only selected API translation.
-
-After the flashlight guard, SpringBoard reaches its main run loop but the
-Control Center Now Playing module synchronously creates a media routing context.
-Its original Info.plist identifies com.apple.mediaremote.controlcenter.nowplaying.
-The desktop library now wraps CCUIModuleInstanceManager's
-_instantiateModuleWithMetadata: and returns nil only for that exact module ID,
-forwarding every other module to its original implementation. Signature checked.
-Both dyld descriptor-close patches have been deselected and their two cached
-60-byte records and standalone dyld backup restored successfully; the guest still
-boots, confirming those EPERM workarounds are unnecessary with the live filter fix.
-
-Skipping Now Playing removes that stack. The next main-queue task comes from
-MediaControlsAudioModule, which creates the same unavailable route context via
-MRAVEndpointGetLocalEndpoint. Its original bundle ID is
-com.apple.mediaremote.controlcenter.audio; the same wrapper now omits that exact
-second media module as well. Backboardd's main thread is in its normal run loop.
-
-The second guard removes that task as well; the next stack constructs the
-system mirroring context from MediaControls and CCUIContentModuleContainerViewController.
-The original AirPlayMirroringModule ID is
-com.apple.mediaremote.controlcenter.airplaymirroring. It is the third and final
-mediaremote Control Center module in this IPSW; the wrapper now omits these three
-exact IDs. All other modules still call their original factory.
-
-All three media-module guards pass: SpringBoard's main thread is now in
-CFRunLoopRunSpecific/UIApplicationMain, with no synchronous startup blocker.
-Visual verification is pending because the host Mac is locked; the user has
-been asked to unlock it. A generic guest unlock request reports passcode_enabled
-on this fresh, keybag-less lab; no user passcode was provisioned and no passcode
-is guessed. Earlier dyld-close/media-profile experiment implementations have
-been archived outside the source tree and removed from the final declarations,
-presets and installer after successful opt-out restoration. Their unrelated
-encoder/parser additions are also reverted. Only measured startup compatibility
-remains in the source tree. No iOS 16 desktop display success is claimed yet.
-
-After host unlock, the running window is still black/0 fps. A native notify probe
-reports SpringBoard finishedstartup=31. Terminating the hung PreBoard temporarily
-allows SBSUndimScreen to change hasBlankedScreen from 1 to 0, but no frame appears.
-A native framebuffer probe successfully opens the real main display, reads
-1179x2556 and a nonzero IOConnect port. On 20G81 the public SwapEnd dispatch pointer
-is at connection+0x730 (not the later layout's +0x7C8); its value resolves exactly
-to _kern_SwapEnd at unslid 0x1B21CED04. Therefore a force-kern patch is not indicated.
-Temporary IOConnectCallStructMethod return tracing in the selected backboard
-library will measure method-5 submission rather than assuming a routing failure.
-
-No method-5 trace was observed through the temporary interposer; it is removed,
-since this alone cannot distinguish absent swaps from cached binding behavior.
-Backboard's native BKSystemShellSentinel has a separate in-memory completion gate.
-The earlier no-wait check-in did not set it. Static 20G81 analysis identifies
--dataMigratorDidComplete (0x100066834, v16@0:8), which notifies local observers,
-sets _lock_migratorDidComplete at +0x50 and updates shell state; -unblockSystemApp
-(0x1000665E0, B16@0:8) locks and clears the separate +0x51 block through the native
-helper at 0x100065134. The selected lab check-in now invokes these native methods
-once, before entering its original non-waiting check-in, with both signatures
-checked. No keybag is unlocked and no migration is actually performed. This is
-an explicit fresh-lab shell-state bypass, not evidence of data migration success.
-
-Result of the local completion/unblock experiment: still black/0 fps. The native
-main IOMFB connection and mode enumeration work, but no visible desktop or guest
-screenshot is obtained. The completion/unblock code has therefore been reverted;
-no such fake completion is retained in the final source. The missing first frame
-is unresolved. iOS 16 remains an unsuccessful desktop bring-up, despite a running
-SpringBoard, and no minimum-version compatibility claim is added.
+
+## Experimental iOS 16.6.1 desktop bring-up
+
+Measured pairing: iPhone15,2 (iPhone 14 Pro), iOS 16.6.1/20G81 userland,
+cloudOS 26.1/23B85 vphone600 boot chain. All additions below are manual opt-ins;
+shipped presets and the no-plan path leave them disabled. See
+`Research/Guest/ios16_bringup.md` for procedure, evidence and limitations.
+
+- `system-launchd-exp-ios16_mach_ports` bridges the old out-of-line self-task
+ Mach-port API to the newer fixed-three-port RPCs in the native launch hooks.
+ `dyld-exp-ios16_mach_ports_lookup` updates the old libxpc client's pre-constructor
+ lookup through a symbol-derived, bounded cache patch with undo capture.
+- `system-backboard-exp-ios16_migration` skips the fresh lab's measured migration
+ wait and releases its local shell sentinel/PreBoard re-block. It does not
+ migrate existing user data or persist completion. `system-springboard-exp-ios16_desktop`
+ avoids unavailable startup media, widget and flashlight services and uses the
+ native local setup-state setter. These services remain unavailable.
+- `system-systemhook-exp-ios16_surface` converts capability replies 0x28 ->
+ 0x18 and allocation/lookup replies 0xC68 -> 0xA68, including narrowed fields
+ and the changed plane stride. Offline metadata derives the framework-private
+ transport stub, verifies its instruction pattern and records its Mach-O UUID.
+ The runtime detour checks UUID/expected bytes, suspends peer threads, uses
+ private COW memory without writable executable pages, and restores protection.
+- `system-systemhook-exp-ios16_framebuffer` translates the measured old 0x46C
+ SwapEnd payload into the modern 0x560 layout. It inserts the new event/port
+ slots, retaining frame token, surfaces, rectangles and measured flags. Native
+ create/lock/write/read/unlock and surface lookup probes pass; submitted color
+ bars and the real SpringBoard desktop are visible.
+- `preboot-exp-ios16_ephemeral_storage` changes only the existing chosen/product
+ ephemeral-storage fields, preserving their widths and tree size. Native
+ `hw.ephemeral_storage` and `os_variant_uses_ephemeral_storage` then report 1;
+ PreBoard no longer owns the shell. Restore pre-ephemeral snapshots to undo
+ guest data effects; restoring device-tree bits alone is insufficient.
+- `system-vphoned-exp-ios16_touchscreen` registers a built-in HID touchscreen
+ only when none exists. With desktop startup selected, native backlight-state
+ changes also publish the legacy HID factor. Real mouse swipes and clicks now
+ reach the guest rather than being dropped as missing-digitizer/display-off.
+- `system-springboard-exp-ios16_keybagless_ui` is restricted to a fresh ephemeral
+ lab. The root daemon requires explicit markers and a strict session/persona
+ keybag-directory allowlist before publishing a single-link, root-owned,
+ magic-checked lease. Three signature-checked UI getters honor that lease for
+ at most three seconds and otherwise forward to native. MKB/AKS and encrypted
+ data remain unchanged; this is not working credentials or protected storage.
+- The existing battery helper weak-imports the unavailable newer precise-power
+ API and falls back to its existing ByType API. This resolves the measured
+ Preferences pre-main dyld crash without synthesizing an IOKit export.
+
+The real guest displays Home Screen, accepts mouse input and opens Settings >
+General > About (16.6.1, iPhone 14 Pro, 64 GB). Initial About lookup can wait for
+IOKit/SystemConfiguration quiescence; a proposed fallback was never deployed and
+is excluded. Wallpaper preview fails without Metal; its cancelled, unvalidated
+prototype is excluded as well. No general iOS 16/15, Metal, full audio, camera,
+networking or persistent protected-data compatibility is claimed.
diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swift
index 5a2e5e6d..499ae7cd 100644
--- a/VPhoneDaemon/Daemon/main.swift
+++ b/VPhoneDaemon/Daemon/main.swift
@@ -34,6 +34,8 @@ GuestHomePodDisplay.startOnStartup()
// Multi-finger injection is resolved here so the first pinch is not the call
// that pays for `dlopen`; a base without the symbols logs and stays a no-op.
_ = vp_hid_load()
+vp_ios16_touchscreen_start()
+vp_ios16_keybagless_ui_start()
// The VM's touchscreen has no wake gesture; a tap on a dark screen lights it.
GuestScreenUnlock.startTapToWake()
GuestIrisinInstaller.refreshBootstrapOnStartup()
diff --git a/VPhoneDaemon/Native/Include/VPhoneIOS16LabPolicy.h b/VPhoneDaemon/Native/Include/VPhoneIOS16LabPolicy.h
new file mode 100644
index 00000000..ea39f3f3
--- /dev/null
+++ b/VPhoneDaemon/Native/Include/VPhoneIOS16LabPolicy.h
@@ -0,0 +1,33 @@
+#ifndef VPHONE_IOS16_LAB_POLICY_H
+#define VPHONE_IOS16_LAB_POLICY_H
+#include <stdbool.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#define VP_IOS16_KEYBAGLESS_SELECTION "/usr/lib/vphone-ios16-keybagless-ui"
+#define VP_IOS16_KEYBAGLESS_ATTESTATION "/private/var/run/vphone-ios16-keybagless-ui"
+#define VP_IOS16_KEYBAGLESS_MAGIC "VPKEYLESS1\n"
+
+// Root refreshes this short lease only while it can verify that the ephemeral
+// lab has no persistent system keybag. Mobile cannot inspect that directory.
+static inline bool vp_ios16_lab_lease_valid(const struct stat *s, time_t now) {
+ return S_ISREG(s->st_mode) && s->st_uid == 0 && s->st_nlink == 1 &&
+ !(s->st_mode & 022) && s->st_size == sizeof(VP_IOS16_KEYBAGLESS_MAGIC) - 1 &&
+ now >= s->st_mtime && now - s->st_mtime <= 3;
+}
+
+static inline bool vp_ios16_keybagless_ui_attested(void) {
+ int fd = open(VP_IOS16_KEYBAGLESS_ATTESTATION, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd < 0) return false;
+ struct stat s;
+ char bytes[sizeof(VP_IOS16_KEYBAGLESS_MAGIC) - 1];
+ bool valid = fstat(fd, &s) == 0 && vp_ios16_lab_lease_valid(&s, time(NULL)) &&
+ read(fd, bytes, sizeof(bytes)) == (ssize_t)sizeof(bytes) &&
+ memcmp(bytes, VP_IOS16_KEYBAGLESS_MAGIC, sizeof(bytes)) == 0;
+ close(fd);
+ return valid;
+}
+#endif
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index 72513dc0..68328533 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -105,6 +105,10 @@ char * _Null_unspecified vp_homeview_distance_copy_json(const char * _Null_unspe
/// safe to call more than once; returns false (injection then stays a no-op)
/// on bases that do not expose the private symbols.
bool vp_hid_load(void);
+/// Register the opt-in iOS 16 lab's missing main touchscreen service.
+void vp_ios16_touchscreen_start(void);
+/// Maintain the explicitly selected fresh ephemeral lab's UI-only lease.
+void vp_ios16_keybagless_ui_start(void);
/// A keyboard/consumer hold transition, including KeyboardLongPress on release.
bool vp_hid_keyboard_hold(uint16_t page, uint16_t usage, bool down);
diff --git a/VPhoneDaemon/Native/vphoned_ios16_keybagless.m b/VPhoneDaemon/Native/vphoned_ios16_keybagless.m
new file mode 100644
index 00000000..9612683c
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_ios16_keybagless.m
@@ -0,0 +1,72 @@
+#import "Include/VphonedNative.h"
+#import "Include/VPhoneIOS16LabPolicy.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <sys/sysctl.h>
+
+static dispatch_source_t gIOS16LabLease;
+
+static bool lab_has_only_ephemeral_bags(void) {
+ int ephemeral = 0;
+ size_t size = sizeof(ephemeral);
+ if (getuid() != 0 || access(VP_IOS16_KEYBAGLESS_SELECTION, F_OK) != 0 ||
+ access("/usr/lib/vphone-ios16-keybag-ephemeral", F_OK) != 0 ||
+ sysctlbyname("hw.ephemeral_storage", &ephemeral, &size, NULL, 0) != 0 || ephemeral != 1) return false;
+ int fd = open("/private/var/keybags", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd < 0) return false;
+ struct stat directory;
+ if (fstat(fd, &directory) != 0 || directory.st_uid != 0 || (directory.st_mode & 022)) {
+ close(fd);
+ return false;
+ }
+ DIR *entries = fdopendir(fd);
+ if (!entries) { close(fd); return false; }
+ bool fresh = true;
+ struct dirent *entry;
+ errno = 0;
+ while ((entry = readdir(entries))) {
+ if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
+ // The measured ephemeral boot creates only these session/persona bags.
+ // A system bag, backup, lockout file, symlink or unknown entry refuses
+ // UI-only mode. Never read or modify any key material.
+ struct stat file;
+ if ((strcmp(entry->d_name, "persona.kb") && strcmp(entry->d_name, "usersession.kb")) ||
+ fstatat(fd, entry->d_name, &file, AT_SYMLINK_NOFOLLOW) != 0 ||
+ !S_ISREG(file.st_mode) || file.st_uid != 0 || (file.st_mode & 022)) { fresh = false; break; }
+ }
+ if (errno != 0) fresh = false;
+ closedir(entries);
+ return fresh;
+}
+
+static void refresh_lab_lease(void) {
+ if (!lab_has_only_ephemeral_bags()) {
+ unlink(VP_IOS16_KEYBAGLESS_ATTESTATION);
+ return;
+ }
+ char temporary[] = VP_IOS16_KEYBAGLESS_ATTESTATION ".XXXXXX";
+ int fd = mkstemp(temporary);
+ if (fd < 0) return;
+ const char magic[] = VP_IOS16_KEYBAGLESS_MAGIC;
+ bool ready = write(fd, magic, sizeof(magic) - 1) == (ssize_t)sizeof(magic) - 1 && fchmod(fd, 0644) == 0;
+ close(fd);
+ if (ready) rename(temporary, VP_IOS16_KEYBAGLESS_ATTESTATION);
+ unlink(temporary);
+}
+
+void vp_ios16_keybagless_ui_start(void) {
+ NSOperatingSystemVersion version = NSProcessInfo.processInfo.operatingSystemVersion;
+ if (version.majorVersion != 16 || version.minorVersion != 6 ||
+ access(VP_IOS16_KEYBAGLESS_SELECTION, F_OK) != 0) return;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ refresh_lab_lease();
+ dispatch_queue_t queue = dispatch_queue_create("com.vphone.vphoned.ios16-lab-lease", DISPATCH_QUEUE_SERIAL);
+ gIOS16LabLease = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
+ dispatch_source_set_timer(gIOS16LabLease, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC),
+ NSEC_PER_SEC, NSEC_PER_SEC / 10);
+ dispatch_source_set_event_handler(gIOS16LabLease, ^{ refresh_lab_lease(); });
+ dispatch_resume(gIOS16LabLease);
+ });
+}
diff --git a/VPhoneDaemon/Native/vphoned_ios16_touchscreen.m b/VPhoneDaemon/Native/vphoned_ios16_touchscreen.m
new file mode 100644
index 00000000..c5eb365c
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_ios16_touchscreen.m
@@ -0,0 +1,64 @@
+#import "Include/VphonedNative.h"
+
+#include <dlfcn.h>
+#include <unistd.h>
+
+// 20G81 backboardd routes accessibility digitizer events through its main
+// touchscreen. The VZ touchscreen's newer DriverKit driver cannot start on
+// this base, leaving that service absent. Register a HID touchscreen so the
+// normal, unchanged touch/edge/multi-finger injection has a native route.
+// No reports are synthesized here; the device exists for vphoned's lifetime.
+static CFTypeRef gIOS16Touchscreen;
+static const uint8_t touchscreenDescriptor[] = {
+ 0x05, 0x0d, 0x09, 0x04, 0xa1, 0x01, 0x85, 0x01, // Touchscreen, report 1.
+ 0x09, 0x22, 0xa1, 0x02, // Finger.
+ 0x09, 0x42, 0x09, 0x32, 0x15, 0x00, 0x25, 0x01,
+ 0x75, 0x01, 0x95, 0x02, 0x81, 0x02, // Tip switch and range.
+ 0x75, 0x06, 0x95, 0x01, 0x81, 0x03, // Padding.
+ 0x09, 0x51, 0x15, 0x00, 0x25, 0x7f,
+ 0x75, 0x08, 0x95, 0x01, 0x81, 0x02, // Contact identifier.
+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31,
+ 0x15, 0x00, 0x26, 0xff, 0x7f,
+ 0x75, 0x10, 0x95, 0x02, 0x81, 0x02, 0xc0, // Absolute X and Y.
+ 0x05, 0x0d, 0x09, 0x54, 0x15, 0x00, 0x25, 0x01,
+ 0x75, 0x08, 0x95, 0x01, 0x81, 0x02, 0xc0, // Contact count.
+};
+
+void vp_ios16_touchscreen_start(void) {
+ NSOperatingSystemVersion version = NSProcessInfo.processInfo.operatingSystemVersion;
+ if (version.majorVersion != 16 || version.minorVersion != 6 ||
+ access("/usr/lib/vphone-ios16-touchscreen", F_OK) != 0) return;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ void *ioKit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);
+ void *(*createDevice)(CFAllocatorRef, CFDictionaryRef) = ioKit ? dlsym(ioKit, "IOHIDUserDeviceCreate") : NULL;
+ void *(*createClient)(CFAllocatorRef) = ioKit ? dlsym(ioKit, "IOHIDEventSystemClientCreate") : NULL;
+ CFArrayRef (*copyServices)(const void *) = ioKit ? dlsym(ioKit, "IOHIDEventSystemClientCopyServices") : NULL;
+ CFTypeRef (*copyProperty)(const void *, CFStringRef) = ioKit ? dlsym(ioKit, "IOHIDServiceClientCopyProperty") : NULL;
+ if (!createDevice || !createClient || !copyServices || !copyProperty) return;
+ void *client = createClient(kCFAllocatorDefault);
+ if (!client) return;
+ CFArrayRef services = copyServices(client);
+ BOOL alreadyPresent = NO;
+ for (CFIndex index = 0; services && index < CFArrayGetCount(services); index++) {
+ const void *service = CFArrayGetValueAtIndex(services, index);
+ NSNumber *page = CFBridgingRelease(copyProperty(service, CFSTR("PrimaryUsagePage")));
+ NSNumber *usage = CFBridgingRelease(copyProperty(service, CFSTR("PrimaryUsage")));
+ if ([page isKindOfClass:NSNumber.class] && [usage isKindOfClass:NSNumber.class] &&
+ page.unsignedIntValue == 13 && usage.unsignedIntValue == 4) alreadyPresent = YES;
+ }
+ if (services) CFRelease(services);
+ CFRelease(client);
+ if (alreadyPresent) return;
+ NSDictionary *properties = @{
+ @"ReportDescriptor": [NSData dataWithBytes:touchscreenDescriptor length:sizeof(touchscreenDescriptor)],
+ @"VendorID": @0x05ac, @"ProductID": @0x7651,
+ @"Product": @"vphone iOS 16 lab touchscreen",
+ @"SerialNumber": [NSString stringWithFormat:@"%d", getpid()],
+ @"Transport": @"USB", @"PrimaryUsagePage": @13, @"PrimaryUsage": @4,
+ @"Built-In": @YES, @"DisplayIntegrated": @YES,
+ };
+ gIOS16Touchscreen = createDevice(kCFAllocatorDefault, (__bridge CFDictionaryRef)properties);
+ NSLog(@"vphoned: iOS 16 lab touchscreen %@", gIOS16Touchscreen ? @"registered" : @"unavailable");
+ });
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
index f68f929b..545cb272 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
@@ -66,6 +66,36 @@ public enum CustomFirmwarePostRestoreDeviceTree {
// MARK: - File-level patching
+ @discardableResult
+ public static func presentIOS16EphemeralStorage(at url: URL, dryRun: Bool = false) throws -> Outcome {
+ try rewrite(at: url, dryRun: dryRun, verbose: true) { blob in
+ let (result, changes) = try withIOS16EphemeralStorage(blob)
+ return (result, changes, blob.count)
+ }
+ }
+
+ /// Native XNU hw.ephemeral_storage and the corresponding MobileGestalt
+ /// product answer, for an explicitly selected fresh, keybag-less lab.
+ /// Existing slots only: no topology, size, root identity or disk edit.
+ public static func withIOS16EphemeralStorage(_ blob: Data) throws -> (Data, [Change]) {
+ let root = try parseTree(blob, label: "DT")
+ var changes: [Change] = []
+ for (nodeName, propertyName) in [("chosen", "ephemeral-storage"), ("product", "ephemeral-data-mode")] {
+ let nodes = root.children.filter { child in
+ child.properties.contains { $0.name == "name" && String(decoding: $0.value.prefix(while: { $0 != 0 }), as: UTF8.self) == nodeName }
+ }
+ guard nodes.count == 1, let property = nodes.first?.properties.first(where: { $0.name == propertyName }),
+ (nodeName == "chosen" ? [4] : [4, 8]).contains(property.value.count),
+ property.value.dropFirst().allSatisfy({ $0 == 0 }), property.value.first.map({ $0 <= 1 }) == true
+ else { throw PatcherError.patchVerificationFailed("iOS 16 ephemeral storage: unknown \(nodeName)/\(propertyName) slot") }
+ if property.value.first == 0 {
+ property.value[0] = 1
+ changes.append(Change(property: "\(nodeName)/\(propertyName)", before: "0", after: "1"))
+ }
+ }
+ return (changes.isEmpty ? blob : serializeNode(root), changes)
+ }
+
/// Patch a `devicetree.img4` (preferred) or bare `devicetree.im4p` in place.
@discardableResult
public static func patch(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOS16SurfaceAdapter.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOS16SurfaceAdapter.swift
new file mode 100644
index 00000000..35f24545
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOS16SurfaceAdapter.swift
@@ -0,0 +1,80 @@
+import Foundation
+import MachO
+import VPhonePatchKit
+
+/// Describes one private COW stub detour; the on-disk cache is not modified.
+/// The native bridge translates IOSurfaceRoot's widened 26.1 replies to 20G81.
+public enum DyldSharedCacheIOS16SurfaceAdapter {
+ public static let image = "/System/Library/Frameworks/IOSurface.framework/IOSurface"
+
+ public static func metadata(directory: URL) throws -> Data {
+ try prepare(directory: directory, image: image, anchorName: "_IOSurfaceCreate",
+ entryName: "_IOSurfaceClientCreateChild", methodName: "_IOConnectCallMethod", surface: true)
+ }
+
+ public static func swapMetadata(directory: URL) throws -> Data {
+ try prepare(directory: directory,
+ image: "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer",
+ anchorName: "_IOMobileFramebufferSwapEnd", entryName: "_kern_SwapEnd",
+ methodName: "_IOConnectCallStructMethod", surface: false)
+ }
+
+ private static func prepare(directory: URL, image: String, anchorName: String,
+ entryName: String, methodName: String, surface: Bool) throws -> Data {
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)
+ let anchor = try resolver.address(of: anchorName, inImage: image)
+ let create = try resolver.address(of: entryName, inImage: image)
+ let method = try resolver.address(of: methodName, inImage: "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit")
+ let decoder = ARM64Disassembler()
+ let body = decoder.disassemble(try chunks.readAtVMA(create, length: 512), at: create)
+ guard body.contains(where: {
+ $0.mnemonic == "mov" && $0.detail?.operands.first?.reg.name == (surface ? "w8" : "w3") &&
+ (surface ? [Int64(0xA68)] : [Int64(0x46C), Int64(0x560)]).contains($0.detail?.operands.last?.imm ?? -1)
+ }) else { throw PatcherError.patchSiteNotFound("IOSurface: legacy lock-result size not found") }
+ var candidates = Set<UInt64>()
+ for call in body where call.mnemonic == "bl" {
+ guard let operand = call.detail?.operands.first, operand.type == .immediate else { continue }
+ let target = UInt64(bitPattern: operand.imm)
+ let stub = decoder.disassemble(try chunks.readAtVMA(target, length: 16), at: target)
+ guard stub.count == 4, stub[0].mnemonic == "adrp", stub[1].mnemonic == "add",
+ stub[2].mnemonic == "br", stub[3].mnemonic == "brk",
+ let page = stub[0].detail?.operands, page.count == 2,
+ page[0].reg.name == "x16", page[1].type == .immediate,
+ let add = stub[1].detail?.operands, add.count == 3,
+ add[0].reg.name == "x16", add[1].reg.name == "x16", add[2].type == .immediate,
+ stub[2].detail?.operands.first?.reg.name == "x16",
+ UInt64(bitPattern: page[1].imm) + UInt64(add[2].imm) == method else { continue }
+ candidates.insert(target)
+ }
+ guard candidates.count == 1, let stub = candidates.first,
+ let load = ARM64Encoder.encodeLdrXLiteral(rt: 16, from: 0, to: 8),
+ let branch = ARM64Encoder.encodeBR(rn: 16)
+ else { throw PatcherError.patchSiteNotFound("IOSurface: unique direct IOKit transport stub not found") }
+
+ // Bind the metadata to the exact framework UUID, not a global cache slide.
+ let header = try resolver.headerAddress(ofImage: image)
+ let commands = try chunks.readAtVMA(header, length: 0x4000)
+ func word(_ offset: Int) -> UInt32 { commands.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: offset, as: UInt32.self).littleEndian } }
+ guard word(0) == MH_MAGIC_64, word(20) <= 0x4000 - 32 else {
+ throw PatcherError.patchVerificationFailed("IOSurface load-command bounds")
+ }
+ var uuid: Data?
+ var cursor = 32
+ let end = cursor + Int(word(20))
+ for _ in 0..<word(16) {
+ guard cursor + 8 <= end else { throw PatcherError.patchVerificationFailed("IOSurface command header") }
+ let size = Int(word(cursor + 4))
+ guard size >= 8, cursor + size <= end else { throw PatcherError.patchVerificationFailed("IOSurface command size") }
+ if word(cursor) == LC_UUID, size == 24 { uuid = commands.subdata(in: cursor + 8..<cursor + 24) }
+ cursor += size
+ }
+ guard let uuid else { throw PatcherError.patchVerificationFailed("IOSurface UUID missing") }
+ var result = Data("VPIS16\u{1}\0".utf8) // eight-byte versioned header
+ var displacement = (Int64(stub) - Int64(anchor)).littleEndian
+ withUnsafeBytes(of: &displacement) { result.append(contentsOf: $0) }
+ result.append(try chunks.readAtVMA(stub, length: 16))
+ result.append(load); result.append(branch); result.append(uuid)
+ return result
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 5bd78d99..483ffcba 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -30,6 +30,15 @@ public enum FirmwareGuestSystemPatchSet {
public static let ios16Migration = "system-backboard-exp-ios16_migration"
public static let ios16Desktop = "system-springboard-exp-ios16_desktop"
public static let ios16Keybag = "system-keybag-exp-ios16_ephemeral"
+ public static let ios16Surface = "system-systemhook-exp-ios16_surface"
+ public static let ios16SurfaceMarker = "/usr/lib/vphone-ios16-surface"
+ public static let ios16Framebuffer = "system-systemhook-exp-ios16_framebuffer"
+ public static let ios16FramebufferMarker = "/usr/lib/vphone-ios16-framebuffer"
+ public static let ios16EphemeralStorage = "preboot-exp-ios16_ephemeral_storage"
+ public static let ios16Touchscreen = "system-vphoned-exp-ios16_touchscreen"
+ public static let ios16TouchscreenMarker = "/usr/lib/vphone-ios16-touchscreen"
+ public static let ios16KeybaglessUI = "system-springboard-exp-ios16_keybagless_ui"
+ public static let ios16KeybaglessUIMarker = "/usr/lib/vphone-ios16-keybagless-ui"
public static let ios16KeybagMarker = "/usr/lib/vphone-ios16-keybag-ephemeral"
public static let ios16MachPortsMarker = "/usr/lib/vphone-ios16-mach-ports"
public static let metalCacheReuse = "system-systemhook-cfw-metal_cache_reuse"
@@ -105,10 +114,45 @@ public enum FirmwareGuestSystemPatchSet {
name: "Guest System",
summary: "Shared-cache policy gates, patched system daemons and the vphone guest payload",
patches: [
+ VPhonePatchDeclaration(
+ identifier: ios16EphemeralStorage,
+ title: "iOS 16 fresh-lab ephemeral storage",
+ summary: "Declares temporary storage through the existing chosen and product device-tree flags. Tests the native keybag-less platform path; user preferences may not persist. Fresh labs only, experimental and off by default.",
+ target: .prebootDeviceTree,
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
+ ),
+ VPhonePatchDeclaration(
+ identifier: ios16Framebuffer,
+ title: "iOS 16 lab framebuffer transport",
+ summary: "Translates iOS 16's frame token, surfaces, rectangles and verified flags into cloudOS 26.1's swap layout. New event fields stay zero. Experimental, off by default; restart after changing.",
+ target: .guestFile(path: ios16FramebufferMarker),
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
+ ),
+ VPhonePatchDeclaration(
+ identifier: ios16Surface,
+ title: "iOS 16 lab IOSurface transport",
+ summary: "Adapts the widened IOSurfaceRoot capability and allocation replies to iOS 16's layout through a UUID-checked, private runtime stub. Experimental, off by default; restart after changing.",
+ target: .guestFile(path: ios16SurfaceMarker),
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
+ ),
+ VPhonePatchDeclaration(
+ identifier: ios16KeybaglessUI,
+ title: "iOS 16 fresh keybag-less lab UI",
+ summary: "Enables UI-only desktop testing while root verifies ephemeral storage and no persistent keybag. Does not unlock encrypted storage or provide passcode support. Requires desktop startup; experimental, off by default.",
+ target: .guestFile(path: ios16KeybaglessUIMarker),
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
+ ),
+ VPhonePatchDeclaration(
+ identifier: ios16Touchscreen,
+ title: "iOS 16 lab touchscreen service",
+ summary: "Registers a built-in HID touchscreen when the lab has none and, with desktop startup, mirrors native backlight states to legacy HID. Experimental, off by default.",
+ target: .guestFile(path: ios16TouchscreenMarker),
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
+ ),
VPhonePatchDeclaration(
identifier: ios16Desktop,
title: "iOS 16 lab desktop startup",
- summary: "Skips SpringBoard's unavailable audio controller, widget descriptor fetch and virtual flashlight startup waits. Audio, widget content and flashlight remain unavailable. Experimental, off by default.",
+ summary: "Skips unavailable media/widget/flashlight waits and keeps Setup mode off in the fresh lab's local shell state. Audio and widgets remain unavailable; no setup preference is persisted. Experimental, off by default.",
target: .guestExecutable(path: "/System/Library/CoreServices/SpringBoard.app/SpringBoard"),
applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
),
@@ -122,9 +166,9 @@ public enum FirmwareGuestSystemPatchSet {
VPhonePatchDeclaration(
identifier: ios16Migration,
title: "iOS 16 lab startup migration wait",
- summary: "Skips backboardd's blocking first-boot migration call on a fresh iOS 16 lab guest. Does not complete data migration or unlock the keybag. Experimental, off by default.",
+ summary: "Skips the fresh lab's migration wait, clears the local shell sentinel and omits its measured PreBoard-only re-block. Does not migrate user data, persist migration completion or unlock the keybag. Experimental, off by default.",
target: .guestExecutable(path: "/usr/libexec/backboardd"),
- applicability: VPhonePatchApplicability(iOSBase: .major(16)),
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 16, minor: 6), cloudOS: .release(major: 26, minor: 1)),
),
VPhonePatchDeclaration(
identifier: ios16PortsLookup,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 94df2a86..7a20fbd2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -68,7 +68,7 @@ public enum FirmwarePatchSetCatalog {
Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier))
.union(hypervisorConcealmentPatches)
.union(experimentalIdentityPatches)
- .union([FirmwareGuestSystemPatchSet.homeViewEnvironmentService, FirmwareGuestSystemPatchSet.ios17Desktop, FirmwareGuestSystemPatchSet.ios16MachPorts, FirmwareGuestSystemPatchSet.ios16Desktop, FirmwareGuestSystemPatchSet.ios16Keybag, FirmwareGuestSystemPatchSet.ios16Migration, FirmwareGuestSystemPatchSet.ios16PortsLookup])
+ .union([FirmwareGuestSystemPatchSet.homeViewEnvironmentService, FirmwareGuestSystemPatchSet.ios17Desktop, FirmwareGuestSystemPatchSet.ios16MachPorts, FirmwareGuestSystemPatchSet.ios16KeybaglessUI, FirmwareGuestSystemPatchSet.ios16Touchscreen, FirmwareGuestSystemPatchSet.ios16EphemeralStorage, FirmwareGuestSystemPatchSet.ios16Framebuffer, FirmwareGuestSystemPatchSet.ios16Surface, FirmwareGuestSystemPatchSet.ios16Desktop, FirmwareGuestSystemPatchSet.ios16Keybag, FirmwareGuestSystemPatchSet.ios16Migration, FirmwareGuestSystemPatchSet.ios16PortsLookup])
.union([FirmwareGuestSystemPatchSet.homeViewProfileLookup, FirmwareGuestSystemPatchSet.homeViewDisplayLookups, FirmwareGuestSystemPatchSet.homeViewSetupBypass, FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall])
.union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.tvLegacySetup])
@@ -233,7 +233,7 @@ public enum FirmwarePatchSetCatalog {
freshly restored 26.4 guest does not survive. The HomePod-only top cap is off.
""",
patchSets: bundledReferences,
- selection: .block([FirmwareGuestSystemPatchSet.ios16Desktop, FirmwareGuestSystemPatchSet.ios16Keybag, FirmwareGuestSystemPatchSet.ios16Migration, FirmwareGuestSystemPatchSet.ios16PortsLookup, FirmwareGuestSystemPatchSet.ios16MachPorts, FirmwareGuestSystemPatchSet.ios17Desktop, FirmwareGuestSystemPatchSet.homeViewEnvironmentService, FirmwareGuestSystemPatchSet.homeViewProfileLookup, FirmwareGuestSystemPatchSet.homeViewDisplayLookups, FirmwareGuestSystemPatchSet.homeViewSetupBypass, FirmwareGuestSystemPatchSet.tvLegacySetup, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]),
+ selection: .block([FirmwareGuestSystemPatchSet.ios16KeybaglessUI, FirmwareGuestSystemPatchSet.ios16Touchscreen, FirmwareGuestSystemPatchSet.ios16EphemeralStorage, FirmwareGuestSystemPatchSet.ios16Framebuffer, FirmwareGuestSystemPatchSet.ios16Surface, FirmwareGuestSystemPatchSet.ios16Desktop, FirmwareGuestSystemPatchSet.ios16Keybag, FirmwareGuestSystemPatchSet.ios16Migration, FirmwareGuestSystemPatchSet.ios16PortsLookup, FirmwareGuestSystemPatchSet.ios16MachPorts, FirmwareGuestSystemPatchSet.ios17Desktop, FirmwareGuestSystemPatchSet.homeViewEnvironmentService, FirmwareGuestSystemPatchSet.homeViewProfileLookup, FirmwareGuestSystemPatchSet.homeViewDisplayLookups, FirmwareGuestSystemPatchSet.homeViewSetupBypass, FirmwareGuestSystemPatchSet.tvLegacySetup, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]),
)
/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
index 49487f7e..593d2983 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
@@ -82,6 +82,8 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {
VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand.self,
VPhoneCustomFirmwarePatchIOMFBSwapEndCommand.self,
VPhoneCustomFirmwarePatchIOS16MachPortsCommand.self,
+ VPhoneCustomFirmwarePrepareIOS16SurfaceCommand.self,
+ VPhoneCustomFirmwarePrepareIOS16FramebufferCommand.self,
VPhoneCustomFirmwarePatchIOMFBForceKernCommand.self,
VPhoneCustomFirmwarePatchDyldSharedCacheMaxSlideCommand.self,
VPhoneCustomFirmwarePatchLSDEmbeddedRegCommand.self,
@@ -331,6 +333,32 @@ struct VPhoneCustomFirmwarePatchIOMFBForceKernCommand: ParsableCommand {
}
}
+struct VPhoneCustomFirmwarePrepareIOS16FramebufferCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "prepare-ios16-framebuffer",
+ abstract: "Prepare UUID-checked runtime metadata for the iOS 16 framebuffer adapter"
+ )
+ @Argument(transform: URL.init(fileURLWithPath:)) var chunksDirectory: URL
+ @Argument(transform: URL.init(fileURLWithPath:)) var output: URL
+ func run() throws {
+ let metadata = try DyldSharedCacheIOS16SurfaceAdapter.swapMetadata(directory: chunksDirectory)
+ try metadata.write(to: output, options: .atomic)
+ }
+}
+
+struct VPhoneCustomFirmwarePrepareIOS16SurfaceCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "prepare-ios16-surface",
+ abstract: "Prepare UUID-checked runtime metadata for the iOS 16 IOSurface adapter"
+ )
+ @Argument(transform: URL.init(fileURLWithPath:)) var chunksDirectory: URL
+ @Argument(transform: URL.init(fileURLWithPath:)) var output: URL
+ func run() throws {
+ let metadata = try DyldSharedCacheIOS16SurfaceAdapter.metadata(directory: chunksDirectory)
+ try metadata.write(to: output, options: .atomic)
+ }
+}
+
struct VPhoneCustomFirmwarePatchIOS16MachPortsCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "patch-ios16-mach-ports",
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 3b42a1e1..0ce88b12 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -1328,6 +1328,10 @@ struct VPhoneCustomFirmwareInstaller {
&& identifier != FirmwareGuestSystemPatchSet.ios16Migration
&& identifier != FirmwareGuestSystemPatchSet.ios16Desktop
&& identifier != FirmwareGuestSystemPatchSet.ios16Keybag
+ && identifier != FirmwareGuestSystemPatchSet.ios16Surface
+ && identifier != FirmwareGuestSystemPatchSet.ios16Framebuffer
+ && identifier != FirmwareGuestSystemPatchSet.ios16Touchscreen
+ && identifier != FirmwareGuestSystemPatchSet.ios16KeybaglessUI
}
guard plan.isEnabled(identifier) else {
print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")
@@ -1728,27 +1732,47 @@ struct VPhoneCustomFirmwareInstaller {
(FirmwareGuestSystemPatchSet.ios16Migration, "usr/libexec/backboardd", "libvphoneios16migration.dylib"),
(FirmwareGuestSystemPatchSet.ios16Desktop, "System/Library/CoreServices/SpringBoard.app/SpringBoard", "libvphoneios16desktop.dylib"),
] {
- isolate([desktop]) {
- if on(desktop) {
- try system.replaceFile("usr/lib/" + library, fromFileAt: VPhoneGuestBinaries.resolve(library), mode: 0o755, owner: Self.guestOwner)
- try patchMachO(system: system, work: work, path: path,
- preserveEntitlements: true, injectedDylibPath: "/usr/lib/" + library)
- live.insert(desktop)
- } else {
- if priorGuest.contains(desktop) {
- guard try revertMachO(system: system, work: work, path: path) else {
- live.insert(desktop)
- throw ValidationError("\(desktop) has no \(path) backup; cannot safely remove its library.")
+ isolate([desktop]) {
+ if on(desktop) {
+ try system.replaceFile("usr/lib/" + library, fromFileAt: VPhoneGuestBinaries.resolve(library), mode: 0o755, owner: Self.guestOwner)
+ try patchMachO(system: system, work: work, path: path,
+ preserveEntitlements: true, injectedDylibPath: "/usr/lib/" + library)
+ live.insert(desktop)
+ } else {
+ if priorGuest.contains(desktop) {
+ guard try revertMachO(system: system, work: work, path: path) else {
+ live.insert(desktop)
+ throw ValidationError("\(desktop) has no \(path) backup; cannot safely remove its library.")
+ }
}
+ try system.removeItem("usr/lib/" + library)
}
- try system.removeItem("usr/lib/" + library)
}
}
- }
// 2. The dyld shared cache. The version branches and the declarations'
// applicability say the same thing; this is what a VM with no plan
// still follows.
+ for (surface, marker, verb) in [
+ (FirmwareGuestSystemPatchSet.ios16Surface, FirmwareGuestSystemPatchSet.ios16SurfaceMarker, "prepare-ios16-surface"),
+ (FirmwareGuestSystemPatchSet.ios16Framebuffer, FirmwareGuestSystemPatchSet.ios16FramebufferMarker, "prepare-ios16-framebuffer"),
+ ] {
+ let surfaceMarker = String(marker.dropFirst())
+ isolate([surface]) {
+ if on(surface) {
+ // Resolve in a child, like the cache patch verbs: MachOKit's
+ // shared-cache views must release every mapping before unmount.
+ let staged = work.file(verb + "-metadata")
+ try patch(verb, [dsc, staged.path])
+ let metadata = try Data(contentsOf: staged)
+ try system.writeFile(surfaceMarker, contents: metadata, mode: 0o644, owner: Self.guestOwner)
+ live.insert(surface)
+ print(" [+] \(surface): installed UUID-checked display adapter metadata")
+ } else {
+ try system.removeItem(surfaceMarker)
+ }
+ }
+ }
var dyld: [(id: String, verb: String, args: [String])] = []
if version.hasPrefix("27.") {
dyld += [
@@ -1881,6 +1905,20 @@ struct VPhoneCustomFirmwareInstaller {
}
machO("system-seputil-boot-gigalocker_uuid", path: "usr/libexec/seputil", verbs: ["patch-seputil"], codeIdentifier: "com.apple.seputil")
+ for (identifier, marker) in [
+ (FirmwareGuestSystemPatchSet.ios16Touchscreen, FirmwareGuestSystemPatchSet.ios16TouchscreenMarker),
+ (FirmwareGuestSystemPatchSet.ios16KeybaglessUI, FirmwareGuestSystemPatchSet.ios16KeybaglessUIMarker),
+ ] {
+ let path = String(marker.dropFirst())
+ isolate([identifier]) {
+ if on(identifier) {
+ try system.writeFile(path, contents: Data("1\n".utf8), mode: 0o644, owner: Self.guestOwner)
+ live.insert(identifier)
+ } else {
+ try system.removeItem(path)
+ }
+ }
+ }
let keybag = FirmwareGuestSystemPatchSet.ios16Keybag
let keybagMarker = String(FirmwareGuestSystemPatchSet.ios16KeybagMarker.dropFirst())
machO(keybag, path: "usr/libexec/keybagd", preserveEntitlements: true,
@@ -3441,7 +3479,8 @@ struct VPhoneCustomFirmwareInstaller {
// Whether a device-tree patch is enabled. A VM with no plan gets every
// one, which is what it was restored with.
func enabled(_ identifier: String) -> Bool {
- plan?.isEnabled(identifier) ?? true
+ if identifier == FirmwareGuestSystemPatchSet.ios16EphemeralStorage { return plan?.isEnabled(identifier) == true }
+ return plan?.isEnabled(identifier) ?? true
}
let identity = FirmwareGuestIdentityPatchSet.prebootDeviceTreeIdentity
@@ -3502,6 +3541,7 @@ struct VPhoneCustomFirmwareInstaller {
boardDeviceTree.map { [$0.path] } ?? []))
}
repairGroup.append((FirmwareGuestSystemPatchSet.prebootHaptics, "patch-dt-haptics", []))
+ repairGroup.append((FirmwareGuestSystemPatchSet.ios16EphemeralStorage, "patch-dt-ios16-ephemeral", []))
repairGroup.append((FirmwareGuestSystemPatchSet.prebootMicrophoneArray, "patch-dt-microphone-array", []))
let repairsOn = repairGroup.filter { enabled($0.id) }
for off in repairGroup where !enabled(off.id) {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
index cddceb09..9ab8c921 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
@@ -710,6 +710,16 @@ struct VPhoneCustomFirmwarePatchFoldableDisplaysCommand: ParsableCommand {
}
}
+struct VPhoneCustomFirmwarePatchIOS16EphemeralCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-dt-ios16-ephemeral",
+ abstract: "Declare ephemeral storage for an explicitly selected fresh iOS 16 lab"
+ )
+ @Argument(transform: URL.init(fileURLWithPath:)) var deviceTree: URL
+ @Flag(name: .customLong("dry-run")) var dryRun = false
+ func run() throws { try CustomFirmwarePostRestoreDeviceTree.presentIOS16EphemeralStorage(at: deviceTree, dryRun: dryRun) }
+}
+
// MARK: - patch-dt-haptics
struct VPhoneCustomFirmwarePatchHapticsCommand: ParsableCommand {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
index 34ebacd3..727539e9 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
@@ -262,6 +262,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {
VPhoneCustomFirmwarePatchFoldableProductIdCommand.self,
VPhoneCustomFirmwarePatchFoldableDisplaysCommand.self,
VPhoneCustomFirmwarePatchHapticsCommand.self,
+ VPhoneCustomFirmwarePatchIOS16EphemeralCommand.self,
VPhoneCustomFirmwarePatchMicrophoneArrayCommand.self,
] + VPhoneCustomFirmwareMachOVerbs.all + VPhoneCustomFirmwareDyldSharedCacheVerbs.all,
)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index b3bdfad1..ffedd273 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -90,6 +90,20 @@ public enum ARM64Encoder {
// MARK: - Branch Encoding
+ /// BR Xn; XZR is not a branch target.
+ public static func encodeBR(rn: UInt32) -> Data? {
+ guard rn < 31 else { return nil }
+ return ARM64.encodeU32(0xD61F_0000 | (rn << 5))
+ }
+
+ /// LDR Xt, label: signed, word-aligned PC-relative literal within ±1 MiB.
+ public static func encodeLdrXLiteral(rt: UInt32, from pc: Int, to target: Int) -> Data? {
+ guard rt < 32 else { return nil }
+ let delta = target - pc
+ guard delta & 3 == 0, delta >= -(1 << 20), delta < (1 << 20) else { return nil }
+ return ARM64.encodeU32(0x5800_0000 | ((UInt32(truncatingIfNeeded: delta >> 2) & 0x7FFFF) << 5) | rt)
+ }
+
/// Encode unconditional B (branch) instruction.
///
/// Format: `[31:26] = 0b000101`, `[25:0] = signed offset / 4`
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
index e12569cc..7e9d8550 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
@@ -99,6 +99,11 @@
<string>system-backboard-exp-ios16_migration</string>
<string>system-keybag-exp-ios16_ephemeral</string>
<string>system-springboard-exp-ios16_desktop</string>
+ <string>system-systemhook-exp-ios16_surface</string>
+ <string>system-systemhook-exp-ios16_framebuffer</string>
+ <string>preboot-exp-ios16_ephemeral_storage</string>
+ <string>system-vphoned-exp-ios16_touchscreen</string>
+ <string>system-springboard-exp-ios16_keybagless_ui</string>
<string>system-userprofilesd-exp-keybag_lookup</string>
<string>system-breadboard-exp-mach_lookup</string>
<string>system-homeview-exp-setup_bypass</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index c0dc437f..d32de3ac 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -161,6 +161,11 @@
<string>system-backboard-exp-ios16_migration</string>
<string>system-keybag-exp-ios16_ephemeral</string>
<string>system-springboard-exp-ios16_desktop</string>
+ <string>system-systemhook-exp-ios16_surface</string>
+ <string>system-systemhook-exp-ios16_framebuffer</string>
+ <string>preboot-exp-ios16_ephemeral_storage</string>
+ <string>system-vphoned-exp-ios16_touchscreen</string>
+ <string>system-springboard-exp-ios16_keybagless_ui</string>
</array>
</dict>
<key>Summary</key>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
index 88c9eb88..69c5be8c 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
@@ -169,6 +169,11 @@
<string>system-backboard-exp-ios16_migration</string>
<string>system-keybag-exp-ios16_ephemeral</string>
<string>system-springboard-exp-ios16_desktop</string>
+ <string>system-systemhook-exp-ios16_surface</string>
+ <string>system-systemhook-exp-ios16_framebuffer</string>
+ <string>preboot-exp-ios16_ephemeral_storage</string>
+ <string>system-vphoned-exp-ios16_touchscreen</string>
+ <string>system-springboard-exp-ios16_keybagless_ui</string>
</array>
</dict>
<key>Summary</key>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
index f94e22dc..0f3b574e 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
@@ -121,6 +121,11 @@
<string>system-backboard-exp-ios16_migration</string>
<string>system-keybag-exp-ios16_ephemeral</string>
<string>system-springboard-exp-ios16_desktop</string>
+ <string>system-systemhook-exp-ios16_surface</string>
+ <string>system-systemhook-exp-ios16_framebuffer</string>
+ <string>preboot-exp-ios16_ephemeral_storage</string>
+ <string>system-vphoned-exp-ios16_touchscreen</string>
+ <string>system-springboard-exp-ios16_keybagless_ui</string>
</array>
</dict>
<key>Summary</key>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index c0f9bee0..d87583ec 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -168,6 +168,11 @@
<string>system-backboard-exp-ios16_migration</string>
<string>system-keybag-exp-ios16_ephemeral</string>
<string>system-springboard-exp-ios16_desktop</string>
+ <string>system-systemhook-exp-ios16_surface</string>
+ <string>system-systemhook-exp-ios16_framebuffer</string>
+ <string>preboot-exp-ios16_ephemeral_storage</string>
+ <string>system-vphoned-exp-ios16_touchscreen</string>
+ <string>system-springboard-exp-ios16_keybagless_ui</string>
</array>
</dict>
<key>Summary</key>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 15de58c9..b46a9ece 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -176,6 +176,11 @@
<string>system-backboard-exp-ios16_migration</string>
<string>system-keybag-exp-ios16_ephemeral</string>
<string>system-springboard-exp-ios16_desktop</string>
+ <string>system-systemhook-exp-ios16_surface</string>
+ <string>system-systemhook-exp-ios16_framebuffer</string>
+ <string>preboot-exp-ios16_ephemeral_storage</string>
+ <string>system-vphoned-exp-ios16_touchscreen</string>
+ <string>system-springboard-exp-ios16_keybagless_ui</string>
</array>
</dict>
<key>Summary</key>
diff --git a/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c b/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c
index 4e1b9b75..e1e1b9e8 100644
--- a/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c
+++ b/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c
@@ -61,7 +61,9 @@
// but not IOKit/ps/IOPowerSources.h.
extern CFTypeRef IOPSCopyPowerSourcesInfo(void);
extern CFTypeRef IOPSCopyPowerSourcesByType(int type);
-extern IOReturn IOPSCopyPowerSourcesByTypePrecise(int type, CFTypeRef *blob);
+// Older bases expose ByType but not Precise. A strong import prevents dyld
+// from starting Settings, before any optional battery UI is requested.
+extern IOReturn IOPSCopyPowerSourcesByTypePrecise(int type, CFTypeRef *blob) __attribute__((weak_import));
extern Boolean MGGetBoolAnswer(CFStringRef question);
#define VP_MITIGATION_STATE_NAME "com.apple.thermalmonitor.ageAwareMitigationState"
@@ -256,6 +258,11 @@ static CFTypeRef vpCopyPowerSourcesByType(int type) {
}
static IOReturn vpCopyPowerSourcesByTypePrecise(int type, CFTypeRef *blob) {
+ if (!IOPSCopyPowerSourcesByTypePrecise) {
+ if (!blob) return kIOReturnBadArgument;
+ *blob = vpCopyPowerSourcesByType(type);
+ return *blob ? kIOReturnSuccess : kIOReturnNoMemory;
+ }
IOReturn status = IOPSCopyPowerSourcesByTypePrecise(type, blob);
if (blob && *blob)
*blob = vpBlobWithHealth(*blob);
diff --git a/VPhoneGuestComponents/IOS16Desktop/libvphoneios16desktop.m b/VPhoneGuestComponents/IOS16Desktop/libvphoneios16desktop.m
index 12b8ff93..e7a4be74 100644
--- a/VPhoneGuestComponents/IOS16Desktop/libvphoneios16desktop.m
+++ b/VPhoneGuestComponents/IOS16Desktop/libvphoneios16desktop.m
@@ -3,10 +3,44 @@
#import <objc/message.h>
#import <dlfcn.h>
#import <string.h>
+#import <unistd.h>
+#include "VPhoneIOS16LabPolicy.h"
+
+static BOOL (*originalHasPasscode)(id, SEL);
+static BOOL (*originalEffectivelyLocked)(id, SEL);
+static BOOL (*originalMCPasscode)(id, SEL);
+static BOOL labHasPasscode(id self, SEL selector) {
+ return vp_ios16_keybagless_ui_attested() ? NO : originalHasPasscode(self, selector);
+}
+static BOOL labEffectivelyLocked(id self, SEL selector) {
+ return vp_ios16_keybagless_ui_attested() ? NO : originalEffectivelyLocked(self, selector);
+}
+static BOOL labMCPasscode(id self, SEL selector) {
+ return vp_ios16_keybagless_ui_attested() ? NO : originalMCPasscode(self, selector);
+}
+
+static void (*originalBacklight)(id, SEL, NSInteger, NSInteger, BOOL, id);
+static int (*setLegacyBacklight)(float, float, BOOL);
+static void backlightWithLegacyHIDState(id self, SEL selector, NSInteger state,
+ NSInteger source, BOOL animated, id completion) {
+ originalBacklight(self, selector, state, source, animated, completion);
+ float factor = ((float (*)(id, SEL, NSInteger))objc_msgSend)(self,
+ sel_registerName("_factorToPublishForBacklightState:"), state);
+ if (factor >= 0.f && factor <= 1.f) {
+ int result = setLegacyBacklight(factor, 0.f, YES);
+ NSLog(@"[ios16-desktop] legacy HID backlight state %ld factor %g: %d", (long)state, factor, result);
+ }
+}
static id unavailableController(id self, SEL selector) { return nil; }
static void skipWidgets(id self, SEL selector) {}
static BOOL noFlashlightCapability(id self, SEL selector) { return NO; }
+static BOOL labSetupMode(id self, SEL selector) {
+ // The fresh, keybag-less lab cannot persist purplebuddy preferences. Keep
+ // this in SpringBoard's local state; do not claim setup or migration was
+ // completed in the user's preferences or touch the keybag.
+ return ((BOOL (*)(id, SEL, NSUInteger))objc_msgSend)(self, sel_registerName("_setSetupRequiredReason:"), 0);
+}
static id (*originalModule)(id, SEL, id);
static id moduleWithoutMediaServices(id self, SEL selector, id metadata) {
SEL identifier = sel_registerName("moduleIdentifier");
@@ -22,6 +56,66 @@ static id moduleWithoutMediaServices(id self, SEL selector, id metadata) {
__attribute__((constructor)) static void start(void) {
if (NSProcessInfo.processInfo.operatingSystemVersion.majorVersion != 16 ||
![NSProcessInfo.processInfo.processName isEqualToString:@"SpringBoard"]) return;
+ if (access(VP_IOS16_KEYBAGLESS_SELECTION, F_OK) == 0) {
+ // UI model only. The MKB/AKS APIs and encrypted storage remain native.
+ // Every query needs a fresh root-owned lease; it expires when vphoned
+ // stops or notices any persistent/unknown keybag directory entry.
+ dlopen("/System/Library/PrivateFrameworks/ManagedConfiguration.framework/ManagedConfiguration", RTLD_NOW);
+ Class bag = objc_getClass("SBFMobileKeyBag");
+ Method passcode = class_getInstanceMethod(bag, sel_registerName("hasPasscodeSet"));
+ Class state = objc_getClass("SBFMobileKeyBagState");
+ Method locked = class_getInstanceMethod(state, sel_registerName("isEffectivelyLocked"));
+ Class managed = objc_getClass("MCPasscodeManager");
+ Method mcPasscode = class_getInstanceMethod(managed, sel_registerName("isPasscodeSet"));
+ if (passcode && locked && mcPasscode &&
+ !strcmp(method_getTypeEncoding(passcode), "B16@0:8") &&
+ !strcmp(method_getTypeEncoding(locked), "B16@0:8") &&
+ !strcmp(method_getTypeEncoding(mcPasscode), "B16@0:8")) {
+ originalHasPasscode = (void *)method_getImplementation(passcode);
+ class_replaceMethod(bag, sel_registerName("hasPasscodeSet"), (IMP)labHasPasscode, method_getTypeEncoding(passcode));
+ originalEffectivelyLocked = (void *)method_getImplementation(locked);
+ class_replaceMethod(state, sel_registerName("isEffectivelyLocked"), (IMP)labEffectivelyLocked, method_getTypeEncoding(locked));
+ originalMCPasscode = (void *)method_getImplementation(mcPasscode);
+ class_replaceMethod(managed, sel_registerName("isPasscodeSet"), (IMP)labMCPasscode, method_getTypeEncoding(mcPasscode));
+ }
+ }
+ if (access("/usr/lib/vphone-ios16-touchscreen", F_OK) == 0) {
+ // The newer brightness backend does not publish the old HID backlight
+ // factor. Even a visibly rendered Lock Screen is consequently rejected
+ // as "backlight dim/off". Mirror each native requested state through
+ // the legacy system-app API, including dim/off; do not force it awake.
+ void *backboard = dlopen("/System/Library/PrivateFrameworks/BackBoardServices.framework/BackBoardServices", RTLD_NOW);
+ setLegacyBacklight = backboard ? dlsym(backboard, "BKSHIDServicesSetBacklightFactorWithFadeDuration") : NULL;
+ Class backlight = objc_getClass("SBBacklightController");
+ SEL transition = sel_registerName("setBacklightState:source:animated:completion:");
+ Method setter = class_getInstanceMethod(backlight, transition);
+ Method factor = class_getInstanceMethod(backlight, sel_registerName("_factorToPublishForBacklightState:"));
+ if (setLegacyBacklight && setter && factor &&
+ !strcmp(method_getTypeEncoding(setter), "v44@0:8q16q24B32@?36") &&
+ !strcmp(method_getTypeEncoding(factor), "f24@0:8q16")) {
+ originalBacklight = (void *)method_getImplementation(setter);
+ class_replaceMethod(backlight, transition, (IMP)backlightWithLegacyHIDState, method_getTypeEncoding(setter));
+ }
+ }
+ Class setup = objc_getClass("SBSetupManager");
+ SEL update = sel_registerName("updateInSetupMode");
+ Method updater = class_getInstanceMethod(setup, update);
+ Method reason = class_getInstanceMethod(setup, sel_registerName("_setSetupRequiredReason:"));
+ if (updater && reason && !strcmp(method_getTypeEncoding(updater), "B16@0:8") &&
+ (!strcmp(method_getTypeEncoding(reason), "B24@0:8Q16") ||
+ !strcmp(method_getTypeEncoding(reason), "B24@0:8q16"))) {
+ class_replaceMethod(setup, update, (IMP)labSetupMode, method_getTypeEncoding(updater));
+ NSLog(@"[ios16-desktop] kept setup mode off for the fresh lab");
+ }
+ Class media = objc_getClass("SBMediaController");
+ Method mediaInit = class_getInstanceMethod(media, @selector(init));
+ if (mediaInit && !strcmp(method_getTypeEncoding(mediaInit), "@16@0:8")) {
+ // First unlock lazily creates both video and music routing contexts
+ // here. Neither service exists in this desktop-only lab. Leave the
+ // optional singleton nil rather than manufacturing a partial object.
+ class_replaceMethod(media, @selector(init), (IMP)unavailableController, method_getTypeEncoding(mediaInit));
+ NSLog(@"[ios16-desktop] skipped unavailable media controller");
+ }
dlopen("/System/Library/PrivateFrameworks/MediaExperience.framework/MediaExperience", RTLD_NOW);
Class controller = objc_getClass("AVSystemController");
Method method = class_getInstanceMethod(controller, @selector(init));
diff --git a/VPhoneGuestComponents/IOS16Migration/libvphoneios16migration.m b/VPhoneGuestComponents/IOS16Migration/libvphoneios16migration.m
index 2463c1b6..2d678fe5 100644
--- a/VPhoneGuestComponents/IOS16Migration/libvphoneios16migration.m
+++ b/VPhoneGuestComponents/IOS16Migration/libvphoneios16migration.m
@@ -1,5 +1,6 @@
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
+#import <objc/message.h>
#import <dlfcn.h>
#import <string.h>
@@ -11,7 +12,39 @@ static BOOL skipStartupMigration(id self, SEL selector, id connection,
return YES;
}
static void (*originalCheckIn)(id, SEL, NSNumber *, id);
+static BOOL (*originalBlock)(id, SEL);
+static void (*originalAlternate)(id, SEL, NSString *);
+static Ivar alternateSystemApp;
+static char suppressedPreBoard;
+static void alternateExceptLabPreBoard(id self, SEL selector, NSString *identifier) {
+ BOOL preBoard = [identifier isKindOfClass:NSString.class] && [identifier isEqualToString:@"com.apple.PreBoard"];
+ objc_setAssociatedObject(self, &suppressedPreBoard, preBoard ? @YES : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ originalAlternate(self, selector, preBoard ? nil : identifier);
+}
+static BOOL blockExceptLabPreBoard(id self, SEL selector) {
+ // The native caller already holds the sentinel lock. Read its ivar through
+ // runtime metadata instead of its locking getter. Keep every other block.
+ if ([objc_getAssociatedObject(self, &suppressedPreBoard) boolValue]) return NO;
+ id alternate = object_getIvar(self, alternateSystemApp);
+ if ([alternate isKindOfClass:NSString.class] && [alternate isEqualToString:@"com.apple.PreBoard"]) return NO;
+ return originalBlock(self, selector);
+}
static void checkInWithoutMigrationWait(id self, SEL selector, NSNumber *wait, id reply) {
+ static dispatch_once_t localShell;
+ dispatch_once(&localShell, ^{
+ SEL complete = sel_registerName("dataMigratorDidComplete");
+ SEL unblock = sel_registerName("unblockSystemApp");
+ Method completion = class_getInstanceMethod(object_getClass(self), complete);
+ Method unblocking = class_getInstanceMethod(object_getClass(self), unblock);
+ if (completion && unblocking && !strcmp(method_getTypeEncoding(completion), "v16@0:8") &&
+ !strcmp(method_getTypeEncoding(unblocking), "B16@0:8")) {
+ // Dismiss the lab's PreBoard curtain through the native local
+ // sentinel transitions. No DataMigrator preference is written and
+ // no encrypted user storage or keybag is unlocked.
+ ((void (*)(id, SEL))objc_msgSend)(self, complete);
+ (void)((BOOL (*)(id, SEL))objc_msgSend)(self, unblock);
+ }
+ });
originalCheckIn(self, selector, @NO, reply);
}
__attribute__((constructor)) static void start(void) {
@@ -27,6 +60,20 @@ __attribute__((constructor)) static void start(void) {
// migration call returns. Preserve the native check-in and reply handling,
// requesting its existing non-waiting mode instead.
Class sentinel = objc_getClass("BKSystemShellSentinel");
+ SEL block = sel_registerName("_lock_blockSystemApp");
+ Method blocker = class_getInstanceMethod(sentinel, block);
+ Ivar alternate = class_getInstanceVariable(sentinel, "_lock_activeAlternateSystemAppBundleIdentifier");
+ SEL setAlternate = sel_registerName("setActiveAlternateSystemAppBundleIdentifier:");
+ Method setter = class_getInstanceMethod(sentinel, setAlternate);
+ if (blocker && alternate && !strcmp(method_getTypeEncoding(blocker), "B16@0:8") &&
+ !strcmp(ivar_getTypeEncoding(alternate), "@\"NSString\"") && setter &&
+ !strcmp(method_getTypeEncoding(setter), "v24@0:8@16")) {
+ alternateSystemApp = alternate;
+ originalAlternate = (void *)method_getImplementation(setter);
+ class_replaceMethod(sentinel, setAlternate, (IMP)alternateExceptLabPreBoard, method_getTypeEncoding(setter));
+ originalBlock = (void *)method_getImplementation(blocker);
+ class_replaceMethod(sentinel, block, (IMP)blockExceptLabPreBoard, method_getTypeEncoding(blocker));
+ }
SEL checkIn = sel_registerName("checkInAndWaitForDataMigration:completionBlock:");
Method check = class_getInstanceMethod(sentinel, checkIn);
if (check && !strcmp(method_getTypeEncoding(check), "v32@0:8@16@?24")) {
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 5db4a8a8..d5f2974b 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -370,7 +370,7 @@ $(SYSTEMHOOK): $(SYSTEMHOOK_SOURCES) $(SYSTEMHOOK_INCLUDES) SystemHook Shared $(
$(CLANG) $(GUEST_C_FLAGS) -dynamiclib \
-I$(MACHPORTS_GENERATED) -ILaunchHook -include VPhoneMachMessage.h \
-install_name /usr/lib/SystemHook-vphone.dylib \
- -o $@ $(SYSTEMHOOK_SOURCES) $(MACHPORTS_GENERATED)/VPhoneMachPortsUser.c -Wl,-not_for_dyld_shared_cache
+ -o $@ $(SYSTEMHOOK_SOURCES) $(MACHPORTS_GENERATED)/VPhoneMachPortsUser.c -framework IOKit -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
$(MISFIX): $(MISFIX_SOURCES) $(MISFIX_INCLUDES) MISFix | $(STAGE)/misfix
@@ -695,6 +695,13 @@ test-ios17-desktop:
../.build/ios17-desktop-tests/test ../.build/ios17-desktop-tests/hook.dylib 18 SpringBoard
../.build/ios17-desktop-tests/test ../.build/ios17-desktop-tests/hook.dylib 17 OtherProcess
+.PHONY: test-ios16-surface
+test-ios16-surface:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -Wall -Wextra -Werror -fsanitize=address,undefined -ISystemHook \
+ -o $(OUT)/IOS16SurfaceReplyTest Tests/IOS16SurfaceReplyTest.c SystemHook/VPhoneIOS16SurfaceReply.c
+ @$(OUT)/IOS16SurfaceReplyTest
+
.PHONY: test-mach-ports-compat
test-mach-ports-compat: $(MACHPORTS_STAMP)
@mkdir -p ../.build/machports-test
@@ -708,7 +715,14 @@ $(IOS16MIGRATION): IOS16Migration/libvphoneios16migration.m
$(CLANG) $(COMMON_FLAGS) -dynamiclib -install_name /usr/lib/libvphoneios16migration.dylib -o $@ $< -framework Foundation -lobjc -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
-$(IOS16DESKTOP): IOS16Desktop/libvphoneios16desktop.m
+$(IOS16DESKTOP): IOS16Desktop/libvphoneios16desktop.m ../VPhoneDaemon/Native/Include/VPhoneIOS16LabPolicy.h
@mkdir -p $(STAGE)/ios16desktop
- $(CLANG) $(COMMON_FLAGS) -dynamiclib -install_name /usr/lib/libvphoneios16desktop.dylib -o $@ $< -framework Foundation -lobjc -Wl,-not_for_dyld_shared_cache
+ $(CLANG) $(COMMON_FLAGS) -I../VPhoneDaemon/Native/Include -dynamiclib -install_name /usr/lib/libvphoneios16desktop.dylib -o $@ $< -framework Foundation -lobjc -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
+
+.PHONY: test-ios16-lab-policy
+test-ios16-lab-policy:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -Wall -Wextra -Werror -fsanitize=address,undefined \
+ -I../VPhoneDaemon/Native/Include -o $(OUT)/IOS16LabPolicyTest Tests/IOS16LabPolicyTest.c
+ @$(OUT)/IOS16LabPolicyTest
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index b5eb0f8f..a06f386f 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -18,6 +18,7 @@
static int vpInXPCProxy;
static int vpInBootstrap;
+extern void vpInstallSurfaceAdapter(void);
static int vpIsBootstrapPath(const char *path, const char *root) {
if (path && strncmp(path, "/var/jb/", 8) == 0)
@@ -222,6 +223,7 @@ static void vpLoadLibrary(const char *kind, const char *library) {
// xpcproxy needs this bridge because launchd only spawns the proxy, not its target.
__attribute__((constructor)) static void vpLogProcess(void) {
+ vpInstallSurfaceAdapter();
// Request cross-boot reuse at constructor entry: libCoreFSCache normally
// invalidates Metal caches when the boot session changes. Preserve an
// explicit environment setting. See Research/Guest/gpu_acceleration.md.
diff --git a/VPhoneGuestComponents/SystemHook/VPhoneIOS16Surface.c b/VPhoneGuestComponents/SystemHook/VPhoneIOS16Surface.c
new file mode 100644
index 00000000..6b144b8b
--- /dev/null
+++ b/VPhoneGuestComponents/SystemHook/VPhoneIOS16Surface.c
@@ -0,0 +1,152 @@
+#include "VPhoneIOS16SurfaceReply.h"
+#include <dlfcn.h>
+#include <fcntl.h>
+#include <libkern/OSCacheControl.h>
+#include <mach/mach.h>
+#include <mach-o/loader.h>
+#include <ptrauth.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+extern kern_return_t IOConnectCallMethod(mach_port_t, uint32_t,
+ const uint64_t *, uint32_t, const void *, size_t, uint64_t *, uint32_t *, void *, size_t *);
+extern kern_return_t IOConnectCallStructMethod(mach_port_t, uint32_t, const void *, size_t, void *, size_t *);
+
+static kern_return_t vpFramebufferMethod(mach_port_t connection, uint32_t selector,
+ const void *input, size_t inputSize, void *output, size_t *outputSize) {
+ if (selector == 5 && input && (inputSize == 0x46C || inputSize == 0x560)) {
+ uint8_t modern[0x560];
+ vpIOS16FramebufferSwap(modern, input);
+ return IOConnectCallStructMethod(connection, selector, modern, sizeof(modern), output, outputSize);
+ }
+ return IOConnectCallStructMethod(connection, selector, input, inputSize, output, outputSize);
+}
+
+static kern_return_t vpSurfaceMethod(mach_port_t connection, uint32_t selector,
+ const uint64_t *scalarIn, uint32_t scalarCount, const void *input, size_t inputSize,
+ uint64_t *scalarOut, uint32_t *outputCount, void *output, size_t *outputSize) {
+ if (output && outputSize && *outputSize == VP_IOS16_SURFACE_REPLY) {
+ uint8_t modern[VP_MODERN_SURFACE_REPLY] = {0};
+ size_t size = sizeof(modern);
+ kern_return_t result = IOConnectCallMethod(connection, selector, scalarIn, scalarCount,
+ input, inputSize, scalarOut, outputCount, modern, &size);
+ if (result != KERN_SUCCESS) return result;
+ if (size != sizeof(modern) || !vpIOS16SurfaceReply(output, modern)) return 0xE00002C2;
+ *outputSize = VP_IOS16_SURFACE_REPLY;
+ return KERN_SUCCESS;
+ }
+ if (selector == 13 && output && outputSize && *outputSize == 0x18) {
+ uint8_t modern[0x28] = {0};
+ size_t size = sizeof(modern);
+ kern_return_t result = IOConnectCallMethod(connection, selector, scalarIn, scalarCount,
+ input, inputSize, scalarOut, outputCount, modern, &size);
+ if (result != KERN_SUCCESS) return result;
+ if (size != sizeof(modern) || !vpIOS16SurfaceInfo(output, modern)) return 0xE00002C2;
+ *outputSize = 0x18;
+ return KERN_SUCCESS;
+ }
+ return IOConnectCallMethod(connection, selector, scalarIn, scalarCount,
+ input, inputSize, scalarOut, outputCount, output, outputSize);
+}
+
+typedef struct {
+ char magic[8];
+ int64_t displacement;
+ uint8_t original[16];
+ uint8_t prefix[8];
+ uint8_t uuid[16];
+} VPSurfaceMetadata;
+_Static_assert(sizeof(VPSurfaceMetadata) == 56, "host metadata ABI");
+
+static bool vpImageUUID(const struct mach_header_64 *header, const uint8_t uuid[16]) {
+ if (!header || header->magic != MH_MAGIC_64 || header->sizeofcmds > 0x10000) return false;
+ const uint8_t *cursor = (const uint8_t *)(header + 1), *end = cursor + header->sizeofcmds;
+ for (uint32_t index = 0; index < header->ncmds; index++) {
+ if ((size_t)(end - cursor) < sizeof(struct load_command)) return false;
+ const struct load_command *command = (const void *)cursor;
+ if (command->cmdsize < sizeof(*command) || command->cmdsize > (size_t)(end - cursor)) return false;
+ if (command->cmd == LC_UUID && command->cmdsize == sizeof(struct uuid_command))
+ return !memcmp(((const struct uuid_command *)command)->uuid, uuid, 16);
+ cursor += command->cmdsize;
+ }
+ return false;
+}
+
+static void vpInstallAdapter(const char *marker, const char *imagePath,
+ const char *anchorName, void *replacementMethod) {
+ int file = open(marker, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (file < 0) return;
+ VPSurfaceMetadata metadata;
+ ssize_t size = read(file, &metadata, sizeof(metadata));
+ uint8_t extra;
+ bool complete = size == sizeof(metadata) && read(file, &extra, 1) == 0;
+ close(file);
+ if (!complete || memcmp(metadata.magic, "VPIS16\1\0", 8) ||
+ metadata.displacement < 0 || metadata.displacement > 0x10000000) return;
+ // Leave processes that do not use IOSurface alone. The framework is a
+ // dependency of CoreAnimation and is mapped before their constructors run.
+ void *image = dlopen(imagePath, RTLD_LAZY | RTLD_NOLOAD);
+ if (!image) return;
+ void *anchor = ptrauth_strip(dlsym(image, anchorName), ptrauth_key_function_pointer);
+ Dl_info information = {0};
+ if (!anchor || !dladdr(anchor, &information) || !vpImageUUID(information.dli_fbase, metadata.uuid)) {
+ dlclose(image); return;
+ }
+ uint8_t *stub = (uint8_t *)anchor + metadata.displacement;
+ if (memcmp(stub, metadata.original, sizeof(metadata.original))) { dlclose(image); return; }
+ uint8_t replacement[16];
+ memcpy(replacement, metadata.prefix, 8);
+ uintptr_t method = (uintptr_t)ptrauth_strip(replacementMethod, ptrauth_key_function_pointer);
+ memcpy(replacement + 8, &method, sizeof(method));
+ vm_address_t page = (vm_address_t)stub & ~((vm_address_t)vm_page_size - 1);
+ if ((vm_address_t)stub + sizeof(replacement) > page + vm_page_size) { dlclose(image); return; }
+
+ // This is a process-private copy. Stop peer threads while execute is
+ // removed; no shared-cache file or another process's code is modified.
+ thread_act_array_t threads = NULL;
+ mach_msg_type_number_t count = 0;
+ bool ready = task_threads(mach_task_self(), &threads, &count) == KERN_SUCCESS;
+ uint8_t *suspended = ready ? calloc(count, 1) : NULL;
+ mach_port_t current = mach_thread_self();
+ if (!suspended) ready = false;
+ for (mach_msg_type_number_t index = 0; ready && index < count; index++) {
+ if (threads[index] == current) continue;
+ if (thread_suspend(threads[index]) != KERN_SUCCESS) ready = false;
+ else suspended[index] = 1;
+ }
+ kern_return_t result = KERN_FAILURE;
+ if (ready) {
+ result = vm_protect(mach_task_self(), page, vm_page_size, false,
+ VM_PROT_COPY | VM_PROT_READ | VM_PROT_WRITE);
+ if (result == KERN_SUCCESS) {
+ memcpy(stub, replacement, sizeof(replacement));
+ sys_icache_invalidate(stub, sizeof(replacement));
+ result = vm_protect(mach_task_self(), page, vm_page_size, false, VM_PROT_READ | VM_PROT_EXECUTE);
+ if (result != KERN_SUCCESS) {
+ memcpy(stub, metadata.original, sizeof(metadata.original));
+ sys_icache_invalidate(stub, sizeof(metadata.original));
+ (void)vm_protect(mach_task_self(), page, vm_page_size, false, VM_PROT_READ | VM_PROT_EXECUTE);
+ }
+ }
+ }
+ for (mach_msg_type_number_t index = 0; index < count; index++) {
+ if (suspended && suspended[index]) (void)thread_resume(threads[index]);
+ mach_port_deallocate(mach_task_self(), threads[index]);
+ }
+ mach_port_deallocate(mach_task_self(), current);
+ if (threads) vm_deallocate(mach_task_self(), (vm_address_t)threads, count * sizeof(*threads));
+ free(suspended);
+ dlclose(image);
+ if (ready) fprintf(stderr, "[ios16-display] %s %s adapter: %d\n", getprogname(), anchorName, result);
+}
+
+void vpInstallSurfaceAdapter(void) {
+ if (getpid() == 1 || !strcmp(getprogname(), "xpcproxy")) return;
+ vpInstallAdapter("/usr/lib/vphone-ios16-surface",
+ "/System/Library/Frameworks/IOSurface.framework/IOSurface", "IOSurfaceCreate", (void *)vpSurfaceMethod);
+ vpInstallAdapter("/usr/lib/vphone-ios16-framebuffer",
+ "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer",
+ "IOMobileFramebufferSwapEnd", (void *)vpFramebufferMethod);
+}
diff --git a/VPhoneGuestComponents/SystemHook/VPhoneIOS16SurfaceReply.c b/VPhoneGuestComponents/SystemHook/VPhoneIOS16SurfaceReply.c
new file mode 100644
index 00000000..5f51f031
--- /dev/null
+++ b/VPhoneGuestComponents/SystemHook/VPhoneIOS16SurfaceReply.c
@@ -0,0 +1,59 @@
+#include "VPhoneIOS16SurfaceReply.h"
+#include <string.h>
+
+void vpIOS16FramebufferSwap(uint8_t modern[0x560], const uint8_t legacy[0x46C]) {
+ memset(modern, 0, 0x560);
+ // Debug/parameter pointers keep their positions. Nine new event values
+ // precede the frame token, and nine new event ports precede subtitle data.
+ memcpy(modern, legacy, 0x50);
+ memcpy(modern + 0x98, legacy + 0x50, 0x210);
+ memcpy(modern + 0x2CC, legacy + 0x260, 0x86);
+ // SwapSetLayer's video/EDR flags split in the newer packed suffix. Only
+ // copy fields identified by the paired 20G81/21H16 setter implementations.
+ modern[0x353] = legacy[0x2E6];
+ memcpy(modern + 0x384, legacy + 0x30C, 0x57); // SwapSetParams types 1/2
+ for (unsigned plane = 0; plane < 4; plane++) modern[0x503 + plane] = legacy[0x467 + plane];
+}
+
+static bool narrow(uint8_t *destination, const uint8_t *source) {
+ uint64_t wide;
+ memcpy(&wide, source, sizeof(wide));
+ if (wide > UINT32_MAX) return false;
+ uint32_t value = (uint32_t)wide;
+ memcpy(destination, &value, sizeof(value));
+ return true;
+}
+
+bool vpIOS16SurfaceInfo(uint8_t legacy[0x18], const uint8_t modern[0x28]) {
+ memcpy(legacy, modern, 12);
+ if (!narrow(legacy + 12, modern + 16) || !narrow(legacy + 16, modern + 24)) return false;
+ memcpy(legacy + 20, modern + 32, 4);
+ return true;
+}
+
+bool vpIOS16SurfaceReply(uint8_t legacy[VP_IOS16_SURFACE_REPLY],
+ const uint8_t modern[VP_MODERN_SURFACE_REPLY]) {
+ uint32_t planes;
+ memcpy(&planes, modern + 0x58, sizeof(planes));
+ if (planes > 20) return false;
+ memset(legacy, 0, VP_IOS16_SURFACE_REPLY);
+ // Mapped addresses and surface ID retain their layout. Six dimensions and
+ // strides widen to uint64_t, increasing the header by 0x20 and each plane
+ // by 0x18. Keep every other metadata byte, including component descriptions.
+ memcpy(legacy, modern, 0x1C);
+ for (unsigned field = 0; field < 5; field++)
+ if (!narrow(legacy + 0x1C + field * 4, modern + 0x20 + field * 8)) return false;
+ memcpy(legacy + 0x30, modern + 0x48, 4);
+ if (!narrow(legacy + 0x34, modern + 0x50)) return false;
+ memcpy(legacy + 0x38, modern + 0x58, 0x30);
+ // Zero planes denotes the implicit packed plane. Unused records are not
+ // initialized by the driver, and must not be inspected or narrowed.
+ for (unsigned plane = 0; plane < (planes ? planes : 1); plane++) {
+ uint8_t *out = legacy + 0x68 + plane * 0x80;
+ const uint8_t *in = modern + 0x88 + plane * 0x98;
+ for (unsigned field = 0; field < 6; field++)
+ if (!narrow(out + field * 4, in + field * 8)) return false;
+ memcpy(out + 0x18, in + 0x30, 0x68);
+ }
+ return true;
+}
diff --git a/VPhoneGuestComponents/SystemHook/VPhoneIOS16SurfaceReply.h b/VPhoneGuestComponents/SystemHook/VPhoneIOS16SurfaceReply.h
new file mode 100644
index 00000000..75c8cc90
--- /dev/null
+++ b/VPhoneGuestComponents/SystemHook/VPhoneIOS16SurfaceReply.h
@@ -0,0 +1,9 @@
+#pragma once
+#include <stdbool.h>
+#include <stdint.h>
+
+enum { VP_IOS16_SURFACE_REPLY = 0xA68, VP_MODERN_SURFACE_REPLY = 0xC68 };
+bool vpIOS16SurfaceReply(uint8_t legacy[VP_IOS16_SURFACE_REPLY],
+ const uint8_t modern[VP_MODERN_SURFACE_REPLY]);
+bool vpIOS16SurfaceInfo(uint8_t legacy[0x18], const uint8_t modern[0x28]);
+void vpIOS16FramebufferSwap(uint8_t modern[0x560], const uint8_t legacy[0x46C]);