Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

fix(ota): preserve removed system apps across full updates

Jackya4a7fb0ea463
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 97f9a856..026887fb 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -306,6 +306,12 @@
> patch failure. This is host-driven payload installation; Apple's UpdateBrain
> protocol and application migration are not implied. See
> [the implementation and validation record](Restore/data_preserving_full_ota.md).
+
+> **OTA removed-app state (2026-10-25):** capture preserves the guest's removed
+> system-app IDs, and complete/commit/verify include LaunchServices placeholders
+> in their absence checks. Reconciliation retains the original removal backups
+> and independent app data. No instruction patch or preset changes; see the
+> [removed-app regression](Restore/data_preserving_full_ota.md#preserve-removed-system-apps-2026-10-25).
> **2026-10-21 correction:** full updates also stage, validate and install
> `payloadv2/links.txt`. The 24A446 iPad OTA omits 24,835 duplicate paths from
> its numbered chunks. Missing J410 media resources made audiomxd trap in
diff --git a/Research/Restore/data_preserving_full_ota.md b/Research/Restore/data_preserving_full_ota.md
index c076d7bf..743b0100 100644
--- a/Research/Restore/data_preserving_full_ota.md
+++ b/Research/Restore/data_preserving_full_ota.md
@@ -254,6 +254,66 @@ below before the app is assessed.
## Retained applications after a major userland change (2026-10-21)
+### Preserve removed system apps (2026-10-25)
+
+The production `wecom-01` and `wecom-02` guests retained all nine original
+`apps.remove_system` backups after the 24A446 OTA, but SpringBoard's IconState
+again contained eight of their identifiers. `apps.list` omitted them and
+`staged_system_apps` was empty. A native LaunchServices probe found
+`isPlaceholder=true`, `isInstalled=false` records at new UUID bundle paths,
+including News, which was not in the visible icon lists. The SMS placeholder
+Info.plist named `Executable` and `MinimumOSVersion=27.0`. The normal system
+uninstall API refused it. Installed-app absence was therefore a false
+acceptance signal, not proof that the removal policy survived migration.
+
+`apps.removed_system` now includes fresh LaunchServices `registered`,
+`installed`, `placeholder` and current `bundle_path` fields alongside each
+original backup. Capture stores the valid absent/placeholder IDs in
+`removed_system_apps`; an already reinstalled program is excluded even when
+an old backup remains. `ota.apps.apply` accepts that baseline as
+`removed_bundle_ids`, removes those registrations (including placeholders)
+and their validated UUID program containers without overwriting the old
+backups or touching independent user/group containers, then updates retained
+programs. It returns `removed_pending`; complete, commit and verify all check
+that the removal baseline is absent and its backups remain usable. There is
+no blanket icon-layout reset or SpringBoard restart.
+
+Legacy journals infer only absent apps and placeholders with valid removal
+backups. They never infer removal of a currently installed program from a
+historical backup alone. An older daemon that cannot report placeholder
+state fails verification instead of silently accepting the OTA. The source
+backup manifests, rather than a hardcoded default trim list, determine policy.
+
+This is an application-state reconciliation change, not a new binary patch
+or patch preset. Migration may seed placeholders before complete reconciles
+them; the no-placeholder gate is required before networking is committed.
+
+Production repair used the same native enumeration/unregistration bridge in a
+temporary signed helper, restricted to the nine IDs whose original manifests
+were present. Every target had to be a placeholder, not an installed program;
+the UUID container and its Info.plist identifier were checked before mutation.
+The new placeholder containers were renamed into
+`/private/var/db/vphoned/ota-placeholders-20261025/` after LS absence read-back,
+keeping recovery material instead of destroying it. Both machines returned
+nine absent registrations, zero failures, and no matching identifiers in
+SpringBoard's persisted icon lists. Neither SpringBoard nor WeCom was restarted:
+WeCom PIDs remained 69286/5397, and bundle/data/group paths and version/build
+matched the before samples. The original nine removal backups remain separate.
+Both machines passed a second invocation with zero changes and zero registered
+targets; all nine original backups remained restorable with their original
+removal dates. The temporary launchd jobs were then unloaded.
+
+Validation: complete Debug `VPhone` bundle build/admission passed; all ten
+`OTAUpdateTests` passed, including absent/placeholder/reinstalled distinctions,
+old-daemon rejection, corrupt-backup rejection and rollback/commit coverage.
+The maintenance script passed all 148 Swift policy checks and 13 APFS C parser
+checks with AddressSanitizer/UndefinedBehaviorSanitizer. The shared native
+header now explicitly marks legacy pointers `_Null_unspecified`, preserving
+their Swift import while satisfying nullability completeness under `-Werror`;
+no warning was disabled. No full OTA or cold reboot was performed
+on these business machines for this repair. The new bundle was built locally;
+the production repair did not publish or replace their bundle.
+
The protected app's executable had an ad hoc CodeDirectory identifier different
from its bundle ID, with no explicit container-required entitlement. The
existing data container's metadata matched that signing identifier. A same-byte
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 47d8da21..ab2ed577 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -380,7 +380,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) |
-| OTA Apple app programs | `ota.apps.status`, `ota.apps.apply {force:true}` (capability `ota_system_apps`; only matching installed removable Apple apps from the installed 24A446 System payload, no caller-selected paths or third-party app IDs; result `{build, apps, pending}`; preserves user-data/group containers and retains old programs/placeholders; see [the OTA runbook](Restore/data_preserving_full_ota.md#retained-apple-app-programs)) |
+| OTA Apple app programs | `ota.apps.status`, `ota.apps.apply {force:true, removed_bundle_ids?:[]}` (capability `ota_system_apps`; reconciles removed Apple app registrations including placeholders against valid removal backups, then updates retained programs from the installed 24A446 payload; no caller-selected paths or third-party IDs; result `{build, apps, pending, removed_bundle_ids, removed_pending}`; an omitted baseline infers only absent/placeholder apps, never installed apps; preserves user-data/group containers and original removal backups; see [the OTA runbook](Restore/data_preserving_full_ota.md#preserve-removed-system-apps-2026-10-25)) |
| 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) |
diff --git a/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift b/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift
index 842c8914..4027d668 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift
@@ -23,10 +23,10 @@ extension GuestAPI {
static func executeSystemApps(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
switch method {
case "ota.apps.status":
- return try updateOTASystemApps(apply: false)
+ return try updateOTASystemApps(apply: false, removedIDs: systemAppIDs(params, key: "removed_bundle_ids"))
case "ota.apps.apply":
try requireForce(params, "update retained Apple app programs from the installed OTA")
- return try updateOTASystemApps(apply: true)
+ return try updateOTASystemApps(apply: true, removedIDs: systemAppIDs(params, key: "removed_bundle_ids"))
case "apps.remove_system":
guard let ids = try systemAppIDs(params) else {
throw GuestAPIError.invalidRequest("bundle_ids must list the apps to remove")
@@ -42,7 +42,7 @@ extension GuestAPI {
try requireForce(params, "restore removed system apps")
return try restoreSystemApps(ids, respring: bool(params, "respring", default: true))
case "apps.removed_system":
- return removedSystemApps()
+ return try removedSystemApps()
default:
return nil
}
@@ -53,7 +53,7 @@ extension GuestAPI {
/// Deliberately separate from apps.install/register: this owns no ordinary
/// app container. It accepts no caller-selected path or identifier and only
/// replaces matching Apple apps already registered in UUID containers.
- private static func updateOTASystemApps(apply: Bool) throws -> [String: Any] {
+ private static func updateOTASystemApps(apply: Bool, removedIDs: [String]?) throws -> [String: Any] {
otaAppsLock.lock()
defer { otaAppsLock.unlock() }
let fm = FileManager.default
@@ -64,6 +64,23 @@ extension GuestAPI {
metadata["Build"] == systemBuildVersion, metadata["Build"] == build else {
throw GuestAPIError.operationFailed("No matching installed OTA system-app payload.")
}
+ // An old journal has no removal baseline. Infer only absent apps and
+ // placeholders with a valid backup, never a deliberately reinstalled app.
+ let backups = try removedSystemApps()["backups"] as? [[String: Any]] ?? []
+ let inferred = backups.filter { $0["installed"] as? Bool == false }.compactMap { $0["bundle_id"] as? String }
+ let removed = removedIDs ?? inferred
+ for id in removed {
+ try GuestSystemAppPolicy.validateBundleID(id)
+ guard backups.contains(where: { $0["bundle_id"] as? String == id && $0["restorable"] as? Bool == true && $0["error"] == nil }) else {
+ throw GuestAPIError.operationFailed("No valid removal backup for \(id); refusing OTA reconciliation.")
+ }
+ }
+ if apply, !removed.isEmpty {
+ // Do not overwrite the original complete program backup with a
+ // newly seeded placeholder. No respring: LS notifies SpringBoard.
+ _ = try removeSystemApps(removed, backup: false, respring: false)
+ }
+ let removedPending = try removed.filter { try systemAppState($0)["registered"] as? Bool == true }
let apps = try listApps()["apps"] as? [[String: Any]] ?? []
let installed = Dictionary(apps.compactMap { app in (app["bundle_id"] as? String).map { ($0, app) } },
uniquingKeysWith: { first, _ in first })
@@ -81,6 +98,7 @@ extension GuestAPI {
throw GuestAPIError.operationFailed("Invalid staged Apple app: \(name)")
}
try GuestSystemAppPolicy.validateBundleID(id)
+ if removed.contains(id) { continue }
guard let bundlePath = installed[id]?["bundle_path"] as? String,
let location = try? GuestSystemAppLocation(bundlePath: bundlePath) else { continue }
guard location.appDirectoryName == name, try bundleContainerExists(location) else {
@@ -168,14 +186,15 @@ extension GuestAPI {
}
rows.append(row)
}
- return ["build": build, "apps": rows, "pending": rows.filter { $0["current"] as? Bool != true }.count]
+ return ["build": build, "apps": rows, "pending": rows.filter { $0["current"] as? Bool != true }.count,
+ "removed_bundle_ids": removed, "removed_pending": removedPending]
}
/// `bundle_ids` in request order without repeats, or nil when absent.
- private static func systemAppIDs(_ params: [String: Any]) throws -> [String]? {
- guard let value = params["bundle_ids"] else { return nil }
- guard let ids = value as? [String], !ids.isEmpty, ids.allSatisfy({ !$0.isEmpty }) else {
- throw GuestAPIError.invalidRequest("bundle_ids must be a non-empty list of bundle identifiers")
+ private static func systemAppIDs(_ params: [String: Any], key: String = "bundle_ids") throws -> [String]? {
+ guard let value = params[key] else { return nil }
+ guard let ids = value as? [String], (key == "removed_bundle_ids" || !ids.isEmpty), ids.allSatisfy({ !$0.isEmpty }) else {
+ throw GuestAPIError.invalidRequest("\(key) must list bundle identifiers")
}
var seen = Set<String>()
return ids.filter { seen.insert($0).inserted }
@@ -208,7 +227,8 @@ extension GuestAPI {
var result: [String: Any] = ["bundle_id": id, "removed": false]
do {
try GuestSystemAppPolicy.validateBundleID(id)
- guard let record = try installedApp(id) else {
+ let record = try systemAppState(id)
+ guard record["registered"] as? Bool == true else {
return try finishInterruptedRemoval(id, result: result)
}
let bundlePath = record["bundle_path"] as? String ?? ""
@@ -220,7 +240,7 @@ extension GuestAPI {
guard try bundleContainerExists(location) else {
// LaunchServices lists a bundle whose container is gone:
// dropping the record is all that is left to do.
- let unregistered = try unregisterSystemApp(bundlePath)
+ let unregistered = try unregisterSystemApp(bundlePath, id: id)
result["unregistered"] = unregistered["unregistered"] as? Bool ?? false
result["status"] = "unregistered_stale"
result["removed"] = true
@@ -236,7 +256,7 @@ extension GuestAPI {
result["backup_method"] = made.method
}
do {
- let unregistered = try unregisterSystemApp(bundlePath)
+ let unregistered = try unregisterSystemApp(bundlePath, id: id)
result["unregistered"] = unregistered["unregistered"] as? Bool ?? false
if let attempts = unregistered["attempts"] as? Int, attempts > 1 {
result["unregister_attempts"] = attempts
@@ -531,7 +551,7 @@ extension GuestAPI {
/// The backups in the backup directory, then those an older vphoned left
/// in the legacy directory, each marked `legacy`.
- private static func removedSystemApps() -> [String: Any] {
+ private static func removedSystemApps() throws -> [String: Any] {
var backups: [[String: Any]] = []
for directory in GuestSystemAppPolicy.backupDirectories {
let ids = Set(directoryEntries(directory).compactMap(GuestSystemAppPolicy.bundleID(forBackupEntry:))).sorted()
@@ -542,6 +562,10 @@ extension GuestAPI {
"backup": pathExists(backupPath) ? backupPath : NSNull(),
"legacy": GuestSystemAppPolicy.isLegacy(directory),
]
+ let current = try systemAppState(id)
+ for key in ["registered", "installed", "placeholder", "bundle_path"] {
+ entry[key] = current[key]
+ }
do {
let manifest = try readManifest(id, in: directory)
let location = try manifest.location()
@@ -584,22 +608,26 @@ extension GuestAPI {
/// Unregisters the app at `path` and waits for LaunchServices to drop its
/// record, unregistering once more if it does not
- /// (`GuestAppUnregistration`). IcliKit's `unregisterApp` looks at the
- /// record straight away, and its "still lists the app" is not the last
- /// word. Throws when the app is still listed after the last attempt.
- private static func unregisterSystemApp(_ path: String) throws -> [String: Any] {
+ /// (`GuestAppUnregistration`). Include placeholders: ordinary installed-app
+ /// enumeration cannot prove these records have gone. Throws when the app
+ /// is still listed after the last attempt.
+ private static func unregisterSystemApp(_ path: String, id: String) throws -> [String: Any] {
var attempt = 1
while true {
var result: [String: Any] = [:]
var failure: Error?
do {
- result = try unregisterApp(path, force: true)
+ if let error = vp_ls_unregister_system_app(id, path) {
+ defer { free(error) }
+ throw GuestAPIError.operationFailed(String(cString: error))
+ }
+ result = ["unregistered": true, "path": path]
} catch {
failure = error
}
let start = Date()
polling: while true {
- let registered = try appRegistration(path)["registered"] as? Bool == true
+ let registered = try systemAppState(id)["registered"] as? Bool == true
switch GuestAppUnregistration.next(registered: registered, attempt: attempt, waited: Date().timeIntervalSince(start)) {
case .done:
if failure != nil || attempt > 1 {
@@ -625,6 +653,17 @@ extension GuestAPI {
}
}
+ private static func systemAppState(_ id: String) throws -> [String: Any] {
+ guard let raw = vp_ls_system_app_state(id) else {
+ throw GuestAPIError.operationFailed("Could not enumerate LaunchServices state for \(id)")
+ }
+ defer { free(raw) }
+ guard let state = try JSONSerialization.jsonObject(with: Data(String(cString: raw).utf8)) as? [String: Any] else {
+ throw GuestAPIError.operationFailed("Invalid LaunchServices state for \(id)")
+ }
+ return state
+ }
+
/// The live LaunchServices record for `id`, never a cached one.
private static func installedApp(_ id: String) throws -> [String: Any]? {
let apps = try listApps()["apps"] as? [[String: Any]] ?? []
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index c3bdd62f..c1c9a632 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -6,8 +6,12 @@
#import <Foundation/Foundation.h>
#endif
+// Keep legacy bridge pointers explicitly unspecified: their Swift import stays
+// unchanged while sharing this header with APIs that declare nonnull pointers.
+// Do not assume nonnull for error strings or optional output parameters.
+
/// Sign all executable code in an extracted app. Returns a malloc-owned error or NULL.
-char *vp_sign_app_for_install(const char *appPath, const char *certificatePath);
+char * _Null_unspecified vp_sign_app_for_install(const char * _Null_unspecified appPath, const char * _Null_unspecified certificatePath);
void vp_native_bootstrap_cached_binary(void);
void vp_native_confirm_cached_binary(void);
/// 0 = launchd proxy, 1 = --io worker, -1 = invalid arguments.
@@ -20,11 +24,11 @@ void vp_vcam_start(void);
void vp_homepod_display_start(void);
bool vp_homepod_display_is_configured(void);
/// Latest guest-written MiniDisplay frame and geometry, malloc-owned JSON.
-char *vp_homepod_display_copy_json(void);
+char * _Null_unspecified vp_homepod_display_copy_json(void);
/// SoundBoardServices debug controls, available only on HomePod firmware.
bool vp_homepod_debug_available(void);
/// Validated operation result or error, returned as malloc-owned JSON.
-char *vp_homepod_debug_copy_json(const char *operation, const char *arguments_json);
+char * _Null_unspecified vp_homepod_debug_copy_json(const char * _Null_unspecified operation, const char * _Null_unspecified arguments_json);
/// Load the IOKit digitizer symbols used for multi-finger injection. Idempotent,
/// safe to call more than once; returns false (injection then stays a no-op)
@@ -82,71 +86,73 @@ typedef struct {
} VPProcessUsage;
/// Identity and resource usage for one process. Returns false when the process is gone.
-bool vp_process_usage(int pid, VPProcessUsage *usage);
+bool vp_process_usage(int pid, VPProcessUsage * _Null_unspecified usage);
/// Make `serial` the USB serial string the host sees, re-enumerating only when
/// it changes or `force` is set (`*changed`). Returns a malloc-owned error or NULL.
-char *vp_usb_set_serial(const char *serial, bool force, bool *changed);
+char * _Null_unspecified vp_usb_set_serial(const char * _Null_unspecified serial, bool force, bool * _Null_unspecified changed);
/// The guest's own USB serial, built from `/chosen` `chip-id` and
/// `unique-chip-id`. malloc-owned, or NULL when the device tree lacks either.
-char *vp_usb_own_serial(void);
+char * _Null_unspecified vp_usb_own_serial(void);
/// The names of the APFS snapshots of the volume mounted at `mount`, in
/// `*names` (free with `vp_apfs_snapshot_names_free`). Returns 0 or an errno value.
-int vp_apfs_snapshot_list(const char *mount, char ***names, int *count);
-void vp_apfs_snapshot_names_free(char **names, int count);
+int vp_apfs_snapshot_list(const char * _Null_unspecified mount, char * _Null_unspecified * _Null_unspecified * _Null_unspecified names, int * _Null_unspecified count);
+void vp_apfs_snapshot_names_free(char * _Null_unspecified * _Null_unspecified names, int count);
/// Append the names in one `fs_snapshot_list` batch of `entries` entries
/// (`ATTR_CMN_RETURNED_ATTRS | ATTR_CMN_NAME`) to `*names`, skipping names
/// already there and malformed entries; `*added` counts the new ones.
/// Returns 0 or ENOMEM.
-int vp_apfs_snapshot_parse(const char *buffer, size_t size, int entries, char ***names, int *count, int *added);
+int vp_apfs_snapshot_parse(const char * _Null_unspecified buffer, size_t size, int entries, char * _Null_unspecified * _Null_unspecified * _Null_unspecified names, int * _Null_unspecified count, int * _Null_unspecified added);
/// Delete the snapshot `name` of the volume mounted at `mount`. Returns 0 or
/// an errno value. Needs root and com.apple.private.vfs.snapshot.
-int vp_apfs_snapshot_delete(const char *mount, const char *name);
+int vp_apfs_snapshot_delete(const char * _Null_unspecified mount, const char * _Null_unspecified name);
/// Register the Apple app bundle at `app_path`, inside the bundle container
/// `container_path`, with LaunchServices as a deletable system app. Returns a
/// malloc-owned error or NULL, with the registration call that worked in
/// `*method` (malloc-owned).
-char *vp_ls_register_system_app(const char *app_path, const char *container_path, char **method);
+char * _Null_unspecified vp_ls_register_system_app(const char * _Null_unspecified app_path, const char * _Null_unspecified container_path, char * _Null_unspecified * _Null_unspecified method);
+char * _Null_unspecified vp_ls_system_app_state(const char * _Null_unspecified bundle_id);
+char * _Null_unspecified vp_ls_unregister_system_app(const char * _Null_unspecified bundle_id, const char * _Null_unspecified app_path);
#ifdef __OBJC__
/// The configured radians/second and the injected HID provider's heartbeat.
-NSDictionary *vp_gyro_get(void);
+NSDictionary * _Null_unspecified vp_gyro_get(void);
BOOL vp_gyro_set(double x, double y, double z, bool enabled);
/// The backboardd HID gravity provider used by display.rotation.
NSDictionary * _Nonnull vp_accelerometer_get(void);
BOOL vp_accelerometer_set_orientation(NSString * _Nonnull spec);
-NSDictionary *vp_attitude_get(void);
+NSDictionary * _Null_unspecified vp_attitude_get(void);
BOOL vp_attitude_set(double roll, double pitch, double yaw, bool enabled);
/// Snapshot-local nested accessibility tree, using actual private iOS child links.
-NSDictionary *vp_ax_hierarchy(int pid, int maxElements, int maxDepth, int timeoutMS);
+NSDictionary * _Null_unspecified vp_ax_hierarchy(int pid, int maxElements, int maxDepth, int timeoutMS);
/// `interface`'s IPv4 settings in configd's network preferences: `method`
/// (dhcp or manual), `address`, `subnet_mask`, `router`, `dns`, and `managed`
/// when vphoned wrote them. Nil with `*error` set when there is no such service.
-NSDictionary *vp_network_ipv4_get(NSString *interface, NSString **error);
+NSDictionary * _Null_unspecified vp_network_ipv4_get(NSString * _Null_unspecified interface, NSString * _Null_unspecified * _Null_unspecified error);
/// Set `interface` to `params` (`method` dhcp, or manual with `address`,
/// `subnet_mask`, `router` and `dns`), commit and apply. DHCP only undoes a
/// manual setting vphoned made. Returns the result of `vp_network_ipv4_get`
/// plus `changed`.
-NSDictionary *vp_network_ipv4_set(NSString *interface, NSDictionary *params, NSString **error);
+NSDictionary * _Null_unspecified vp_network_ipv4_set(NSString * _Null_unspecified interface, NSDictionary * _Null_unspecified params, NSString * _Null_unspecified * _Null_unspecified error);
/// The guest's mDNS name (`local_host_name`, null when unset) and whether
/// vphoned set it (`managed`).
-NSDictionary *vp_network_hostname_get(NSString **error);
+NSDictionary * _Null_unspecified vp_network_hostname_get(NSString * _Null_unspecified * _Null_unspecified error);
/// Set the mDNS name, or with nil put back the one vphoned replaced. Only a
/// name vphoned set is ever undone. Returns the get result plus `changed`.
-NSDictionary *vp_network_hostname_set(NSString *name, NSString **error);
+NSDictionary * _Null_unspecified vp_network_hostname_set(NSString * _Null_unspecified name, NSString * _Null_unspecified * _Null_unspecified error);
/// Apply the preferences as they are, changing nothing: every process
/// watching them, configd's preferences monitor first, reads them again and
/// publishes what it derives from them.
-BOOL vp_preferences_apply(NSString **error);
+BOOL vp_preferences_apply(NSString * _Null_unspecified * _Null_unspecified error);
#endif
diff --git a/VPhoneDaemon/Native/vphoned_apps.m b/VPhoneDaemon/Native/vphoned_apps.m
index 23c49d30..deb5035b 100644
--- a/VPhoneDaemon/Native/vphoned_apps.m
+++ b/VPhoneDaemon/Native/vphoned_apps.m
@@ -35,8 +35,58 @@
saveObserver:(id)observer
registrationError:(NSError **)error;
- (NSURL *)bundleURL;
+- (NSArray *)allApplications;
+- (NSString *)applicationIdentifier;
+- (BOOL)isPlaceholder;
+- (BOOL)isInstalled;
+- (BOOL)unregisterApplication:(NSURL *)url;
@end
+// allInstalledApplications deliberately excludes OTA placeholders. Enumerate
+// allApplications for removal and read-back; a cached proxy for an identifier
+// can otherwise outlive its registration.
+static id vp_apps_find(NSString *identifier) {
+ id workspace = [NSClassFromString(@"LSApplicationWorkspace") defaultWorkspace];
+ if (![workspace respondsToSelector:@selector(allApplications)]) {
+ [NSException raise:@"VPhoneLaunchServices" format:@"allApplications is unavailable"];
+ }
+ NSArray *applications = [workspace allApplications];
+ if (!applications) [NSException raise:@"VPhoneLaunchServices" format:@"Application enumeration failed"];
+ for (id proxy in applications) {
+ if ([[proxy applicationIdentifier] isEqualToString:identifier]) return proxy;
+ }
+ return nil;
+}
+
+char *vp_ls_system_app_state(const char *bundle_id) {
+ @autoreleasepool { @try {
+ id proxy = vp_apps_find(@(bundle_id));
+ NSDictionary *state = proxy
+ ? @{@"bundle_id": @(bundle_id), @"registered": @YES,
+ @"bundle_path": [[proxy bundleURL] path] ?: @"",
+ @"placeholder": @([proxy isPlaceholder]), @"installed": @([proxy isInstalled])}
+ : @{@"bundle_id": @(bundle_id), @"registered": @NO, @"placeholder": @NO, @"installed": @NO};
+ NSData *data = [NSJSONSerialization dataWithJSONObject:state options:0 error:nil];
+ return data ? strndup(data.bytes, data.length) : NULL;
+ } @catch (NSException *exception) { return NULL; } }
+}
+
+// Return an error string or NULL. The caller validates a UUID bundle-container
+// path and polls vp_ls_system_app_state before touching its filesystem.
+char *vp_ls_unregister_system_app(const char *bundle_id, const char *app_path) {
+ @autoreleasepool { @try {
+ id proxy = vp_apps_find(@(bundle_id));
+ if (!proxy) return NULL;
+ NSURL *url = [proxy bundleURL];
+ if (![[url.path stringByStandardizingPath] isEqualToString:[@(app_path) stringByStandardizingPath]])
+ return strdup("LaunchServices app path changed before unregistration");
+ id workspace = [NSClassFromString(@"LSApplicationWorkspace") defaultWorkspace];
+ if (![workspace respondsToSelector:@selector(unregisterApplication:)] || ![workspace unregisterApplication:url])
+ return strdup("LaunchServices refused system app unregistration");
+ return NULL;
+ } @catch (NSException *exception) { return strdup(exception.reason.UTF8String); } }
+}
+
// MARK: - Read Back
static NSString *vp_apps_comparable(NSString *path) {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swift
index 8bdc5d79..3e1953cf 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swift
@@ -60,7 +60,9 @@ struct VPhoneFirmwareOTACommand: ParsableCommand {
case .quiesce: try quiesce(bundle)
case .prepare: try prepare(bundle)
case .complete: try complete(bundle)
- case .commit: try VPhoneOTAUpdate.commit(of: bundle)
+ case .commit:
+ try verifyRemovedSystemApps(bundle, source: sourceState(VPhoneOTAUpdate.read(of: bundle)))
+ try VPhoneOTAUpdate.commit(of: bundle)
case .verify: try verifyCommitted(bundle)
case .rollback:
if try VPhoneOTAUpdate.read(of: bundle).phase == .completed, !force {
@@ -161,8 +163,9 @@ struct VPhoneFirmwareOTACommand: ParsableCommand {
protected.append(app)
}
let restore = try JSONSerialization.jsonObject(with: Data(contentsOf: bundle.url.appendingPathComponent("restore-info.json")))
+ let removed = try VPhoneOTAUpdate.removedSystemAppIDs(call(bundle, "apps.removed_system"))
let state: [String: Any] = ["device": info, "profile": profile, "auto_lock": autoLock,
- "apps": protected, "restore": restore]
+ "apps": protected, "restore": restore, "removed_system_apps": removed]
var record = VPhoneOTAUpdate.Record(bundle: bundle, build: build, version: version,
source: try JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]))
record.operationID = operationID
@@ -256,11 +259,15 @@ struct VPhoneFirmwareOTACommand: ParsableCommand {
record.phase = .installed
try VPhoneOTAUpdate.write(record, of: bundle)
}
- let systemApps = try call(bundle, "ota.apps.apply", ["force": true], timeout: 180)
- guard systemApps["pending"] as? Int == 0 else {
+ let source = try sourceState(record)
+ var appParams: [String: Any] = ["force": true]
+ if let removed = source["removed_system_apps"] as? [String] { appParams["removed_bundle_ids"] = removed }
+ let systemApps = try call(bundle, "ota.apps.apply", appParams, timeout: 180)
+ guard systemApps["pending"] as? Int == 0,
+ (systemApps["removed_pending"] as? [String])?.isEmpty == true else {
throw ValidationError("Retained Apple app programs have not finished updating.")
}
- let source = try sourceState(record)
+ try verifyRemovedSystemApps(bundle, source: source)
for app in source["apps"] as? [[String: Any]] ?? [] {
guard let id = app["bundle_id"] as? String else { throw ValidationError("Invalid protected app record.") }
try requireUnchanged(bundle, app: app, id: id, fields: ["bundle_path", "data_path", "group_containers", "version", "build"]) {
@@ -369,6 +376,7 @@ struct VPhoneFirmwareOTACommand: ParsableCommand {
}
_ = try requireTargetMigration(bundle, record)
let state = try sourceState(record)
+ try verifyRemovedSystemApps(bundle, source: state)
for app in state["apps"] as? [[String: Any]] ?? [] {
guard let id = app["bundle_id"] as? String else { continue }
try requireUnchanged(bundle, app: app, id: id, fields: ["bundle_path", "data_path", "group_containers"]) {
@@ -380,6 +388,16 @@ struct VPhoneFirmwareOTACommand: ParsableCommand {
}
}
+ private func verifyRemovedSystemApps(_ bundle: VPhoneBundle, source: [String: Any]) throws {
+ let inventory = try call(bundle, "apps.removed_system")
+ // Legacy journals lack this baseline. Still reject any remaining
+ // placeholders backed by a removal record; never remove an installed
+ // app just because a historical backup exists.
+ let ids = try source["removed_system_apps"] as? [String]
+ ?? VPhoneOTAUpdate.removedSystemAppIDs(inventory)
+ try VPhoneOTAUpdate.requireRemovedSystemApps(ids, inventory: inventory)
+ }
+
/// Services DataMigrator needs that a trimmed source may have disabled.
static let migrationDependencies = [
"com.apple.siriactionsd", "com.apple.assistantd", "com.apple.SpringBoard",
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swift
index 9a76f57d..e94c7b4a 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swift
@@ -36,8 +36,16 @@ struct VPhoneFirmwareOTAPreflightCommand: ParsableCommand {
let managedDisabled = (profile["disabled"] as? [String] ?? []).sorted()
let externallyDisabled = VPhoneFirmwareOTACommand.externallyDisabledDependencies(profile: profile, disabled: disabled)
let migrationDone = setup["data_migration_done"] as? Bool
+ var removed: [String] = []
+ var removalError: String?
+ do {
+ removed = try VPhoneOTAUpdate.removedSystemAppIDs(call("apps.removed_system"))
+ } catch {
+ removalError = error.localizedDescription
+ }
// The same gate fw ota capture applies, so a ready report is accepted there.
let ready = managedDisabled.isEmpty && externallyDisabled.isEmpty
+ && removalError == nil
&& VPhoneFirmwareOTACommand.sourceFinishedMigration(setup: setup, migration: migration)
let report: [String: Any] = [
"machine": bundle.name,
@@ -45,6 +53,8 @@ struct VPhoneFirmwareOTAPreflightCommand: ParsableCommand {
"service_profile_record": record,
"profile_owned_disabled": managedDisabled,
"externally_disabled_dependencies": externallyDisabled,
+ "removed_system_apps": removed,
+ "removed_system_apps_error": removalError.map { $0 as Any } ?? NSNull(),
"data_migration_done": migrationDone.map { $0 as Any } ?? NSNull(),
"last_migration_result": lastResult.map { $0 as Any } ?? NSNull(),
"notes": [
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swift
index 7bfe18e9..eb43b499 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swift
@@ -5,6 +5,42 @@ import Foundation
/// changing ordinary snapshot semantics. The journal lives outside the machine
/// folder so guest-side phases can record progress while the VM is running.
public enum VPhoneOTAUpdate {
+ /// Backups are not themselves a removal policy: a user may have installed
+ /// the app again. Only absent apps/placeholders belong in a new baseline.
+ public static func removedSystemAppIDs(_ response: [String: Any]) throws -> [String] {
+ guard let rows = response["backups"] as? [[String: Any]] else {
+ throw Failure("Missing removed-system-app inventory.")
+ }
+ var ids = Set<String>()
+ for row in rows {
+ guard let id = row["bundle_id"] as? String, id.hasPrefix("com.apple."),
+ let installed = row["installed"] as? Bool,
+ row["registered"] is Bool, row["placeholder"] is Bool else {
+ throw Failure("The guest cannot report system-app placeholders; update vphoned before OTA.")
+ }
+ if installed { continue }
+ guard row["restorable"] as? Bool == true, row["error"] == nil else {
+ throw Failure("Invalid removal backup for \(id).")
+ }
+ ids.insert(id)
+ }
+ return ids.sorted()
+ }
+
+ public static func requireRemovedSystemApps(_ ids: [String], inventory: [String: Any]) throws {
+ guard let rows = inventory["backups"] as? [[String: Any]] else {
+ throw Failure("Missing removed-system-app verification.")
+ }
+ for id in ids {
+ guard let row = rows.first(where: { $0["bundle_id"] as? String == id }),
+ row["registered"] as? Bool == false, row["installed"] as? Bool == false,
+ row["placeholder"] as? Bool == false, row["restorable"] as? Bool == true,
+ row["error"] == nil else {
+ throw Failure("Removed system app \(id) returned after OTA or lost its backup.")
+ }
+ }
+ }
+
public enum Phase: String, Codable, Sendable {
case captured, checkpointing, checkpointed, quiesced, preparing, prepared
case installed, completed, committed, rollingBack, rolledBack
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swift
index 35bf68fa..2614b4c8 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swift
@@ -4,6 +4,36 @@ import Testing
@testable import VPhoneCoreKit
struct OTAUpdateTests {
+ @Test func `OTA removal baseline distinguishes placeholders from deliberately reinstalled apps`() throws {
+ func row(_ id: String, installed: Bool, placeholder: Bool) -> [String: Any] {
+ ["bundle_id": id, "installed": installed, "placeholder": placeholder,
+ "registered": installed || placeholder, "restorable": true]
+ }
+ let absent = row("com.apple.news", installed: false, placeholder: false)
+ let placeholder = row("com.apple.MobileSMS", installed: false, placeholder: true)
+ let reinstalled = row("com.apple.tv", installed: true, placeholder: false)
+ let inventory: [String: Any] = ["backups": [absent, placeholder, reinstalled]]
+ #expect(try VPhoneOTAUpdate.removedSystemAppIDs(inventory) == ["com.apple.MobileSMS", "com.apple.news"])
+ #expect(throws: VPhoneOTAUpdate.Failure.self) {
+ try VPhoneOTAUpdate.requireRemovedSystemApps(["com.apple.MobileSMS"], inventory: inventory)
+ }
+ try VPhoneOTAUpdate.requireRemovedSystemApps(["com.apple.news"], inventory: inventory)
+ #expect(throws: VPhoneOTAUpdate.Failure.self) {
+ try VPhoneOTAUpdate.requireRemovedSystemApps(["com.apple.Home"], inventory: inventory)
+ }
+ #expect(throws: VPhoneOTAUpdate.Failure.self) {
+ _ = try VPhoneOTAUpdate.removedSystemAppIDs(["backups": [["bundle_id": "com.apple.news", "restorable": true]]])
+ }
+ var corrupt = absent
+ corrupt["error"] = "Invalid manifest"
+ #expect(throws: VPhoneOTAUpdate.Failure.self) {
+ _ = try VPhoneOTAUpdate.removedSystemAppIDs(["backups": [corrupt]])
+ }
+ #expect(throws: VPhoneOTAUpdate.Failure.self) {
+ try VPhoneOTAUpdate.requireRemovedSystemApps(["com.apple.news"], inventory: ["backups": [corrupt]])
+ }
+ }
+
private func fixture() throws -> (URL, VPhoneBundle) {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)