Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add vphoned system app removal and orig-fs snapshot deletion
Jacky5ebfa466164f
diff --git a/Research/Guest/post_setup_signin_and_appstore.md b/Research/Guest/post_setup_signin_and_appstore.mdindex cd415abf..895a0811 100644--- a/Research/Guest/post_setup_signin_and_appstore.md+++ b/Research/Guest/post_setup_signin_and_appstore.md@@ -200,11 +200,19 @@ after the App Store bundle is gone; disable them too (`services.disable`, as in`ota_software_update_block.md`) for no store traffic. Keep `storekitd` — appsthe researcher installs may link StoreKit.-### Still worth a single verb--A vphoned `apps.remove_system` (backup → `apps.unregister` → remove container →-respring) would fold the durable sequence into one call instead of four RPCs-with the re-stage foot-gun between them. Not built yet.+### One verb: `apps.remove_system`++vphoned now folds the durable sequence into one call:+`apps.remove_system {"bundle_ids":[…],"force":true}` reads each app's current+container from the live app list, backs the whole container up to+`/private/var/mobile/Library/removed-system-apps/<bundle_id>.container` with a+manifest beside it, unregisters the app, removes the container and resprings+once. It refuses apps outside `/private/var/containers/Bundle/Application/<UUID>/`+(Phone and the rest of `/Applications`). `apps.restore_system` moves a backup+back to its original UUID path and registers it, and `apps.removed_system`+lists the backups. icli's `apps.register` refuses Apple's apps since 0.7.17, so+the hand recipe's revert step above no longer works through it. See+`Research/vphoned_http_api.md`, "Removable system apps and APFS snapshots".## Open itemsdiff --git a/Research/Guest/template_snapshot_deletion.md b/Research/Guest/template_snapshot_deletion.mdnew file mode 100644index 00000000..07ded21e--- /dev/null+++ b/Research/Guest/template_snapshot_deletion.md@@ -0,0 +1,119 @@+# Deleting the orig-fs snapshot in the guest++Why the CFW-renamed system snapshot has to go before trimming files from the+system volume saves anything, what the iOS kernel requires to delete it, and+what was measured. The RPC is `apfs.snapshot.delete` (`Research/vphoned_http_api.md`,+"Removable system apps and APFS snapshots"). Measured 2026-10-07 on a+`--new-identity` clone of an iPhone17,3 iOS 27.0 (24A435) machine with a+vphone 2.7.0 local bundle, using a standalone prototype of the same calls.++## Why the snapshot pins the space++The restored system volume carries one snapshot, the sealed update snapshot+`com.apple.os.update-<hash>`. CFW install renames it to+`orig-fs.disabled.rn-<hash>` (`VPhoneAPFSSnapshot.rename`) and the patched+kernel (`kernel-boot-apfs_root_snapshot`) boots the live file system instead.+From then on the snapshot is an ordinary dangling snapshot, but it still+references every block of the system volume as it was before CFW.++Deleting files from the live system volume therefore frees nothing: the+snapshot keeps their blocks. In the experiment, 1.09 GiB of standard-tier+files were deleted from a host-mounted system volume (`usr/standalone/update`+353 MB, `SharingDeviceAssets` 232 MB, `NanoTimeKit` face bundles 144 MB, 57+non-English/Chinese `LinguisticData` packages 409 MB). The container's usage+went from 20,483,211,264 B to 20,483,629,056 B and the host `Disk.img` grew by+2,152 blocks. Nothing was reclaimed until the snapshot was deleted.++The snapshot's own extra cost is small. The system volume shrank about+21.5 MB more than the files deleted: the originals of the system files CFW+modified, which only the snapshot still referenced. Deleting the snapshot+without trimming files saves about 20 MB per template; the gain comes from the+trim the deletion makes effective.++## The host cannot do it++On the host, `diskutil apfs deleteSnapshot` on the attached guest container+fails with `-69863 Insufficient privileges`, as the user and as root, whether+the volume was mounted by the user or by root. The host's SIP (Filesystem+Protections) protects snapshots of a System-role volume. CFW install runs as+root under the same SIP, so this cannot move into the host-side install+either. Changing the volume role or editing APFS metadata offline was judged+too risky. The deletion happens in the guest.++## What the iOS kernel requires++From the strings of `kernelcache.research.vphone600` and the experiment:++| Requirement | Evidence | Result |+| --- | --- | --- |+| A vfs snapshot entitlement | `"%s (pid %d) is missing vfs snapshot entitlements"`; candidates `com.apple.developer.vfs.snapshot`, `com.apple.private.vfs.snapshot`, `com.apple.private.vfs.snapshot.user` | The prototype was signed with all three and succeeded. vphoned carries only `com.apple.developer.vfs.snapshot` (see "Not yet verified") |+| Root | XNU `fs_snapshot` checks `PRIV_VFS_SNAPSHOT` | vphoned runs as root |+| Not the volume's default root snapshot, not set to root or revert to, not mounted | `cannot delete snapshot '%s' because it is the default root snapshot…`, `…set to root from it`, `…set to revert to it…`, `cannot delete mounted snapshot` | `orig-fs.disabled.rn-*` meets none of them after CFW |+| No replication and no merge from an earlier deletion in progress | `Can't delete snapshots while volume is replicating`, `merge in progress due to previous snapshot deletion` | Not hit with a single snapshot; vphoned reports EBUSY as retryable |+| AMFI accepts the ad hoc signature's entitlements | JB patches: `AMFIIsCDHashInTrustCache` always true, `_postValidation` skipped | The binary ran with its entitlements |++That is why `apfs.snapshot.delete` deletes only names starting+`orig-fs.disabled.rn-`. Any other snapshot, `com.apple.os.update-*` above all,+may be the volume's root or revert target, and the guest may not boot without+it.++## Measured reclaim and TRIM timing++The prototype (`fs_snapshot_list` with `ATTR_CMN_RETURNED_ATTRS |+ATTR_CMN_NAME`, then `fs_snapshot_delete(open("/"), name, 0)`) ran as a root+launchd job after the files had been trimmed offline. It listed one snapshot,+deleted it on the first call and then listed none.++| Time | Host `Disk.img` blocks (512 B, `stat -f %b`) | Note |+| --- | --- | --- |+| after clone | 39,905,304 | baseline |+| files trimmed offline, image detached | 39,907,456 | snapshot holds the blocks |+| booted, before the deletion | 40,138,464 | first boot wrote about 118 MB |+| 14 s after the deletion | 38,044,176 | |+| 20–100 s after | 37,829,656 → 37,819,728 | settled: −2.32 M blocks, **1.19 GB** |++The system volume went from 16,212,312,064 B to 15,024,877,568 B+(−1,187,434,496 B), matching the host. The guest TRIMs the freed blocks and+the host image is hole-punched within about 15 seconds; a later reboot+reclaimed nothing more. A template's `Disk.img` is a restored, unshared file,+so the 1.19 GB returns to the host volume. On a clone, the blocks it shares+with its source are not freed by its own TRIM.++## The guest still boots++After the deletion the guest was stopped and started again. vphoned answered+within 10 seconds, `setup.status` reported setup done, 258 apps were+registered, 338 processes ran (SpringBoard, backboardd, sharingd and+mobileassetd among them), there was no panic and no new crash report, and the+volume still had no snapshot. The device tree's `root-snapshot-name` is the+original `com.apple.os.update-<hash>`, which CFW's rename already made+unfindable, and the patched kernel boots the live file system either way. The+CFW pipeline does not need the snapshot afterwards: a full `cfw install`+logs and continues when `VPhoneAPFSSnapshot.rename` finds no+`com.apple.os.update-*` snapshot, and `cfw update-environment` and `cfw+update-kernel` do not touch snapshots.++## Where it runs in the template build++As the first step of the template's setup boot, before `setup.skip`, and+after the offline file trim:++```json+{"method":"apfs.snapshot.delete","params":{"force":true}}+```++It depends only on vphoned answering, so a later step failing does not affect+it. It runs once, on the template: clones inherit an image without the+snapshot, and calling it on one is a no-op. The template's final check should+see `apfs.snapshots` return an empty list. No wait for TRIM is needed before+shutdown.++## Not yet verified++- The prototype carried all three vfs snapshot entitlements. vphoned has only+ `com.apple.developer.vfs.snapshot`. If `apfs.snapshot.delete` answers+ `not_permitted`, the next one to add is `com.apple.private.vfs.snapshot`.+- The experiment ran on a clone that had completed Setup, not inside a full+ template build, and no screenshot of the home screen was taken; boot health+ was judged from vphoned, `setup.status`, `apps.list`, the process list and+ crash logs.diff --git a/Research/README.md b/Research/README.mdindex 20b77c66..f7ea6298 100644--- a/Research/README.md+++ b/Research/README.md@@ -20,7 +20,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) || 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), [sharing identical disk blocks with `vm rebase`](Host/disk_rebase.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) |+| 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) || 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.mdindex 3bfdc7e3..e9c60aee 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -294,9 +294,10 @@ request carries `"force": true`.| Logs | `logs.syslog {seconds, process?, level?, max_lines?}` (a bounded capture of at most 60 s), `logs.crashes {bundle_id?}`, `logs.crash {path}` || 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 | `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` || 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` || Motion | `motion.gyroscope.get`, `motion.gyroscope.set {x,y,z,enabled?}`, `motion.gyroscope.clear` (capability `motion_gyroscope`; finite JSON numbers in [-1000,1000] rad/s, all axes required; `enabled` defaults to true and must be a JSON Boolean; capability `motion_gyroscope_toggle` supports disabling while retaining configured axes; returns configuration, `units`, `provider`, and `provider_running`; HID provider status is not proof of CoreMotion app delivery) || Keychain | `keychain.list {class?}`, `add`, `delete`, `get`, `update`, `database` |@@ -524,6 +525,101 @@ panels an older agent cannot serve. icli failures reach the caller withicli's own error `code` (`failed`, `unavailable`, `device_locked`, …) andmessage.+## Removable system apps and APFS snapshots++These methods trim a guest that will serve as a template; `/v1/health` lists+them as `system_app_removal` and `apfs_snapshots`.++**`apps.remove_system {bundle_ids: [...], backup?: true, respring?: true, force}`**+(`VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift`) removes Apple's removable+apps durably. For each identifier it reads the app's current `bundle_path`+from the live app list (the container UUID changes with every install, so+nothing is cached) and requires a `com.apple.` app whose bundle is+`/private/var/containers/Bundle/Application/<UUID>/<Name>.app`. An app under+`/Applications` or `/System` (Phone, Settings) is refused, as is any other+path shape (`GuestSystemAppPolicy.swift`). Then, in this order:++1. the whole container is cloned (or copied) to+ `/private/var/mobile/Library/removed-system-apps/<bundle_id>.container`, with+ `<bundle_id>.manifest.json` beside it (`bundle_id`, `container_uuid`, `app`,+ `container_path`, `removed_at`); `backup: false` skips this;+2. the app is unregistered from LaunchServices (icli's `unregisterApp`, as+ `apps.unregister`);+3. the container is removed recursively, with `SerializedPlaceholder.ipa`,+ `BundleMetadata.plist` and the container metadata.++Unregistering first matters: a registered app whose bundle is missing is+repaired by installd from the placeholder on the next boot+(`Research/Guest/post_setup_signin_and_appstore.md`). SpringBoard restarts once+at the end when anything was removed and `respring` is not false. The result+is `{results: [{bundle_id, status, removed, container, app, backup,+unregistered, error?}], removed, failed, backup_directory, respring}`.+`status` is `removed`, `absent` (not installed: a no-op that succeeds; a+removal an earlier call left half done, with its backup in place, is finished+instead), `unregistered_stale` (LaunchServices listed a container that is+gone) or `failed`. One app's failure does not stop the others; if any failed,+the call returns error `command_failed` (`error: "remove_incomplete"`) whose+body carries the same fields.++```json+{"method":"apps.remove_system","params":{"bundle_ids":["com.apple.news","com.apple.mobilephone"],"force":true}}+→ error: {"code":"command_failed","message":"1 of 2 apps were not removed; see results","removed":1,"failed":1,+ "results":[{"bundle_id":"com.apple.news","status":"removed","removed":true,"unregistered":true,+ "container":"/private/var/containers/Bundle/Application/6EB8…55A1","app":"News.app",+ "backup":"/private/var/mobile/Library/removed-system-apps/com.apple.news.container"},+ {"bundle_id":"com.apple.mobilephone","status":"failed","removed":false,+ "error":"/Applications/MobilePhone.app is not in a bundle container under /private/var/containers/Bundle/Application; …"}],+ "respring":{"method":"frontboard_relaunch",…}}+```++**`apps.restore_system {bundle_ids?, respring?: true, force}`** moves each+backup container back to the UUID path its manifest names (validated as a+removal is) and registers the app in it with LaunchServices as a deletable+system app (`VPhoneDaemon/Native/vphoned_apps.m`: `registerApplication:`, then+`registerApplicationDictionary:`, then the containerized interface, each read+back). icli's `registerApp`, behind `apps.register`, refuses Apple's apps since+0.7.17. Without `bundle_ids` every backup is restored. An app that is+installed is reported `present` and its backup left alone; a restore that+moved the container but could not register it keeps the manifest, so calling+it again retries the registration. Results mirror the removal (`status`+`restored`, `present` or `failed`, plus `registration`, the call that worked;+`error: "restore_incomplete"` when any failed). **`apps.removed_system`** lists+the backups: `{directory, backups: [{bundle_id, backup, container,+container_uuid, app, removed_at, restorable}], other}`, where `other` names+entries without a bundle identifier, such as `News.container` backups made by+hand before this verb existed.++**`apfs.snapshots {mount?: "/"}`** returns `{mount, snapshots: [name]}` from+`fs_snapshot_list` (`VPhoneDaemon/Native/vphoned_apfs.m`).+**`apfs.snapshot.delete {mount?: "/", name? | prefix?, force}`** deletes with+`fs_snapshot_delete` only snapshots named `orig-fs.disabled.rn-*`, the sealed+update snapshot CFW install renamed (`GuestSnapshotPolicy.swift`). A `name` or+`prefix` that does not start with that is refused, `com.apple.os.update-*`+included; with neither, every `orig-fs.disabled.rn-*` snapshot is selected.+A selection that matches nothing succeeds with nothing deleted, and a snapshot+already gone (ENOENT) is listed under `already_deleted`. The result is `{mount,+before, deleted, already_deleted, after, remaining}`. A refusal from the+kernel stops the call: EINVAL and ENOTSUP are invalid requests; EPERM or+EACCES (`reason: "not_permitted"`: vphoned is not root or lacks+`com.apple.developer.vfs.snapshot`), EBUSY (`reason: "busy"`, `retryable:+true`: mounted, or APFS is still merging an earlier deletion) and anything+else return `command_failed` with `reason`, `retryable`, `errno`, `snapshot`+and the `before`/`deleted`/`after` listings. Why and when to call it:+`Research/Guest/template_snapshot_deletion.md`.++```json+{"method":"apfs.snapshot.delete","params":{"force":true}}+→ {"mount":"/","before":["orig-fs.disabled.rn-4EC2…ECB9"],"deleted":["orig-fs.disabled.rn-4EC2…ECB9"],+ "already_deleted":[],"after":[],"remaining":[]}+```++The path, identifier, manifest, snapshot-name and errno rules, and the+`fs_snapshot_list` batch parser, are checked on the Mac without a guest:++```sh+VPhoneDaemon/Tests/run-system-maintenance-tests.sh+```+## Nested accessibility snapshots`ui.tree` (alias `accessibility.tree`) keeps its existing flat result unlessdiff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlementsindex b824a035..d062d6db 100644--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements@@ -65,6 +65,8 @@<true/><key>com.apple.developer.usernotifications.time-sensitive</key><true/>+ <key>com.apple.developer.vfs.snapshot</key>+ <true/><key>com.apple.frontboard.launchapplications</key><true/><key>com.apple.frontboard.shutdown</key>diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swiftindex 2a2f81cb..456824da 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift@@ -12,7 +12,9 @@ extension GuestAPI {executeService,executeLog,executeAppDetail,+ executeSystemApps,executeFileTool,+ executeStorage,executeEnvironment,executeDeviceIdentity,executeSetupAssistant,diff --git a/VPhoneDaemon/Daemon/GuestAPI+Storage.swift b/VPhoneDaemon/Daemon/GuestAPI+Storage.swiftnew file mode 100644index 00000000..43e2a8c9--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestAPI+Storage.swift@@ -0,0 +1,113 @@+import Darwin+import Foundation+import IcliSystem+import VphonedNative++// MARK: - APFS Snapshots++/// `apfs.snapshots` lists a volume's snapshots; `apfs.snapshot.delete`+/// removes the `orig-fs.disabled.rn-*` snapshot CFW install leaves on the+/// system volume, and nothing else (`GuestSnapshotPolicy`). Until it is gone,+/// files trimmed from the system volume free no space: the snapshot still+/// references their blocks. The guest TRIMs the freed blocks within seconds,+/// so the host's disk image shrinks without a reboot. The host cannot do this+/// itself: its SIP refuses to delete snapshots of a System-role volume.+/// `Research/Guest/template_snapshot_deletion.md` has the measurements.+extension GuestAPI {+ static func executeStorage(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {+ switch method {+ case "apfs.snapshots":+ let mount = try snapshotMount(params)+ return try ["mount": mount, "snapshots": snapshotNames(mount)]+ case "apfs.snapshot.delete":+ let mount = try snapshotMount(params)+ let selection: GuestSnapshotPolicy.Selection+ do {+ selection = try GuestSnapshotPolicy.Selection.make(+ name: optionalString(params, "name"),+ prefix: optionalString(params, "prefix"),+ )+ } catch {+ throw GuestAPIError.invalidRequest(String(describing: error))+ }+ try requireForce(params, "delete APFS snapshots on \(mount)")+ return try deleteSnapshots(mount: mount, selection: selection)+ default:+ return nil+ }+ }++ private static func snapshotMount(_ params: [String: Any]) throws -> String {+ let mount = optionalString(params, "mount") ?? GuestSnapshotPolicy.defaultMount+ do {+ try GuestSnapshotPolicy.validateMount(mount)+ } catch {+ throw GuestAPIError.invalidRequest(String(describing: error))+ }+ return mount+ }++ static func snapshotNames(_ mount: String) throws -> [String] {+ var names: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?+ var count: Int32 = 0+ let status = vp_apfs_snapshot_list(mount, &names, &count)+ guard status == 0 else {+ throw snapshotError(status, operation: "fs_snapshot_list(\(mount))", details: ["mount": mount])+ }+ defer { vp_apfs_snapshot_names_free(names, count) }+ return (0 ..< Int(count)).compactMap { index in names?[index].map { String(cString: $0) } }.sorted()+ }++ /// Deletes the selected snapshots one by one and stops at the first the+ /// kernel refuses. A snapshot already gone counts as deleted, and a+ /// selection that matches nothing succeeds with nothing deleted.+ private static func deleteSnapshots(mount: String, selection: GuestSnapshotPolicy.Selection) throws -> [String: Any] {+ let before = try snapshotNames(mount)+ var deleted: [String] = []+ var alreadyDeleted: [String] = []+ for name in selection.targets(in: before) {+ let status = vp_apfs_snapshot_delete(mount, name)+ if status == 0 {+ deleted.append(name)+ continue+ }+ if GuestSnapshotPolicy.Failure(errno: status) == .alreadyDeleted {+ alreadyDeleted.append(name)+ continue+ }+ throw snapshotError(status, operation: "fs_snapshot_delete(\(name))", details: [+ "mount": mount,+ "snapshot": name,+ "before": before,+ "deleted": deleted,+ "after": (try? snapshotNames(mount)) ?? NSNull(),+ ])+ }+ let after = try snapshotNames(mount)+ return [+ "mount": mount,+ "before": before,+ "deleted": deleted,+ "already_deleted": alreadyDeleted,+ "after": after,+ "remaining": after.filter(selection.matches),+ ]+ }++ /// An invalid request is an ordinary invalid request; any other refusal+ /// carries `reason`, `retryable` and `errno` beside the listings.+ private static func snapshotError(_ status: Int32, operation: String, details: [String: Any]) -> Error {+ let failure = GuestSnapshotPolicy.Failure(errno: status)+ let message = GuestSnapshotPolicy.message(failure, errno: status, operation: operation)+ if failure == .invalidRequest {+ return GuestAPIError.invalidRequest(message)+ }+ return IcliError.commandFailed(details.merging([+ "error": "snapshot_operation_failed",+ "message": message,+ "reason": failure.rawValue,+ "retryable": failure.retryable,+ "errno": Int(status),+ ]) { $1 })+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift b/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swiftnew file mode 100644index 00000000..076b7708--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift@@ -0,0 +1,411 @@+import Darwin+import Foundation+import IcliKit+import IcliSystem+import VphonedNative++// MARK: - Removable System Apps++/// `apps.remove_system` removes Apple's removable apps durably;+/// `apps.restore_system` puts them back from the backup it kept, and+/// `apps.removed_system` lists those backups.+///+/// The order is fixed. The whole bundle container is backed up, the app is+/// unregistered from LaunchServices, and only then is the container removed,+/// with its `SerializedPlaceholder.ipa` and metadata. Removing only the `.app`+/// leaves a registered app with a missing bundle, which installd repairs from+/// the placeholder on the next boot; removing the container while the app is+/// still registered does the same. Each app's container path comes from the+/// live app list, since the UUID changes with every install.+/// `GuestSystemAppPolicy` decides which apps qualify;+/// `Research/Guest/post_setup_signin_and_appstore.md` has the measurements.+extension GuestAPI {+ static func executeSystemApps(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {+ switch method {+ case "apps.remove_system":+ guard let ids = try systemAppIDs(params) else {+ throw GuestAPIError.invalidRequest("bundle_ids must list the apps to remove")+ }+ try requireForce(params, "remove \(ids.joined(separator: ", "))")+ return try removeSystemApps(+ ids,+ backup: bool(params, "backup", default: true),+ respring: bool(params, "respring", default: true),+ )+ case "apps.restore_system":+ let ids = try systemAppIDs(params) ?? backedUpSystemAppIDs()+ try requireForce(params, "restore removed system apps")+ return try restoreSystemApps(ids, respring: bool(params, "respring", default: true))+ case "apps.removed_system":+ return removedSystemApps()+ default:+ return nil+ }+ }++ /// `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")+ }+ var seen = Set<String>()+ return ids.filter { seen.insert($0).inserted }+ }++ // MARK: - Remove++ private static func removeSystemApps(_ ids: [String], backup: Bool, respring restart: Bool) throws -> [String: Any] {+ let results = ids.map { removeSystemApp($0, backup: backup) }+ let changed = results.filter { $0["removed"] as? Bool == true }.count+ let failed = results.filter { $0["status"] as? String == "failed" }.count+ var result: [String: Any] = [+ "results": results,+ "removed": changed,+ "failed": failed,+ "backup_directory": backup ? GuestSystemAppPolicy.backupDirectory : NSNull(),+ "respring": restart && changed > 0 ? respringResult() : NSNull(),+ ]+ guard failed == 0 else {+ result["error"] = "remove_incomplete"+ result["message"] = "\(failed) of \(ids.count) apps were not removed; see results"+ throw IcliError.commandFailed(result)+ }+ return result+ }++ /// One app. Errors land in the result, so one app's failure does not+ /// stop the others.+ private static func removeSystemApp(_ id: String, backup: Bool) -> [String: Any] {+ var result: [String: Any] = ["bundle_id": id, "removed": false]+ do {+ try GuestSystemAppPolicy.validateBundleID(id)+ guard let record = try installedApp(id) else {+ return try finishInterruptedRemoval(id, result: result)+ }+ let bundlePath = record["bundle_path"] as? String ?? ""+ let location = try GuestSystemAppLocation(bundlePath: bundlePath)+ result["bundle_path"] = bundlePath+ result["container"] = location.containerPath+ result["app"] = location.appDirectoryName++ 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 unregisterApp(bundlePath, force: true)+ result["unregistered"] = unregistered["unregistered"] as? Bool ?? false+ result["status"] = "unregistered_stale"+ result["removed"] = true+ result["backup"] = NSNull()+ return result+ }+ try checkBundleIdentifier(location, id)++ result["backup"] = NSNull()+ if backup {+ result["backup"] = try backUpContainer(id, location)+ }+ do {+ let unregistered = try unregisterApp(bundlePath, force: true)+ result["unregistered"] = unregistered["unregistered"] as? Bool ?? false+ } catch {+ if backup {+ discardBackup(id)+ result["backup"] = NSNull()+ }+ throw error+ }+ do {+ _ = try removePath(location.containerPath, recursive: true, force: true)+ } catch {+ throw GuestAPIError.operationFailed(+ "\(id) is unregistered but its container \(location.containerPath) was not removed "+ + "(\(describe(error))); "+ + (backup ? "run apps.remove_system again to finish" : "remove it with files.remove"),+ )+ }+ result["status"] = "removed"+ result["removed"] = true+ } catch {+ result["status"] = "failed"+ result["error"] = describe(error)+ }+ return result+ }++ /// The app is not registered. If an earlier removal unregistered it and+ /// backed it up but stopped before the container was gone, finish it;+ /// otherwise there is nothing to do. A container a failed restore moved+ /// back has no backup beside it and is left alone.+ private static func finishInterruptedRemoval(_ id: String, result: [String: Any]) throws -> [String: Any] {+ var result = result+ result["status"] = "absent"+ let backupPath = GuestSystemAppPolicy.backupContainerPath(id)+ result["backup"] = pathExists(backupPath) ? backupPath : NSNull()+ guard pathExists(GuestSystemAppPolicy.manifestPath(id)), pathExists(backupPath) else { return result }+ let location = try readManifest(id).location()+ guard try bundleContainerExists(location) else { return result }+ try checkBundleIdentifier(location, id)+ _ = try removePath(location.containerPath, recursive: true, force: true)+ result["container"] = location.containerPath+ result["app"] = location.appDirectoryName+ result["status"] = "removed"+ result["removed"] = true+ return result+ }++ /// Copies the whole container to `<bundle_id>.container` (an APFS clone+ /// when it can) and writes `<bundle_id>.manifest.json` beside it. An older+ /// backup of the same app is replaced once the new copy is complete.+ private static func backUpContainer(_ id: String, _ location: GuestSystemAppLocation) throws -> String {+ let files = FileManager.default+ try files.createDirectory(+ atPath: GuestSystemAppPolicy.backupDirectory,+ withIntermediateDirectories: true,+ attributes: [.posixPermissions: 0o755],+ )+ let destination = GuestSystemAppPolicy.backupContainerPath(id)+ let staging = destination + ".partial"+ if pathExists(staging) {+ try files.removeItem(atPath: staging)+ }+ // clonefile keeps owners and modes when root calls it; the container+ // must come back as installd left it.+ if clonefile(location.containerPath, staging, UInt32(CLONE_NOFOLLOW)) != 0 {+ let reason = String(cString: strerror(errno))+ if pathExists(staging) {+ try? files.removeItem(atPath: staging)+ }+ do {+ try files.copyItem(atPath: location.containerPath, toPath: staging)+ } catch {+ try? files.removeItem(atPath: staging)+ throw GuestAPIError.operationFailed(+ "Could not back up \(location.containerPath): clone failed (\(reason)), copy failed (\(describe(error)))",+ )+ }+ }+ if pathExists(destination) {+ try files.removeItem(atPath: destination)+ }+ guard rename(staging, destination) == 0 else {+ let reason = String(cString: strerror(errno))+ try? files.removeItem(atPath: staging)+ throw GuestAPIError.operationFailed("Could not move the backup into place: \(reason)")+ }+ let manifest = GuestSystemAppManifest(bundleID: id, location: location, removedAt: Date())+ do {+ try manifest.encoded().write(+ to: URL(fileURLWithPath: GuestSystemAppPolicy.manifestPath(id)),+ options: .atomic,+ )+ } catch {+ try? files.removeItem(atPath: destination)+ throw GuestAPIError.operationFailed("Could not write the backup manifest: \(describe(error))")+ }+ return destination+ }++ private static func discardBackup(_ id: String) {+ try? FileManager.default.removeItem(atPath: GuestSystemAppPolicy.backupContainerPath(id))+ try? FileManager.default.removeItem(atPath: GuestSystemAppPolicy.manifestPath(id))+ }++ // MARK: - Restore++ private static func restoreSystemApps(_ ids: [String], respring restart: Bool) throws -> [String: Any] {+ let results = ids.map(restoreSystemApp)+ let changed = results.filter { $0["restored"] as? Bool == true }.count+ let failed = results.filter { $0["status"] as? String == "failed" }.count+ var result: [String: Any] = [+ "results": results,+ "restored": changed,+ "failed": failed,+ "respring": restart && changed > 0 ? respringResult() : NSNull(),+ ]+ guard failed == 0 else {+ result["error"] = "restore_incomplete"+ result["message"] = "\(failed) of \(ids.count) apps were not restored; see results"+ throw IcliError.commandFailed(result)+ }+ return result+ }++ /// Moves the backup container back to its original UUID path and+ /// registers the app in it. The manifest stays until LaunchServices lists+ /// the app, so a restore that moved the container but could not register+ /// it is finished by running it again.+ private static func restoreSystemApp(_ id: String) -> [String: Any] {+ var result: [String: Any] = ["bundle_id": id, "restored": false]+ do {+ try GuestSystemAppPolicy.validateBundleID(id)+ let backupPath = GuestSystemAppPolicy.backupContainerPath(id)+ guard pathExists(GuestSystemAppPolicy.manifestPath(id)) else {+ if let record = try installedApp(id) {+ result["status"] = "present"+ result["bundle_path"] = record["bundle_path"] ?? ""+ return result+ }+ throw GuestAPIError.operationFailed(+ pathExists(backupPath)+ ? "\(backupPath) has no manifest naming its original container"+ : "No backup of \(id) in \(GuestSystemAppPolicy.backupDirectory)",+ )+ }+ let location = try readManifest(id).location()+ result["container"] = location.containerPath+ result["app"] = location.appDirectoryName+ if let record = try installedApp(id) {+ result["status"] = "present"+ result["bundle_path"] = record["bundle_path"] ?? ""+ result["message"] = "\(id) is installed; the backup was left in place"+ return result+ }+ if pathExists(backupPath) {+ guard !pathExists(location.containerPath) else {+ throw GuestAPIError.operationFailed("\(location.containerPath) already exists; the backup was left in place")+ }+ guard rename(backupPath, location.containerPath) == 0 else {+ throw GuestAPIError.operationFailed(+ "Could not move \(backupPath) back: \(String(cString: strerror(errno)))",+ )+ }+ } else {+ guard try bundleContainerExists(location) else {+ throw GuestAPIError.operationFailed("The backup container \(backupPath) is missing")+ }+ }+ try checkBundleIdentifier(location, id)++ var method: UnsafeMutablePointer<CChar>?+ if let error = vp_ls_register_system_app(location.appPath, location.containerPath, &method) {+ defer { free(error) }+ throw GuestAPIError.operationFailed(+ "\(String(cString: error)); the container is back at \(location.containerPath), "+ + "run apps.restore_system again to retry the registration",+ )+ }+ defer { free(method) }+ let registration = try appRegistration(location.appPath)+ guard registration["registered"] as? Bool == true else {+ throw GuestAPIError.operationFailed("LaunchServices does not list \(location.appPath) after registration")+ }+ try? FileManager.default.removeItem(atPath: GuestSystemAppPolicy.manifestPath(id))+ result["registration"] = method.map { String(cString: $0) } ?? ""+ result["status"] = "restored"+ result["restored"] = true+ } catch {+ result["status"] = "failed"+ result["error"] = describe(error)+ }+ return result+ }++ // MARK: - Backups++ /// Every app with a backup or a manifest in the backup directory.+ private static func backedUpSystemAppIDs() -> [String] {+ let names = (try? FileManager.default.contentsOfDirectory(atPath: GuestSystemAppPolicy.backupDirectory)) ?? []+ return Set(names.compactMap(GuestSystemAppPolicy.bundleID(forBackupEntry:))).sorted()+ }++ private static func removedSystemApps() -> [String: Any] {+ let names = (try? FileManager.default.contentsOfDirectory(atPath: GuestSystemAppPolicy.backupDirectory)) ?? []+ let backups = backedUpSystemAppIDs().map { id -> [String: Any] in+ let backupPath = GuestSystemAppPolicy.backupContainerPath(id)+ var entry: [String: Any] = [+ "bundle_id": id,+ "backup": pathExists(backupPath) ? backupPath : NSNull(),+ ]+ do {+ let manifest = try readManifest(id)+ let location = try manifest.location()+ entry["container"] = location.containerPath+ entry["container_uuid"] = location.containerUUID+ entry["app"] = location.appDirectoryName+ entry["removed_at"] = ISO8601DateFormatter().string(from: manifest.removedAt)+ entry["restorable"] = pathExists(backupPath) || pathExists(location.containerPath)+ } catch {+ entry["restorable"] = false+ entry["error"] = describe(error)+ }+ return entry+ }+ // Backups made by hand before this verb existed (`News.container`)+ // name no bundle identifier and have no manifest.+ let other = names.filter { GuestSystemAppPolicy.bundleID(forBackupEntry: $0) == nil }.sorted()+ return ["directory": GuestSystemAppPolicy.backupDirectory, "backups": backups, "other": other]+ }++ private static func readManifest(_ id: String) throws -> GuestSystemAppManifest {+ let path = GuestSystemAppPolicy.manifestPath(id)+ var info = stat()+ guard lstat(path, &info) == 0, info.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG), info.st_size <= 64 * 1024 else {+ throw GuestAPIError.operationFailed("\(path) is not a manifest file")+ }+ return try GuestSystemAppManifest.decode(Data(contentsOf: URL(fileURLWithPath: path)), expectedBundleID: id)+ }++ // MARK: - Helpers++ /// 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]] ?? []+ return apps.first { $0["bundle_id"] as? String == id }+ }++ /// False when the container is gone. A container that is a symbolic link,+ /// not a directory, or resolves elsewhere is refused.+ private static func bundleContainerExists(_ location: GuestSystemAppLocation) throws -> Bool {+ var info = stat()+ guard lstat(location.containerPath, &info) == 0 else { return false }+ guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR),+ let resolved = realpath(location.containerPath, nil)+ else {+ throw GuestAPIError.operationFailed("\(location.containerPath) is not a bundle container directory")+ }+ defer { free(resolved) }+ guard String(cString: resolved) == location.containerPath else {+ throw GuestAPIError.operationFailed("\(location.containerPath) resolves to \(String(cString: resolved))")+ }+ return true+ }++ /// The bundle on disk must be the app asked for, not whatever a stale+ /// record or a hand-edited manifest points at.+ private static func checkBundleIdentifier(_ location: GuestSystemAppLocation, _ id: String) throws {+ var info = stat()+ guard lstat(location.appPath, &info) == 0, info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) else {+ throw GuestAPIError.operationFailed("\(location.appPath) is not an app bundle")+ }+ let plist = NSDictionary(contentsOfFile: location.appPath + "/Info.plist")+ guard let found = plist?["CFBundleIdentifier"] as? String else {+ throw GuestAPIError.operationFailed("\(location.appPath) has no readable Info.plist")+ }+ guard found == id else {+ throw GuestAPIError.operationFailed("\(location.appPath) is \(found), not \(id)")+ }+ }++ private static func pathExists(_ path: String) -> Bool {+ var info = stat()+ return lstat(path, &info) == 0+ }++ private static func respringResult() -> Any {+ do {+ return try respring()+ } catch {+ return ["error": describe(error)]+ }+ }++ private static func describe(_ error: Error) -> String {+ switch error {+ case let error as IcliError: error.message+ case let error as GuestAPIError: error.description+ case let error as GuestSystemAppPolicyError: error.description+ default: (error as NSError).localizedDescription+ }+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 37d7af62..33f8d146 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -126,9 +126,11 @@ enum GuestAPI {"logs","network_capture","app_details",+ "system_app_removal","system_control","system_shutdown","file_tools",+ "apfs_snapshots","files_app_drop","packages","environment_update",diff --git a/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swift b/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swiftnew file mode 100644index 00000000..45064952--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestSnapshotPolicy.swift@@ -0,0 +1,129 @@+import Darwin+import Foundation++// MARK: - APFS Snapshot Deletion Policy++/// Which APFS snapshots `apfs.snapshot.delete` may remove and how it reads+/// the kernel's answer, kept free of IcliKit and UIKit so+/// `VPhoneDaemon/Tests/run-system-maintenance-tests.sh` checks it on the Mac.+///+/// CFW install renames the system volume's sealed update snapshot+/// (`com.apple.os.update-<hash>`) to `orig-fs.disabled.rn-<hash>` and the+/// patched kernel boots the live file system instead. The renamed snapshot is+/// then an ordinary dangling snapshot that pins every block a later file trim+/// frees. Only that prefix is ever deleted: another snapshot may be the+/// volume's root or revert target, and deleting it can leave the guest unable+/// to boot. `Research/Guest/template_snapshot_deletion.md` has the evidence.+enum GuestSnapshotPolicy {+ static let deletablePrefix = "orig-fs.disabled.rn-"+ static let defaultMount = "/"++ /// The snapshots a request selects: `name` alone, every snapshot starting+ /// with `prefix`, or with neither every deletable one.+ enum Selection: Equatable {+ case name(String)+ case prefix(String)++ static func make(name: String?, prefix: String?) throws(GuestSnapshotPolicyError) -> Selection {+ switch (name, prefix) {+ case (.some, .some):+ throw .invalidRequest("Pass name or prefix, not both")+ case let (.some(name), nil):+ guard name.hasPrefix(deletablePrefix), name.count > deletablePrefix.count else {+ throw .refused(name)+ }+ guard !name.contains("/") else { throw .invalidRequest("\(name) is not a snapshot name") }+ return .name(name)+ case let (nil, .some(prefix)):+ guard prefix.hasPrefix(deletablePrefix) else { throw .refused(prefix + "*") }+ return .prefix(prefix)+ case (nil, nil):+ return .prefix(deletablePrefix)+ }+ }++ func matches(_ snapshot: String) -> Bool {+ guard snapshot.hasPrefix(GuestSnapshotPolicy.deletablePrefix) else { return false }+ switch self {+ case let .name(name): return snapshot == name+ case let .prefix(prefix): return snapshot.hasPrefix(prefix)+ }+ }++ /// The listed snapshots this selection deletes. A name that is not+ /// listed is still tried, so a stale listing cannot hide it; ENOENT+ /// then counts as already deleted.+ func targets(in snapshots: [String]) -> [String] {+ switch self {+ case let .name(name): matches(name) ? [name] : []+ case .prefix: snapshots.filter(matches)+ }+ }+ }++ /// A mount point is an absolute path without `.` or `..` components.+ static func validateMount(_ mount: String) throws(GuestSnapshotPolicyError) {+ guard mount.hasPrefix("/"),+ !mount.split(separator: "/").contains(where: { $0 == "." || $0 == ".." })+ else {+ throw .invalidRequest("mount must be an absolute path: \(mount)")+ }+ }++ // MARK: - errno++ enum Failure: String, Equatable {+ /// The snapshot is not there: a delete counts it as done.+ case alreadyDeleted = "already_deleted"+ /// vphoned lacks `com.apple.developer.vfs.snapshot` or is not root.+ case notPermitted = "not_permitted"+ /// Mounted, or APFS is still merging an earlier deletion. Retry later.+ case busy+ /// Not APFS, or a snapshot the kernel will not delete (root or revert target).+ case invalidRequest = "invalid_request"+ case failed++ init(errno code: Int32) {+ switch code {+ case ENOENT: self = .alreadyDeleted+ case EPERM, EACCES: self = .notPermitted+ case EBUSY: self = .busy+ case EINVAL, ENOTSUP: self = .invalidRequest+ default: self = .failed+ }+ }++ var retryable: Bool { self == .busy }+ }++ static func message(_ failure: Failure, errno code: Int32, operation: String) -> String {+ let reason = String(cString: strerror(code))+ return switch failure {+ case .alreadyDeleted:+ "\(operation): the snapshot no longer exists (\(reason))"+ case .notPermitted:+ "\(operation): \(reason). vphoned must run as root and carry com.apple.developer.vfs.snapshot"+ case .busy:+ "\(operation): \(reason). The snapshot is mounted or APFS is still merging an earlier deletion; retry later"+ case .invalidRequest:+ "\(operation): \(reason). The volume is not APFS, or the kernel will not delete this snapshot"+ case .failed:+ "\(operation): \(reason) (errno \(code))"+ }+ }+}++enum GuestSnapshotPolicyError: Error, Equatable, CustomStringConvertible {+ case invalidRequest(String)+ case refused(String)++ var description: String {+ switch self {+ case let .invalidRequest(message):+ message+ case let .refused(name):+ "Refusing to delete \(name): only \(GuestSnapshotPolicy.deletablePrefix)* snapshots, "+ + "which CFW install leaves behind, may be deleted"+ }+ }+}diff --git a/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swift b/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swiftnew file mode 100644index 00000000..718d3741--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestSystemAppPolicy.swift@@ -0,0 +1,192 @@+import Foundation++// MARK: - Removable System Apps++/// The rules `apps.remove_system` and `apps.restore_system` follow, kept free+/// of IcliKit and UIKit so `VPhoneDaemon/Tests/run-system-maintenance-tests.sh`+/// checks them on the Mac.+///+/// A removable system app (App Store, Home, TV, News …) is a placeholder in+/// `/System/Library/AppPlaceholders` that installd expands on first boot into+/// its own bundle container on the data volume,+/// `/private/var/containers/Bundle/Application/<UUID>/<Name>.app`. Only an app+/// in such a container is removed; anything under `/Applications` or+/// `/System` (Phone, Settings, SpringBoard) is refused. The UUID changes with+/// every install, so the path always comes from the live app list.+/// `Research/Guest/post_setup_signin_and_appstore.md` has the measurements.+enum GuestSystemAppPolicy {+ static let containersRoot = "/private/var/containers/Bundle/Application"+ static let backupDirectory = "/private/var/mobile/Library/removed-system-apps"+ static let backupSuffix = ".container"+ static let manifestSuffix = ".manifest.json"++ /// Only Apple's apps are removable system apps. The identifier also names+ /// the backup files, so it is limited to reverse-DNS characters.+ static func validateBundleID(_ bundleID: String) throws(GuestSystemAppPolicyError) {+ let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-")+ guard !bundleID.isEmpty, bundleID.count <= 255,+ bundleID.unicodeScalars.allSatisfy(allowed.contains),+ !bundleID.contains("..")+ else {+ throw .invalidBundleID(bundleID)+ }+ guard bundleID.hasPrefix("com.apple."), bundleID.count > "com.apple.".count else {+ throw .notSystemApp(bundleID)+ }+ }++ static func backupContainerPath(_ bundleID: String) -> String {+ backupDirectory + "/" + bundleID + backupSuffix+ }++ static func manifestPath(_ bundleID: String) -> String {+ backupDirectory + "/" + bundleID + manifestSuffix+ }++ /// The bundle identifier a backup directory entry belongs to, or nil for+ /// another file.+ static func bundleID(forBackupEntry name: String) -> String? {+ for suffix in [backupSuffix, manifestSuffix] where name.hasSuffix(suffix) {+ let id = String(name.dropLast(suffix.count))+ return (try? validateBundleID(id)) == nil ? nil : id+ }+ return nil+ }+}++enum GuestSystemAppPolicyError: Error, Equatable, CustomStringConvertible {+ case invalidBundleID(String)+ case notSystemApp(String)+ case notInBundleContainer(String)+ case invalidManifest(String)++ var description: String {+ switch self {+ case let .invalidBundleID(id):+ "\(id) is not a bundle identifier"+ case let .notSystemApp(id):+ "\(id) is not an Apple app; only removable system apps can be removed this way"+ case let .notInBundleContainer(path):+ "\(path) is not in a bundle container under \(GuestSystemAppPolicy.containersRoot); "+ + "apps in /Applications or /System are part of the system volume and are not removed"+ case let .invalidManifest(reason):+ "The backup manifest is not usable: \(reason)"+ }+ }+}++// MARK: - Bundle Container Location++/// Where one installed copy lives: `<containersRoot>/<UUID>/<Name>.app`.+struct GuestSystemAppLocation: Equatable {+ let containerUUID: String+ let appDirectoryName: String++ var containerPath: String { GuestSystemAppPolicy.containersRoot + "/" + containerUUID }+ var appPath: String { containerPath + "/" + appDirectoryName }++ /// Accepts the path LaunchServices reports, with or without the+ /// `/private` prefix and with a trailing slash. Anything else, a `.` or+ /// `..` component, an empty component, a container that is not named by+ /// a UUID (RootHide's `.jbroot-*` among them) or a bundle nested deeper,+ /// is refused.+ init(bundlePath: String) throws(GuestSystemAppPolicyError) {+ var path = bundlePath+ while path.count > 1, path.hasSuffix("/") {+ path.removeLast()+ }+ if path.hasPrefix("/var/") {+ path = "/private" + path+ }+ let root = GuestSystemAppPolicy.containersRoot + "/"+ guard path.hasPrefix(root) else { throw .notInBundleContainer(bundlePath) }+ let parts = path.dropFirst(root.count).split(separator: "/", omittingEmptySubsequences: false).map(String.init)+ guard parts.count == 2,+ let uuid = UUID(uuidString: parts[0]), uuid.uuidString == parts[0].uppercased(),+ Self.isAppDirectoryName(parts[1])+ else {+ throw .notInBundleContainer(bundlePath)+ }+ containerUUID = parts[0]+ appDirectoryName = parts[1]+ }++ init(containerUUID: String, appDirectoryName: String) throws(GuestSystemAppPolicyError) {+ try self.init(bundlePath: GuestSystemAppPolicy.containersRoot + "/" + containerUUID + "/" + appDirectoryName)+ }++ private static func isAppDirectoryName(_ name: String) -> Bool {+ name.hasSuffix(".app") && name.count > 4 && !name.hasPrefix(".") && !name.contains("/")+ }+}++// MARK: - Backup Manifest++/// Written beside the backup container, never inside it: the container is+/// moved back as it is, and a file in it would land in the restored app's+/// bundle container.+struct GuestSystemAppManifest: Codable, Equatable {+ static let currentVersion = 1++ let version: Int+ let bundleID: String+ let containerUUID: String+ let appDirectoryName: String+ /// The container path when the app was removed, for people reading the+ /// file; the restore rebuilds it from the UUID.+ let containerPath: String+ let removedAt: Date++ enum CodingKeys: String, CodingKey {+ case version+ case bundleID = "bundle_id"+ case containerUUID = "container_uuid"+ case appDirectoryName = "app"+ case containerPath = "container_path"+ case removedAt = "removed_at"+ }++ init(bundleID: String, location: GuestSystemAppLocation, removedAt: Date) {+ version = Self.currentVersion+ self.bundleID = bundleID+ containerUUID = location.containerUUID+ appDirectoryName = location.appDirectoryName+ containerPath = location.containerPath+ self.removedAt = removedAt+ }++ /// The location the restore moves the container back to, validated as a+ /// removal is: the backup directory is the mobile user's, so the manifest+ /// is not trusted to name any other path.+ func location() throws(GuestSystemAppPolicyError) -> GuestSystemAppLocation {+ try GuestSystemAppPolicy.validateBundleID(bundleID)+ return try GuestSystemAppLocation(containerUUID: containerUUID, appDirectoryName: appDirectoryName)+ }++ func encoded() throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ encoder.dateEncodingStrategy = .iso8601+ return try encoder.encode(self)+ }++ /// Decodes and validates a manifest written for `expectedBundleID`.+ static func decode(_ data: Data, expectedBundleID: String) throws(GuestSystemAppPolicyError) -> Self {+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ let manifest: Self+ do {+ manifest = try decoder.decode(Self.self, from: data)+ } catch {+ throw .invalidManifest("it is not a manifest (\(error.localizedDescription))")+ }+ guard manifest.version == currentVersion else {+ throw .invalidManifest("version \(manifest.version) is not \(currentVersion)")+ }+ guard manifest.bundleID == expectedBundleID else {+ throw .invalidManifest("it names \(manifest.bundleID), not \(expectedBundleID)")+ }+ _ = try manifest.location()+ return manifest+ }+}diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex b45c5a7e..990a2914 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -1,5 +1,6 @@#pragma once#include <stdbool.h>+#include <stddef.h>#include <stdint.h>#ifdef __OBJC__#import <Foundation/Foundation.h>@@ -56,6 +57,27 @@ char *vp_usb_set_serial(const char *serial, bool force, bool *changed);/// `unique-chip-id`. malloc-owned, or NULL when the device tree lacks either.char *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);++/// 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);++/// Delete the snapshot `name` of the volume mounted at `mount`. Returns 0 or+/// an errno value. Needs root and a vfs snapshot entitlement.+int vp_apfs_snapshot_delete(const char *mount, const char *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);+#ifdef __OBJC__/// The configured radians/second and the injected HID provider's heartbeat.NSDictionary *vp_gyro_get(void);diff --git a/VPhoneDaemon/Native/vphoned_apfs.m b/VPhoneDaemon/Native/vphoned_apfs.mnew file mode 100644index 00000000..628c8cd3--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_apfs.m@@ -0,0 +1,133 @@+/*+ * vphoned_apfs — list and delete APFS snapshots of a mounted volume.+ *+ * fs_snapshot_list reads the snapshots of the volume a directory descriptor+ * is on, in getattrlistbulk's packed format; fs_snapshot_delete removes one+ * by name. The kernel lets a root caller holding a vfs snapshot entitlement+ * (vphoned carries com.apple.developer.vfs.snapshot) delete a snapshot that+ * is not the volume's root or revert target and is not mounted.+ *+ * Both return 0 or an errno value. Which snapshot may be deleted is decided+ * in Swift (GuestSnapshotPolicy); this file does no filtering.+ * Research/Guest/template_snapshot_deletion.md has the evidence.+ */++#import "Include/VphonedNative.h"++#include <errno.h>+#include <fcntl.h>+#include <stdlib.h>+#include <string.h>+#include <sys/attr.h>+#include <sys/snapshot.h>+#include <unistd.h>++#define VP_APFS_LIST_BUFFER (64 * 1024)++// MARK: - Parsing++void vp_apfs_snapshot_names_free(char **names, int count) {+ if (!names) return;+ for (int index = 0; index < count; index++) free(names[index]);+ free(names);+}++static bool vp_apfs_contains(char **names, int count, const char *name) {+ for (int index = 0; index < count; index++) {+ if (strcmp(names[index], name) == 0) return true;+ }+ return false;+}++int vp_apfs_snapshot_parse(const char *buffer, size_t size, int entries, char ***names, int *count, int *added) {+ if (!buffer || !names || !count || !added) return EINVAL;+ *added = 0;+ const char *entry = buffer;+ const char *end = buffer + size;+ for (int index = 0; index < entries; index++) {+ // Each entry: its length, the attributes returned, then an+ // attrreference whose offset is relative to the reference itself.+ if ((size_t)(end - entry) < sizeof(uint32_t) + sizeof(attribute_set_t)) break;+ uint32_t length;+ memcpy(&length, entry, sizeof(length));+ if (length < sizeof(uint32_t) + sizeof(attribute_set_t) || length > (size_t)(end - entry)) break;+ attribute_set_t returned;+ memcpy(&returned, entry + sizeof(uint32_t), sizeof(returned));+ const char *field = entry + sizeof(uint32_t) + sizeof(attribute_set_t);+ const char *entryEnd = entry + length;+ if ((returned.commonattr & ATTR_CMN_NAME) && (size_t)(entryEnd - field) >= sizeof(attrreference_t)) {+ attrreference_t reference;+ memcpy(&reference, field, sizeof(reference));+ const char *name = field + reference.attr_dataoffset;+ if (reference.attr_dataoffset >= (int32_t)sizeof(attrreference_t) && reference.attr_length > 1+ && name < entryEnd && reference.attr_length <= (size_t)(entryEnd - name)+ && name[reference.attr_length - 1] == '\0' && !vp_apfs_contains(*names, *count, name)) {+ char *copy = strdup(name);+ char **grown = copy ? realloc(*names, sizeof(char *) * (size_t)(*count + 1)) : NULL;+ if (!grown) {+ free(copy);+ return ENOMEM;+ }+ *names = grown;+ (*names)[(*count)++] = copy;+ (*added)++;+ }+ }+ entry = entryEnd;+ }+ return 0;+}++// MARK: - Listing++int vp_apfs_snapshot_list(const char *mount, char ***names, int *count) {+ if (!mount || !names || !count) return EINVAL;+ *names = NULL;+ *count = 0;+ int directory = open(mount, O_RDONLY | O_DIRECTORY, 0);+ if (directory < 0) return errno ?: EIO;++ struct attrlist attributes;+ memset(&attributes, 0, sizeof(attributes));+ attributes.bitmapcount = ATTR_BIT_MAP_COUNT;+ attributes.commonattr = ATTR_CMN_RETURNED_ATTRS | ATTR_CMN_NAME;++ // Each call continues where the last one stopped and returns 0 at the+ // end. A batch that adds no new name ends the walk as well, so a kernel+ // that answers every call from the start cannot loop forever.+ char *buffer = malloc(VP_APFS_LIST_BUFFER);+ int status = buffer ? 0 : ENOMEM;+ char **list = NULL;+ int total = 0;+ for (int batch = 0; status == 0 && batch < 64; batch++) {+ int entries = fs_snapshot_list(directory, &attributes, buffer, VP_APFS_LIST_BUFFER, 0);+ if (entries < 0) {+ status = errno ?: EIO;+ break;+ }+ if (entries == 0) break;+ int added = 0;+ status = vp_apfs_snapshot_parse(buffer, VP_APFS_LIST_BUFFER, entries, &list, &total, &added);+ if (added == 0) break;+ }+ free(buffer);+ close(directory);+ if (status != 0) {+ vp_apfs_snapshot_names_free(list, total);+ return status;+ }+ *names = list;+ *count = total;+ return 0;+}++// MARK: - Deletion++int vp_apfs_snapshot_delete(const char *mount, const char *name) {+ if (!mount || !name || !name[0]) return EINVAL;+ int directory = open(mount, O_RDONLY | O_DIRECTORY, 0);+ if (directory < 0) return errno ?: EIO;+ int status = fs_snapshot_delete(directory, name, 0) == 0 ? 0 : (errno ?: EIO);+ close(directory);+ return status;+}diff --git a/VPhoneDaemon/Native/vphoned_apps.m b/VPhoneDaemon/Native/vphoned_apps.mnew file mode 100644index 00000000..23c49d30--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_apps.m@@ -0,0 +1,126 @@+/*+ * vphoned_apps — register a restored removable system app with LaunchServices.+ *+ * `apps.restore_system` moves an Apple app's bundle container back to its+ * original UUID path and must register the bundle again. icli's registerApp+ * (since 0.7.17) refuses Apple's apps and apps another installer put in a+ * container, so this calls LSApplicationWorkspace directly, the way uicache+ * does for a system app:+ *+ * 1. registerApplication: with the bundle URL;+ * 2. registerApplicationDictionary: with the Info.plist, Path and a System,+ * deletable application type (iOS 27 answers NO and registers nothing);+ * 3. the containerized interface with the same dictionary plus the bundle+ * container.+ *+ * After each attempt LaunchServices is asked, for up to a second, whether it+ * lists the identifier at this path; the first attempt it does ends the call.+ * The Swift caller reads the registration back again through icli.+ */++#import "Include/VphonedNative.h"++#import <Foundation/Foundation.h>+#include <stdlib.h>+#include <unistd.h>++@interface NSObject (VPhoneLaunchServices)++ (id)defaultWorkspace;++ (id)applicationProxyForIdentifier:(NSString *)identifier;+- (BOOL)registerApplication:(NSURL *)url;+- (BOOL)registerApplicationDictionary:(NSDictionary *)dictionary;+- (BOOL)registerContainerizedApplicationWithInfoDictionaries:(NSArray *)infos+ operationUUID:(NSUUID *)uuid+ requestContext:(id)context+ saveObserver:(id)observer+ registrationError:(NSError **)error;+- (NSURL *)bundleURL;+@end++// MARK: - Read Back++static NSString *vp_apps_comparable(NSString *path) {+ NSString *resolved = path.stringByResolvingSymlinksInPath.stringByStandardizingPath;+ if ([resolved hasPrefix:@"/private/var/"]) resolved = [resolved substringFromIndex:@"/private".length];+ while (resolved.length > 1 && [resolved hasSuffix:@"/"]) resolved = [resolved substringToIndex:resolved.length - 1];+ return resolved;+}++static BOOL vp_apps_listed(NSString *bundleID, NSString *path) {+ Class proxyClass = NSClassFromString(@"LSApplicationProxy");+ if (![proxyClass respondsToSelector:@selector(applicationProxyForIdentifier:)]) return NO;+ NSString *expected = vp_apps_comparable(path);+ for (int attempt = 0; attempt < 10; attempt++) {+ if (attempt) usleep(100 * 1000);+ id proxy = [proxyClass applicationProxyForIdentifier:bundleID];+ NSURL *url = [proxy respondsToSelector:@selector(bundleURL)] ? [proxy bundleURL] : nil;+ if (url.path && [vp_apps_comparable(url.path) isEqualToString:expected]) return YES;+ }+ return NO;+}++// MARK: - Registration++char *vp_ls_register_system_app(const char *app_path, const char *container_path, char **method) {+ if (method) *method = NULL;+ @autoreleasepool {+ if (!app_path || !container_path) return strdup("no app path");+ NSString *path = @(app_path);+ NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:@"Info.plist"]];+ NSString *bundleID = info[@"CFBundleIdentifier"];+ if (![bundleID isKindOfClass:NSString.class] || !bundleID.length) {+ return strdup([NSString stringWithFormat:@"%@ has no bundle identifier", path].UTF8String);+ }+ Class workspaceClass = NSClassFromString(@"LSApplicationWorkspace");+ id workspace = [workspaceClass respondsToSelector:@selector(defaultWorkspace)] ? [workspaceClass defaultWorkspace] : nil;+ if (!workspace) return strdup("LSApplicationWorkspace is unavailable");++ if ([workspace respondsToSelector:@selector(registerApplication:)]+ && [workspace registerApplication:[NSURL fileURLWithPath:path isDirectory:YES]]+ && vp_apps_listed(bundleID, path)) {+ if (method) *method = strdup("registerApplication");+ return NULL;+ }++ NSMutableDictionary *dictionary = [info mutableCopy];+ dictionary[@"Path"] = path;+ dictionary[@"ApplicationType"] = @"System";+ dictionary[@"IsDeletable"] = @YES;+ if ([NSFileManager.defaultManager fileExistsAtPath:[path stringByAppendingPathComponent:@"Settings.bundle/Root.plist"]]) {+ dictionary[@"HasSettingsBundle"] = @YES;+ }+ if ([workspace respondsToSelector:@selector(registerApplicationDictionary:)]+ && [workspace registerApplicationDictionary:dictionary]+ && vp_apps_listed(bundleID, path)) {+ if (method) *method = strdup("registerApplicationDictionary");+ return NULL;+ }++ SEL containerized = @selector(+ registerContainerizedApplicationWithInfoDictionaries:operationUUID:requestContext:saveObserver:registrationError:);+ if ([workspace respondsToSelector:containerized]) {+ NSMutableDictionary *record = [dictionary mutableCopy];+ record[@"CodeInfoIdentifier"] = bundleID;+ record[@"BundleContainer"] = @(container_path);+ record[@"CompatibilityState"] = @0;+ record[@"SignerIdentity"] = @"Apple iPhone OS Application Signing";+ record[@"SignerOrganization"] = @"Apple Inc.";+ NSError *error = nil;+ [workspace registerContainerizedApplicationWithInfoDictionaries:@[record]+ operationUUID:[NSUUID UUID]+ requestContext:nil+ saveObserver:nil+ registrationError:&error];+ if (!error && vp_apps_listed(bundleID, path)) {+ if (method) *method = strdup("registerContainerizedApplication");+ return NULL;+ }+ if (error) {+ return strdup([NSString stringWithFormat:@"LaunchServices refused %@: %@", bundleID,+ error.localizedDescription].UTF8String);+ }+ }+ return strdup([NSString stringWithFormat:@"LaunchServices does not list %@ at %@ after registration", bundleID,+ path].UTF8String);+ }+}diff --git a/VPhoneDaemon/Tests/APFSSnapshotParseTests.m b/VPhoneDaemon/Tests/APFSSnapshotParseTests.mnew file mode 100644index 00000000..13949204--- /dev/null+++ b/VPhoneDaemon/Tests/APFSSnapshotParseTests.m@@ -0,0 +1,86 @@+#import <Foundation/Foundation.h>+#include <assert.h>+#include <stdio.h>+#include <string.h>+#include <sys/attr.h>+#import "../Native/Include/VphonedNative.h"++// Feeds vp_apfs_snapshot_parse hand-built fs_snapshot_list batches. Nothing+// here lists or deletes a real snapshot: the runner never calls+// vp_apfs_snapshot_list or vp_apfs_snapshot_delete on the Mac.++static size_t appendEntry(char *buffer, size_t offset, const char *name, bool withName, int32_t dataOffset) {+ size_t nameLength = strlen(name) + 1;+ size_t length = sizeof(uint32_t) + sizeof(attribute_set_t) + sizeof(attrreference_t) + nameLength;+ length = (length + 7) & ~(size_t)7;+ char *entry = buffer + offset;+ memset(entry, 0, length);+ uint32_t stored = (uint32_t)length;+ memcpy(entry, &stored, sizeof(stored));+ attribute_set_t returned = {0};+ returned.commonattr = withName ? ATTR_CMN_NAME : 0;+ memcpy(entry + sizeof(uint32_t), &returned, sizeof(returned));+ attrreference_t reference = {.attr_dataoffset = dataOffset, .attr_length = (u_int32_t)nameLength};+ char *field = entry + sizeof(uint32_t) + sizeof(attribute_set_t);+ memcpy(field, &reference, sizeof(reference));+ memcpy(field + sizeof(reference), name, nameLength);+ return offset + length;+}++static int checks, failures;+static void check(bool condition, const char *message) {+ checks++;+ if (!condition) {+ failures++;+ printf("FAIL: %s\n", message);+ }+}++int main(void) {+ char buffer[4096];+ char **names = NULL;+ int count = 0, added = 0;+ const int32_t direct = (int32_t)sizeof(attrreference_t);++ size_t size = appendEntry(buffer, 0, "com.apple.os.update-4EC2ECB9", true, direct);+ size = appendEntry(buffer, size, "orig-fs.disabled.rn-4EC2ECB9", true, direct);+ check(vp_apfs_snapshot_parse(buffer, size, 2, &names, &count, &added) == 0, "parses a batch");+ check(count == 2 && added == 2, "two names");+ check(count == 2 && strcmp(names[0], "com.apple.os.update-4EC2ECB9") == 0, "first name");+ check(count == 2 && strcmp(names[1], "orig-fs.disabled.rn-4EC2ECB9") == 0, "second name");++ // The same batch again adds nothing: the listing loop stops on that.+ check(vp_apfs_snapshot_parse(buffer, size, 2, &names, &count, &added) == 0 && added == 0 && count == 2,+ "repeated batch adds nothing");++ // Malformed entries are skipped or end the batch, never read past it.+ size = appendEntry(buffer, 0, "no-name-attribute", false, direct);+ size = appendEntry(buffer, size, "bad-offset", true, 4096);+ size = appendEntry(buffer, size, "negative-offset", true, -64);+ size_t valid = appendEntry(buffer, size, "orig-fs.disabled.rn-7A11", true, direct);+ check(vp_apfs_snapshot_parse(buffer, valid, 4, &names, &count, &added) == 0 && added == 1 && count == 3,+ "skips entries without a usable name");+ check(count == 3 && strcmp(names[2], "orig-fs.disabled.rn-7A11") == 0, "keeps the valid entry");++ // More entries claimed than the buffer holds, and a truncated entry.+ check(vp_apfs_snapshot_parse(buffer, valid, 50, &names, &count, &added) == 0 && added == 0,+ "entry count beyond the buffer");+ check(vp_apfs_snapshot_parse(buffer, 10, 1, &names, &count, &added) == 0 && added == 0, "truncated header");+ uint32_t huge = 1u << 30;+ memcpy(buffer, &huge, sizeof(huge));+ check(vp_apfs_snapshot_parse(buffer, valid, 1, &names, &count, &added) == 0 && added == 0, "oversized entry length");+ uint32_t zero = 0;+ memcpy(buffer, &zero, sizeof(zero));+ check(vp_apfs_snapshot_parse(buffer, valid, 4, &names, &count, &added) == 0 && added == 0, "zero entry length");++ // A name without its terminator is refused.+ size = appendEntry(buffer, 0, "unterminated", true, direct);+ buffer[sizeof(uint32_t) + sizeof(attribute_set_t) + sizeof(attrreference_t) + strlen("unterminated")] = 'x';+ check(vp_apfs_snapshot_parse(buffer, size, 1, &names, &count, &added) == 0 && added == 0, "unterminated name");++ check(vp_apfs_snapshot_parse(NULL, 0, 1, &names, &count, &added) == EINVAL, "null buffer");+ vp_apfs_snapshot_names_free(names, count);++ printf("%d/%d parser checks passed\n", checks - failures, checks);+ return failures == 0 ? 0 : 1;+}diff --git a/VPhoneDaemon/Tests/SystemMaintenanceTests.swift b/VPhoneDaemon/Tests/SystemMaintenanceTests.swiftnew file mode 100644index 00000000..fb9028e0--- /dev/null+++ b/VPhoneDaemon/Tests/SystemMaintenanceTests.swift@@ -0,0 +1,257 @@+import Darwin+import Foundation++// Checks the guest-free rules behind apps.remove_system, apps.restore_system+// and apfs.snapshot.delete: GuestSystemAppPolicy.swift and+// GuestSnapshotPolicy.swift, compiled for the Mac by+// run-system-maintenance-tests.sh. Nothing here touches a file system.++@main+enum SystemMaintenanceTests {+ nonisolated(unsafe) static var failures = 0+ nonisolated(unsafe) static var checks = 0++ static func check(_ condition: Bool, _ message: String, line: Int = #line) {+ checks += 1+ if !condition {+ failures += 1+ print("FAIL line \(line): \(message)")+ }+ }++ static func throwsError(_ body: () throws -> Void) -> Bool {+ do {+ try body()+ return false+ } catch {+ return true+ }+ }++ static let uuid = "6EB8CC54-634C-4191-9A18-8287D20C55A1"+ static let otherUUID = "22E11AE9-A1A6-4533-8F4F-CBF82D1FF026"+ static let root = "/private/var/containers/Bundle/Application"++ static func main() {+ containerPaths()+ bundleIdentifiers()+ backupNames()+ manifests()+ snapshotSelection()+ snapshotErrno()+ print("\(checks - failures)/\(checks) checks passed")+ exit(failures == 0 ? 0 : 1)+ }++ // MARK: - Container paths++ static func containerPaths() {+ let location = try? GuestSystemAppLocation(bundlePath: "\(root)/\(uuid)/News.app")+ check(location?.containerPath == "\(root)/\(uuid)", "container path")+ check(location?.appPath == "\(root)/\(uuid)/News.app", "app path")+ check(location?.containerUUID == uuid, "container UUID")+ check(location?.appDirectoryName == "News.app", "app directory name")++ let unprefixed = try? GuestSystemAppLocation(bundlePath: "/var/containers/Bundle/Application/\(uuid)/AppStore.app/")+ check(unprefixed?.containerPath == "\(root)/\(uuid)", "/var path and trailing slash normalized")++ let lowercase = try? GuestSystemAppLocation(bundlePath: "\(root)/\(uuid.lowercased())/Home.app")+ check(lowercase?.containerUUID == uuid.lowercased(), "lowercase UUID kept as written")++ let refused = [+ "/Applications/MobilePhone.app",+ "/Applications/Preferences.app",+ "/System/Library/AppPlaceholders/News.app",+ "/private/var/staged_system_apps/News.app",+ "\(root)/\(uuid)/../\(otherUUID)/News.app",+ "\(root)/../../../../System/Library/CoreServices/SpringBoard.app",+ "\(root)/\(uuid)/./News.app",+ "\(root)/\(uuid)//News.app",+ "\(root)/.jbroot-000114514191980C/Applications/Irisin.app",+ "\(root)/\(uuid)/News.app/PlugIns/Widget.appex",+ "\(root)/\(uuid)/News.app/Extra.app",+ "\(root)/\(uuid)/.app",+ "\(root)/\(uuid)/.hidden.app",+ "\(root)/\(uuid)/News",+ "\(root)/\(uuid)",+ "\(root)/not-a-uuid/News.app",+ "\(root)/\(uuid)X/News.app",+ "/private/var/mobile/Containers/Data/Application/\(uuid)/News.app",+ "private/var/containers/Bundle/Application/\(uuid)/News.app",+ "",+ "/",+ ]+ for path in refused {+ check(throwsError { _ = try GuestSystemAppLocation(bundlePath: path) }, "refuses \(path)")+ }+ do {+ _ = try GuestSystemAppLocation(bundlePath: "/Applications/MobilePhone.app")+ } catch {+ check(error == .notInBundleContainer("/Applications/MobilePhone.app"), "Phone refused as not in a container")+ }+ check(throwsError { _ = try GuestSystemAppLocation(containerUUID: "../../System", appDirectoryName: "X.app") },+ "manifest UUID traversal refused")+ check(throwsError { _ = try GuestSystemAppLocation(containerUUID: uuid, appDirectoryName: "../X.app") },+ "manifest app traversal refused")+ }++ // MARK: - Bundle identifiers++ static func bundleIdentifiers() {+ for id in ["com.apple.news", "com.apple.MobileSMS", "com.apple.AppStore", "com.apple.Passbook", "com.apple.tv"] {+ check(!throwsError { try GuestSystemAppPolicy.validateBundleID(id) }, "accepts \(id)")+ }+ for id in ["", "com.apple.", "com.apple..news", "com.apple.news/../x", "com.apple.news x", "com.apple.news\n",+ "../com.apple.news", "com.apple.nëws"]+ {+ check(throwsError { try GuestSystemAppPolicy.validateBundleID(id) }, "refuses \(id.debugDescription)")+ }+ do {+ try GuestSystemAppPolicy.validateBundleID("com.example.app")+ check(false, "third-party app refused")+ } catch {+ check(error == .notSystemApp("com.example.app"), "third-party app is not a system app")+ }+ }++ // MARK: - Backup names++ static func backupNames() {+ let directory = "/private/var/mobile/Library/removed-system-apps"+ check(GuestSystemAppPolicy.backupDirectory == directory, "backup directory")+ check(GuestSystemAppPolicy.backupContainerPath("com.apple.news") == "\(directory)/com.apple.news.container",+ "backup container path")+ check(GuestSystemAppPolicy.manifestPath("com.apple.news") == "\(directory)/com.apple.news.manifest.json",+ "manifest path")+ check(GuestSystemAppPolicy.bundleID(forBackupEntry: "com.apple.news.container") == "com.apple.news",+ "id from container entry")+ check(GuestSystemAppPolicy.bundleID(forBackupEntry: "com.apple.news.manifest.json") == "com.apple.news",+ "id from manifest entry")+ for name in ["News.container", "com.apple.news.container.partial", ".DS_Store", "com.apple.news", ".container"] {+ check(GuestSystemAppPolicy.bundleID(forBackupEntry: name) == nil, "ignores entry \(name)")+ }+ }++ // MARK: - Manifests++ static func manifests() {+ guard let location = try? GuestSystemAppLocation(bundlePath: "\(root)/\(uuid)/FindMy.app") else {+ check(false, "location for manifest")+ return+ }+ let date = Date(timeIntervalSince1970: 1_791_414_420)+ let manifest = GuestSystemAppManifest(bundleID: "com.apple.findmy", location: location, removedAt: date)+ guard let data = try? manifest.encoded() else {+ check(false, "manifest encodes")+ return+ }+ let decoded = try? GuestSystemAppManifest.decode(data, expectedBundleID: "com.apple.findmy")+ check(decoded == manifest, "manifest round trip")+ check((try? decoded?.location()) == location, "manifest location round trip")++ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]+ check(Set(object.keys) == ["version", "bundle_id", "container_uuid", "app", "container_path", "removed_at"],+ "manifest keys")+ check(object["container_path"] as? String == "\(root)/\(uuid)", "manifest container path")+ check(object["removed_at"] as? String == "2026-10-07T23:07:00Z", "manifest date is ISO 8601")++ check(throwsError { _ = try GuestSystemAppManifest.decode(data, expectedBundleID: "com.apple.news") },+ "manifest for another app refused")+ check(throwsError { _ = try GuestSystemAppManifest.decode(Data("not json".utf8), expectedBundleID: "com.apple.findmy") },+ "garbage refused")++ func tampered(_ key: String, _ value: Any) -> Data {+ var copy = object+ copy[key] = value+ return (try? JSONSerialization.data(withJSONObject: copy)) ?? Data()+ }+ check(throwsError { _ = try GuestSystemAppManifest.decode(tampered("container_uuid", "../../../System"),+ expectedBundleID: "com.apple.findmy") },+ "tampered UUID refused")+ check(throwsError { _ = try GuestSystemAppManifest.decode(tampered("app", "../../Applications/X.app"),+ expectedBundleID: "com.apple.findmy") },+ "tampered app refused")+ check(throwsError { _ = try GuestSystemAppManifest.decode(tampered("version", 2),+ expectedBundleID: "com.apple.findmy") },+ "unknown version refused")+ check(throwsError {+ _ = try GuestSystemAppManifest.decode(tampered("bundle_id", "com.example.app"), expectedBundleID: "com.example.app")+ }, "third-party manifest refused")+ }++ // MARK: - Snapshot names++ static func snapshotSelection() {+ typealias Selection = GuestSnapshotPolicy.Selection+ let prefix = "orig-fs.disabled.rn-"+ let snapshots = [+ "com.apple.os.update-4EC2ECB9",+ "\(prefix)4EC2ECB9",+ "\(prefix)7A11",+ "com.apple.TimeMachine.2026-10-07-230000.local",+ ]++ check((try? Selection.make(name: nil, prefix: nil)) == .prefix(prefix), "default selects the CFW prefix")+ check((try? Selection.make(name: nil, prefix: nil))?.targets(in: snapshots) == ["\(prefix)4EC2ECB9", "\(prefix)7A11"],+ "default deletes only orig-fs snapshots")+ check((try? Selection.make(name: nil, prefix: "\(prefix)4E"))?.targets(in: snapshots) == ["\(prefix)4EC2ECB9"],+ "narrower prefix")+ check((try? Selection.make(name: "\(prefix)4EC2ECB9", prefix: nil))?.targets(in: snapshots) == ["\(prefix)4EC2ECB9"],+ "exact name")+ check((try? Selection.make(name: "\(prefix)GONE", prefix: nil))?.targets(in: snapshots) == ["\(prefix)GONE"],+ "an unlisted name is still tried")+ check((try? Selection.make(name: nil, prefix: nil))?.targets(in: ["com.apple.os.update-4EC2ECB9"]) == [],+ "nothing matched selects nothing")+ check((try? Selection.make(name: nil, prefix: nil))?.targets(in: []) == [], "empty volume selects nothing")++ for name in ["com.apple.os.update-4EC2ECB9", prefix, "orig-fs", "x\(prefix)A", "ORIG-FS.DISABLED.RN-A"] {+ check(throwsError { _ = try Selection.make(name: name, prefix: nil) }, "refuses name \(name)")+ }+ for refusedPrefix in ["", "orig-fs", "com.apple.os.update-", "o"] {+ check(throwsError { _ = try Selection.make(name: nil, prefix: refusedPrefix) }, "refuses prefix \(refusedPrefix)")+ }+ check(throwsError { _ = try Selection.make(name: "\(prefix)A", prefix: prefix) }, "name and prefix together refused")+ check(throwsError { _ = try Selection.make(name: "\(prefix)A/B", prefix: nil) }, "slash in name refused")+ do {+ _ = try Selection.make(name: "com.apple.os.update-4EC2ECB9", prefix: nil)+ } catch {+ check(error == .refused("com.apple.os.update-4EC2ECB9"), "update snapshot refusal reason")+ }++ let selection = Selection.prefix(prefix)+ check(!selection.matches("com.apple.os.update-4EC2ECB9"), "update snapshot never matches")+ check(!Selection.name("com.apple.os.update-4EC2ECB9").matches("com.apple.os.update-4EC2ECB9"),+ "a hand-built selection still refuses the update snapshot")+ check(Selection.name("com.apple.os.update-4EC2ECB9").targets(in: snapshots) == [],+ "a hand-built selection never targets the update snapshot")++ check(!throwsError { try GuestSnapshotPolicy.validateMount("/") }, "root mount")+ check(!throwsError { try GuestSnapshotPolicy.validateMount("/private/var") }, "data mount")+ for mount in ["", "private/var", "/private/../System", "/./"] {+ check(throwsError { try GuestSnapshotPolicy.validateMount(mount) }, "refuses mount \(mount)")+ }+ }++ // MARK: - errno++ static func snapshotErrno() {+ typealias Failure = GuestSnapshotPolicy.Failure+ check(Failure(errno: ENOENT) == .alreadyDeleted, "ENOENT is already deleted")+ check(Failure(errno: EPERM) == .notPermitted, "EPERM is not permitted")+ check(Failure(errno: EACCES) == .notPermitted, "EACCES is not permitted")+ check(Failure(errno: EBUSY) == .busy, "EBUSY is busy")+ check(Failure(errno: EINVAL) == .invalidRequest, "EINVAL is an invalid request")+ check(Failure(errno: ENOTSUP) == .invalidRequest, "ENOTSUP is an invalid request")+ check(Failure(errno: EIO) == .failed, "EIO fails")+ check(Failure(errno: EBUSY).retryable, "busy is retryable")+ for failure in [Failure.alreadyDeleted, .notPermitted, .invalidRequest, .failed] {+ check(!failure.retryable, "\(failure.rawValue) is not retryable")+ }+ check(Failure.notPermitted.rawValue == "not_permitted" && Failure.alreadyDeleted.rawValue == "already_deleted"+ && Failure.invalidRequest.rawValue == "invalid_request", "wire reasons")+ let message = GuestSnapshotPolicy.message(.notPermitted, errno: EPERM, operation: "fs_snapshot_delete(x)")+ check(message.contains("com.apple.developer.vfs.snapshot") && message.contains("root"),+ "permission message names the entitlement")+ check(GuestSnapshotPolicy.message(.busy, errno: EBUSY, operation: "x").contains("retry"), "busy message says retry")+ }+}diff --git a/VPhoneDaemon/Tests/run-system-maintenance-tests.sh b/VPhoneDaemon/Tests/run-system-maintenance-tests.shnew file mode 100755index 00000000..d1d60bea--- /dev/null+++ b/VPhoneDaemon/Tests/run-system-maintenance-tests.sh@@ -0,0 +1,28 @@+#!/bin/zsh+set -euo pipefail++# Builds the guest-free rules of apps.remove_system, apps.restore_system and+# apfs.snapshot.delete, and the fs_snapshot_list batch parser, for the Mac and+# runs their checks. Nothing lists or deletes a snapshot and no guest is+# needed; the binaries live in a temporary directory.++daemon="${0:a:h:h}"+temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-system-maintenance-tests.XXXXXX")"+trap '/bin/rm -rf "$temporary"' EXIT++/usr/bin/xcrun --sdk macosx swiftc -swift-version 6 -parse-as-library \+ -module-name SystemMaintenanceTests \+ "$daemon/Daemon/GuestSystemAppPolicy.swift" \+ "$daemon/Daemon/GuestSnapshotPolicy.swift" \+ "$daemon/Tests/SystemMaintenanceTests.swift" \+ -o "$temporary/system-maintenance-tests"++"$temporary/system-maintenance-tests"++/usr/bin/xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror \+ -fsanitize=address,undefined \+ -framework Foundation \+ "$daemon/Tests/APFSSnapshotParseTests.m" "$daemon/Native/vphoned_apfs.m" \+ -o "$temporary/apfs-snapshot-parse-tests"++"$temporary/apfs-snapshot-parse-tests"