Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Keep the guest's clock on the Mac's

Jacky3715b5bf59c8
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index cade1e7c..72571602 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -40,6 +40,10 @@ Closing the VM window, ⌘Q, `vm stop` and Control-C in the `vm launch` terminal
The guest shows the VM's name as its device name, in Xcode's device list and `xcrun devicectl list devices`, and cannot be renamed from inside the guest or from Finder, Xcode or `idevicename`: a rename there reports success and changes nothing. `vphone-vm` hands the name to the guest each time it connects to vphoned, a few seconds into every boot, and the guest keeps it for the next boot. After `vm rename`, Finder and `ideviceinfo` see the new name as soon as the machine is up; Xcode and `devicectl` read it when the device appears and may show the old name until the following boot. An existing machine moved to a bundle with this feature receives the guest library with its environment update and uses it from the boot after that. The guest's own name stays in its preferences, untouched. A VM name of more than 255 UTF-8 bytes, or with a control character, is not used, and the guest shows its own name. See `Research/Guest/device_name_pinning.md`.
+## Clock and time zone
+
+The guest follows the Mac's time zone and clock. `vphone-vm` sends the Mac's zone each time it connects to vphoned, and the Mac's time then and every minute after, so a guest that was off for a day, or sat under a sleeping Mac, is back on the Mac's time within a minute without reaching an NTP server. A guest within a second of the Mac is left alone. To give the guest another date or time, pick it in the guest's Settings › General › Date & Time: that turns its automatic time off and the Mac's time is no longer applied. Turning Set Automatically on there brings the Mac's time back.
+
## Templates
A template is a complete machine kept in `<library>/.templates/<id>/`. It boots once while it is built, its setup boot, and never again once it is frozen. `vm create` without `--no-template` works out the template key from its options and the two IPSWs before anything is restored: the guest device, the iOS and cloudOS versions and builds, the patch preset and the boot-chain patches it resolves to, the bundle series (`2.9` for 2.9.x), the disk size, what is trimmed from the guest's System volume (`--trim`), and the slimming switches below. Then:
diff --git a/Research/Guest/host_clock_sync.md b/Research/Guest/host_clock_sync.md
new file mode 100644
index 00000000..0c8b1bf1
--- /dev/null
+++ b/Research/Guest/host_clock_sync.md
@@ -0,0 +1,177 @@
+# Host clock sync
+
+`vphone-vm` keeps a guest's wall clock on the Mac's. It sends the Mac's time
+after every connect to vphoned, every minute, when the Mac wakes and when the
+Mac's own clock is set; vphoned offers it to timed as an NTP result, and timed
+sets the clock.
+
+Static analysis of `/usr/libexec/timed` (CoreTime-334.0.16.3) from an iOS
+26.6.2 (23G90) `iPhone17,3` guest and of macOS 27's `timed` (CoreTime-340.0.14,
+the same sources, read with Ghidra), 2026-10-12. Run on iOS 26.6.2 and iOS
+27.0.1 (24A446) guests; see [Verification](#verification).
+
+## What goes wrong without it
+
+A guest was found 18 h 28 min behind the Mac, with the right time zone. Its
+`/var/db/timed/com.apple.timed.plist` held a time filter (`TDTF`) with one
+input, `FilesystemTimestamp`, taken 2 s after boot: UTC 2026-10-11 06:00:31 at
+RTC 2026-10-12 00:28:56. The RTC value was right; the UTC value was the last
+time the guest had run.
+
+The guest's kernel takes the Mac's time from the virtual RTC at boot, so the
+clock starts right. timed then replaces it:
+
+1. `TMCache initWithPath:clock:` reads the plist. `readValidCache:clock:`
+ accepts it only if the format version matches, the kernel's monotonic clock
+ has not gone back, its offset is not zero, the platform has a PMU RTC
+ (`kern.monotonicclock_usecs` exists) and the host UUID is the same.
+2. On a guest the saved state does not pass on a new boot. Which check turns
+ it down was not captured: timed logs it before vphoned is up to read the
+ log. Restarted within one boot, timed loads the same file
+ (`Boot UUID matches`, `TDTF,lastQualityTime,Src,NTP,…`).
+3. When the state is turned down and it says the system time was once set
+ (`TMSystemTimeSet`), timed takes the plist's modification time, empties the
+ file, and, with `UseFilesystemTimestamp` (on by default where there is a
+ PMU RTC), feeds it to the filter as `FilesystemTimestamp` with an
+ uncertainty of 1.5e9 s (`Injecting filesystem timestamp`).
+4. `testAndApplySystemTime` then moves the clock to the filter's time, more
+ than `SettimeofdayThreshold` (0.05 s) away, with `settimeofday`.
+
+So a guest whose clock timed has set once comes up, on every later boot,
+behind by as long as it was off, and stays there until an NTP result arrives.
+A guest that has never had one keeps the RTC's time: its plist has
+`TMSystemTimeSet` false and the filter is not running.
+
+NTP is `time.apple.com` over UDP 123, through the Mac's network. A proxy on
+the Mac in fake-IP mode answers the name with an address of its own and may
+not carry UDP 123: on the Mac where this was found, `sntp time.apple.com`
+timed out against `198.18.147.230` while `sntp ntp.aliyun.com` answered, and
+the guest resolved the same address. (Two hours later the guest's own fetches
+to that address were answered, 0.3 to 0.55 s late.) A Mac that sleeps also stops a running
+guest's clock for as long as it sleeps.
+
+## What timed accepts
+
+A client hands timed a time with CoreTime's `TMSetSourceTime(CFStringRef
+source, CFAbsoluteTime time, CFTimeInterval uncertainty)`. It sends an XPC
+message (`TMCommand` `TMSetSourceTime`, `TMSource`, `TMCurrentTime`,
+`TMTimeError`, `TMMachTime`) and gets no reply.
+
+timed's command check lets a command
+through for a client with `com.apple.timed`, or for root, and for
+`TMSetSourceTime` and `TMSetSourceTimeZone` also wants the source's name in
+the client's `com.apple.timed.sources` array.
+(`TMSetAuthenticatedSourceTime` wants it in `com.apple.private.timed.sources`.)
+vphoned has `com.apple.timed` for the time zone, and now
+`com.apple.timed.sources = [NTP]`.
+
+`TMDaemonCore setSourceTime:` hands the time to the filter's
+`update:withError:`:
+
+- An uncertainty under 1e-6 s is refused.
+- `MobileLockdown`, the source a paired computer sets through lockdownd, is
+ used only while the filter is not running (`ignoreMobileLockdown`). On a
+ guest the filter is running from the filesystem timestamp, so it is no use.
+- A filter that is not running starts from the input.
+- Otherwise the input is compared with the filter's prediction. Within 5
+ standard deviations (3 for `TMLSSourceComputed`, 10 for
+ `TimeSourceGnssValidPos`) of prediction and input together, it is averaged
+ in. Outside, it is turned down (`RejectATime`).
+- For `NTP`, `GPS`, `TimeSourceGnss`, `TimeSourceGnssValidPos` and
+ `TMLSSourceComputedReliable`, a turned-down input counts. At the fifth in a
+ row, or at once when the prediction is more than four times as uncertain as
+ the input, the filter starts over from the input (`ResetSynthesizer`). Any
+ other source can be turned down for ever.
+
+That is why the source is `NTP`: after a Mac's sleep the guest is behind by
+far more than the filter expects, and only a counted source gets it to start
+over. It is also what the offered time is: the Mac's NTP-disciplined clock,
+relayed.
+
+`testAndApplySystemTime` applies the filter to the clock only while automatic
+time is on (`TMAutomaticTimeOnlyEnabled` in timed's preferences,
+`/var/db/timed/Library/Preferences/com.apple.timed.plist`). Settings' Set
+Automatically shows off on a guest, because the time zone sync turns the
+automatic time zone off, while automatic time stays on. Picking a date or time
+there turns automatic time off too, and timed then leaves the clock alone.
+
+## What vphone does
+
+`time.clock` (capability `clock`; REST `GET/PUT /v1/clock`,
+`VPhoneDaemon/Daemon/GuestAPI+Clock.swift`, `VPhoneDaemon/Native/vphoned_clock.m`):
+
+- alone, returns `{time, automatic}`: the guest's clock in seconds since 1970
+ and `TMIsAutomaticTimeEnabled`.
+- `{time}` is the Mac's time. vphoned adds the time the request has waited
+ since it was read. A guest within 1 s is left alone, and so is one with
+ automatic time off. Otherwise vphoned calls
+ `TMSetSourceTime("NTP", time, 0.1)` and reads the clock for 0.3 s, up to six
+ times, until the clock is within 1 s. An offset over 1 s is more than the 5
+ standard deviations a filter fed at 0.1 s allows (about 0.7 s), so an offer
+ is never averaged in: the filter takes it whole, at once from a filesystem
+ timestamp and after five offers otherwise. The answer adds `offset` (the
+ Mac's time less the guest's, before) and `changed`. If the clock has not
+ moved after six offers the request fails with timed's remaining offset.
+- `{automatic}` turns automatic time on or off with
+ `TMSetAutomaticTimeEnabled`; with `time` it is applied first.
+
+`VPhoneClockSync` in `vphone-vm` sends the Mac's time when the guest reports
+`clock`, then every 60 s, on `NSWorkspace.didWakeNotification` and on
+`NSSystemClockDidChange`. It logs a move (`[clock] guest was 302.4 s behind,
+set to the Mac's time`) every time and any other outcome once.
+
+An NTP result of the guest's own is still used. It is averaged in when it is
+within the filter's 5 standard deviations of the Mac's time, which the Mac's
+clock normally is.
+
+## Limits
+
+- The clock is wrong from boot until vphoned connects, about ten seconds.
+ Turning `UseFilesystemTimestamp` off in timed's preferences would leave the
+ RTC's time in place over that stretch; it was not tried.
+- A Mac whose own clock is more than a second off real time, with a guest
+ whose NTP works, has timed and the host each start the filter over in turn:
+ every turned-down input makes timed fetch NTP at once (`RequestFastTime`),
+ and five of its results in a row undo the offer. A result that arrives
+ between offers and agrees with the filter also clears the count, and the
+ request then fails with `timed kept its own time`. Turning automatic time
+ off in the guest ends it.
+- The Mac's time is known in the guest to the request's time on the control
+ connection, 10 to 20 ms as measured.
+
+## Verification
+
+New `iPhone17,3` guests on iOS 26.6.2 (23G90) and iOS 27.0.1 (24A446), cloudOS
+26.4, 2026-10-12. Offsets are the guest's `time.clock` less the Mac's clock
+at the middle of the round trip.
+
+| Case | iOS 26.6.2 | iOS 27.0.1 |
+| --- | --- | --- |
+| `time` 0.5 s ahead of the Mac | left alone | left alone |
+| `time` 1.5 s ahead | moved, +1.498 s | moved, +1.495 s |
+| `time` 1 h ahead | moved, +3599.997 s | moved, +3599.997 s |
+| `time` 1 day behind | moved, −86400.002 s | moved, −86400.005 s |
+| `{automatic: false}`, then `time` 1 h ahead | left alone | left alone |
+| `{automatic: true, time}` 120 s ahead | moved on the second try, +119.996 s | moved, +119.996 s |
+| The host's next send after that | back within 60 s, +0.004 s | back within 60 s, +0.002 s |
+| `time` of 12, and of a string | refused | not run |
+| Booted after some minutes off, once timed had set the clock | `guest was 302.4 s behind, set to the Mac's time` at connect, then steady | `guest was 405.8 s behind, set to the Mac's time`, then −0.027 s over 70 s |
+| The same boot with Unlock at Startup | unlocked, on the Mac's time | not run |
+
+On an earlier build, which offered the time with an uncertainty of 0.5 s, the
+iOS 26.6.2 guest also kept a date picked in its Settings (8 days ahead,
+automatic time off) over 70 s of host sends, and came back to −0.005 s at
+once when Set Automatically was turned on there. On that build a time 1.5 s
+ahead was averaged in and the guest ended 0.75 s ahead, which is why the
+uncertainty is 0.1 s.
+
+The first try of `{automatic: true, time}` on iOS 26.6.2 failed with
+`timed kept its own time, -120.003 s from the Mac's`. The guest's own NTP was
+answering through the Mac's proxy at that moment (`cmd,fetchTime … delay
+0.32 … ip 198.18.147.230`, results of ±0.32 s), so the offered time, wrong on
+purpose, ran into the second limit above. The same results are what moved
+that guest's clock by 0.06 s shortly after each sync: the Mac was about half
+a second ahead of real time.
+
+Not run: a Mac that sleeps and wakes, and a change of the Mac's own clock.
+Both send through the same path as the minute's timer.
diff --git a/Research/README.md b/Research/README.md
index 85724bb4..c26c8075 100644
--- a/Research/README.md
+++ b/Research/README.md
@@ -21,7 +21,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-
| Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) |
| Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md), [guest MAC, fixed address, port forwarding and names](Host/network_fixed_address.md), [machine identity and `vm clone --new-identity`](Host/machine_identity_and_clone.md) |
| VM disk space | [Where a VM's disk space goes](Host/disk_space.md) (overview and measured savings), [machine templates](Host/machine_templates.md), [sharing identical disk blocks with `vm rebase`](Host/disk_rebase.md), [guest TRIM and offline compaction](Host/guest_discard.md), [why the disk layout was not made deterministic](Host/deterministic_disk_layout.md), [why there is no content-addressed block store over NBD](Host/content_addressed_block_store.md) |
-| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [GPU acceleration](Guest/gpu_acceleration.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md), [locationd startup deadlock](Guest/locationd_startup_deadlock.md), [trimming system services](Guest/service_trimming.md), [deleting the orig-fs snapshot for templates](Guest/template_snapshot_deletion.md) |
+| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [GPU acceleration](Guest/gpu_acceleration.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md), [locationd startup deadlock](Guest/locationd_startup_deadlock.md), [host clock sync](Guest/host_clock_sync.md), [trimming system services](Guest/service_trimming.md), [deleting the orig-fs snapshot for templates](Guest/template_snapshot_deletion.md) |
| Historical project records | [Migration ledger](History/intg_update_status.md), [manifest refactoring summary](History/manifest_and_refactoring_summary.md) |
`KernelSymbols/` holds symbol datasets and indexes; `Reference/` holds source references when present. They are evidence inputs, not steps for running the distributed app. The files in `History/` are preserved snapshots and may describe scripts or variants that have since been removed.
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index eb642b0f..da8dcecf 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -305,7 +305,7 @@ request carries `"force": true`.
| Darwin notifications | `notify.post {name, state?}` (`postDarwinNotification`; `state` is a UInt64, as a number or a decimal string, stored before the post), `notify.state {name}` (`darwinNotificationState`) |
| Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.ipv4.get {interface?}`, `network.ipv4.set {interface?, method, address?, subnet_mask?, router?, dns?}`, `network.hostname.get`, `network.hostname.set {local_host_name?}`, `device.name.get`, `device.name.set {name}` (see below), `network.static_names.get`, `network.static_names.set {entries}`, `network.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` |
| Apps | `apps.list`, `search`, `refresh`, `launch`, `terminate`, `foreground`, `open_url`, `install`, `info`, `binary`, `data_dir`, `url_schemes`, `handlers`, `registration`, `register`, `network_policy {repair?}`; `apps.uninstall`, `unregister`, `unregister_dir` **force**; `apps.removed_system`, `apps.remove_system {bundle_ids, backup?, respring?}` **force**, `apps.restore_system {bundle_ids?, respring?}` **force** (removable system apps, see below) |
-| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `system.shutdown` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}` (see below), `diagnostics.self_test` |
+| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `system.shutdown` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}`, `time.clock {time?, automatic?}` (see below), `diagnostics.self_test` |
| Files | `files.list`, `mkdir`, `remove`, `rename`, `read {binary?, limit?}`, `write`, `find`, `copy`, `symlink`, `chmod`, `chown`, `plist`, `plist_set {value \| remove}` |
| APFS snapshots | `apfs.snapshots {mount?}`, `apfs.snapshot.delete {mount?, name? \| prefix?}` **force** (only `orig-fs.disabled.rn-*`, see below) |
| Preferences, clipboard, location | `settings.get/set/delete`, `clipboard.get/set/clear`, `location.set/clear/current` |
@@ -389,6 +389,22 @@ back to timed. Both add `changed`. `vphone-vm` sends the Mac's zone after
every connect and whenever the Mac's zone changes (`VPhoneTimeZoneSync`), so
the guest's clock reads the same local time as the host.
+`time.clock` (capability `clock`; REST `GET/PUT /v1/clock`) returns
+`{time, automatic}`: the guest's clock in seconds since 1970 and whether timed
+sets it (CoreTime's `TMIsAutomaticTimeEnabled`). `{time}` is the Mac's time. A
+guest within a second of it is left alone, and so is one with automatic time
+off, whose clock was set by hand in Settings. Otherwise vphoned offers the
+time to timed as an NTP result (`TMSetSourceTime`, which timed takes only with
+`com.apple.timed` and `NTP` in `com.apple.timed.sources`), up to six times,
+and timed sets the clock and posts the time change itself. The answer adds
+`offset`, the Mac's time less the guest's before the offer, and `changed`. A
+clock that has not moved after six offers fails the request: timed holds a
+time it trusts more. `{automatic}` turns automatic time on or off
+(`TMSetAutomaticTimeEnabled`) and adds `changed`; with `time` it is applied
+first. `vphone-vm` sends the Mac's time after every connect, every minute,
+when the Mac wakes and when the Mac's clock is set (`VPhoneClockSync`). The
+analysis is in `Research/Guest/host_clock_sync.md`.
+
`audio.host_latency` (capability `audio_host_latency`) reads or sets what the
Mac's output device adds after its mixer, in seconds, which the guest's
sound plugin adds to its speaker's output latency so a player in the guest
diff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.md
index f84ed1ab..58532eae 100644
--- a/Skills/vphone-guest-control/references/rpc-methods.md
+++ b/Skills/vphone-guest-control/references/rpc-methods.md
@@ -186,6 +186,7 @@ size problem.
| `clipboard.get` / `set` / `clear` | `set` takes `text` |
| `location.set` / `clear` / `current` | `set` takes latitude/longitude; `set` and `current` fail with `location_services_off` while the guest's Location Services switch is off (vphoned never turns it on); read-back can fail on some guests |
| `time.timezone` | none reads `{identifier, automatic, seconds_from_gmt}`; `identifier` (Olson name) pins the zone and turns automatic off; `automatic: true` hands it back to timed. The VM sends the Mac's zone on every connect |
+| `time.clock` | none reads `{time, automatic}` (seconds since 1970; `automatic` is timed's automatic time); `time` (the Mac's time) moves a guest more than a second away onto it unless `automatic` is off, and adds `offset` and `changed`; `automatic` turns automatic time on or off. The VM sends the Mac's time on every connect and every minute, so a time set this way lasts only with `automatic: false` |
| `notify.post` / `notify.state` | `name`, `state?` |
| `keychain.*` | Lists, adds and edits secrets; use only on request and never print values |
diff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
index ac50f255..2aa98f56 100644
--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
@@ -543,6 +543,10 @@
<true/>
<key>com.apple.timed</key>
<true/>
+ <key>com.apple.timed.sources</key>
+ <array>
+ <string>NTP</string>
+ </array>
<key>com.apple.tzlink.allow</key>
<true/>
<key>com.apple.usernotification.notificationregistrarproxy</key>
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Clock.swift b/VPhoneDaemon/Daemon/GuestAPI+Clock.swift
new file mode 100644
index 00000000..f80a1eb6
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Clock.swift
@@ -0,0 +1,129 @@
+import Foundation
+import VphonedNative
+
+// MARK: - Clock
+
+/// The guest's wall clock, kept on the Mac's.
+///
+/// A guest boots with the Mac's time, from the virtual RTC. Once timed has
+/// set the clock from a time source, it replaces that on every later boot
+/// with the last time the guest ran, and waits for NTP. A guest whose NTP
+/// does not get through is left behind by as long as it was powered off, and
+/// a Mac that sleeps under a running guest leaves it behind as well.
+///
+/// `{time}` (seconds since 1970) is the Mac's time. A guest within
+/// `clockTolerance` of it is left alone, and so is one whose automatic time
+/// is off: that clock was set by hand in Settings. Otherwise the time is
+/// offered to timed as an NTP result, and timed sets the clock itself and
+/// tells the system. timed turns down a result its filter does not expect
+/// until it has seen five, so the offer is repeated. `{automatic}` turns
+/// timed's automatic time on or off, as Set Automatically does for the
+/// clock; with `time` as well, it is applied first.
+///
+/// Each answer is `{time, automatic}`, plus `changed` after a set and
+/// `offset` (the Mac's time less the guest's, before the change) after an
+/// offer.
+///
+/// See Research/Guest/host_clock_sync.md.
+extension GuestAPI {
+ /// A guest this close to the Mac is left alone. timed's filter turns
+ /// down anything further out than about seven times `clockUncertainty`
+ /// and then starts over from it, so no offer is ever averaged in.
+ private static let clockTolerance = 1.0
+ /// What timed is told the offered time is good to: the request's way
+ /// through the control connection, and the Mac's own clock.
+ private static let clockUncertainty = 0.1
+ /// One more than timed turns down before it starts over from a result.
+ private static let clockOffers = 6
+ private static let clockLock = NSLock()
+
+ static func executeClock(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ guard method == "time.clock" else { return nil }
+ let received = DispatchTime.now()
+ let automatic = params["automatic"] as? Bool
+ guard params["time"] != nil else {
+ guard let automatic else { return try clockState() }
+ return try clockLock.withLock { try setAutomaticClock(automatic) }
+ }
+ let time = try requiredNumber(params, "time")
+ // timed refuses anything before 2001; nothing sends that in earnest.
+ guard time > kCFAbsoluteTimeIntervalSince1970 else {
+ throw GuestAPIError.invalidRequest("time must be seconds since 1970")
+ }
+ return try clockLock.withLock {
+ let switched = try automatic.map { try setAutomaticClock($0)["changed"] as? Bool ?? false } ?? false
+ var state = try offerClock {
+ time + Double(DispatchTime.now().uptimeNanoseconds - received.uptimeNanoseconds) / 1e9
+ }
+ state["changed"] = switched || state["changed"] as? Bool == true
+ return state
+ }
+ }
+
+ private static func clockState() throws -> [String: Any] {
+ let automatic: Any = switch vp_clock_automatic() {
+ case 1: true
+ case 0: false
+ case -2: throw GuestAPIError.operationFailed("timed did not answer within 3 seconds")
+ default: NSNull()
+ }
+ return ["time": Date().timeIntervalSince1970, "automatic": automatic]
+ }
+
+ private static func setAutomaticClock(_ enabled: Bool) throws -> [String: Any] {
+ var state = try clockState()
+ guard let current = state["automatic"] as? Bool else {
+ throw GuestAPIError.operationFailed("CoreTime's automatic time setting is unavailable on this guest")
+ }
+ if current != enabled {
+ guard vp_clock_set_automatic(enabled) == 0 else {
+ throw GuestAPIError.operationFailed("timed did not take the automatic time setting")
+ }
+ var applied = false
+ for _ in 0 ..< 40 where !applied {
+ Thread.sleep(forTimeInterval: 0.05)
+ applied = vp_clock_automatic() == (enabled ? 1 : 0)
+ }
+ guard applied else {
+ throw GuestAPIError.operationFailed("timed did not apply the automatic time setting")
+ }
+ NSLog("vphoned: automatic time turned %@", enabled ? "on" : "off")
+ state = try clockState()
+ }
+ state["changed"] = current != enabled
+ return state
+ }
+
+ private static func offerClock(_ hostTime: () -> Double) throws -> [String: Any] {
+ var state = try clockState()
+ let offset = hostTime() - Date().timeIntervalSince1970
+ state["offset"] = offset
+ state["changed"] = false
+ guard abs(offset) >= clockTolerance, state["automatic"] as? Bool != false else { return state }
+
+ var remaining = offset
+ for _ in 0 ..< clockOffers {
+ switch vp_clock_offer(hostTime(), clockUncertainty) {
+ case 0: break
+ case -1: throw GuestAPIError.operationFailed("CoreTime has no TMSetSourceTime on this guest")
+ default: throw GuestAPIError.operationFailed("timed did not take the time within 3 seconds")
+ }
+ // timed sets the clock on its own queue, a few milliseconds later.
+ for _ in 0 ..< 6 {
+ Thread.sleep(forTimeInterval: 0.05)
+ remaining = hostTime() - Date().timeIntervalSince1970
+ if abs(remaining) < clockTolerance { break }
+ }
+ guard abs(remaining) >= clockTolerance else {
+ NSLog("vphoned: clock moved %.3f s to the Mac's time", offset)
+ state["time"] = Date().timeIntervalSince1970
+ state["changed"] = true
+ return state
+ }
+ }
+ throw GuestAPIError.operationFailed(String(
+ format: "timed kept its own time, %.3f s from the Mac's. It holds a time it trusts more, or vphoned lacks NTP in com.apple.timed.sources.",
+ -remaining,
+ ))
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
index 456824da..4a4d257a 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -20,6 +20,7 @@ extension GuestAPI {
executeSetupAssistant,
executeFirstBoot,
executeTimeZone,
+ executeClock,
executeAudioLatency,
executeGyroscope,
executeAttitude,
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index a18c3437..6bdf60a6 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -143,6 +143,7 @@ enum GuestAPI {
"network_static_names",
"network_resolve",
"timezone",
+ "clock",
"audio_host_latency",
"motion_gyroscope",
"motion_gyroscope_toggle",
diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift
index 1190ca54..2fcb9ba6 100644
--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift
+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift
@@ -245,6 +245,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandle
case (.POST, "/v1/developer-mode/enable"): "developer_mode.enable"
case (.GET, "/v1/low-power-mode"), (.PUT, "/v1/low-power-mode"): "power.low_power_mode"
case (.GET, "/v1/timezone"), (.PUT, "/v1/timezone"): "time.timezone"
+ case (.GET, "/v1/clock"), (.PUT, "/v1/clock"): "time.clock"
case (.GET, "/v1/clipboard"), (.PUT, "/v1/clipboard"): verb == .GET ? "clipboard.get" : "clipboard.set"
case (.DELETE, "/v1/clipboard"): "clipboard.clear"
case (.GET, "/v1/files"): "files.list"
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index 1302ee1f..07a07561 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -35,6 +35,23 @@ bool vp_screen_undim(void);
/// accepted, otherwise an errno value. Needs root.
int vp_system_halt(void);
+/// Whether timed sets the clock itself (Settings' Set Automatically): 1 on,
+/// 0 off, -1 when CoreTime does not offer it, -2 when timed did not answer.
+int vp_clock_automatic(void);
+
+/// Turn timed's automatic time on or off, as Set Automatically does for the
+/// clock. timed sends no reply, so the caller reads it back. 0 once sent, -1
+/// when CoreTime does not offer it, -2 when timed did not take it within 3
+/// seconds. Needs com.apple.timed.
+int vp_clock_set_automatic(bool enabled);
+
+/// Offer timed `unixTime`, good to `uncertainty` seconds, as an NTP result.
+/// timed weighs it against what it has and sets the clock itself; nothing is
+/// returned, so the caller reads the clock. 0 once sent, -1 when CoreTime has
+/// no TMSetSourceTime, -2 when timed did not take it within 3 seconds. Needs
+/// com.apple.timed and NTP in com.apple.timed.sources.
+int vp_clock_offer(double unixTime, double uncertainty);
+
typedef struct {
int32_t pid;
int32_t ppid;
diff --git a/VPhoneDaemon/Native/vphoned_clock.m b/VPhoneDaemon/Native/vphoned_clock.m
new file mode 100644
index 00000000..d9626b9f
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_clock.m
@@ -0,0 +1,59 @@
+/*
+ * vphoned_clock — hand timed the Mac's time.
+ *
+ * timed owns the wall clock while Set Automatically is on. It keeps a filter
+ * from the kernel's monotonic clock to UTC, feeds it from its time sources
+ * and calls settimeofday itself; a clock set behind its back is put back the
+ * next time the filter is applied. A time is offered through CoreTime's
+ * TMSetSourceTime, which timed accepts from a client with com.apple.timed
+ * whose com.apple.timed.sources lists the source. Neither function is in the
+ * SDK.
+ *
+ * CoreTime's getter waits for timed with no timeout, so each call runs on a
+ * queue of its own: a timed that never answers costs a thread, not the caller.
+ *
+ * See Research/Guest/host_clock_sync.md.
+ */
+
+#import "Include/VphonedNative.h"
+
+#include <dlfcn.h>
+
+static BOOL runWithin(int64_t seconds, dispatch_block_t work) {
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ work();
+ dispatch_semaphore_signal(done);
+ });
+ return dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC)) == 0;
+}
+
+static void *coreTimeSymbol(const char *name) {
+ void *coreTime = dlopen("/System/Library/PrivateFrameworks/CoreTime.framework/CoreTime", RTLD_NOW);
+ return coreTime ? dlsym(coreTime, name) : NULL;
+}
+
+int vp_clock_automatic(void) {
+ bool (*isEnabled)(void) = coreTimeSymbol("TMIsAutomaticTimeEnabled");
+ if (!isEnabled) return -1;
+ __block bool enabled = false;
+ if (!runWithin(3, ^{ enabled = isEnabled(); })) return -2;
+ return enabled ? 1 : 0;
+}
+
+int vp_clock_set_automatic(bool enabled) {
+ // timed takes this command without a reply; the caller reads it back.
+ void (*setEnabled)(bool) = coreTimeSymbol("TMSetAutomaticTimeEnabled");
+ if (!setEnabled) return -1;
+ if (!runWithin(3, ^{ setEnabled(enabled); })) return -2;
+ return 0;
+}
+
+int vp_clock_offer(double unixTime, double uncertainty) {
+ // timed takes this command without a reply; the caller reads the clock.
+ void (*setSourceTime)(CFStringRef, CFAbsoluteTime, CFTimeInterval) = coreTimeSymbol("TMSetSourceTime");
+ if (!setSourceTime) return -1;
+ CFAbsoluteTime time = unixTime - kCFAbsoluteTimeIntervalSince1970;
+ if (!runWithin(3, ^{ setSourceTime(CFSTR("NTP"), time, uncertainty); })) return -2;
+ return 0;
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
index 94cf09fc..2b179379 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
@@ -49,6 +49,22 @@ extension VPhoneGuestControl {
return result["changed"] as? Bool ?? false
}
+ // MARK: - Clock
+
+ /// Offers the guest the Mac's time. `offset` is the Mac's time less the
+ /// guest's before the offer, `changed` whether the guest moved its clock,
+ /// and `automatic` whether timed sets its clock; a guest with that off
+ /// keeps the time set by hand in its Settings.
+ func setClock() async throws -> (offset: Double, changed: Bool, automatic: Bool) {
+ // Read as late as possible: the guest takes this as the time it is now.
+ let result = try await call("time.clock", params: ["time": Date().timeIntervalSince1970])
+ return (
+ (result["offset"] as? NSNumber)?.doubleValue ?? 0,
+ result["changed"] as? Bool ?? false,
+ result["automatic"] as? Bool ?? true,
+ )
+ }
+
// MARK: - Audio
/// Tells the guest's sound plugin what the Mac's output device adds after
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneClockSync.swift b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneClockSync.swift
new file mode 100644
index 00000000..a5596bf6
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneClockSync.swift
@@ -0,0 +1,96 @@
+import AppKit
+import Foundation
+
+/// Keeps the guest's clock on the Mac's. A guest boots with the Mac's time
+/// and timed then replaces it with the last time the guest ran; only NTP
+/// corrects that, and where the guest's NTP does not get through the guest
+/// stays behind by as long as it was powered off. A Mac that sleeps leaves a
+/// running guest behind as well. vphoned offers timed the time the host
+/// sends instead.
+///
+/// Call `start()` when the guest reports the "clock" capability, on every
+/// connect: it sends the Mac's time, then again every minute, when the Mac
+/// wakes and when the Mac's own clock is set. vphoned leaves a clock within a
+/// second of the Mac's alone, and one set by hand in the guest's Settings.
+///
+/// See Research/Guest/host_clock_sync.md.
+@MainActor
+class VPhoneClockSync {
+ /// Nothing tells the host that a guest's clock moved, so it asks. An
+ /// answer of "close enough" costs the guest one read of its clock.
+ private static let interval: Duration = .seconds(60)
+
+ private let control: VPhoneGuestControl
+ private var observers: [(NotificationCenter, NSObjectProtocol)] = []
+ private var ticking: Task<Void, Never>?
+ private var sending: Task<Void, Never>?
+ /// What the last send came to, so a minute's repeat of it is not logged.
+ private var lastOutcome: String?
+
+ init(control: VPhoneGuestControl) {
+ self.control = control
+ }
+
+ func start() {
+ if observers.isEmpty {
+ let sources: [(NotificationCenter, Notification.Name)] = [
+ (.default, .NSSystemClockDidChange),
+ (NSWorkspace.shared.notificationCenter, NSWorkspace.didWakeNotification),
+ ]
+ observers = sources.map { center, name in
+ let observer = center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
+ Task { @MainActor in self?.send() }
+ }
+ return (center, observer)
+ }
+ }
+ lastOutcome = nil
+ ticking?.cancel()
+ ticking = Task { [weak self] in
+ while !Task.isCancelled {
+ self?.send()
+ try? await Task.sleep(for: Self.interval)
+ }
+ }
+ }
+
+ func stop() {
+ for (center, observer) in observers {
+ center.removeObserver(observer)
+ }
+ observers = []
+ ticking?.cancel()
+ ticking = nil
+ sending?.cancel()
+ sending = nil
+ }
+
+ private func send() {
+ // A send still out carries a time as good as a new one would.
+ guard sending == nil else { return }
+ sending = Task { [weak self, control] in
+ let outcome: String
+ var moved = false
+ do {
+ let answer = try await control.setClock()
+ moved = answer.changed
+ outcome = if answer.changed {
+ String(format: "guest was %.1f s %@, set to the Mac's time", abs(answer.offset), answer.offset > 0 ? "behind" : "ahead")
+ } else if answer.automatic {
+ "guest is on the Mac's time"
+ } else {
+ "guest keeps the time set in its Settings (automatic time is off)"
+ }
+ } catch {
+ outcome = "could not set the guest's clock: \(error)"
+ }
+ guard !Task.isCancelled, let self else { return }
+ sending = nil
+ // A clock moved twice says so twice; anything else once.
+ if moved || outcome != lastOutcome {
+ print("[clock] \(outcome)")
+ }
+ lastOutcome = outcome
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index 07fb8db6..09101615 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -14,6 +14,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
private var appWindowController: VPhoneAppWindowController?
private var locationProvider: VPhoneLocationProvider?
private var timeZoneSync: VPhoneTimeZoneSync?
+ private var clockSync: VPhoneClockSync?
private var hostAudioLatencySync: VPhoneHostAudioLatencySync?
private var hostAutomationServer: VPhoneHostAutomationServer?
private var cameraServer: VPhoneCameraServer?
@@ -124,6 +125,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
let provider = VPhoneLocationProvider(control: control)
locationProvider = provider
timeZoneSync = VPhoneTimeZoneSync(control: control)
+ clockSync = VPhoneClockSync(control: control)
hostAudioLatencySync = VPhoneHostAudioLatencySync(control: control)
let camServer = VPhoneCameraServer()
@@ -256,7 +258,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
menuController = mc
// Wire location toggle through onConnect/onDisconnect
- control.onConnect = { [weak self, weak mc, weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] caps in
+ control.onConnect = { [weak self, weak mc, weak provider = locationProvider, weak timeZoneSync, weak clockSync, weak hostAudioLatencySync] caps in
mc?.updateConnectAvailability(available: true)
mc?.updateInstallAvailability(available: caps.contains("ipa_install"))
mc?.updateBootstrapAvailability(available: caps.contains("bootstrap_install"))
@@ -283,6 +285,9 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
if caps.contains("timezone") {
timeZoneSync?.start()
}
+ if caps.contains("clock") {
+ clockSync?.start()
+ }
if caps.contains("audio_host_latency") {
hostAudioLatencySync?.start()
}
@@ -290,7 +295,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
await self?.installPackageIfRequested(caps: caps)
}
}
- control.onDisconnect = { [weak mc, weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] in
+ control.onDisconnect = { [weak mc, weak provider = locationProvider, weak timeZoneSync, weak clockSync, weak hostAudioLatencySync] in
mc?.updateConnectAvailability(available: false)
mc?.updateInstallAvailability(available: false)
mc?.updateBootstrapAvailability(available: false)
@@ -307,11 +312,12 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
provider?.stopForwarding()
mc?.updateLocationCapability(available: false)
timeZoneSync?.stop()
+ clockSync?.stop()
hostAudioLatencySync?.stop()
}
} else if !command.dfu {
// Headless mode: no menu, so the machine's setting alone decides.
- control.onConnect = { [weak self, weak control, weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] caps in
+ control.onConnect = { [weak self, weak control, weak provider = locationProvider, weak timeZoneSync, weak clockSync, weak hostAudioLatencySync] caps in
if !caps.contains("location") {
print("[location] guest does not support location simulation")
} else if control?.syncsHostLocation == true {
@@ -320,6 +326,9 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
if caps.contains("timezone") {
timeZoneSync?.start()
}
+ if caps.contains("clock") {
+ clockSync?.start()
+ }
if caps.contains("audio_host_latency") {
hostAudioLatencySync?.start()
}
@@ -327,10 +336,11 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
await self?.installPackageIfRequested(caps: caps)
}
}
- control.onDisconnect = { [weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] in
+ control.onDisconnect = { [weak provider = locationProvider, weak timeZoneSync, weak clockSync, weak hostAudioLatencySync] in
provider?.stopReplay()
provider?.stopForwarding()
timeZoneSync?.stop()
+ clockSync?.stop()
hostAudioLatencySync?.stop()
}
}
@@ -467,6 +477,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
locationProvider?.stopForwarding()
locationProvider?.stopReplay()
timeZoneSync?.stop()
+ clockSync?.stop()
hostAudioLatencySync?.stop()
cameraServer?.disconnect()
menuController?.stopBatteryMonitoring()
@@ -484,6 +495,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
appWindowController = nil
locationProvider = nil
timeZoneSync = nil
+ clockSync = nil
hostAudioLatencySync = nil
cameraServer = nil
hostAutomationServer = nil