Run a virtual iPhone on an Apple Silicon Mac.
Swift
Fix virtual-camera session tracking during deallocation
James Jackson7042bcf958cd
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 80cb7f8b..3189a604 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -75,3 +75,4 @@ jobs:make -C VPhoneGuestComponents test-vcam-prewarmmake -C VPhoneGuestComponents test-vcam-drive-gatemake -C VPhoneGuestComponents test-camfix-geometry+ make -C VPhoneGuestComponents test-camfix-session-lifetimediff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 7399847c..5b8bb7f2 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,12 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **Camera session teardown (2026-10-29).** Source-only change in libcamfix.+> Session tracking uses `objc_storeWeakOrNil` and a strong weak-load before+> weak-table insertion. It skips sessions already in deallocation.+> No firmware patch or preset changes. A small camera app reproduces the+> original abort on iOS 27.0.1 (24A446). See+> [reproduction and crash stack](Guest/camera_session_teardown.md).+> **Apple TV RootHide bootstrap and environment hooks (2026-10-26).** No new> declaration or instruction patch. An arm64e Apple TV now admits> `system-launchdaemons-boot-environment` anddiff --git a/Research/Guest/Evidence/camfix_session_teardown_crash.txt b/Research/Guest/Evidence/camfix_session_teardown_crash.txtnew file mode 100644index 00000000..22c1ba74--- /dev/null+++ b/Research/Guest/Evidence/camfix_session_teardown_crash.txt@@ -0,0 +1,27 @@+SessionProbe crash excerpt+Libraries: stock vPhone 2.13.4 camera libraries+Guest: iOS 27.0.1 (24A446)+Exception: EXC_CRASH (SIGABRT)+Termination namespace: OBJC++Crashed thread:+ 0 libsystem_kernel.dylib __abort_with_payload + 8+ 1 libsystem_kernel.dylib abort_with_payload_wrapper_internal + 104+ 2 libsystem_kernel.dylib abort_with_reason + 32+ 3 libobjc.A.dylib _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 116+ 4 libobjc.A.dylib _objc_fatal(char const*, ...) + 32+ 5 libobjc.A.dylib weak_register_no_lock + 396+ 6 libobjc.A.dylib objc_storeWeak + 468+ 7 Foundation -[NSConcreteHashTable addObject:] + 96+ 8 libcamfix.dylib cfx_track_vcam_session + 128+ 9 libcamfix.dylib cfx_session_isRunning_hook + 76+10 AVFCapture -[AVCaptureInput setSession:] + 64+11 AVFCapture -[AVCaptureDeviceInput setSession:] + 272+12 AVFCapture -[AVCaptureSession _removeInput:] + 232+13 AVFCapture -[AVCaptureSession removeInput:] + 344+14 AVFCapture -[AVCaptureSession dealloc] + 308+15 Foundation _NSKVOPerformWithDeallocatingObservable + 180+16 Foundation NSKVODeallocate + 184+17 libobjc.A.dylib AutoreleasePoolPage::releaseUntil(objc_object**) + 204+18 libobjc.A.dylib objc_autoreleasePoolPop + 244+19 SessionProbe RunCameraSessionProbe + 440diff --git a/Research/Guest/camera_session_teardown.md b/Research/Guest/camera_session_teardown.mdnew file mode 100644index 00000000..f62fbda5--- /dev/null+++ b/Research/Guest/camera_session_teardown.md@@ -0,0 +1,81 @@+# Camera session teardown crash++The virtual-camera `isRunning` hook adds a weak reference to a session during deallocation.+Objective-C rejects the reference and aborts the app.+AVFoundation reaches the hook through `AVCaptureInput setSession:` while it removes the session inputs.++The getter must keep tracking live sessions.+Some camera clients skip `startRunning` because the getter already returns `YES`.+Removing tracking from the getter can stop frame delivery for those clients.++`cfx_live_session` uses `objc_storeWeakOrNil` to skip objects already in deallocation.+Its strong weak-load keeps live sessions alive through table insertion.+The tracking argument uses `__unsafe_unretained` so ARC does not retain a dying session on entry.++## Reproduction++Build the small camera app:++```sh+make -C VPhoneGuestComponents build-camfix-session-reproducer+```++Install `.build/siblings/camera-session-reproducer/SessionProbe.ipa` in an iOS guest.+Run `org.example.vphone.SessionProbe`.+The app automatically creates and releases 100 sessions with the virtual-camera input and a video data output.+It adds a KVO observer for `running` on alternate cycles.+It does not start capture.++The original library aborts during session deallocation.+The patched library completes all cycles.+The app shows the result and writes `Documents/result.txt` in its data container.++## Crash stack with the original 2.13.4 library++The [crash log excerpt](Evidence/camfix_session_teardown_crash.txt) includes the abort frames and library names.++```text+Exception: EXC_CRASH (SIGABRT)+Termination namespace: OBJC++weak_register_no_lock + 396+objc_storeWeak + 468+-[NSConcreteHashTable addObject:] + 96+cfx_track_vcam_session + 128+cfx_session_isRunning_hook + 76+-[AVCaptureInput setSession:] + 64+-[AVCaptureDeviceInput setSession:] + 272+-[AVCaptureSession _removeInput:] + 232+-[AVCaptureSession removeInput:] + 344+-[AVCaptureSession dealloc] + 308+_NSKVOPerformWithDeallocatingObservable + 180+NSKVODeallocate + 184+AutoreleasePoolPage::releaseUntil(objc_object**) + 204+objc_autoreleasePoolPop + 244+RunCameraSessionProbe + 440+```++## Results on iOS 27.0.1 (24A446)++- The original 2.13.4 libcamfix crashed twice with the same test app.+- A repeat with both stock 2.13.4 camera libraries produced the same crash.+- The clean-branch libcamfix with stock libvcamcaptured completed 100 release cycles.+- With that pair, Camera.app showed the host test pattern and saved photos and an 8.32-second movie.+- The movie contained 1280x720 H.264 video. All 251 decoded frames had distinct hashes.+- Camera.app also saved a photo after a cold reopening. No Camera.app crash reports appeared.++Camera.app was a regression check. The small test app reproduced the crash.+The final comparison used stock libvcamcaptured in both runs.+Only libcamfix changed. No local 1080p format changes were present.+These results cover one firmware pairing.++The full `VPhone` Debug build and bundle admission passed with Xcode 27.2.+The bundled libcamfix hash matched the clean-branch library used in the final guest run.+The camera geometry, data plane, prewarm, drive gate, loader links, and session lifetime tests passed.++The host regression test covers nil, live sessions, and deallocation.+It also checks that weak tracking does not retain a session after its owner releases it.++```sh+make -C VPhoneGuestComponents test-camfix-session-lifetime+```diff --git a/VPhoneGuestComponents/CamFix/CamFixPrivate.h b/VPhoneGuestComponents/CamFix/CamFixPrivate.hindex 0625a672..b1d872c1 100644--- a/VPhoneGuestComponents/CamFix/CamFixPrivate.h+++ b/VPhoneGuestComponents/CamFix/CamFixPrivate.h@@ -85,7 +85,7 @@ CFX_HIDDEN void cfx_install_remote_queue_tap(void);// MARK: - sessions (Session/)-CFX_HIDDEN void cfx_track_vcam_session(id session);+CFX_HIDDEN void cfx_track_vcam_session(id __unsafe_unretained session);CFX_HIDDEN void cfx_deliver_video_frames_once(void);CFX_HIDDEN void cfx_install_session_guards(void);CFX_HIDDEN void cfx_install_input_diagnostics(void);diff --git a/VPhoneGuestComponents/CamFix/Session/CamFixSessionLifetime.h b/VPhoneGuestComponents/CamFix/Session/CamFixSessionLifetime.hnew file mode 100644index 00000000..fe40699d--- /dev/null+++ b/VPhoneGuestComponents/CamFix/Session/CamFixSessionLifetime.h@@ -0,0 +1,13 @@+#import <Foundation/Foundation.h>++// The ordinary weak store aborts if AVFoundation calls a session getter from+// -dealloc. This runtime entry point leaves the slot nil instead. Use an alias+// so ARC still manages the local weak slot and its subsequent strong load.+extern id cfx_storeWeakOrNil(id __weak *location, id value)+ __asm("_objc_storeWeakOrNil");++static inline id cfx_live_session(id __unsafe_unretained session) {+ __weak id candidate = nil;+ cfx_storeWeakOrNil(&candidate, session);+ return candidate;+}diff --git a/VPhoneGuestComponents/CamFix/Session/CamFixVideoDelivery.m b/VPhoneGuestComponents/CamFix/Session/CamFixVideoDelivery.mindex e6bb6c7d..eb184149 100644--- a/VPhoneGuestComponents/CamFix/Session/CamFixVideoDelivery.m+++ b/VPhoneGuestComponents/CamFix/Session/CamFixVideoDelivery.m@@ -3,6 +3,7 @@#import "CamFixPrivate.h"#include "CamFixFrameGeometry.h"+#include "CamFixSessionLifetime.h"// MARK: - client-side video delivery for vcam sessions//@@ -21,7 +22,8 @@ static _Atomic int cfx_video_deliver_logged = 0;// Also arms the 30 Hz pump: a session with a data output and no preview// layer would otherwise never start it.-void cfx_track_vcam_session(id session) {+void cfx_track_vcam_session(id __unsafe_unretained candidate) {+ id session = cfx_live_session(candidate);if (!session) return;BOOL added = NO;pthread_mutex_lock(&cfx_vcam_sessions_lock);diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex ccb51597..434c77fd 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -574,6 +574,19 @@ test-vcam-drive-gate:Tests/VCamDriveGateTests.c VCamCaptured/Frames/VCamDriveGate.c@$(OUT)/VCamDriveGateTests+# Host proof harness for camera-session weak registration during teardown.+.PHONY: test-camfix-session-lifetime+test-camfix-session-lifetime:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -fobjc-arc -O1 -Wall -Wextra -Werror \+ -ICamFix/Session -framework Foundation \+ -o $(OUT)/CamFixSessionLifetimeTests Tests/CamFixSessionLifetimeTests.m+ @$(OUT)/CamFixSessionLifetimeTests++.PHONY: build-camfix-session-reproducer+build-camfix-session-reproducer:+ zsh Tests/CameraSessionReproducer/build.zsh "$(OUT)/camera-session-reproducer"+# Host proof harness for the crop, size and turn plan libcamfix uses for# AVCaptureVideoDataOutput frames..PHONY: test-camfix-geometrydiff --git a/VPhoneGuestComponents/Tests/CamFixSessionLifetimeTests.m b/VPhoneGuestComponents/Tests/CamFixSessionLifetimeTests.mnew file mode 100644index 00000000..3327fa21--- /dev/null+++ b/VPhoneGuestComponents/Tests/CamFixSessionLifetimeTests.m@@ -0,0 +1,32 @@+#import "CamFixSessionLifetime.h"+#include <assert.h>++static BOOL checkedDealloc;+static NSHashTable *sessions;+@interface SessionProbe : NSObject+@end+@implementation SessionProbe+- (void)dealloc {+ // Mirrors isRunning -> tracking during AVCaptureSession teardown.+ assert(cfx_live_session(self) == nil);+ checkedDealloc = YES;+}+@end++int main(void) {+ @autoreleasepool {+ assert(cfx_live_session(nil) == nil);+ sessions = [NSHashTable weakObjectsHashTable];+ @autoreleasepool {+ SessionProbe *session = [SessionProbe new];+ id live = cfx_live_session(session);+ assert(live == session);+ [sessions addObject:live];+ assert([sessions containsObject:session]);+ assert(!checkedDealloc);+ }+ assert(checkedDealloc);+ assert(sessions.allObjects.count == 0);+ }+ puts("CamFix session lifetime: passed");+}diff --git a/VPhoneGuestComponents/Tests/CameraSessionReproducer/Bridge.h b/VPhoneGuestComponents/Tests/CameraSessionReproducer/Bridge.hnew file mode 100644index 00000000..14d98af0--- /dev/null+++ b/VPhoneGuestComponents/Tests/CameraSessionReproducer/Bridge.h@@ -0,0 +1,2 @@+#import <Foundation/Foundation.h>+NSString * _Nonnull RunCameraSessionProbe(void);diff --git a/VPhoneGuestComponents/Tests/CameraSessionReproducer/CameraSessionProbe.m b/VPhoneGuestComponents/Tests/CameraSessionReproducer/CameraSessionProbe.mnew file mode 100644index 00000000..552b8fe9--- /dev/null+++ b/VPhoneGuestComponents/Tests/CameraSessionReproducer/CameraSessionProbe.m@@ -0,0 +1,37 @@+#import <AVFoundation/AVFoundation.h>++@interface RunningObserver : NSObject+@end+@implementation RunningObserver+- (void)observeValueForKeyPath:(NSString *)path ofObject:(id)object+ change:(NSDictionary *)change context:(void *)context {}+@end++// Public AVFoundation API only.+// Run on a background queue. This does not start capture or save images.+NSString *RunCameraSessionProbe(void) {+ AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];+ if (!device) return @"INCONCLUSIVE: no video device";+ if (![device.uniqueID isEqualToString:@"vphone:vcam:0"])+ return @"INCONCLUSIVE: expected vPhone synthetic camera";+ RunningObserver *observer = [RunningObserver new];+ for (NSUInteger cycle = 0; cycle < 100; cycle++) {+ @autoreleasepool {+ NSError *error = nil;+ AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];+ if (!input) return [NSString stringWithFormat:@"INCONCLUSIVE: input creation: %@", error];+ AVCaptureSession *session = [AVCaptureSession new];+ if (![session canAddInput:input]) return @"INCONCLUSIVE: input rejected";+ [session addInput:input];+ AVCaptureVideoDataOutput *output = [AVCaptureVideoDataOutput new];+ if (![session canAddOutput:output]) return @"INCONCLUSIVE: output rejected";+ [session addOutput:output];+ // Exercise both ordinary and KVO-observed session destruction.+ // Modern Foundation removes registrations during observed-object dealloc.+ if (cycle % 2) [session addObserver:observer forKeyPath:@"running" options:0 context:NULL];+ NSLog(@"SessionProbe cycle %lu releasing configured session", (unsigned long)cycle);+ session = nil;+ }+ }+ return @"Completed 100 configured-session release cycles. This alone does not verify frame delivery.";+}diff --git a/VPhoneGuestComponents/Tests/CameraSessionReproducer/Info.plist b/VPhoneGuestComponents/Tests/CameraSessionReproducer/Info.plistnew file mode 100644index 00000000..0eb0ca1a--- /dev/null+++ b/VPhoneGuestComponents/Tests/CameraSessionReproducer/Info.plist@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleIdentifier</key><string>org.example.vphone.SessionProbe</string>+<key>CFBundleName</key><string>SessionProbe</string>+<key>CFBundleExecutable</key><string>SessionProbe</string>+<key>CFBundlePackageType</key><string>APPL</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleShortVersionString</key><string>1.0</string>+<key>MinimumOSVersion</key><string>26.0</string>+<key>LSRequiresIPhoneOS</key><true/>+<key>NSCameraUsageDescription</key><string>Test synthetic camera session lifetime without saving images.</string>+<key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key><false/></dict>+<key>UILaunchScreen</key><dict/>+</dict></plist>diff --git a/VPhoneGuestComponents/Tests/CameraSessionReproducer/Probe.swift b/VPhoneGuestComponents/Tests/CameraSessionReproducer/Probe.swiftnew file mode 100644index 00000000..c22f9545--- /dev/null+++ b/VPhoneGuestComponents/Tests/CameraSessionReproducer/Probe.swift@@ -0,0 +1,23 @@+import SwiftUI++@main struct SessionProbeApp: App {+ var body: some Scene { WindowGroup { ProbeView() } }+}++struct ProbeView: View {+ @State private var status = "Ready"+ var body: some View {+ VStack(spacing: 20) {+ Text("Camera Session Lifetime")+ Text(status)+ }.padding().task {+ status = "Configuring and releasing synthetic sessions"+ DispatchQueue.global(qos: .userInitiated).async {+ let result = RunCameraSessionProbe()+ let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]+ try? result.write(to: documents.appendingPathComponent("result.txt"), atomically: true, encoding: .utf8)+ DispatchQueue.main.async { status = result }+ }+ }+ }+}diff --git a/VPhoneGuestComponents/Tests/CameraSessionReproducer/build.zsh b/VPhoneGuestComponents/Tests/CameraSessionReproducer/build.zshnew file mode 100644index 00000000..eb7c0f22--- /dev/null+++ b/VPhoneGuestComponents/Tests/CameraSessionReproducer/build.zsh@@ -0,0 +1,15 @@+#!/bin/zsh+set -euo pipefail+cd "${0:a:h}"+output=${1:?Pass an absolute output directory}+app="$output/Payload/SessionProbe.app"+mkdir -p "$app"+sdk=$(xcrun --sdk iphoneos --show-sdk-path)+xcrun --sdk iphoneos clang -fobjc-arc -O1 -target arm64-apple-ios26.0 \+ -isysroot "$sdk" -c CameraSessionProbe.m -o "$output/CameraSessionProbe.o"+xcrun --sdk iphoneos swiftc -O -target arm64-apple-ios26.0 -sdk "$sdk" \+ -parse-as-library -import-objc-header Bridge.h Probe.swift "$output/CameraSessionProbe.o" \+ -framework AVFoundation -o "$app/SessionProbe"+cp Info.plist "$app/"+codesign --force --sign - "$app"+ditto -c -k --keepParent "$output/Payload" "$output/SessionProbe.ipa"