Run a virtual iPhone on an Apple Silicon Mac.
Swift
Show a healthy virtual battery in Battery Health instead of a spinner
Jackyf79c2bdabfab
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 365d0917..6b396b71 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -528,6 +528,7 @@ do NOT execute these).| 21 | No binary change: SystemHook `dlopen`s `libhapticsfix.dylib` into `SpringBoard` at startup, where it replaces every `CHHapticEngine` initialiser's IMP so the initialiser returns nil — **all bases** | none (new guest dylib `VPhoneGuestComponents/HapticsFix/libhapticsfix.c`, installed at `/usr/lib/libhapticsfix.dylib`) | **Stop SpringBoard dying the first time UIKit plays a haptic.** The VM has no haptic device — Virtualization.framework exposes none on any base — and a real device without one gets nil from `CHHapticEngine`'s initialisers, so UIKit runs with no feedback, as on every non-Pro iPad. A guest reporting an iPad Pro model instead has an OS that *expects* the haptic stack, and CoreHaptics treats its absence as an internal error: measured on `iPad16,1 26.6.2 (23G90)`, 4h14m after launch, the first feedback event ran `-[_UIFeedbackCoreHapticsIgnoreCaptureHapticsOnlyEngine _internal_createCoreHapticsEngine]` → `-[CHHapticEngine initWithAudioSession:sessionIsShared:options:error:]` → `createHapticPlayerWithOptions:` → `Haptic_RaiseException` → `objc_exception_throw`, and the unwind resumed at an address inside a `---/---` Memory Tag 255 COW region next to the commpage — `EXC_BAD_ACCESS (SIGBUS)`, `KERN_PROTECTION_FAILURE`, a dead SpringBoard. The hook restores the no-hardware answer before UIKit can reach an initialiser: the constructor `dlopen`s CoreHaptics (it is not loaded that early, and the class must be in the runtime before UIKit asks), then `method_setImplementation` on every selector that is `init` or `init` + uppercase part — covering `initWithAudioSession:sessionIsShared:options:error:` today and any renamed sibling on other bases — with one IMP that ignores its arguments and returns nil, the framework's own answer on haptic-less hardware. Scope is SpringBoard only (`vpIsSpringBoard` in SystemHook, loaded before the app/bootstrap gate that would otherwise return first): it is the one UIKit process measured creating the haptics-only engine without asking CoreHaptics first, and apps that follow the documented `capabilitiesForHardware` path already answer no on the guest. Loaded like the camera hooks rather than inserted like libmisfix because interposing must be in place at launch while a method swizzle just has to run before first use; `DISABLE_TWEAKS` and safe mode skip it with everything else SystemHook loads. Ships with `system-launchdaemons-boot-environment`; existing guests receive it through the vphoned environment update (a missing file reports no hash, which is what triggers the push) and need a respring, which is deliberately the caller's call. See `VPhoneGuestComponents/HapticsFix/libhapticsfix.c`. | Y | Y | Y || 22 | No binary change: `libvcamcaptured.dylib` (already loaded into `cameracaptured` by SystemHook) wraps `+[FigCaptureSourceBackingsProvider sharedCaptureSourceBackingsProvider]` from its constructor; when the original returns nil it returns a microphone-only provider instead — **iOS 26.6+ layout, measured on iOS 27.0** | none (`VPhoneGuestComponents/VCamCaptured/Microphone/VCamMicrophoneSource.m`) | **Give an audio-only `AVCaptureSession` its microphone on a guest with no camera.** The built-in sources come from one provider that CMCapture builds only after `BWFigCaptureDeviceVendor` creates the `Default` camera device; a VM has no ISP plugin, so `Cannot create device without create function!`, -12786, `Wiping com.apple.cameracapture.volatile`, and no provider — the microphone, described by the same `AVCaptureSession.plist` call, is lost with the camera, and iOS 27 Voice Memos fails with `CaptureSessionRecorderError` 1 (`failedToCreateAudioDevice`). The wrapper feeds the exported `FigCaptureCreateSourceInfoArrayFromDeviceAndModelSpecificPlist` a NULL device and the shipped product plist (the guest's own `VPHONE600` has none; `D47` on the iPhone17,3 image) reduced to its `"soun"` entries, without persisting, and builds the provider with `-initWithSourceInfoDictionaries:commonSettings:`. A provider the daemon built itself passes through untouched. While that provider is in use, the same dylib also makes `-[AudioRemixSessionManager startNewSessionBlocking]` report success (0) without building the SoundAnalysis Audio Mix session, whose neural net faults cameracaptured 2 s into every spatial recording on the guest (`BNNSGraphContextMakeStreaming`, `KERN_INVALID_ADDRESS 0x300`). Success, not an error: `BWAudioRemixAnalysisMetadataNode` forwards a Stop marker on its metadata output only when the next session starts, and an error there left the movie-file sink waiting forever (measured with the first version, which returned -16992). With no session the node passes audio through and the Audio Mix metadata track is written without samples. It also logs the level of the audio passing the node. `VCamCaptured/Microphone/VCamMicrophoneRemix.m`. See `Research/Guest/ios27_capture_microphone_source.md`. | Y | Y | Y || 23 | No binary change: `libvcamcaptured.dylib`, which SystemHook already loads into `cameracaptured`, rewrites the `bl PrewarmThreadSafeSBPs` in `__FigCapturePreloadShadersInternal_block_invoke_2` to `nop` in the daemon's own memory. This runs from the dylib's constructor and only when the paravirtual Metal driver is installed — **all bases** | none (guest dylib `VPhoneGuestComponents/VCamCaptured/Prewarm/`, installed at `/usr/lib/libvcamcaptured.dylib`) | **Stop `cameracaptured` crashing at every boot, and the SpringBoard freeze that follows.** At launch the daemon preloads its shaders. `PrewarmThreadSafeSBPs` runs each video processor's `-prewarm`, and NRFV3's reaches `-[ToneMappingCurves initWithWithContext:]`, which fills textures made from a shared `MTLHeap` with `-replaceRegion:…`. The cloudOS 26.4 `AppleParavirtGPUMetalIOGPUFamily` never sets `_dimension` (a texture's CPU layout) in `-initWithHeap:resource:offset:length:descriptor:`, and `-replaceRegion:` loads it unchecked, so the daemon faults with `KERN_INVALID_ADDRESS` at `0xc` (measured on `iPad16,1 26.6.2 (23G90)`, `standard`: launchd at `successive crashes = 6`). While the daemon crash-loops, SpringBoard's main thread blocked in a synchronous XPC to it as soon as an app started recording. The daemon does have a Metal device, so `kernel-exp-paravirt_user_clients` does not help. Prewarming is only an optimisation, and nothing waits on that function: no return value, no global, no signal. The rest of the preload (processor flags, data migration, and the deferred shader cache copy, whose semaphore deferred processing waits on) is kept. The call site is found from the exported `FigCapturePreloadShaders`: its `b` to the internal function, that function's one `adrp/add/pacia x16` block invoke, then the block's one `ldr x0, [xN, #0x20]; bl` into CMCapture's `__text`. That gives `0x1aeb2fd68` on 23G90 and `0x1b0759d10` on 24A435. Any mismatch leaves the prewarm in place and logs the step that failed. Host test: `make -C VPhoneGuestComponents test-vcam-prewarm`. Validation: `vcamcaptured.log` has `gpu prewarm: … skipped`, no new `cameracaptured` crash report, and `successive crashes = 0`. See `Research/Guest/gpu_acceleration.md` ("Heap Textures Have No CPU Layout"). | Y | Y | Y |+| 24 | No binary change: both spawn hooks insert `libbatteryhealthfix.dylib` into `Settings` (`/Applications/Preferences.app/Preferences`) beside SystemHook, where it interposes `IOPSCopyPowerSourcesInfo`, `IOPSCopyPowerSourcesByType`, `IOPSCopyPowerSourcesByTypePrecise`, `notify_register_check` / `notify_get_state` / `notify_cancel` and `MGGetBoolAnswer` — **all bases** | none (new guest dylib `VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c`, installed at `/usr/lib/libbatteryhealthfix.dylib`) | **Stop Settings → Battery → Battery Health & Charging loading forever.** The VM's battery is Virtualization.framework's synthetic power source (charge and connectivity only), and the health half of a real battery's description comes from AppleSmartBattery, which no VM has. Measured on `iPhone17,3 27.0 (24A435)`: powerd's internal battery description has one `BatteryPacks` entry holding only `PackID`, `Cycle count` and `Transport Type`, no `Battery Service State`/`Flags` or `Maximum Capacity Percent` anywhere, and `com.apple.thermalmonitor.ageAwareMitigationState` stays 0. `-[BatteryHealthUIController specifiers]` asks `-[BatteryHealthUIInformation batteryDataUnavailable]`, which answers YES while `+getManagementState` is 0, while no pack parses (`-[BatteryHealthUIPackInformation initWithPowerSourceInformation:]` drops a pack without service flags and state), or while the overall genuine status is -1 — and it is -1 because `MGGetBoolAnswer("D6/BMDrlb8V3WSiqL8gL+w")` (HasBatteryModuleAuth, `+[PLGestaltUtilities hasBatteryModuleAuth]`) answers 1 on the guest, sending `+genuineBatteryStatusForPackIndex:` to an `AppleBatteryAuth`/`AppleAuthCPRelay` service that does not exist. The controller then shows its global spinner and re-asks on a timer. iPadOS 26.6.2 (23G90) has the same gate in `+[BatteryUIResourceClass batteryDataUnavailable]`, reading the flat keys of `IOPSCopyPowerSourcesByType`'s array, the same notify name and the same MobileGestalt key. The hook answers as a new battery without battery authentication: each internal-battery description is copied with `Battery Service State` 0, `Battery Service Flags` 0, `Maximum Capacity Percent` 100 and `Cycle count` 0 at the top level, and each of powerd's packs (or one new pack) completed with a `BatteryHealth` dictionary of the same three numbers plus `Date of manufacture`/`Date of first use` (the birth time of `/private/var/mobile`, i.e. the restore); keys already present are never replaced, and a description that already has them is passed through. A mitigation state of 0 on a token registered for the age-aware name reads as 2 ("supporting normal peak performance"). HasBatteryModuleAuth reads as no only while `IOServiceGetMatchingService("AppleBatteryAuth")` finds nothing. Interposing reaches the callers because `BatteryUsageUI.bundle` is a standalone Mach-O bound through dyld's interposing table (cache-to-cache calls are not; see `MISFix/MISFixSignature.c`), and inserting it — rather than SystemHook `dlopen`ing it like row 21 — is what puts the table in place before the bundle loads. `vpInsertedLibraryFor` in `Shared/InjectionEnvironment.h` picks it or libmisfix for a path; the two target sets do not overlap. Ships with `system-launchdaemons-boot-environment`; existing guests get it from the vphoned environment update on their next start with the new bundle (offline `cfw update-environment` only replaces libraries a VM already has). launchd starts Settings itself, so it is the launchd hook that inserts it: a guest updated only by that online sync needs one more reboot before launchd runs the new hook, which the update already reports as `reboot_required`; an offline environment update replaces the hook before boot. **Validated (2026-10-04, `bhtest-iphone`, `iPhone17,3 27.0 (24A435)` + cloudOS 26.4):** before, the page showed only the spinner and the two charging switches; after, Maximum Capacity 100%, Peak Performance Capability "Your battery is currently supporting normal peak performance", the two switches, no spinner; the hook's log shows all three answers taken once per process. Re-checked on the final bundle after a reboot of the same guest, with the launchd hook logging `inserted+batteryhealthfix` for each Settings launch. **iPad16,1 26.6.2 (23G90), `bhtest-ipad`, created with the new bundle:** the hook is inserted and stays inert, and Settings runs without a crash; that iPad has no Battery Health page at all, because `-[BatteryUIController setUpBatteryHealthGroup]` offers the row only on an iPhone or, through `+[PLBatteryUIBackendModel shouldShowModifiedHealthController]`, on an iPad that supports the fixed charge limit with the `PerfPowerServices/battery_health_details` feature on — the model decides, as on hardware. The 26.x gate inside the page is from static analysis; no 26.x iPhone image was at hand to run it. | Y | Y | Y |### Swift port status — the eight DSC patchers (2026-09-23)diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swiftindex b280f553..6dca2b90 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift@@ -16,6 +16,7 @@ extension GuestAPI {"libcamfix.dylib","libmisfix.dylib","libhapticsfix.dylib",+ "libbatteryhealthfix.dylib",]static let environmentStaging = "/var/root/Library/Caches/vphone-environment"diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 451a76b8..d093f778 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -173,7 +173,8 @@ public enum FirmwareGuestSystemPatchSet {and into lockdownd and remoted, which tell the host a configured UDID. It also \ships libhapticsfix.dylib, which SystemHook loads into SpringBoard so UIKit's \feedback engine takes the no-haptics path instead of crashing on the VM's absent \- haptic hardware.+ haptic hardware, and libbatteryhealthfix.dylib, inserted into Settings, which gives \+ the virtual battery the health record Battery Health waits for.""",target: .guestFile(path: "/Library/LaunchDaemons"),bootEssential: true,diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 4dfd36c0..3e93d5a6 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -74,6 +74,7 @@ fi/bin/cp "$guest_products/misfix/libmisfix.dylib" "$guest/libmisfix.dylib"/bin/cp "$guest_products/misfix/libmisfix.plist" "$guest/libmisfix.plist"/bin/cp "$guest_products/hapticsfix/libhapticsfix.dylib" "$guest/libhapticsfix.dylib"+/bin/cp "$guest_products/batteryhealthfix/libbatteryhealthfix.dylib" "$guest/libbatteryhealthfix.dylib"/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"# The HAL plugin is a bundle, signed whole by the Makefile; copied as a tree sodiff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex 7b71b23a..0e18f844 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -88,7 +88,8 @@ for preset in "$resources/patches_presets/"*.plist; dodonefor name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \- libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do+ libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib \+ libAppleParavirtCompilerPluginIOGPUFamily.dylib; dorequire_signed_macho "$guest/$name"donefor name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist; dodiff --git a/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c b/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.cnew file mode 100644index 00000000..4e1b9b75--- /dev/null+++ b/VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c@@ -0,0 +1,369 @@+// libbatteryhealthfix.c — give Settings the battery health record a real+// battery's power source carries, so Battery Health stops loading forever.+//+// The guest's battery is Virtualization.framework's synthetic power source:+// charge and connectivity, nothing else. powerd publishes it as the internal+// battery, but the health half of the description comes from AppleSmartBattery+// (`BatteryData`, one `AppleSmartBatteryPack` per pack), which no VM has.+// Measured on iOS 27.0 (24A435): the description's one `BatteryPacks` entry+// holds only `PackID`, `Cycle count` and `Transport Type`, with no+// `BatteryHealth`; there is no `Battery Service State` or `Maximum Capacity+// Percent`; and thermalmonitord leaves the age-aware mitigation state at 0.+// Settings → Battery → Battery Health & Charging reads all of them:+//+// iOS 27.0 (24A435): -[BatteryHealthUIController specifiers] asks+// -[BatteryHealthUIInformation batteryDataUnavailable], which answers YES+// while +getManagementState is 0 (the notify state of+// com.apple.thermalmonitor.ageAwareMitigationState) or no pack parses: a+// pack without `Battery Service Flags` and `Battery Service State` is+// dropped — or while the pack's genuineness is unknown, which it is+// whenever HasBatteryModuleAuth says yes and AppleBatteryAuth is absent.+// The controller then shows `startSpinner`'s global spinner and re-asks on+// a timer, forever: the spinner the user sees above the two charging+// switches.+//+// iPadOS 26.6.2 (23G90): +[BatteryUIResourceClass batteryDataUnavailable]+// makes the same checks against the flat `Battery Service State` and+// `Maximum Capacity Percent` keys of IOPSCopyPowerSourcesByType's array.+//+// Both read the description through IOPSCopyPowerSourcesInfo,+// IOPSCopyPowerSourcesByType or IOPSCopyPowerSourcesByTypePrecise, the state+// through notify_register_check and notify_get_state, and the capability+// through MGGetBoolAnswer. This interposes those, plus notify_cancel to keep+// track of tokens, and answers as a new, healthy battery without battery+// authentication would: service state 0 (normal), no service flags, 100%+// maximum capacity, no cycles, first used when the guest's data volume was+// created, and a mitigation state of 2, "supporting normal peak performance".+// powerd's packs are kept and completed (one is made if there are none), and+// a key the description already has is never replaced, so a base whose powerd+// learns to fill these in wins.+//+// The interposes reach the callers that matter because BatteryUsageUI.bundle+// is a standalone Mach-O, not a shared-cache image: dyld binds its imports+// through the interposing table. (Cache-to-cache calls are not rebound; see+// MISFix/MISFixSignature.c.) The spawn hooks insert this into Settings only —+// `vpIsBatteryHealthFixTarget` in Shared/InjectionEnvironment.h — so no other+// process sees a battery it does not have.++#include <CoreFoundation/CoreFoundation.h>+#include <IOKit/IOKitLib.h>+#include <fcntl.h>+#include <notify.h>+#include <os/lock.h>+#include <pthread.h>+#include <stdatomic.h>+#include <stdio.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++// IOKit's power source API; the iPhoneOS SDK ships IOKit.tbd and IOKitLib.h+// but not IOKit/ps/IOPowerSources.h.+extern CFTypeRef IOPSCopyPowerSourcesInfo(void);+extern CFTypeRef IOPSCopyPowerSourcesByType(int type);+extern IOReturn IOPSCopyPowerSourcesByTypePrecise(int type, CFTypeRef *blob);+extern Boolean MGGetBoolAnswer(CFStringRef question);++#define VP_MITIGATION_STATE_NAME "com.apple.thermalmonitor.ageAwareMitigationState"+// BatteryHealthUIController's states: 1 management applied, 2 normal peak+// performance, 3 management turned off by the user, 4 dynamic (CPMS).+#define VP_MITIGATION_STATE_NORMAL 2++// MARK: - Log++// Settings runs as mobile and owns this directory; the mode keeps a root+// writer of the same log from silencing later ones, as in SystemHook.+static void vpLog(const char *message) {+ int fd = open("/var/mobile/Library/Caches/vphone-batteryhealthfix.log",+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666);+ if (fd < 0)+ return;+ fchmod(fd, 0666);+ dprintf(fd, "pid=%d %s\n", getpid(), message);+ close(fd);+}++// One line per kind of answer per process, not one per query: Settings asks+// on every specifier reload.+static void vpLogOnce(atomic_int *logged, const char *message) {+ if (atomic_exchange(logged, 1) == 0)+ vpLog(message);+}++// MARK: - Description++static void vpSetNumber(CFMutableDictionaryRef dictionary, CFStringRef key, int value) {+ if (CFDictionaryContainsKey(dictionary, key))+ return;+ CFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &value);+ if (!number)+ return;+ CFDictionarySetValue(dictionary, key, number);+ CFRelease(number);+}++static void vpSetValue(CFMutableDictionaryRef dictionary, CFStringRef key, CFTypeRef value) {+ if (value && !CFDictionaryContainsKey(dictionary, key))+ CFDictionarySetValue(dictionary, key, value);+}++static CFMutableDictionaryRef vpCreateMutableDictionary(void) {+ return CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks,+ &kCFTypeDictionaryValueCallBacks);+}++// The health numbers BatteryUsageUI reads, at the description's top level+// (iOS 26) and in each pack's `BatteryHealth` (iOS 27).+static void vpSetHealth(CFMutableDictionaryRef dictionary) {+ vpSetNumber(dictionary, CFSTR("Battery Service State"), 0);+ vpSetNumber(dictionary, CFSTR("Battery Service Flags"), 0);+ vpSetNumber(dictionary, CFSTR("Maximum Capacity Percent"), 100);+}++// When the guest's data volume was created, which is when it was restored:+// the closest thing a VM has to a battery's first use.+static CFDateRef vpCreateFirstUseDate(void) {+ struct stat info;+ CFAbsoluteTime time = stat("/private/var/mobile", &info) == 0 && info.st_birthtimespec.tv_sec > 0+ ? (CFAbsoluteTime)info.st_birthtimespec.tv_sec - kCFAbsoluteTimeIntervalSince1970+ : CFAbsoluteTimeGetCurrent();+ return CFDateCreate(kCFAllocatorDefault, time);+}++// A pack as BatteryUsageUI reads it: powerd's own keys (on 27.0 `PackID`,+// `Cycle count` and `Transport Type`) kept, and the ones that come from+// AppleSmartBatteryPack added. NULL `existing` makes the one pack a+// description without any gets.+static CFDictionaryRef vpCreatePack(CFTypeRef existing) {+ CFMutableDictionaryRef pack = existing && CFGetTypeID(existing) == CFDictionaryGetTypeID()+ ? CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, existing)+ : vpCreateMutableDictionary();+ CFMutableDictionaryRef health = vpCreateMutableDictionary();+ CFDateRef firstUse = vpCreateFirstUseDate();+ if (pack && health) {+ vpSetNumber(pack, CFSTR("PackID"), 0);+ vpSetNumber(pack, CFSTR("Cycle count"), 0);+ vpSetValue(pack, CFSTR("Date of manufacture"), firstUse);+ vpSetValue(pack, CFSTR("Date of first use"), firstUse);+ vpSetHealth(health);+ vpSetValue(pack, CFSTR("BatteryHealth"), health);+ }+ if (health)+ CFRelease(health);+ if (firstUse)+ CFRelease(firstUse);+ return pack;+}++static int vpIsInternalBattery(CFTypeRef value) {+ if (!value || CFGetTypeID(value) != CFDictionaryGetTypeID())+ return 0;+ CFTypeRef type = CFDictionaryGetValue((CFDictionaryRef)value, CFSTR("Type"));+ return type && CFGetTypeID(type) == CFStringGetTypeID() &&+ CFEqual(type, CFSTR("InternalBattery"));+}++static CFArrayRef vpPacks(CFDictionaryRef description) {+ CFTypeRef packs = CFDictionaryGetValue(description, CFSTR("BatteryPacks"));+ return packs && CFGetTypeID(packs) == CFArrayGetTypeID() ? packs : NULL;+}++// An internal battery without the service state at its top level, without a+// pack, or with a pack that has no `BatteryHealth`. A real battery's+// description has all three, and is left alone.+static int vpNeedsHealth(CFTypeRef value) {+ if (!vpIsInternalBattery(value))+ return 0;+ CFDictionaryRef description = value;+ if (!CFDictionaryContainsKey(description, CFSTR("Battery Service State")))+ return 1;+ CFArrayRef packs = vpPacks(description);+ if (!packs || CFArrayGetCount(packs) == 0)+ return 1;+ for (CFIndex index = 0; index < CFArrayGetCount(packs); index++) {+ CFTypeRef pack = CFArrayGetValueAtIndex(packs, index);+ if (!pack || CFGetTypeID(pack) != CFDictionaryGetTypeID() ||+ !CFDictionaryContainsKey(pack, CFSTR("BatteryHealth")))+ return 1;+ }+ return 0;+}++static CFDictionaryRef vpCreateDescriptionWithHealth(CFDictionaryRef description) {+ CFMutableDictionaryRef copy = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, description);+ CFMutableArrayRef packs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);+ if (!copy || !packs) {+ if (copy)+ CFRelease(copy);+ if (packs)+ CFRelease(packs);+ return NULL;+ }+ CFArrayRef existing = vpPacks(description);+ CFIndex count = existing ? CFArrayGetCount(existing) : 0;+ for (CFIndex index = 0; index < (count ? count : 1); index++) {+ CFDictionaryRef pack = vpCreatePack(count ? CFArrayGetValueAtIndex(existing, index) : NULL);+ if (pack) {+ CFArrayAppendValue(packs, pack);+ CFRelease(pack);+ }+ }+ vpSetHealth(copy);+ vpSetNumber(copy, CFSTR("Cycle count"), 0);+ CFDictionarySetValue(copy, CFSTR("BatteryPacks"), packs);+ CFRelease(packs);+ return copy;+}++// A power source blob is an array of description dictionaries; IOKit finds a+// description by membership in that array, so a copy whose battery entry is+// replaced is still self-consistent for IOPSCopyPowerSourcesList and+// IOPSGetPowerSourceDescription. Takes the caller's reference to `blob` and+// returns one; anything that is not that shape comes back untouched.+static CFTypeRef vpBlobWithHealth(CFTypeRef blob) {+ static atomic_int logged;+ if (!blob || CFGetTypeID(blob) != CFArrayGetTypeID())+ return blob;+ CFArrayRef sources = blob;+ CFIndex count = CFArrayGetCount(sources);+ CFMutableArrayRef copy = NULL;+ for (CFIndex index = 0; index < count; index++) {+ CFTypeRef source = CFArrayGetValueAtIndex(sources, index);+ if (!vpNeedsHealth(source))+ continue;+ CFDictionaryRef description = vpCreateDescriptionWithHealth(source);+ if (!description)+ continue;+ if (!copy)+ copy = CFArrayCreateMutableCopy(kCFAllocatorDefault, count, sources);+ if (copy)+ CFArraySetValueAtIndex(copy, index, description);+ CFRelease(description);+ }+ if (!copy)+ return blob;+ vpLogOnce(&logged, "internal battery description given a healthy pack");+ CFRelease(blob);+ return copy;+}++static CFTypeRef vpCopyPowerSourcesInfo(void) {+ return vpBlobWithHealth(IOPSCopyPowerSourcesInfo());+}++static CFTypeRef vpCopyPowerSourcesByType(int type) {+ return vpBlobWithHealth(IOPSCopyPowerSourcesByType(type));+}++static IOReturn vpCopyPowerSourcesByTypePrecise(int type, CFTypeRef *blob) {+ IOReturn status = IOPSCopyPowerSourcesByTypePrecise(type, blob);+ if (blob && *blob)+ *blob = vpBlobWithHealth(*blob);+ return status;+}++// MARK: - Mitigation state++// Tokens notify_register_check handed out for the mitigation state, so+// notify_get_state can tell them apart. BatteryUsageUI registers, reads and+// cancels each time, and notifyd reuses a cancelled token for another name, so+// notify_cancel takes a token back out.+#define VP_TOKEN_SLOTS 8+static os_unfair_lock vpTokenLock = OS_UNFAIR_LOCK_INIT;+static int vpMitigationTokens[VP_TOKEN_SLOTS];+static int vpMitigationTokenCount;++static void vpRememberToken(int token) {+ os_unfair_lock_lock(&vpTokenLock);+ if (vpMitigationTokenCount < VP_TOKEN_SLOTS)+ vpMitigationTokens[vpMitigationTokenCount++] = token;+ os_unfair_lock_unlock(&vpTokenLock);+}++// Whether `token` is one of the remembered ones; `forget` also drops it.+static int vpIsMitigationToken(int token, int forget) {+ int found = 0;+ os_unfair_lock_lock(&vpTokenLock);+ for (int index = 0; index < vpMitigationTokenCount; index++) {+ if (vpMitigationTokens[index] != token)+ continue;+ found = 1;+ if (forget)+ vpMitigationTokens[index] = vpMitigationTokens[--vpMitigationTokenCount];+ break;+ }+ os_unfair_lock_unlock(&vpTokenLock);+ return found;+}++static uint32_t vpNotifyRegisterCheck(const char *name, int *token) {+ uint32_t status = notify_register_check(name, token);+ if (status == NOTIFY_STATUS_OK && token && name && strcmp(name, VP_MITIGATION_STATE_NAME) == 0)+ vpRememberToken(*token);+ return status;+}++static uint32_t vpNotifyGetState(int token, uint64_t *state) {+ static atomic_int logged;+ uint32_t status = notify_get_state(token, state);+ if (status == NOTIFY_STATUS_OK && state && *state == 0 && vpIsMitigationToken(token, 0)) {+ *state = VP_MITIGATION_STATE_NORMAL;+ vpLogOnce(&logged, "age-aware mitigation state 0 answered as 2 (normal peak performance)");+ }+ return status;+}++static uint32_t vpNotifyCancel(int token) {+ vpIsMitigationToken(token, 1);+ return notify_cancel(token);+}++// MARK: - Battery authentication++// MobileGestalt's HasBatteryModuleAuth, as BatteryUsageUI asks it+// (+[PLGestaltUtilities hasBatteryModuleAuth] on 27.0, the same key on 26.6.2).+#define VP_BATTERY_MODULE_AUTH CFSTR("D6/BMDrlb8V3WSiqL8gL+w")++static int vpHasBatteryAuthService;+static pthread_once_t vpBatteryAuthOnce = PTHREAD_ONCE_INIT;++static void vpLookUpBatteryAuthService(void) {+ io_service_t service = IOServiceGetMatchingService(MACH_PORT_NULL, IOServiceMatching("AppleBatteryAuth"));+ vpHasBatteryAuthService = service != IO_OBJECT_NULL;+ if (service != IO_OBJECT_NULL)+ IOObjectRelease(service);+}++// The guest's device identity says its battery authenticates itself, but no+// VM has the AppleBatteryAuth service that answers. Asked for a pack's+// genuineness, BatteryUsageUI then gets no authentication data and reports+// the status as unknown (-1), which batteryDataUnavailable also counts as+// "keep loading" (measured on 27.0: the answer is 1, 24 times per visit).+// Without the service the answer is no, as on a device with no battery+// authentication, and the pack counts as genuine; with it, nothing changes.+static Boolean vpGetBoolAnswer(CFStringRef question) {+ static atomic_int logged;+ Boolean answer = MGGetBoolAnswer(question);+ if (!answer || !question || !CFEqual(question, VP_BATTERY_MODULE_AUTH))+ return answer;+ pthread_once(&vpBatteryAuthOnce, vpLookUpBatteryAuthService);+ if (vpHasBatteryAuthService)+ return answer;+ vpLogOnce(&logged, "HasBatteryModuleAuth answered no: no AppleBatteryAuth service");+ return false;+}++int vphone_batteryhealthfix_version(void) { return 1; }++__attribute__((used, section("__DATA,__interpose"))) static const struct {+ const void *replacement;+ const void *replacee;+} vpInterpose[] = {+ {(const void *)vpCopyPowerSourcesInfo, (const void *)IOPSCopyPowerSourcesInfo},+ {(const void *)vpCopyPowerSourcesByType, (const void *)IOPSCopyPowerSourcesByType},+ {(const void *)vpCopyPowerSourcesByTypePrecise, (const void *)IOPSCopyPowerSourcesByTypePrecise},+ {(const void *)vpNotifyRegisterCheck, (const void *)notify_register_check},+ {(const void *)vpNotifyGetState, (const void *)notify_get_state},+ {(const void *)vpNotifyCancel, (const void *)notify_cancel},+ {(const void *)vpGetBoolAnswer, (const void *)MGGetBoolAnswer},+};diff --git a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.cindex 870662a0..22dcee17 100644--- a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c+++ b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c@@ -93,13 +93,15 @@ static int vpSpawnWith(VPSpawnFunction spawn, pid_t *restrict pid, const char *rif (!path || strcmp(path, "/sbin/launchd") == 0)return spawn(pid, path, actions, attributes, argv, envp);// launchd starts some jobs itself rather than through xpcproxy — SpringBoard- // is one — so the MIS hook has to be decided here as well as in SystemHook.- const char *misFix = vpMISFixFor(path);- VPInjectionEnvironment injected = vpInsertHooks(envp, vpBootRoot, misFix);+ // is one — so the MIS and battery health hooks have to be decided here as+ // well as in SystemHook.+ const char *library = vpInsertedLibraryFor(path);+ VPInjectionEnvironment injected = vpInsertHooks(envp, vpBootRoot, library);int status = spawn(pid, path, actions, attributes, argv, injected.values ? injected.values : envp);- if (bootstrapProgram || appProgram || misFix || strcmp(path, "/usr/libexec/xpcproxy") == 0) {+ if (bootstrapProgram || appProgram || library || strcmp(path, "/usr/libexec/xpcproxy") == 0) {const char *event = !injected.values ? "unchanged" :- misFix ? "inserted+misfix" :+ library && strcmp(library, VP_MIS_FIX) == 0 ? "inserted+misfix" :+ library ? "inserted+batteryhealthfix" :vpInjectionDisabled(envp) ? "inserted-tweaks-disabled" : "inserted";vpLogInjection(event, path, status);vpLogSpawn(event, path, status == 0 && pid ? *pid : -1, status);diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex b5a2fe35..6e7ba173 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -51,6 +51,11 @@ MISFIX_INCLUDES := $(wildcard MISFix/*.h)HAPTICSFIX := $(STAGE)/hapticsfix/libhapticsfix.dylibHAPTICSFIX_SOURCES := $(wildcard HapticsFix/*.c)HAPTICSFIX_INCLUDES := $(wildcard HapticsFix/*.h)+# IOKit and MobileGestalt for the calls it interposes (notify is in libSystem),+# CoreFoundation for the descriptions it builds.+BATTERYHEALTHFIX := $(STAGE)/batteryhealthfix/libbatteryhealthfix.dylib+BATTERYHEALTHFIX_SOURCES := $(wildcard BatteryHealthFix/*.c)+BATTERYHEALTHFIX_INCLUDES := $(wildcard BatteryHealthFix/*.h)GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylibGPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)@@ -84,7 +89,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driverVIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(GPU_PLUGIN) $(VIRTIOSOUND)+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(GPU_PLUGIN) $(VIRTIOSOUND)PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \$(STAGE)/misfix/libmisfix.plistGPU_PROVENANCE := $(STAGE)/gpu/README.md@@ -99,7 +104,7 @@ gpu: $(GPU_PLUGIN)package: all@rm -f $(ARCHIVE)- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix gpu virtiosound+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix gpu virtiosound@echo "Packaged $(ARCHIVE)"test-loader-links:@@ -148,7 +153,7 @@ test-vcam-dataplane:-framework CoreGraphics@$(OUT)/VCamDataPlaneTests-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/gpu $(STAGE)/virtiosound:+$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/gpu $(STAGE)/virtiosound:@mkdir -p $@$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix@@ -195,6 +200,14 @@ $(HAPTICSFIX): $(HAPTICSFIX_SOURCES) $(HAPTICSFIX_INCLUDES) HapticsFix | $(STAGE-Wl,-not_for_dyld_shared_cache@codesign --force --sign - $@+$(BATTERYHEALTHFIX): $(BATTERYHEALTHFIX_SOURCES) $(BATTERYHEALTHFIX_INCLUDES) BatteryHealthFix | $(STAGE)/batteryhealthfix+ $(CLANG) $(GUEST_C_FLAGS) -dynamiclib \+ -install_name /usr/lib/libbatteryhealthfix.dylib \+ -o $@ $(BATTERYHEALTHFIX_SOURCES) \+ -framework CoreFoundation -framework IOKit -lMobileGestalt \+ -Wl,-not_for_dyld_shared_cache+ @codesign --force --sign - $@+$(STAGE)/misfix/libmisfix.plist: MISFix/libmisfix.plist | $(STAGE)/misfix@cp $< $@diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.mdindex ff2920fd..260fdfe2 100644--- a/VPhoneGuestComponents/README.md+++ b/VPhoneGuestComponents/README.md@@ -9,6 +9,7 @@ tweak filter plists, and the GPU provenance note:| Camera app hook | `camfix/libcamfix.dylib`, `camfix/libcamfix.plist` || Camera daemon hook | `vcamcaptured/libvcamcaptured.dylib`, `vcamcaptured/libvcamcaptured.plist` || Haptics fix | `hapticsfix/libhapticsfix.dylib` |+| Battery health fix | `batteryhealthfix/libbatteryhealthfix.dylib` || Launchd hook | `launchhook/launchdhook-vphone.dylib` || Process injection bridge | `systemhook/SystemHook-vphone.dylib` || iOS 27 app registrar | `vpregister/vpregister` |@@ -22,7 +23,12 @@ loads `libvcamcaptured.dylib` into `/usr/libexec/cameracaptured` and`libcamfix.dylib` into apps that have AVFoundation loaded; neither camera hookneeds ElleKit or a bootstrap. It loads `libhapticsfix.dylib` into SpringBoard,where UIKit's feedback engine would otherwise die on the haptics hardware no-VM has. After a bootstrap installs ElleKit, the launchd hook+VM has. Both spawn hooks insert `libbatteryhealthfix.dylib` into Settings beside+SystemHook; it completes the internal battery's power source description with+the health keys a real battery has and answers the two questions only battery+hardware can, so Battery Health shows a healthy battery instead of loading+forever.+After a bootstrap installs ElleKit, the launchd hookinserts SystemHook into `xpcproxy`, bootstrap executables, and apps starteddirectly by launchd. Inside `xpcproxy`, SystemHook carries itself into thefinal executable through `posix_spawnp`. Injected App and bootstrap processesdiff --git a/VPhoneGuestComponents/Shared/InjectionEnvironment.h b/VPhoneGuestComponents/Shared/InjectionEnvironment.hindex 2b276443..8ad769b9 100644--- a/VPhoneGuestComponents/Shared/InjectionEnvironment.h+++ b/VPhoneGuestComponents/Shared/InjectionEnvironment.h@@ -61,6 +61,32 @@ static const char *vpMISFixFor(const char *path) {return vpIsMISFixTarget(path) && access(VP_MIS_FIX, R_OK) == 0 ? VP_MIS_FIX : NULL;}+// The battery health hook, which fills in the health half of the internal+// battery's power source description; see+// BatteryHealthFix/libbatteryhealthfix.c. Inserted rather than loaded by+// SystemHook because it interposes: the table has to be in place before+// BatteryUsageUI.bundle is bound.+#define VP_BATTERY_HEALTH_FIX "/usr/lib/libbatteryhealthfix.dylib"++// Settings, the one process that shows Battery Health. Asked by both spawn+// hooks, like the MIS targets, so it holds whichever of them starts the app.+static int vpIsBatteryHealthFixTarget(const char *path) {+ return path && vpPathHasSuffix(path, "/Preferences.app/Preferences");+}++static const char *vpBatteryHealthFixFor(const char *path) {+ return vpIsBatteryHealthFixTarget(path) && access(VP_BATTERY_HEALTH_FIX, R_OK) == 0+ ? VP_BATTERY_HEALTH_FIX+ : NULL;+}++// The one library, if any, the spawn hooks insert beside SystemHook for+// `path`. The MIS and battery health targets do not overlap.+static const char *vpInsertedLibraryFor(const char *path) {+ const char *library = vpMISFixFor(path);+ return library ? library : vpBatteryHealthFixFor(path);+}+typedef struct {char **values;char *hook;diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.cindex a39673a1..410c23d7 100644--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c@@ -99,12 +99,14 @@ static void vpPrepareLoaderLink(const char *path) {// get their loader links prepared.static VPInjectionEnvironment vpPrepareChild(const char *path, char *const envp[], const char *kind) {const int misFix = vpIsMISFixTarget(path);- VPInjectionEnvironment injected = vpInsertHooks(envp, getenv("VPHONE_JB_ROOT"), vpMISFixFor(path));+ const int batteryHealthFix = vpIsBatteryHealthFixTarget(path);+ VPInjectionEnvironment injected = vpInsertHooks(envp, getenv("VPHONE_JB_ROOT"), vpInsertedLibraryFor(path));if (vpIsInjectionTarget(path) || misFix) {vpPrepareLoaderLink(path);- char decision[80];+ char decision[96];snprintf(decision, sizeof(decision), "%s%s%s%s", kind, !injected.values ? "unchanged" : "inserted",- misFix ? "+misfix" : "", vpInjectionDisabled(envp) ? "-tweaks-disabled" : "");+ misFix ? "+misfix" : batteryHealthFix ? "+batteryhealthfix" : "",+ vpInjectionDisabled(envp) ? "-tweaks-disabled" : "");vpLogSpawn(path, decision);}return injected;diff --git a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.cindex ce854616..97bc529f 100644--- a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c+++ b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c@@ -51,11 +51,22 @@ static void namesTheMISFixTargets(void) {assert(!vpIsMISFixTarget(NULL));}+static void namesTheBatteryHealthFixTarget(void) {+ assert(vpIsBatteryHealthFixTarget("/Applications/Preferences.app/Preferences"));+ assert(!vpIsBatteryHealthFixTarget("/Applications/Preferences.app/PreferencesX"));+ assert(!vpIsBatteryHealthFixTarget("/System/Library/CoreServices/SpringBoard.app/SpringBoard"));+ assert(!vpIsBatteryHealthFixTarget(NULL));+ // The two hooks never compete for one process's single extra slot.+ assert(!vpIsMISFixTarget("/Applications/Preferences.app/Preferences"));+ assert(!vpInsertedLibraryFor(NULL));+}+int main(void) {insertsBoth();addsExtraBesideAnExistingHook();leavesACompleteEnvironmentAlone();namesTheMISFixTargets();+ namesTheBatteryHealthFixTarget();puts("InjectionEnvironmentTests: ok");return 0;}diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swiftindex ad92a63b..71710a2f 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift@@ -13,5 +13,6 @@ public enum VPhoneGuestEnvironment {"libcamfix.dylib","libmisfix.dylib","libhapticsfix.dylib",+ "libbatteryhealthfix.dylib",]}