Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Deliver VM location through guest app hook

Lakr4fc4f1b11561
diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml
new file mode 100644
index 00000000..938dfb0c
--- /dev/null
+++ b/.github/workflows/package.yml
@@ -0,0 +1,66 @@
+name: package
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ package:
+ runs-on: macos-26
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build VPhone.bundle
+ env:
+ SWIFT_JOBS: "4"
+ run: |
+ set -o pipefail
+ xcodebuild -workspace VPhone.xcworkspace -scheme VPhone \
+ -configuration Release -destination 'platform=macOS,arch=arm64' \
+ -derivedDataPath .build/XcodeBundle -jobs 4 build \
+ 2>&1 | tee vphone-build.log
+
+ - name: Validate and package VPhone.bundle
+ run: |
+ set -euo pipefail
+ bundle=.build/XcodeBundle/Build/Products/Release/VPhone.bundle
+ zsh VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh "$bundle"
+ ditto -c -k --keepParent "$bundle" "VPhone-${GITHUB_SHA}.zip"
+
+ - name: Build vphone-launchpad.app
+ run: |
+ set -o pipefail
+ xcodebuild -project VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj \
+ -scheme VPhoneLaunchpad -configuration Release \
+ -destination 'platform=macOS,arch=arm64' \
+ -derivedDataPath .build/XcodeLaunchpad build \
+ 2>&1 | tee launchpad-build.log
+
+ - name: Package unsigned vphone-launchpad.app
+ run: |
+ set -euo pipefail
+ app=.build/XcodeLaunchpad/Build/Products/Release/vphone-launchpad.app
+ ditto -c -k --keepParent "$app" "vphone-launchpad-${GITHUB_SHA}.zip"
+
+ - name: Upload Release packages
+ uses: actions/upload-artifact@v4
+ with:
+ name: vphone-release-${{ github.sha }}
+ path: |
+ VPhone-${{ github.sha }}.zip
+ vphone-launchpad-${{ github.sha }}.zip
+ if-no-files-found: error
+ retention-days: 7
+
+ - name: Upload build logs on failure
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: vphone-package-logs-${{ github.sha }}
+ path: |
+ vphone-build.log
+ launchpad-build.log
+ if-no-files-found: ignore
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index d1287e7f..4777db9d 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1412,3 +1412,13 @@ difference that a real directory in the link's place is now an error instead of
silent nested link. `diskutil image resize --plist | plutil -extract max raw` loses the
shell and `plutil`: the plist is parsed in-process, starting at `<?xml` so that a warning
on diskutil's merged stderr can no longer be handed back as the `--size` argument.
+
+## iOS 26.4 location delivery uses an app hook (2026-09-25)
+
+The guest's locationd accepts simulation requests but did not deliver a usable
+fused fix to Maps. This change adds no Apple binary patch. SystemHook loads
+`libvlocation.dylib` into app processes, where it supplies the vphoned-published
+coordinate through `CLLocationManager` for authorized clients. The location
+state is an atomically replaced JSON file, and removal restores the native
+path. Maps showed the Tokyo and Apple Park coordinates in the running 26.4 VM;
+the automatic SystemHook injection path was verified after relaunching Maps.
diff --git a/Research/Guest/location_simulation_26_4_failure.md b/Research/Guest/location_simulation_26_4_failure.md
new file mode 100644
index 00000000..eb5fa9fd
--- /dev/null
+++ b/Research/Guest/location_simulation_26_4_failure.md
@@ -0,0 +1,68 @@
+# iOS 26.4 VM location simulation failure
+
+## Reproduction (2026-09-25)
+
+The running `26.4` VM uses the `jb` firmware variant and iOS 26.4.0. Its
+guest agent is the 2.0.4 bundle's `vphoned`. Location Services are enabled,
+and Maps has While Using permission. The VM has no working Wi-Fi switch.
+
+1. Open Maps and request the current position. The button spins without a blue
+ dot.
+2. Send `PUT /v1/location` with latitude `35.681236` and longitude
+ `139.767125`. Most requests fail after five seconds with `no location
+ within 5 s`; a single earlier request returned a fresh simulated reading,
+ but Maps still did not obtain a position.
+3. Set the same coordinate through Xcode's independent path:
+ `xcrun devicectl device simulate location coordinate --device <VM UDID>
+ --latitude 35.681236 --longitude 139.767125`. This command reports
+ success, while `GET /v1/location` still times out and Maps still spins.
+4. Clear the Xcode simulation with `xcrun devicectl device simulate location
+ clear --device <VM UDID>`.
+
+`locationd` logs `received daemon-side request to start location simulation`
+and emits `@ClxSimulated, Fix` every second. At the same time it repeatedly
+logs `LCOutputBuffer,getLatestDaemonLocation,invalid location` and
+`#fusion,getLatestPredictedFusedLocation,invalid latest selected hypothesis`.
+The TimeZone system-service reader is authorized. The guest agent's
+`com.apple.locationd.simulation` entitlement is present. Developer Mode is
+enabled. These observations put the failure after simulation request delivery
+and before a usable CoreLocation result reaches clients.
+
+## Probes already ruled out
+
+- Removing IcliKit's clear-on-readback-failure kept the simulation active, but
+ did not produce a location for Maps or the authorized reader.
+- Appending two identical points with timestamps one second apart did not
+ produce a location.
+- The guest's `CLSimulationManager` responds to
+ `setSimulatedWifiPower:` and `startWifiSimulation`. Calling both before
+ starting location simulation did not produce a location.
+- A `locationd` process exit seen during testing coincided with restoring a
+ temporary guest agent. The restarted original agent reproduced the failure;
+ the exit is not evidence of the root cause.
+
+These observations predate the application hook below. No Apple binary patch
+was needed for the workaround.
+
+## Separate host-sync issue
+
+The host `CLLocationManager` returned `kCLErrorDomain` code 1 while its
+authorization status was Not Determined. The menu's Sync Host Location
+checkmark only records the requested mode; it does not establish that macOS
+has supplied a coordinate or that the guest accepted one. This does not
+explain preset failure, which also reproduces through the HTTP API and
+`devicectl`.
+
+## Application-level workaround (2026-09-25)
+
+`libvlocation.dylib` is loaded by SystemHook into newly launched apps. It
+overrides `CLLocationManager` updates for authorized clients while vphoned's
+location state file exists. The HTTP `location.set` endpoint publishes that
+file atomically and returns promptly; the locationd simulation request is
+best effort. Clearing removes the override. This route intentionally bypasses
+the iOS 26.4 locationd fusion problem described above.
+
+Live verification on the 26.4 VM moved Maps' blue dot from Tokyo Station to
+Apple Park. A subsequent Maps launch without a test environment variable
+loaded `/usr/lib/libvlocation.dylib` through SystemHook and showed the blue dot
+near Apple Park. This confirms delivery to Maps, beyond an API success reply.
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 742e64a1..df892b79 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -296,21 +296,33 @@ icli's own error `code` (`failed`, `unavailable`, `device_locked`, …) and
message.
The environment update keeps `launchdhook-vphone.dylib`,
-`SystemHook-vphone.dylib`, `libvcamcaptured.dylib` and `libcamfix.dylib` in
+`SystemHook-vphone.dylib`, `libvcamcaptured.dylib`, `libcamfix.dylib`, and
+`libvlocation.dylib` in
`/usr/lib` in step with the host bundle. After each connection the VM
process compares the guest's hashes with `Contents/Resources/guest-resources`,
uploads the libraries that differ to the staging directory
(`/var/root/Library/Caches/vphone-environment`) and calls
-`environment.install`. vphoned accepts only those four names and checks each
+`environment.install`. vphoned accepts only those five names and checks each
SHA-256. When `/` is mounted read-only it runs `/sbin/mount -u -w /`, copies
each library beside its destination, renames it into place with mode 0755
-and owner root, and runs `/sbin/mount -u -r /` again; jailbreak detection
-reads a writable root as a rootful layout. It stops a running
+and owner root, and tries `/sbin/mount -u -r /` again. An APFS guest can reject
+that live read-only remount; in that case the install still reports success
+with `reboot_required: true` and `root_read_only: false`. The reboot restores
+the intended root state for jailbreak detection. It stops a running
`cameracaptured` when a camera hook or SystemHook changed, so the next
camera client loads the new hook. The result lists `installed`,
`restarted_pids` and `reboot_required`, which is true when the launchd hook
changed: launchd keeps the copy it mapped at boot.
+`location.set` publishes the validated coordinate atomically to
+`/var/mobile/Library/Caches/vphone-location.json`. The app hook reads that file
+and delivers updates to authorized `CLLocationManager` clients, including Maps;
+`location.clear` removes it. The system simulation request remains best effort
+because iOS 26.4's location fusion may reject it. `location.current` reports
+`delivery: application_override` when the state file exists; it reports the
+published coordinate, not independent confirmation from each app. Newly
+installed hooks require app relaunch before that app receives overrides.
+
## Connection failure behavior
A dropped HTTP or WebSocket connection closes only that request channel. The
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
index ec2a7ca8..399c4609 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
@@ -14,17 +14,26 @@ extension GuestAPI {
"SystemHook-vphone.dylib",
"libvcamcaptured.dylib",
"libcamfix.dylib",
+ "libvlocation.dylib",
]
static let environmentStaging = "/var/root/Library/Caches/vphone-environment"
static func executeEnvironment(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
switch method {
case "environment.status":
+ var root = statfs()
+ guard statfs("/", &root) == 0 else {
+ throw GuestAPIError.operationFailed("statfs(/): \(String(cString: strerror(errno)))")
+ }
let libraries = environmentLibraries.map { name -> [String: Any] in
let data = try? Data(contentsOf: URL(fileURLWithPath: "/usr/lib/" + name), options: .mappedIfSafe)
return ["name": name, "sha256": data.map(sha256Hex) ?? NSNull()]
}
- return ["libraries": libraries, "staging": environmentStaging]
+ return [
+ "libraries": libraries,
+ "staging": environmentStaging,
+ "root_read_only": root.f_flags & UInt32(MNT_RDONLY) != 0,
+ ]
case "environment.install":
return try installEnvironment(params)
default:
@@ -52,7 +61,7 @@ extension GuestAPI {
names.append(name)
}
- try withWritableRoot {
+ let rootReadOnly = try withWritableRoot {
for name in names {
try installLibrary(from: environmentStaging + "/" + name, to: "/usr/lib/" + name)
}
@@ -71,24 +80,33 @@ extension GuestAPI {
"installed": names,
"restarted_pids": restarted,
// launchd loaded its hook at boot and keeps the old copy mapped.
- "reboot_required": names.contains("launchdhook-vphone.dylib"),
+ "reboot_required": !rootReadOnly || names.contains("launchdhook-vphone.dylib"),
+ "root_read_only": rootReadOnly,
]
}
- /// Runs `body` with `/` writable, then makes a read-only root read-only
- /// again. Jailbreak detection reads a writable root as a rootful layout.
- private static func withWritableRoot(_ body: () throws -> Void) throws {
+ /// Runs `body` with `/` writable, then tries to restore read-only state.
+ /// Some APFS guests reject a live read-only remount; the caller must then
+ /// request a reboot so jailbreak detection does not keep seeing rootful.
+ private static func withWritableRoot(_ body: () throws -> Void) throws -> Bool {
var root = statfs()
guard statfs("/", &root) == 0 else {
throw GuestAPIError.operationFailed("statfs(/): \(String(cString: strerror(errno)))")
}
- guard root.f_flags & UInt32(MNT_RDONLY) != 0 else {
- return try body()
+ if root.f_flags & UInt32(MNT_RDONLY) != 0 {
+ try remountRoot("-w")
}
- try remountRoot("-w")
let result = Result { try body() }
- try remountRoot("-r")
+ let rootReadOnly: Bool
+ do {
+ try remountRoot("-r")
+ rootReadOnly = true
+ } catch {
+ NSLog("[environment] root remains writable until reboot: %@", String(describing: error))
+ rootReadOnly = false
+ }
try result.get()
+ return rootReadOnly
}
/// `mode` is `-w` for read-write or `-r` for read-only.
@@ -96,14 +114,34 @@ extension GuestAPI {
let arguments = ["/sbin/mount", "-u", mode, "/"]
var argv = arguments.map { strdup($0) } + [nil]
defer { argv.forEach { free($0) } }
+ var errorPipe: [Int32] = [0, 0]
+ guard pipe(&errorPipe) == 0 else {
+ throw GuestAPIError.operationFailed("pipe: \(String(cString: strerror(errno)))")
+ }
+ var actions: posix_spawn_file_actions_t?
+ posix_spawn_file_actions_init(&actions)
+ posix_spawn_file_actions_adddup2(&actions, errorPipe[1], STDERR_FILENO)
+ posix_spawn_file_actions_addclose(&actions, errorPipe[0])
var pid: pid_t = 0
- let spawned = posix_spawn(&pid, arguments[0], nil, nil, &argv, environ)
+ let spawned = posix_spawn(&pid, arguments[0], &actions, nil, &argv, environ)
+ posix_spawn_file_actions_destroy(&actions)
+ close(errorPipe[1])
guard spawned == 0 else {
+ close(errorPipe[0])
throw GuestAPIError.operationFailed("mount -u \(mode) /: \(String(cString: strerror(spawned)))")
}
+ var errorText = Data()
+ var buffer = [UInt8](repeating: 0, count: 1024)
+ while errorText.count < 4096 {
+ let count = read(errorPipe[0], &buffer, min(buffer.count, 4096 - errorText.count))
+ if count <= 0 { break }
+ errorText.append(contentsOf: buffer.prefix(count))
+ }
+ close(errorPipe[0])
var status: Int32 = 0
guard waitpid(pid, &status, 0) == pid, status == 0 else {
- throw GuestAPIError.operationFailed("mount -u \(mode) / exited with status \(status)")
+ let details = String(data: errorText, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ throw GuestAPIError.operationFailed("mount -u \(mode) / exited with status \(status): \(details)")
}
}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 21b217ce..9d19c812 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -250,19 +250,19 @@ enum GuestAPI {
}
return try hidPress(page: page, usage: usage)
case "location.set":
- return try simulateLocation(
+ return try GuestLocationSimulation.set(.init(
latitude: number(params, "latitude"),
longitude: number(params, "longitude"),
altitude: number(params, "altitude", default: 0),
horizontalAccuracy: number(params, "horizontal_accuracy", default: 5),
verticalAccuracy: number(params, "vertical_accuracy", default: 5),
- speed: (params["speed"] as? NSNumber)?.doubleValue,
- course: (params["course"] as? NSNumber)?.doubleValue,
- )
+ speed: (params["speed"] as? NSNumber)?.doubleValue ?? -1,
+ course: (params["course"] as? NSNumber)?.doubleValue ?? -1,
+ ))
case "location.clear":
- return try clearSimulatedLocation()
+ return try GuestLocationSimulation.clear()
case "location.current":
- return try currentLocation(timeout: number(params, "timeout", default: 10))
+ return try GuestLocationSimulation.current(timeout: number(params, "timeout", default: 10))
case "developer_mode.status":
return try developerModeStatus()
case "developer_mode.enable":
diff --git a/VPhoneDaemon/Daemon/GuestLocationSimulation.swift b/VPhoneDaemon/Daemon/GuestLocationSimulation.swift
new file mode 100644
index 00000000..fdf40c2a
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestLocationSimulation.swift
@@ -0,0 +1,137 @@
+import Darwin
+import Foundation
+import IcliKit
+
+/// Publishes one location for the app-side CoreLocation bridge. The VM's
+/// locationd accepts simulation commands but can fail to deliver a fused fix.
+enum GuestLocationSimulation {
+ static let path = "/var/mobile/Library/Caches/vphone-location.json"
+ private static let backend = LocationDaemonBackend()
+
+ struct Point: Sendable {
+ let latitude: Double
+ let longitude: Double
+ let altitude: Double
+ let horizontalAccuracy: Double
+ let verticalAccuracy: Double
+ let speed: Double
+ let course: Double
+
+ var json: [String: Double] {
+ [
+ "latitude": latitude, "longitude": longitude, "altitude": altitude,
+ "horizontal_accuracy": horizontalAccuracy, "vertical_accuracy": verticalAccuracy,
+ "speed": speed, "course": course,
+ ]
+ }
+ }
+
+ static func set(_ point: Point) throws -> [String: Any] {
+ guard point.latitude.isFinite, (-90 ... 90).contains(point.latitude),
+ point.longitude.isFinite, (-180 ... 180).contains(point.longitude),
+ point.altitude.isFinite, point.horizontalAccuracy.isFinite, point.horizontalAccuracy >= 0,
+ point.verticalAccuracy.isFinite, point.verticalAccuracy >= 0,
+ point.speed.isFinite, point.course.isFinite
+ else { throw GuestAPIError.invalidRequest("invalid location coordinates or accuracy") }
+
+ let data = try JSONSerialization.data(withJSONObject: point.json)
+ try FileManager.default.createDirectory(
+ atPath: (path as NSString).deletingLastPathComponent,
+ withIntermediateDirectories: true,
+ )
+ try writeAtomically(data)
+ backend.set(point)
+ return ["simulating": true, "delivery": "application_override", "location": point.json]
+ }
+
+ static func clear() throws -> [String: Any] {
+ guard unlink(path) == 0 || errno == ENOENT else {
+ throw GuestAPIError.operationFailed("could not clear simulated location: \(String(cString: strerror(errno)))")
+ }
+ backend.clear()
+ return ["simulating": false]
+ }
+
+ static func current(timeout: Double) throws -> [String: Any] {
+ if let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
+ let state = try? JSONSerialization.jsonObject(with: data) as? [String: Double]
+ {
+ var result: [String: Any] = state
+ result["simulated"] = true
+ result["delivery"] = "application_override"
+ return result
+ }
+ return try currentLocation(timeout: timeout)
+ }
+
+ private static func writeAtomically(_ data: Data) throws {
+ let temporary = path + "." + UUID().uuidString
+ let fd = open(temporary, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0o644)
+ guard fd >= 0 else {
+ throw GuestAPIError.operationFailed("could not open simulated location: \(String(cString: strerror(errno)))")
+ }
+ var openFD = fd
+ defer {
+ if openFD >= 0 { close(openFD) }
+ unlink(temporary)
+ }
+ try data.withUnsafeBytes { buffer in
+ guard let base = buffer.baseAddress else { return }
+ var offset = 0
+ while offset < buffer.count {
+ let written = write(fd, base.advanced(by: offset), buffer.count - offset)
+ guard written > 0 else {
+ throw GuestAPIError.operationFailed("could not write simulated location: \(String(cString: strerror(errno)))")
+ }
+ offset += written
+ }
+ }
+ guard fchmod(fd, 0o644) == 0, close(fd) == 0 else {
+ openFD = -1
+ throw GuestAPIError.operationFailed("could not finish simulated location: \(String(cString: strerror(errno)))")
+ }
+ openFD = -1
+ guard rename(temporary, path) == 0 else {
+ throw GuestAPIError.operationFailed("could not publish simulated location: \(String(cString: strerror(errno)))")
+ }
+ }
+}
+
+/// Best-effort system simulation remains useful on guests whose locationd
+/// publishes a fix. It cannot block application updates or route replay.
+private final class LocationDaemonBackend: @unchecked Sendable {
+ private let queue = DispatchQueue(label: "vphoned.location.simulation")
+ private let lock = NSLock()
+ private var generation: UInt64 = 0
+
+ func set(_ point: GuestLocationSimulation.Point) {
+ lock.lock()
+ generation &+= 1
+ let submitted = generation
+ lock.unlock()
+ queue.async { [self] in
+ lock.lock()
+ let current = generation == submitted
+ lock.unlock()
+ guard current else { return }
+ do {
+ _ = try simulateLocation(
+ latitude: point.latitude, longitude: point.longitude,
+ altitude: point.altitude, horizontalAccuracy: point.horizontalAccuracy,
+ verticalAccuracy: point.verticalAccuracy,
+ speed: point.speed >= 0 ? point.speed : nil,
+ course: point.course >= 0 ? point.course : nil,
+ )
+ } catch {
+ NSLog("[location] system simulation unavailable: %@", String(describing: error))
+ }
+ }
+ }
+
+ func clear() {
+ lock.lock()
+ generation &+= 1
+ lock.unlock()
+ queue.async { _ = try? clearSimulatedLocation() }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index b416f9d3..e56081d8 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -667,8 +667,8 @@ struct VPhoneCustomFirmwareInstaller {
try bundle.replaceFile(".vphoned.signed", fromFileAt: work.file("vphoned"), mode: 0o755, owner: owner)
}
- /// The launchd hook, SystemHook and the camera hooks. SystemHook loads the
- /// camera hooks from /usr/lib without a bootstrap or tweak loader.
+ /// The launchd hook, SystemHook, camera hooks, and location hook. SystemHook
+ /// loads app hooks from /usr/lib without a bootstrap or tweak loader.
private func installEnvironment(system: VPhoneConfinedDirectory) throws {
for name in VPhoneGuestEnvironment.libraries {
let source = try VPhoneGuestBinaries.resolve(name)
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 14987487..9f204014 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -62,6 +62,7 @@ fi
/bin/cp "$guest_products/launchhook/launchdhook-vphone.dylib" "$guest/launchdhook-vphone.dylib"
/bin/cp "$guest_products/systemhook/SystemHook-vphone.dylib" "$guest/SystemHook-vphone.dylib"
/bin/cp "$guest_products/camfix/libcamfix.dylib" "$guest/libcamfix.dylib"
+/bin/cp "$guest_products/locationfix/libvlocation.dylib" "$guest/libvlocation.dylib"
/bin/cp "$guest_products/camfix/libcamfix.plist" "$guest/libcamfix.plist"
/bin/cp "$guest_products/vcamcaptured/libvcamcaptured.dylib" "$guest/libvcamcaptured.dylib"
/bin/cp "$guest_products/vcamcaptured/libvcamcaptured.plist" "$guest/libvcamcaptured.plist"
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index c6aafd13..b4dee45e 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -36,7 +36,7 @@ require_signed_macho() {
for name in vphone-vm vphone-cli VPhoneEscalator libswiftCompatibilitySpan.vphone.dylib; do
require_signed_macho "$macos/$name"
done
-for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
+for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib libvlocation.dylib \
libvcamcaptured.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
done
@@ -45,7 +45,7 @@ for name in vphoned.plist libcamfix.plist libvcamcaptured.plist; do
done
for name in vphoned vphoned.signed vphone-app VPhoneAMFIAllow vphone-archive icli vpregister \
- vphone-ask-for-permission libcamfix.dylib libvcamcaptured.dylib launchdhook-vphone.dylib \
+ vphone-ask-for-permission libcamfix.dylib libvlocation.dylib libvcamcaptured.dylib launchdhook-vphone.dylib \
SystemHook-vphone.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
[[ ! -e "$macos/$name" ]] || { print -u2 "Obsolete binary: Contents/MacOS/$name"; exit 1; }
done
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneLocationProvider.swift b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneLocationProvider.swift
index 4f438a7e..5ddfe3d0 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneLocationProvider.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneLocationProvider.swift
@@ -42,9 +42,10 @@ class VPhoneLocationProvider: NSObject {
private var locationManager: CLLocationManager?
private var delegateProxy: LocationDelegateProxy?
- private var lastLocation: CLLocation?
+ private var lastHostLocation: CLLocation?
private var replayTask: Task<Void, Never>?
private var replayName: String?
+ var onAuthorizationFailure: (() -> Void)?
var isReplaying: Bool {
replayTask != nil
@@ -54,11 +55,14 @@ class VPhoneLocationProvider: NSObject {
self.control = control
super.init()
- let proxy = LocationDelegateProxy { [weak self] location in
- Task { @MainActor in
- self?.forward(location)
- }
- }
+ let proxy = LocationDelegateProxy(
+ locationHandler: { [weak self] location in
+ Task { @MainActor in self?.forward(location) }
+ },
+ authorizationHandler: { [weak self] status in
+ Task { @MainActor in self?.handleAuthorization(status) }
+ },
+ )
delegateProxy = proxy
let mgr = CLLocationManager()
mgr.delegate = proxy
@@ -71,15 +75,10 @@ class VPhoneLocationProvider: NSObject {
func startForwarding() {
stopReplay()
guard let mgr = locationManager else { return }
- mgr.requestAlwaysAuthorization()
- mgr.startUpdatingLocation()
hostModeStarted = true
+ mgr.requestWhenInUseAuthorization()
+ handleAuthorization(mgr.authorizationStatus)
print("[location] started host location tracking")
- // Re-send last known location immediately on reconnect
- if let last = lastLocation {
- forward(last)
- print("[location] re-sent last known host location")
- }
}
/// Stop forwarding host location updates.
@@ -91,6 +90,22 @@ class VPhoneLocationProvider: NSObject {
}
}
+ private func handleAuthorization(_ status: CLAuthorizationStatus) {
+ guard hostModeStarted else { return }
+ switch status {
+ case .authorized, .authorizedAlways:
+ locationManager?.startUpdatingLocation()
+ if let last = lastHostLocation, abs(last.timestamp.timeIntervalSinceNow) < 60 {
+ forward(last)
+ }
+ case .denied, .restricted:
+ stopForwarding()
+ onAuthorizationFailure?()
+ default:
+ break
+ }
+ }
+
/// Send a fixed simulated location to the guest.
func sendPreset(name: String, latitude: Double, longitude: Double, altitude: Double = 0) {
stopReplay()
@@ -179,7 +194,8 @@ class VPhoneLocationProvider: NSObject {
}
private func forward(_ location: CLLocation) {
- lastLocation = location
+ lastHostLocation = location
+ guard hostModeStarted else { return }
guard control.isConnected else {
print("[location] forward: not connected, cached for later")
return
@@ -204,15 +220,6 @@ class VPhoneLocationProvider: NSObject {
speed: Double,
course: Double,
) {
- let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
- lastLocation = CLLocation(
- coordinate: coordinate,
- altitude: altitude,
- horizontalAccuracy: horizontalAccuracy,
- verticalAccuracy: verticalAccuracy,
- timestamp: Date(),
- )
-
guard control.isConnected else {
print("[location] simulate: not connected, cached for later")
return
@@ -234,10 +241,15 @@ class VPhoneLocationProvider: NSObject {
/// Separate object to avoid @MainActor vs nonisolated delegate conflicts.
private class LocationDelegateProxy: NSObject, CLLocationManagerDelegate {
- let handler: (CLLocation) -> Void
+ let locationHandler: (CLLocation) -> Void
+ let authorizationHandler: (CLAuthorizationStatus) -> Void
- init(handler: @escaping (CLLocation) -> Void) {
- self.handler = handler
+ init(
+ locationHandler: @escaping (CLLocation) -> Void,
+ authorizationHandler: @escaping (CLAuthorizationStatus) -> Void,
+ ) {
+ self.locationHandler = locationHandler
+ self.authorizationHandler = authorizationHandler
}
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
@@ -246,7 +258,7 @@ private class LocationDelegateProxy: NSObject, CLLocationManagerDelegate {
print(
"[location] got location: \(String(format: "%.6f,%.6f", c.latitude, c.longitude)) (+/-\(String(format: "%.0f", location.horizontalAccuracy))m)",
)
- handler(location)
+ locationHandler(location)
}
func locationManager(_: CLLocationManager, didFailWithError error: any Error) {
@@ -261,8 +273,6 @@ private class LocationDelegateProxy: NSObject, CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
let status = manager.authorizationStatus
print("[location] authorization status: \(status.rawValue)")
- if status == .authorized || status == .authorizedAlways {
- manager.startUpdatingLocation()
- }
+ authorizationHandler(status)
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index bc03327f..0549956b 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -169,6 +169,13 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
}
if let provider = locationProvider {
mc.locationProvider = provider
+ provider.onAuthorizationFailure = { [weak mc] in
+ mc?.locationMenuItem?.state = .off
+ let alert = NSAlert()
+ alert.messageText = "Host Location Unavailable"
+ alert.informativeText = "Allow location access for vphone in System Settings to sync the Mac's location."
+ alert.runModal()
+ }
}
if let camServer = cameraServer {
mc.cameraServer = camServer
diff --git a/VPhoneGuestComponents/LocationFix/libvlocation.m b/VPhoneGuestComponents/LocationFix/libvlocation.m
new file mode 100644
index 00000000..a73f11d9
--- /dev/null
+++ b/VPhoneGuestComponents/LocationFix/libvlocation.m
@@ -0,0 +1,119 @@
+#import <CoreLocation/CoreLocation.h>
+#import <Foundation/Foundation.h>
+#import <objc/runtime.h>
+
+#include <math.h>
+
+// vphoned replaces this file atomically. An absent file means native location.
+static NSString *const VPhoneLocationPath = @"/var/mobile/Library/Caches/vphone-location.json";
+static char VPhoneLocationTimerKey;
+
+static CLLocation *vphoneLocation(void) {
+ NSData *data = [NSData dataWithContentsOfFile:VPhoneLocationPath];
+ if (!data || data.length > 4096) return nil;
+ NSDictionary *state = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
+ if (![state isKindOfClass:NSDictionary.class]) return nil;
+
+ NSNumber *latitude = state[@"latitude"];
+ NSNumber *longitude = state[@"longitude"];
+ NSNumber *altitude = state[@"altitude"];
+ NSNumber *horizontalAccuracy = state[@"horizontal_accuracy"];
+ NSNumber *verticalAccuracy = state[@"vertical_accuracy"];
+ NSNumber *speed = state[@"speed"];
+ NSNumber *course = state[@"course"];
+ if (![latitude isKindOfClass:NSNumber.class] || ![longitude isKindOfClass:NSNumber.class] ||
+ ![altitude isKindOfClass:NSNumber.class] || ![horizontalAccuracy isKindOfClass:NSNumber.class] ||
+ ![verticalAccuracy isKindOfClass:NSNumber.class] || ![speed isKindOfClass:NSNumber.class] ||
+ ![course isKindOfClass:NSNumber.class]) return nil;
+ if (!isfinite(latitude.doubleValue) || fabs(latitude.doubleValue) > 90 ||
+ !isfinite(longitude.doubleValue) || fabs(longitude.doubleValue) > 180 ||
+ !isfinite(altitude.doubleValue) || !isfinite(horizontalAccuracy.doubleValue) ||
+ horizontalAccuracy.doubleValue < 0 || !isfinite(verticalAccuracy.doubleValue) ||
+ verticalAccuracy.doubleValue < 0 || !isfinite(speed.doubleValue) || !isfinite(course.doubleValue)) return nil;
+
+ return [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude.doubleValue, longitude.doubleValue)
+ altitude:altitude.doubleValue
+ horizontalAccuracy:horizontalAccuracy.doubleValue
+ verticalAccuracy:verticalAccuracy.doubleValue
+ course:course.doubleValue
+ speed:speed.doubleValue
+ timestamp:NSDate.date];
+}
+
+static BOOL vphoneAuthorized(CLLocationManager *manager) {
+ CLAuthorizationStatus status = manager.authorizationStatus;
+ return status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse;
+}
+
+static void vphoneDeliver(CLLocationManager *manager) {
+ if (!vphoneAuthorized(manager)) return;
+ CLLocation *location = vphoneLocation();
+ id<CLLocationManagerDelegate> delegate = manager.delegate;
+ if (location && [delegate respondsToSelector:@selector(locationManager:didUpdateLocations:)])
+ [delegate locationManager:manager didUpdateLocations:@[location]];
+}
+
+@interface CLLocationManager (VPhoneLocation)
+- (void)vphone_startUpdatingLocation;
+- (void)vphone_stopUpdatingLocation;
+- (void)vphone_requestLocation;
+- (CLLocation *)vphone_location;
+@end
+
+@implementation CLLocationManager (VPhoneLocation)
+- (void)vphone_startUpdatingLocation {
+ [self vphone_startUpdatingLocation];
+ dispatch_async(dispatch_get_main_queue(), ^{
+ NSTimer *timer = objc_getAssociatedObject(self, &VPhoneLocationTimerKey);
+ if (!timer) {
+ __weak CLLocationManager *weakManager = self;
+ timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *activeTimer) {
+ CLLocationManager *manager = weakManager;
+ if (manager) vphoneDeliver(manager);
+ else [activeTimer invalidate];
+ }];
+ objc_setAssociatedObject(self, &VPhoneLocationTimerKey, timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ vphoneDeliver(self);
+ });
+}
+
+- (void)vphone_stopUpdatingLocation {
+ [self vphone_stopUpdatingLocation];
+ dispatch_async(dispatch_get_main_queue(), ^{
+ NSTimer *timer = objc_getAssociatedObject(self, &VPhoneLocationTimerKey);
+ [timer invalidate];
+ objc_setAssociatedObject(self, &VPhoneLocationTimerKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ });
+}
+
+- (void)vphone_requestLocation {
+ if (!vphoneAuthorized(self) || !vphoneLocation()) {
+ [self vphone_requestLocation];
+ return;
+ }
+ dispatch_async(dispatch_get_main_queue(), ^{ vphoneDeliver(self); });
+}
+
+- (CLLocation *)vphone_location {
+ if (vphoneAuthorized(self)) {
+ CLLocation *location = vphoneLocation();
+ if (location) return location;
+ }
+ return [self vphone_location];
+}
+@end
+
+static void vphoneSwizzle(SEL original, SEL replacement) {
+ Class manager = CLLocationManager.class;
+ Method originalMethod = class_getInstanceMethod(manager, original);
+ Method replacementMethod = class_getInstanceMethod(manager, replacement);
+ if (originalMethod && replacementMethod) method_exchangeImplementations(originalMethod, replacementMethod);
+}
+
+__attribute__((constructor)) static void vphoneInstallLocation(void) {
+ vphoneSwizzle(@selector(startUpdatingLocation), @selector(vphone_startUpdatingLocation));
+ vphoneSwizzle(@selector(stopUpdatingLocation), @selector(vphone_stopUpdatingLocation));
+ vphoneSwizzle(@selector(requestLocation), @selector(vphone_requestLocation));
+ vphoneSwizzle(@selector(location), @selector(vphone_location));
+}
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 34639942..3977deb8 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -11,6 +11,8 @@ COMMON_FLAGS := $(GUEST_C_FLAGS) -fobjc-arc
CAMFIX := $(STAGE)/camfix/libcamfix.dylib
CAMFIX_SOURCES := $(wildcard CamFix/*.m)
CAMFIX_INCLUDES := $(wildcard CamFix/*.h CamFix/*.inc VCamCaptured/*.h)
+LOCATIONFIX := $(STAGE)/locationfix/libvlocation.dylib
+LOCATIONFIX_SOURCES := $(wildcard LocationFix/*.m)
VCAMCAPTURED := $(STAGE)/vcamcaptured/libvcamcaptured.dylib
VCAMCAPTURED_SOURCES := $(wildcard VCamCaptured/*.m)
VCAMCAPTURED_INCLUDES := $(wildcard VCamCaptured/*.h VCamCaptured/*.inc)
@@ -47,7 +49,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
-Wl,-U,_MTLMetalFunctionCreate \
-Wl,-U,_MTLMetalLibInsertFunction \
-Wl,-U,_MTLWriteMetalLibToMemoryBuffer
-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(GPU_PLUGIN)
+ARTIFACTS := $(CAMFIX) $(LOCATIONFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(GPU_PLUGIN)
PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
@@ -61,7 +63,7 @@ gpu: $(GPU_PLUGIN)
package: all
@rm -f $(ARCHIVE)
- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook gpu
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix locationfix vcamcaptured launchhook systemhook gpu
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -80,7 +82,7 @@ test-vcam-dataplane:
-framework CoreGraphics
@$(OUT)/VCamDataPlaneTests
-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/gpu:
+$(STAGE)/camfix $(STAGE)/locationfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/gpu:
@mkdir -p $@
$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INCLUDES) CamFix VCamCaptured | $(STAGE)/camfix
@@ -92,6 +94,13 @@ $(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INCLUDES) CamFix VCamCaptured | $(STAGE)/c
-framework CoreGraphics -framework QuartzCore
@codesign --force --sign - $@
+$(LOCATIONFIX): $(LOCATIONFIX_SOURCES) LocationFix | $(STAGE)/locationfix
+ $(CLANG) $(COMMON_FLAGS) -dynamiclib \
+ -install_name /usr/lib/libvlocation.dylib \
+ -o $@ $(LOCATIONFIX_SOURCES) \
+ -framework Foundation -framework CoreLocation
+ @codesign --force --sign - $@
+
$(VCAMCAPTURED): $(VCAMCAPTURED_SOURCES) $(VCAMCAPTURED_INCLUDES) VCamCaptured | $(STAGE)/vcamcaptured
$(CLANG) $(COMMON_FLAGS) -dynamiclib \
-install_name @rpath/libvcamcaptured.dylib \
diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.md
index 24478476..43432766 100644
--- a/VPhoneGuestComponents/README.md
+++ b/VPhoneGuestComponents/README.md
@@ -8,13 +8,14 @@ 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` |
+| CoreLocation app hook | `locationfix/libvlocation.dylib` |
| Launchd hook | `launchhook/launchdhook-vphone.dylib` |
| Process injection bridge | `systemhook/SystemHook-vphone.dylib` |
| iOS 27 app registrar | `vpregister/vpregister` |
| PCC GPU driver | `gpu/README.md` (source and extraction flow; no Apple binary) |
The archive is a local build artifact, not a VM bootstrap. `cfw install` places
-the launchd hook, SystemHook and both camera hooks in `/usr/lib`, and the
+the launchd hook, SystemHook, camera hooks, and location hook in `/usr/lib`, and the
vphoned environment update replaces changed copies in a running guest. SystemHook
loads `libvcamcaptured.dylib` into `/usr/libexec/cameracaptured` and
`libcamfix.dylib` into apps that have AVFoundation loaded; neither camera hook
@@ -29,6 +30,11 @@ ElleKit owns tweak selection and loading. It logs PID and executable path to
`/var/mobile/Library/Caches/vphone-systemhook.log`, falling back to the app's
own `Library/Caches` when sandboxed.
`DISABLE_TWEAKS=1` and the safe-mode flags skip injection.
+SystemHook also loads `libvlocation.dylib` into newly started apps. When
+`/var/mobile/Library/Caches/vphone-location.json` exists, the hook supplies its
+coordinate through `CLLocationManager` for authorized clients. A missing state
+file leaves native location in place. Apps already running when the library is
+installed must be relaunched to load it.
Irisin installs ElleKit's own `TweakLoader.dylib` in the selected bootstrap.
The required GPU bundle is extracted from the selected PCC firmware by
`vphone-cli fw prepare` and copied into the VM during JB installation. No
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index 14f4d5fc..cf30ae11 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -139,6 +139,7 @@ static int vpExecve(const char *path, char *const argv[], char *const envp[]) {
// They need no tweak loader: each installs its own Objective-C hooks.
#define VP_CAMERA_DAEMON_HOOK "/usr/lib/libvcamcaptured.dylib"
#define VP_CAMERA_APP_HOOK "/usr/lib/libcamfix.dylib"
+#define VP_LOCATION_APP_HOOK "/usr/lib/libvlocation.dylib"
#define VP_AVFOUNDATION "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"
// A missing library is expected and stays quiet; anything else is logged.
@@ -195,6 +196,8 @@ __attribute__((constructor)) static void vpLogProcess(void) {
}
if (!vpInBootstrap && !vpIsAppPath(path))
return;
+ if (vpIsAppPath(path))
+ vpLoadLibrary("location-hook", VP_LOCATION_APP_HOOK);
if (vpIsAppPath(path) && dlopen(VP_AVFOUNDATION, RTLD_LAZY | RTLD_NOLOAD))
vpLoadLibrary("camera-hook", VP_CAMERA_APP_HOOK);
const char *root = getenv("VPHONE_JB_ROOT");
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
index bb7d9044..9a6ac85c 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
@@ -11,5 +11,6 @@ public enum VPhoneGuestEnvironment {
"SystemHook-vphone.dylib",
"libvcamcaptured.dylib",
"libcamfix.dylib",
+ "libvlocation.dylib",
]
}