Run a virtual iPhone on an Apple Silicon Mac.
Swift
camera: load libcamfix into every AVFoundation client via TweakLoader Filter.Frameworks
zqxwce35a7bd44d8b1
diff --git a/scripts/camfix/libcamfix.m b/scripts/camfix/libcamfix.mindex 5527307d..f1e77a55 100644--- a/scripts/camfix/libcamfix.m+++ b/scripts/camfix/libcamfix.m@@ -33,6 +33,9 @@#include <unistd.h>#include <objc/runtime.h>#include <objc/message.h>+#include <mach-o/dyld.h>+#include <mach-o/loader.h>+#include <string.h>#define LOG_PATH "/tmp/camfix.log"#define SHM_PATH "/var/jb/var/mobile/Library/vphone-vcam-frame.shm"@@ -180,10 +183,78 @@ static void cfx_install_setActiveFormat_hook(void) {cfx_orig_setActiveFormat);}-// MARK: - capturePhoto swizzle (same as libcameratest)+// MARK: - capturePhoto swizzle (modern + deprecated delegate paths)static IMP cfx_orig_capturePhoto = NULL;+// Forward decls: helpers defined further down — shared with the+// moment-capture (Camera.app) delivery path.+static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED;+static CGImageRef cfx_build_cgimage_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED;+static NSData *cfx_build_jpeg_from_shm(uint32_t *outW, uint32_t *outH);+static id cfx_build_avcapturephoto_with_request(IOSurfaceRef surf,+ uint32_t w, uint32_t h,+ id captureRequest);++// Associated-object keys (used by fileDataRepresentation /+// CGImageRepresentation hooks to recognize "our" photos). Defined here+// so cfx_deliver_capturePhoto can reference them before the hooks that+// also use them are declared further down.+static const void *CFX_ASSOC_JPEG_KEY = &CFX_ASSOC_JPEG_KEY;+static const void *CFX_ASSOC_CGIMG_KEY = &CFX_ASSOC_CGIMG_KEY;++static void cfx_deliver_capturePhoto(id output, id delegate, id settings) {+ // Modern path used by any AVF client: build a real AVCapturePhoto from+ // the shm frame, tag it with our JPEG + CGImage so fileDataRepresentation+ // / CGImageRepresentation return our bytes, fire the modern delegate+ // didFinishProcessingPhoto:error:.+ // Falls back to the deprecated CMSampleBuffer delegate if the client+ // opts into it (only test harnesses do; production AVF clients implement+ // the modern method).+ SEL oldSel = NSSelectorFromString(+ @"captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:");+ if ([delegate respondsToSelector:oldSel]) {+ CMSampleBufferRef sbuf = cfx_build_cmsb();+ if (!sbuf) { cfxlog(@"[capturePhoto] build_cmsb returned NULL"); return; }+ cfxlog(@"[capturePhoto] dispatching deprecated didFinishProcessingPhotoSampleBuffer:");+ ((void (*)(id, SEL, id, CMSampleBufferRef, CMSampleBufferRef, id, id, id))objc_msgSend)(+ delegate, oldSel, output, sbuf, NULL, (id)nil, (id)nil, (id)nil);+ CFRelease(sbuf);+ return;+ }++ SEL S5 = @selector(captureOutput:didFinishProcessingPhoto:error:);+ if (![delegate respondsToSelector:S5]) {+ cfxlog(@"[capturePhoto] delegate implements neither modern nor deprecated method");+ return;+ }++ uint32_t w = 0, h = 0;+ IOSurfaceRef surf = cfx_build_iosurface_from_shm(&w, &h);+ if (!surf) { cfxlog(@"[capturePhoto] no IOSurface"); return; }++ // captureRequest = nil (no CAMCaptureEngine outside Camera.app). The+ // AVCapturePhoto init handles nil safely — objc_msgSend on nil returns 0+ // for the resolvedSettings / unresolvedSettings calls it makes during init.+ id photo = cfx_build_avcapturephoto_with_request(surf, w, h, nil);+ CFRelease(surf);+ if (!photo) { cfxlog(@"[capturePhoto] no AVCapturePhoto"); return; }++ NSData *jpeg = cfx_build_jpeg_from_shm(NULL, NULL);+ CGImageRef cgImg = cfx_build_cgimage_from_shm(NULL, NULL);+ if (jpeg) objc_setAssociatedObject(photo, CFX_ASSOC_JPEG_KEY, jpeg,+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ if (cgImg) {+ objc_setAssociatedObject(photo, CFX_ASSOC_CGIMG_KEY,+ (__bridge id)cgImg,+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ CGImageRelease(cgImg);+ }+ cfxlog(@"[capturePhoto] firing didFinishProcessingPhoto: with vcam photo (%lu bytes jpeg)",+ (unsigned long)jpeg.length);+ ((void (*)(id, SEL, id, id, id))objc_msgSend)(delegate, S5, output, photo, nil);+}+static void cfx_capturePhoto_hook(id self, SEL _cmd, id settings, id delegate) {cfxlog(@"[capturePhoto] self=%p settings=%@ delegate=%@",self, settings, delegate);@@ -210,25 +281,12 @@ static void cfx_capturePhoto_hook(id self, SEL _cmd, id settings, id delegate) {((OrigFn)cfx_orig_capturePhoto)(self, _cmd, settings, delegate);return;}+ __strong id retainedSelf = self;+ __strong id retainedDelegate = delegate;+ __strong id retainedSettings = settings;dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{@autoreleasepool {- CMSampleBufferRef sbuf = cfx_build_cmsb();- if (!sbuf) {- cfxlog(@"build_cmsb returned NULL");- return;- }- SEL oldSel = NSSelectorFromString(- @"captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:");- if ([delegate respondsToSelector:oldSel]) {- cfxlog(@"dispatching deprecated didFinishProcessingPhotoSampleBuffer:");- ((void (*)(id, SEL, id, CMSampleBufferRef, CMSampleBufferRef, id, id, id))objc_msgSend)(- delegate, oldSel,- self, sbuf, NULL,- (id)nil, (id)nil, (id)nil);- } else {- cfxlog(@"delegate doesn't implement deprecated sample-buffer method");- }- CFRelease(sbuf);+ cfx_deliver_capturePhoto(retainedSelf, retainedDelegate, retainedSettings);}});}@@ -846,10 +904,8 @@ static id cfx_build_avcapturephoto(IOSurfaceRef surf, uint32_t w, uint32_t h) {// MARK: - fileDataRepresentation / CGImageRepresentation hooks//// We tag synthesized photos via objc_setAssociatedObject so the hook-// recognizes "ours" without a global dict.--static const void *CFX_ASSOC_JPEG_KEY = &CFX_ASSOC_JPEG_KEY;-static const void *CFX_ASSOC_CGIMG_KEY = &CFX_ASSOC_CGIMG_KEY;+// recognizes "ours" without a global dict. Keys are defined earlier in+// the file alongside cfx_deliver_capturePhoto's forward decls.static IMP cfx_orig_fileDataRep = NULL;static IMP cfx_orig_cgImageRep = NULL;@@ -1247,17 +1303,57 @@ static void cfx_install_session_state_lies(void) {}}+// When libcamfix is loaded as an LC_LOAD_DYLIB dependency of AVFoundation+// (via the DSC patch cfw_patch_avf_load_dylib.py), our constructor fires+// during dyld's image-load phase — possibly BEFORE AVFCapture's classes+// are registered. Defer hook installation to a dyld add-image callback+// that fires once for every image. Install hooks the first time we see+// AVFCapture (the framework that actually defines AVCapture*), which+// guarantees its classes are registered. Idempotent: install at most once.++static dispatch_once_t cfx_install_once_token;++static void cfx_install_all_hooks(void) {+ dispatch_once(&cfx_install_once_token, ^{+ cfxlog(@"installing hooks (process=%@, pid=%d)",+ NSProcessInfo.processInfo.processName ?: @"?", getpid());+ cfx_install_setActiveFormat_hook();+ cfx_install_capturePhoto_hook();+ cfx_install_moment_capture_hooks();+ cfx_install_session_guards();+ cfx_install_session_state_lies();+ cfx_install_preview_layer_hooks();+ cfx_install_photo_representation_hooks();+ cfx_install_capturerequest_stubs();+ cfx_start_scan_timer();+ });+}++static BOOL cfx_image_is_avfcapture(const struct mach_header *mh) {+ // dyld add-image callback gives us only the load address; recover the+ // install path via dyld_image_count + dyld_get_image_header iteration.+ uint32_t count = _dyld_image_count();+ for (uint32_t i = 0; i < count; i++) {+ if (_dyld_get_image_header(i) != mh) continue;+ const char *name = _dyld_get_image_name(i);+ if (!name) return NO;+ // AVFCapture lives at .../PrivateFrameworks/AVFCapture.framework/AVFCapture+ return strstr(name, "/AVFCapture.framework/AVFCapture") != NULL;+ }+ return NO;+}++static void cfx_on_add_image(const struct mach_header *mh, intptr_t slide) {+ (void)slide;+ if (cfx_image_is_avfcapture(mh)) cfx_install_all_hooks();+}+__attribute__((constructor))static void cfx_init(void) {- cfxlog(@"loaded into %@ (pid=%d)",+ cfxlog(@"libcamfix loaded into %@ (pid=%d)",NSProcessInfo.processInfo.processName ?: @"?", getpid());- cfx_install_setActiveFormat_hook();- cfx_install_capturePhoto_hook();- cfx_install_moment_capture_hooks();- cfx_install_session_guards();- cfx_install_session_state_lies();- cfx_install_preview_layer_hooks();- cfx_install_photo_representation_hooks();- cfx_install_capturerequest_stubs();- cfx_start_scan_timer();+ // _dyld_register_func_for_add_image fires the callback synchronously+ // for every already-loaded image, then once per future image. So+ // whether AVFCapture loads before or after libcamfix, we catch it.+ _dyld_register_func_for_add_image(cfx_on_add_image);}diff --git a/scripts/camfix/libcamfix.plist b/scripts/camfix/libcamfix.plistindex 753b261a..92f0f56c 100644--- a/scripts/camfix/libcamfix.plist+++ b/scripts/camfix/libcamfix.plist@@ -4,9 +4,9 @@<dict><key>Filter</key><dict>- <key>Bundles</key>+ <key>Frameworks</key><array>- <string>com.apple.camera</string>+ <string>AVFoundation</string></array></dict></dict>diff --git a/scripts/cfw_install_exp.sh b/scripts/cfw_install_exp.shindex 7be39af3..29b11f23 100755--- a/scripts/cfw_install_exp.sh+++ b/scripts/cfw_install_exp.sh@@ -275,8 +275,10 @@ build_libvcamcaptured() {echo "$out"}-# Builds the libcamfix.dylib substrate plugin loaded into Camera.app-# (com.apple.camera) via TweakLoader. Implements the photo-delivery+# Builds the libcamfix.dylib substrate plugin. Loaded into every process+# that links AVFoundation via TweakLoader's Filter.Frameworks key —+# Camera.app, third-party apps, anywhere the+# documented capture interface is used. Implements the photo-delivery# path through CAMCaptureEngine + the preview/state guards that keep# the viewfinder live on the virtual camera.build_libcamfix() {@@ -594,11 +596,11 @@ fiecho " [+] libvcamcaptured installed to procursus/Library/MobileSubstrate/DynamicLibraries/"# ═══════════ JB-4.2 INSTALL libcamfix ═══════════════════════════════-# Substrate plugin loaded into Camera.app (com.apple.camera). Hooks-# AVCapturePhotoOutput's moment-capture path to route synthesized-# AVCapturePhoto instances (backed by vphone shm frames) through-# CAMCaptureEngine's normal photo-save pipeline. Pairs with the-# preview-pump + session-state lies that keep the viewfinder live.+# Substrate plugin loaded by TweakLoader into every process that links+# AVFoundation. The companion plist's Filter.Frameworks = ["AVFoundation"]+# tells TweakLoader to defer the dlopen until AVFoundation actually+# appears in the loaded image list (via _dyld_register_func_for_add_image),+# so processes that don't use AVF don't pay any cost.echo ""echo "[JB-4.2] Building and installing libcamfix..."LIBCAMFIX_OUT="$(build_libcamfix)"@@ -606,8 +608,6 @@ scp_to "$LIBCAMFIX_OUT" "$LIBVCAM_DIR/libcamfix.dylib"ssh_cmd "/usr/sbin/chown 0:0 $LIBVCAM_DIR/libcamfix.dylib"ssh_cmd "/bin/chmod 0755 $LIBVCAM_DIR/libcamfix.dylib"-# Filter.Bundles = ["com.apple.camera"] gates TweakLoader so the dylib-# only loads inside Camera.app.LIBCAMFIX_PLIST="$SCRIPT_DIR/camfix/libcamfix.plist"if [[ -f "$LIBCAMFIX_PLIST" ]]; thenscp_to "$LIBCAMFIX_PLIST" "$LIBVCAM_DIR/libcamfix.plist"diff --git a/scripts/tweakloader/TweakLoader.m b/scripts/tweakloader/TweakLoader.mindex b1420878..0ce05fe7 100644--- a/scripts/tweakloader/TweakLoader.m+++ b/scripts/tweakloader/TweakLoader.m@@ -1,7 +1,10 @@#import <Foundation/Foundation.h>#import <dlfcn.h>#import <fcntl.h>+#import <mach-o/dyld.h>+#import <mach-o/loader.h>#import <stdarg.h>+#import <string.h>#import <unistd.h>static NSString *const kTweakDir = @"/var/jb/Library/MobileSubstrate/DynamicLibraries";@@ -110,57 +113,179 @@ static BOOL TLFilterMatches(NSDictionary *plist, NSString *bundleID, NSString *ereturn YES;}-static void TLLoadTweaks(void) {- NSFileManager *fm = NSFileManager.defaultManager;- NSString *execPath = TLExecutablePath();- NSString *bundleID = NSBundle.mainBundle.bundleIdentifier ?: @"";- NSString *executableName = TLExecutableName();+// Match a loaded dylib path against a "framework name" filter entry.+// "AVFoundation" matches any path containing "/AVFoundation.framework/" —+// catches both /System/Library/Frameworks/... and PrivateFrameworks/....+static BOOL TLPathMatchesFramework(const char *path, NSString *frameworkName) {+ if (!path || !frameworkName.length) return NO;+ NSString *needle = [NSString stringWithFormat:@"/%@.framework/", frameworkName];+ return strstr(path, needle.UTF8String) != NULL;+}- if (!TLShouldRunInCurrentProcess()) {- return;+// Pending framework-filtered tweaks: each entry is @{"dylib": path, "frameworks": @[name,...]}.+static NSMutableArray<NSDictionary *> *gTLPendingFrameworkTweaks = nil;+static NSLock *gTLPendingLock = nil;+static dispatch_once_t gTLAddImageOnce;++// dyld invokes add-image callbacks SYNCHRONOUSLY inside its loader lock.+// Calling dlopen from here would recurse and can deadlock or crash early+// daemons. Hand the actual dlopen off to a background queue so it runs+// outside the loader lock — by the time it executes, the framework that+// triggered it is fully loaded.+static void TLOnImageAdded(const struct mach_header *mh, intptr_t slide) {+ (void)slide;+ Dl_info info; if (!dladdr((const void *)mh, &info)) return;+ const char *cpath = info.dli_fname; if (!cpath) return;+ NSString *imagePath = [NSString stringWithUTF8String:cpath];+ if (!imagePath.length) return;++ NSArray<NSDictionary *> *snapshot;+ [gTLPendingLock lock];+ snapshot = [gTLPendingFrameworkTweaks copy];+ [gTLPendingLock unlock];+ if (!snapshot.count) return;++ NSMutableArray<NSString *> *toLoad = [NSMutableArray array];+ for (NSDictionary *pending in snapshot) {+ NSArray *frameworks = pending[@"frameworks"];+ for (NSString *fw in frameworks) {+ if (TLPathMatchesFramework(imagePath.UTF8String, fw)) {+ [toLoad addObject:pending[@"dylib"]];+ break;+ }+ }}+ if (!toLoad.count) return;- NSArray<NSString *> *files = [fm contentsOfDirectoryAtPath:kTweakDir error:nil];- if (!files.count) {- TLLog(@"No tweak files found for bundle=%@ exec=%@ path=%@",- bundleID, executableName, execPath);+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ for (NSString *dylibPath in toLoad) {+ void *h = dlopen(dylibPath.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);+ if (h) TLLog(@"framework-deferred-load %@ -> %p (triggered by %@)",+ dylibPath, h, imagePath);+ else TLLog(@"framework-deferred-load failed for %@: %s",+ dylibPath, dlerror() ?: "unknown");+ }+ });+}++// Schedule a tweak whose Filter.Frameworks needs at least one framework loaded.+// If a matching framework is already in the process, dlopen via dispatch_async+// (the constructor is still inside dyld's image loading sequence). Otherwise+// queue it; the dyld add-image callback (also async-deferred) handles future.+static void TLScheduleFrameworkTweak(NSString *dylibPath, NSArray *frameworks) {+ // Already-loaded fast path: schedule dlopen on a background queue so it+ // runs after the TweakLoader constructor returns and dyld is idle.+ uint32_t n = _dyld_image_count();+ for (uint32_t i = 0; i < n; i++) {+ const char *p = _dyld_get_image_name(i);+ for (NSString *fw in frameworks) {+ if (TLPathMatchesFramework(p, fw)) {+ TLLog(@"queueing %@ for async load (framework %@ already loaded as %s)",+ dylibPath, fw, p);+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ void *h = dlopen(dylibPath.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);+ if (h) TLLog(@"framework-load %@ -> %p", dylibPath, h);+ else TLLog(@"framework-load failed for %@: %s",+ dylibPath, dlerror() ?: "unknown");+ });+ return;+ }+ }+ }++ // Queue for later; register the add-image callback once.+ [gTLPendingLock lock];+ if (!gTLPendingFrameworkTweaks) gTLPendingFrameworkTweaks = [NSMutableArray array];+ [gTLPendingFrameworkTweaks addObject:@{@"dylib": dylibPath, @"frameworks": frameworks}];+ [gTLPendingLock unlock];++ dispatch_once(&gTLAddImageOnce, ^{+ _dyld_register_func_for_add_image(TLOnImageAdded);+ });+}++static void TLLoadTweaks(void) {+ // Two engagement tiers:+ //+ // 1. Framework-filtered tweaks (Filter.Frameworks in plist): scanned+ // and scheduled in EVERY process. The schedule is a no-op unless+ // the named framework actually loads in this process — the dyld+ // add-image callback (dispatch_async'd dlopen) is what eventually+ // pulls the tweak in. Cost in non-AVF processes: one dir scan,+ // a few plist parses, one callback registration. Safe because+ // no dlopen happens until the framework appears.+ //+ // 2. Non-framework tweaks (Bundles/Executables filter or none):+ // only run in .app/ processes and the explicit daemon allowlist+ // (TLShouldRunInCurrentProcess). Keeping this gate avoids dropping+ // arbitrary tweaks into launch-critical daemons by accident.+ //+ // Everything below is wrapped in @try/@catch so a bad plist or+ // Foundation quirk in an early-boot daemon can't crash the whole+ // process and trigger a launchd respawn loop.+ NSFileManager *fm = nil;+ NSArray<NSString *> *files = nil;+ @try {+ fm = NSFileManager.defaultManager;+ files = [fm contentsOfDirectoryAtPath:kTweakDir error:nil];+ } @catch (NSException *e) {return;}+ if (!files.count) return;++ NSString *execPath = TLExecutablePath();+ NSString *bundleID = NSBundle.mainBundle.bundleIdentifier ?: @"";+ NSString *executableName = TLExecutableName();+ BOOL processAllowed = TLShouldRunInCurrentProcess();- TLLog(@"Scanning %lu tweak entries for bundle=%@ exec=%@ path=%@",- (unsigned long)files.count, bundleID, executableName, execPath);+ if (gTLPendingLock == nil) gTLPendingLock = [[NSLock alloc] init];for (NSString *filename in files) {if (![filename.pathExtension isEqualToString:@"plist"]) continue;- NSString *plistPath = [kTweakDir stringByAppendingPathComponent:filename];- NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:plistPath];- if (![plist isKindOfClass:[NSDictionary class]]) {- TLLog(@"Skipping unreadable plist %@", plistPath);- continue;- }+ NSDictionary *plist = nil;+ NSString *dylibPath = nil;+ @try {+ NSString *plistPath = [kTweakDir stringByAppendingPathComponent:filename];+ plist = [NSDictionary dictionaryWithContentsOfFile:plistPath];+ if (![plist isKindOfClass:[NSDictionary class]]) continue;- if (!TLFilterMatches(plist, bundleID, executableName)) {+ NSString *baseName = filename.stringByDeletingPathExtension;+ dylibPath = [[kTweakDir stringByAppendingPathComponent:baseName]+ stringByAppendingPathExtension:@"dylib"];+ if (![fm isExecutableFileAtPath:dylibPath]) continue;+ } @catch (NSException *e) {continue;}- NSString *baseName = filename.stringByDeletingPathExtension;- NSString *dylibPath = [[kTweakDir stringByAppendingPathComponent:baseName]- stringByAppendingPathExtension:@"dylib"];+ @try {+ NSDictionary *filter = plist[@"Filter"];+ id frameworksRaw = [filter isKindOfClass:[NSDictionary class]] ? filter[@"Frameworks"] : nil;- if (![fm isExecutableFileAtPath:dylibPath]) {- TLLog(@"Skipping %@ because dylib is missing or not executable", dylibPath);- continue;- }+ if ([frameworksRaw isKindOfClass:[NSArray class]] &&+ [(NSArray *)frameworksRaw count] > 0) {+ // Universal: schedule in every process. No-op in processes+ // where the named framework never loads.+ TLScheduleFrameworkTweak(dylibPath, (NSArray *)frameworksRaw);+ continue;+ }++ // Non-framework-filtered: keep the .app/+allowlist gate.+ if (!processAllowed) continue;+ if (!TLFilterMatches(plist, bundleID, executableName)) continue;- void *handle = dlopen(dylibPath.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);- if (handle) {- TLLog(@"Loaded %@", dylibPath);- } else {- const char *err = dlerror();- TLLog(@"Failed to load %@: %s", dylibPath, err ?: "unknown error");+ void *handle = dlopen(dylibPath.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);+ if (handle) {+ TLLog(@"Loaded %@ (exec=%@ bundle=%@)", dylibPath, executableName, bundleID);+ } else {+ const char *err = dlerror();+ TLLog(@"Failed to load %@: %s", dylibPath, err ?: "unknown error");+ }+ } @catch (NSException *e) {+ TLLog(@"Exception loading %@: %@", dylibPath, e);}}+ (void)execPath;}__attribute__((constructor))